diff --git a/Laporan Tugas Irfan Afif 23514027.docx b/Laporan Tugas Irfan Afif 23514027.docx new file mode 100644 index 0000000000..a4bea2dbec Binary files /dev/null and b/Laporan Tugas Irfan Afif 23514027.docx differ diff --git a/README.MD b/README.MD index cd4392434d..3d64dc30b4 100644 --- a/README.MD +++ b/README.MD @@ -1,186 +1,79 @@ -# WebGoat: A deliberately insecure Web Application +# KODE ANALISIS WEB GOAT DAN BUG FIXING WEBGOAT DENGAN MENGGUNAKAN FIND BUGS + +Penyusun : +Irfan Afif - 23514027 -[![Build Status](https://travis-ci.org/WebGoat/WebGoat.svg)](https://travis-ci.org/WebGoat/WebGoat) -[![Coverity Scan Build Status](https://img.shields.io/coverity/scan/6101.svg)](https://scan.coverity.com/projects/webgoat-webgoat) -[![Coverage Status](https://coveralls.io/repos/WebGoat/WebGoat/badge.svg?branch=master&service=github)](https://coveralls.io/github/WebGoat/WebGoat?branch=master) -[![Codacy Badge](https://api.codacy.com/project/badge/b69ee3a86e3b4afcaf993f210fccfb1d)](https://www.codacy.com/app/dm/WebGoat) -[![Dependency Status](https://www.versioneye.com/user/projects/562da95ae346d7000e0369aa/badge.svg?style=flat)](https://www.versioneye.com/user/projects/562da95ae346d7000e0369aa) +### 1. Persiapan -# Important Information +Tugas ini dikerjakan dengan menggunakan Eclipse Luna dan JDK 1.8. Tools yang digunakan adalah tortoise git. Pada tugas ini dibuat folder screenshot yang menjadi rujukan tulisan ini. -### The WebGoat Lesson Server, is currently **UNDER MAJOR DEVELOMENT**. -As of October 2015, this version "7.0-SNAPSHOT" is stable enough for testing. +Langkah awal yang dilakukan : +* Install Maven Plugin di eclipse (m2e) +* Install FindBugs Plugin di eclipse +* Clone Git +* Import Project to Eclipse +* Atur setting FindBugs menjadi menampilkan malicious code dan security (screenshot : “setting findbug eclipse.JPG”) -#### An older stable version and instructions can be found at: [WebGoat-Legacy](https://github.com/WebGoat/WebGoat-Legacy) +### 2. Pencarian Bug -WebGoat is a deliberately insecure web application maintained by [OWASP](http://www.owasp.org/) designed to teach web -application security lessons. +Setelah persiapan selesai, jalankan findbugs. Hasil dari findbugs syang dijalankan (screenshot : “bug found.JPG”) adalah : +* Scary – Normal Confidence : +** Empty Database Password (DatabaseUtilities.java : line 134) +** Empty Database Password (UserDatabase.java : line 51) +* Troubling – High Confidence +** Non Constant String passed to execute or addBatch method on Sql statement (AbstractLesson.java : line 731) +* Of Concern – Normal Confidence +** Field isn’t final and can’t be protected from malicious code (Course.java : line 70) +** Field should be package protected (HammerHead.java : line 78) +* Of Concern – Low confidence +** Field isn’t final but should be (Screen.java : line 53) +** Nonconstant string passed to execute or addBatct method on an SQL statement (ViewDatabase.java line : 82) +** Nonconstant string passed to execute or addBatct method on an SQL statement (CreateDB.java : line 998) +** Nonconstant string passed to execute or addBatct method on an SQL statement (UserDatabase.java : line 90) -This program is a demonstration of common server-side application flaws. The -exercises are intended to be used by people to learn about application security and -penetration testing techniques. +### 3. Testing and Fixing -* [Home Page](http://webgoat.github.io) -* [OWASP Project Home Page](http://www.owasp.org/index.php/Category:OWASP_WebGoat_Project) -* [Source Code](https://github.com/WebGoat/WebGoat) -* [Easy-Run Download](https://s3.amazonaws.com/webgoat-war/webgoat-container-7.0-SNAPSHOT-war-exec.jar) -* [Wiki](https://github.com/WebGoat/WebGoat/wiki) -* [FAQ (old info):](http://code.google.com/p/webgoat/wiki/FAQ) -* [Project Leader - Direct to Bruce Mayhew](mailto:webgoat@owasp.org) -* [Mailing List - WebGoat Community - For most questions](mailto:owasp-webgoat@lists.owasp.org) -* [Artifacts generated from Continuous Integration](http://webgoat-war.s3-website-us-east-1.amazonaws.com/) -* [Output from our Travis.CI Build server](https://travis-ci.org/WebGoat/WebGoat) +#### 3.1. Empty Database Password (DatabaseUtilities.java : line 134) -**WARNING 1:** *While running this program your machine will be extremely -vulnerable to attack. You should to disconnect from the Internet while using -this program.* WebGoat's default configuration binds to localhost to minimize -the exposure. +Bug terjadi karena ketika melakukan pemanggilan koneksi database, parameter yang digunakan menggunakan string kosong. Testing Junit untuk bug ini sulit dilakukan. Perlu dilakukan modifikasi untuk dapat dilakukan JUnit testing. JUnit testing sulit dilakukan untuk kasus ini karena berhubungan dengan state servlet dan koneksi database. Untuk bug ini, dilakukan perbaikan dengan menambahkan parameter password. Fixing dilakukan dengan melakukan pengecekan null atau empty terhadap parameter password tersebut. Setelah itu testing dengan JUnit pada kelas DatabaseUtilitesTest. Hasil perubahan dilakukan commit dengan judul commit diberi kode 1. -**WARNING 2:** *This program is for educational purposes only. If you attempt -these techniques without authorization, you are very likely to get caught. If -you are caught engaging in unauthorized hacking, most companies will fire you. -Claiming that you were doing security research will not work as that is the -first thing that all hackers claim.* +#### 3.2. Empty Database Password (UserDatabase.java : line 51) -# Easy Run ( For non-developers ) +Bug ini terjadi karena melakukan pemanggilan method koneksi database dengan parameter password string kosong. JUnit testing sulit dilakukan untuk kasus ini karena berhubungan dengan koneksi database. Perbaikan dilakukan dengan menggunakan fungsi yang menghasilkan password untuk database. Hasil perbaikan dilakukan commit dengan judul commit diberi kode 2. -Every successful build of the WebGoat Lessons Container and the WebGoat Lessons in our Continuous Integration Server -creates an "Easy Run" Executable JAR file, which contains the WebGoat Lessons Server, the lessons and a embedded Tomcat server. +#### 3.3. Non Constant String passed to execute or addBatch method on Sql statement (AbstractLesson.java : line 731) -You can check for the "Last Modified" date of our "Easy Run" jar file [HERE](http://webgoat-war.s3-website-us-east-1.amazonaws.com/) +Bug ini terjadi karena adanya penggabungan string pada query sql tanpa menggunakan prepared statement. JUnit testing sulit dilakukan karena berhubungan dengan koneksi database dan banyak membutuhkan kelas dan fungsi-fungsi yang lain. Hasil perbaikan dilakukan commit dengan judul commit diberi kode 3. -The "Easy Run" JAR file offers a no hassle approach to testing and running WebGoat. Follow these instructions if you -wish to simply try/test/run the current development version of WebGoat +#### 3.4. Field isn’t final and can’t be protected from malicious code (Course.java : line 70) -### Prerequisites: -* Java VM >= 1.6 installed ( JDK 1.7 recommended) +Terjadi keanehan pada bug ini dikarenakan variabel yang dimaksud sudah bertipe final. Kesalahan sepertinya berada di pendeksian findbugs. Setelah ditelusuri lebih lanjut, bug ini terpengaruh oleh kode HammerHead.java line 89. Sifat bug sulit diperbaiki karena dibutuhkan oleh logic program. Dikarenakan level bug adalah of Concern, maka tidak ada aksi yang dilakukan untuk bug ini. -## Easy Run Instructions: +#### 3.5. Field should be package protected (HammerHead.java : line 78) -#### 1. Download the easy run executable jar file which contains all the lessons and a embedded Tomcat server: +Perbaikan dilakukan dengan merubah variable menjadi private. Hasil perbaikan dilakukan commit dengan judul commit diberi kode 5. -https://s3.amazonaws.com/webgoat-war/webgoat-container-7.0-SNAPSHOT-war-exec.jar +#### 3.6. Field isn’t final but should be (Screen.java : line 53) -#### 2. Run it using java: +Perbaikan dilakukan dengan merubah variable menjadi final. Hasil perbaikan dilakukan commit dengan judul commit diberi kode 5. -Open a command shell/window, browse to where you downloaded the easy run jar and type: +#### 3.7. Nonconstant string passed to execute or addBatct method on an SQL statement (ViewDatabase.java line : 82) -```Shell -java -jar webgoat-container-7.0-SNAPSHOT-war-exec.jar -``` +SQL query didapat dari parameter websession sehingga dibagian ini tidak dapat dilakukan perbaikan bug. -#### 3. Browse to [http://localhost:8080/WebGoat](http://localhost:8080/WebGoat) and happy hacking ! +#### 3.8. Nonconstant string passed to execute or addBatct method on an SQL statement (CreateDB.java : line 998) -#### (Optional) If you would like to change the port or other options, use the help command for guidance: +Dikarenakan SQL query semua berasal dari kode, tidak ada masukan user, maka tidak diperlukan perbaikan. -```Shell -java -jar webgoat-container-7.0-SNAPSHOT-war-exec.jar --help -``` +#### 3.9. Nonconstant string passed to execute or addBatct method on an SQL statement (UserDatabase.java : line 90) -# For Developers +Bug terjadi karena ada SQL Query yang memasukkan parameter dengan menggunakan String replace. Perbaikan dilakukan dengan menggunakan PreparedStatement -Follow these instructions if you wish to run Webgoat and modify the source code as well. +### 4. Penutup -### Prerequisites: +Analisis kode dengan menggunakan findbugs mudah untuk dilakukan. Walaupun begitu, kode analisis dengan menggunakan findbugs belum cukup. Bug yang ditemukan pun masih terdapat kemungkinan salah identifikasi. Terjadi satu bug false positif yaitu kasus nomor delapan. Terdapat juga bug yang tidak dapat diperbaiki karena bertabrakan dengan logika program, terutama pada kasus no 4 dan 7. Walupun begitu, sangat baik jika analisis findbugs dijadikan standar untuk pembuatan program. -* Java >= 1.6 ( JDK 1.7 recommended ) -* Maven > 2.0.9 -* Your favorite IDE, with Maven awareness: Netbeans/IntelliJ/Eclipse with m2e installed. -* Git, or Git support in your IDE +Dalam tugas ini, kesulitan terbesar adalah dalam hal Testing. Hampir sebagian besar bug tidak dapat dilakukan Unit Testing karena kodenya yang saling berkaitan antara satu dengan yang lain, terutama antara WebServlet ataupun session dan dengan koneksi database. Hal ini dikarenakan kode pada bug yang ditemukan tersebut tidak di desain untuk dilakukan unit testing. Salah satu saran yang dapat diberikan dari tugas ini adalah desain kode harus mengakomodir dilakukannya unit testing dan desain tersebut diterapkan dari awal pembuatan program. -## The Easy Way: Developer Edition run using Linux or Mac -The __webgoat_developer_bootstrap.sh__ script will clone the necessary repositories, call the maven goals in order -launch Tomcat listening on localhost:8080 -```Shell -mkdir WebGoat-Workspace -cd WebGoat-Workspace -curl -o webgoat_developer_bootstrap.sh https://raw.githubusercontent.com/WebGoat/WebGoat/master/webgoat_developer_bootstrap.sh -sh webgoat_developer_bootstrap.sh -``` - -## The Manual Way: Developer Edition! - -#### Cloning the Lesson Server and the Lessons project: - -Open a command shell/window, navigate to where you wish to download the source and type: - -```Shell -git clone https://github.com/WebGoat/WebGoat.git -git clone https://github.com/WebGoat/WebGoat-Lessons.git -``` - -#### Now let's start by compiling the WebGoat Lessons server. - -```Shell -cd WebGoat -mvn clean compile install -cd .. -``` - -#### Before you can run the project, we need to compile the lessons and copy them over: -**If you don't run this step, you will not have any Lessons to work with!** - -```Shell -cd WebGoat-Lessons -mvn package -cp target/plugins/*.jar ../WebGoat/webgoat-container/src/main/webapp/plugin_lessons/ -cd .. -``` - -#### Now we are ready to run the project. There are 3 options you can choose from to run the project: - -Then you can run the project with one of the steps below (From the WebGoat folder not WebGoat-Lessons): - -#### Option #1: Using the Maven-Tomcat Plugin -The __maven tomcat7:run-war__ goal runs the project in an embedded tomcat: - -```Shell -cd WebGoat -mvn -pl webgoat-container tomcat7:run-war -``` - -Browse to [http://localhost:8080/WebGoat](http://localhost:8080/WebGoat) and happy hacking ! - -#### Option #2: Java executable JAR -The __maven package__ goal generates an executable .jar file: - -```Shell -cd WebGoat -mvn package -cd webgoat-container/target -java -jar webgoat-container-7.0-SNAPSHOT-war-exec.jar http://localhost:8080/WebGoat -``` - -Browse to [http://localhost:8080/WebGoat](http://localhost:8080/WebGoat) and happy hacking ! - -#### Option #3: Deploy the WebGoat WAR file in your local Tomcat or other Application Serve: -The __maven package__ goal generates a .war file that can deployed into an Application Server, such as Tomcat - -```Shell -cd WebGoat -mvn package -cp webgoat-container/target/webgoat-container-7.0-SNAPSHOT.war /webapps/ -``` - -Browse to [http://localhost:8080/WebGoat](http://localhost:8080/WebGoat) and happy hacking ! - -# Debugging and Troubleshooting - -## Reloading plugins and lessons - -If you want to __reload all the plugin and lessons__, open a new browser tab and visit the following url: - -[http://localhost:8080/WebGoat/service/reloadplugins.mvc](http://localhost:8080/WebGoat/service/reloadplugins.mvc) - -After the plugin reload is complete, _reloading a message_ will appear and you can refresh the __main WebGoat browser tab__. - -## Debugging label properties - -To be able to see which labels are loaded through a property file, open a new browser tab and visit the following url: - -[http://localhost:8080/WebGoat/service/debug/labels.mvc](http://localhost:8080/WebGoat/service/debug/labels.mvc) - -Switch back to the main WebGoat broswer tab and __reload the main WebGoat browser tab__. - -After the reload is complete, all labels which where loaded from a property file will be __marked green__. +# \ No newline at end of file diff --git a/screenshot/bug found.JPG b/screenshot/bug found.JPG new file mode 100644 index 0000000000..be36a29a18 Binary files /dev/null and b/screenshot/bug found.JPG differ diff --git a/screenshot/bug result.JPG b/screenshot/bug result.JPG new file mode 100644 index 0000000000..8d3ba55b59 Binary files /dev/null and b/screenshot/bug result.JPG differ diff --git a/screenshot/setting findbug eclipse.JPG b/screenshot/setting findbug eclipse.JPG new file mode 100644 index 0000000000..6859979258 Binary files /dev/null and b/screenshot/setting findbug eclipse.JPG differ diff --git a/webgoat-container/pom.xml b/webgoat-container/pom.xml index 36dc8d8319..7e7716f4d0 100644 --- a/webgoat-container/pom.xml +++ b/webgoat-container/pom.xml @@ -105,7 +105,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 1.7 1.7 @@ -119,7 +118,7 @@ create-jar - compile + package jar diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java b/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java index 70522a37fe..9b3e3ff109 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java @@ -75,7 +75,7 @@ public class HammerHead extends HttpServlet { /** * Description of the Field */ - protected static SimpleDateFormat httpDateFormat; + private static SimpleDateFormat httpDateFormat; /** * Set the session timeout to be 2 days diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java index 391edbeab7..d1d57c1e70 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java @@ -27,6 +27,7 @@ import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -724,11 +725,13 @@ public boolean isAuthorized(WebSession s, String role, String functionId) { logger.info("Checking if " + role + " authorized for: " + functionId); boolean authorized = false; try { - String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'"; + PreparedStatement preparedStatement = null; + String query = "SELECT * FROM auth WHERE role = '?' and functionid = '?'"; try { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); + preparedStatement = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + preparedStatement.setString(1, role); + preparedStatement.setString(2, functionId); + ResultSet answer_results = preparedStatement.executeQuery(); authorized = answer_results.first(); logger.info("authorized: " + authorized); } catch (SQLException sqle) { diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java index 79b56858c0..07e56ba53c 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java @@ -2,6 +2,7 @@ package org.owasp.webgoat.session; import java.io.IOException; +import java.security.InvalidParameterException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; @@ -9,6 +10,7 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.Map; + import org.apache.ecs.MultiPartElement; import org.apache.ecs.html.B; import org.apache.ecs.html.TD; @@ -114,7 +116,7 @@ private static Connection makeConnection(String user, WebgoatContext context) th { Class.forName(context.getDatabaseDriver()); - if (context.getDatabaseConnectionString().contains("hsqldb")) return getHsqldbConnection(user, context); + if (context.getDatabaseConnectionString().contains("hsqldb")) return getHsqldbConnection(user, context, context.getDatabasePassword()); String userPrefix = context.getDatabaseUser(); String password = context.getDatabasePassword(); @@ -124,14 +126,19 @@ private static Connection makeConnection(String user, WebgoatContext context) th { cnfe.printStackTrace(); throw new SQLException("Couldn't load the database driver: " + cnfe.getLocalizedMessage()); + }catch (InvalidParameterException ipe) { + throw new SQLException("Couldn't load the database driver: " + ipe.getLocalizedMessage()); } } - private static Connection getHsqldbConnection(String user, WebgoatContext context) throws ClassNotFoundException, + private static Connection getHsqldbConnection(String user, WebgoatContext context, String password) throws ClassNotFoundException, SQLException { String url = context.getDatabaseConnectionString().replaceAll("\\$\\{USER\\}", user); - return DriverManager.getConnection(url, "sa", ""); + if (password == null || password.isEmpty()){ + throw new InvalidParameterException("Password database cannot be null or empty"); + } + return DriverManager.getConnection(url, "sa", password); } /** diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java index 40bc3a6d18..7e508e6e41 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java @@ -50,7 +50,7 @@ public abstract class Screen { /** * Description of the Field */ - public static int MAIN_SIZE = 375; + public static final int MAIN_SIZE = 375; // private Head head; private Element content; diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/UserDatabase.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/UserDatabase.java index 25867223ca..df1feb76ae 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/UserDatabase.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/session/UserDatabase.java @@ -18,7 +18,7 @@ class UserDatabase { private final String QUERY_ALL_USERS = "SELECT username FROM users;"; private final String QUERY_ALL_ROLES_FOR_USERNAME = "SELECT rolename FROM roles, user_roles, users WHERE roles.id = user_roles.role_id AND user_roles.user_id = users.id AND users.username = ?;"; - private final String QUERY_TABLE_COUNT = "SELECT count(id) AS count FROM table;"; + private final String QUERY_TABLE_COUNT = "SELECT count(id) AS count FROM ?;"; private final String DELETE_ALL_ROLES_FOR_USER = "DELETE FROM user_roles WHERE user_id IN (SELECT id FROM users WHERE username = ?);"; private final String DELETE_USER = "DELETE FROM users WHERE username = ?;"; @@ -38,6 +38,10 @@ public UserDatabase() { addDefaultRolesToDefaultUsers(); } } + + private static String getCaraLewat(){ + return "ini" + "password" + "budi"; + } /** *

open.

@@ -48,7 +52,7 @@ public boolean open() { try { if (userDB == null || userDB.isClosed()) { Class.forName("org.h2.Driver"); - userDB = DriverManager.getConnection(USER_DB_URI, "webgoat_admin", ""); + userDB = DriverManager.getConnection(USER_DB_URI, "webgoat_admin", getCaraLewat()); } } catch (SQLException e) { e.printStackTrace(); @@ -86,13 +90,14 @@ public int getTableCount(String tableName) { int count = 0; try { open(); - Statement statement = userDB.createStatement(); - ResultSet countResult = statement.executeQuery(QUERY_TABLE_COUNT.replace("table", tableName)); + PreparedStatement prepare = userDB.prepareStatement(QUERY_TABLE_COUNT); + prepare.setString(1, tableName); + ResultSet countResult = prepare.executeQuery(); if (countResult.next()) { count = countResult.getInt("count"); } countResult.close(); - statement.close(); + prepare.close(); close(); } catch (SQLException e) { e.printStackTrace(); diff --git a/webgoat-container/src/test/java/com/irfan/findbug/DatabaseUtilitiesTest.java b/webgoat-container/src/test/java/com/irfan/findbug/DatabaseUtilitiesTest.java new file mode 100644 index 0000000000..98605fce00 --- /dev/null +++ b/webgoat-container/src/test/java/com/irfan/findbug/DatabaseUtilitiesTest.java @@ -0,0 +1,118 @@ +package com.irfan.findbug; + +import static org.junit.Assert.*; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.InvalidParameterException; +import java.sql.SQLException; + +import javax.servlet.http.HttpServlet; + +import org.hamcrest.CoreMatchers; +import org.junit.Test; +import org.owasp.webgoat.session.DatabaseUtilities; +import org.owasp.webgoat.session.WebgoatContext; + +public class DatabaseUtilitiesTest { + + @Test + public void testFunctionGetHsqldbConnectionEmptyPassword() throws NoSuchFieldException, SQLException, IllegalArgumentException, IllegalAccessException { + //prepare for webgoatcontext + HttpServlet servlet = new HttpServlet() { + @Override + public String getInitParameter(String name) { + if (WebgoatContext.DATABASE_PASSWORD.equals(name)){ + return ""; + }else if (WebgoatContext.DATABASE_DRIVER.equals(name)){ + return "java.lang.reflect.Field"; + } + return "hsqldb"; + } + + @Override + public String getServletName() { + return "hsqldb"; + } + }; + WebgoatContext context = new WebgoatContext(servlet); + + //set private field realConnectionString + Field field = WebgoatContext.class.getDeclaredField("realConnectionString"); + field.setAccessible(true); + field.set(context, "hsqldb"); + + try{ + DatabaseUtilities.getConnection("irfan", context); + }catch (Exception e){ + assertThat(e.getMessage(), CoreMatchers.equalTo("Couldn't load the database driver: " + "Password database cannot be null or empty")); + } + } + + @Test + public void testFunctionGetHsqldbConnectionNullPassword() throws NoSuchFieldException, SQLException, IllegalArgumentException, IllegalAccessException { + //prepare for webgoatcontext + HttpServlet servlet = new HttpServlet() { + @Override + public String getInitParameter(String name) { + if (WebgoatContext.DATABASE_PASSWORD.equals(name)){ + return null; + }else if (WebgoatContext.DATABASE_DRIVER.equals(name)){ + return "java.lang.reflect.Field"; + } + return "hsqldb"; + } + + @Override + public String getServletName() { + return "hsqldb"; + } + }; + WebgoatContext context = new WebgoatContext(servlet); + + //set private field realConnectionString + Field field = WebgoatContext.class.getDeclaredField("realConnectionString"); + field.setAccessible(true); + field.set(context, "hsqldb"); + + try{ + DatabaseUtilities.getConnection("irfan", context); + }catch (Exception e){ + assertThat(e.getMessage(), CoreMatchers.equalTo("Couldn't load the database driver: " + "Password database cannot be null or empty")); + } + } + + @Test + public void testFunctionGetHsqldbConnectionNormalPassword() throws NoSuchFieldException, SQLException, IllegalArgumentException, IllegalAccessException { + //prepare for webgoatcontext + HttpServlet servlet = new HttpServlet() { + @Override + public String getInitParameter(String name) { + if (WebgoatContext.DATABASE_PASSWORD.equals(name)){ + return "ini password"; + }else if (WebgoatContext.DATABASE_DRIVER.equals(name)){ + return "java.lang.reflect.Field"; + } + return "hsqldb"; + } + + @Override + public String getServletName() { + return "hsqldb"; + } + }; + WebgoatContext context = new WebgoatContext(servlet); + + //set private field realConnectionString + Field field = WebgoatContext.class.getDeclaredField("realConnectionString"); + field.setAccessible(true); + field.set(context, "hsqldb"); + + try{ + DatabaseUtilities.getConnection("irfan", context); + }catch (Exception e){ + assertThat(e.getMessage(), CoreMatchers.equalTo("No suitable driver found for hsqldb")); + } + } +}