Code style (#696)

* Remove Guava dependency from WebGoat

* Add Checkstyle to the project with very basic standards so we have a
style across lessons. It does not interfere with basic Intellij formatting
This commit is contained in:
Nanne Baars
2019-11-03 18:11:09 +01:00
committed by René Zubcevic
parent 66bd1d8c1a
commit 1a83e2825e
94 changed files with 829 additions and 828 deletions

View File

@ -47,7 +47,7 @@ public class SqlInjectionQuiz extends AssignmentEndpoint {
String[] givenAnswers = {question_0_solution[0], question_1_solution[0], question_2_solution[0], question_3_solution[0], question_4_solution[0]};
for(int i = 0; i < solutions.length; i++) {
for (int i = 0; i < solutions.length; i++) {
if (givenAnswers[i].contains(solutions[i])) {
// answer correct
correctAnswers++;
@ -58,7 +58,7 @@ public class SqlInjectionQuiz extends AssignmentEndpoint {
}
}
if(correctAnswers == solutions.length) {
if (correctAnswers == solutions.length) {
return trackProgress(success().build());
} else {
return trackProgress(failed().build());

View File

@ -93,8 +93,8 @@ public class SqlInjectionLesson10 extends AssignmentEndpoint {
int cols = results.getMetaData().getColumnCount();
return (cols > 0);
} catch (SQLException e) {
String error_msg = e.getMessage();
if (error_msg.contains("object not found: ACCESS_LOG")) {
String errorMsg = e.getMessage();
if (errorMsg.contains("object not found: ACCESS_LOG")) {
return false;
} else {
System.err.println(e.getMessage());

View File

@ -57,19 +57,19 @@ public class SqlInjectionLesson3 extends AssignmentEndpoint {
return injectableQuery(query);
}
protected AttackResult injectableQuery(String _query) {
protected AttackResult injectableQuery(String query) {
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement(TYPE_SCROLL_INSENSITIVE, CONCUR_READ_ONLY)) {
Statement check_statement = connection.createStatement(TYPE_SCROLL_INSENSITIVE,
Statement checkStatement = connection.createStatement(TYPE_SCROLL_INSENSITIVE,
CONCUR_READ_ONLY);
statement.executeUpdate(_query);
ResultSet _results = check_statement.executeQuery("SELECT * FROM employees WHERE last_name='Barnett';");
statement.executeUpdate(query);
ResultSet results = checkStatement.executeQuery("SELECT * FROM employees WHERE last_name='Barnett';");
StringBuffer output = new StringBuffer();
// user completes lesson if the department of Tobi Barnett now is 'Sales'
_results.first();
if (_results.getString("department").equals("Sales")) {
output.append("<span class='feedback-positive'>" + _query + "</span>");
output.append(SqlInjectionLesson8.generateTable(_results));
results.first();
if (results.getString("department").equals("Sales")) {
output.append("<span class='feedback-positive'>" + query + "</span>");
output.append(SqlInjectionLesson8.generateTable(results));
return trackProgress(success().output(output.toString()).build());
} else {
return trackProgress(failed().output(output.toString()).build());

View File

@ -53,16 +53,16 @@ public class SqlInjectionLesson4 extends AssignmentEndpoint {
return injectableQuery(query);
}
protected AttackResult injectableQuery(String _query) {
protected AttackResult injectableQuery(String query) {
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement(TYPE_SCROLL_INSENSITIVE, CONCUR_READ_ONLY)) {
statement.executeUpdate(_query);
statement.executeUpdate(query);
connection.commit();
ResultSet _results = statement.executeQuery("SELECT phone from employees;");
ResultSet results = statement.executeQuery("SELECT phone from employees;");
StringBuffer output = new StringBuffer();
// user completes lesson if column phone exists
if (_results.first()) {
output.append("<span class='feedback-positive'>" + _query + "</span>");
if (results.first()) {
output.append("<span class='feedback-positive'>" + query + "</span>");
return trackProgress(success().output(output.toString()).build());
} else {
return trackProgress(failed().output(output.toString()).build());

View File

@ -22,7 +22,6 @@
package org.owasp.webgoat.sql_injection.introduction;
import org.owasp.webgoat.assignments.AssignmentEndpoint;
import org.owasp.webgoat.assignments.AssignmentHints;
import org.owasp.webgoat.assignments.AttackResult;
@ -62,8 +61,8 @@ public class SqlInjectionLesson5b extends AssignmentEndpoint {
try {
count = Integer.parseInt(login_count);
} catch (Exception e) {
return trackProgress(failed().output("Could not parse: " + login_count + " to a number" +
"<br> Your query was: " + queryString.replace("?", login_count)).build());
return trackProgress(failed().output("Could not parse: " + login_count + " to a number"
+ "<br> Your query was: " + queryString.replace("?", login_count)).build());
}
query.setInt(1, count);
@ -87,8 +86,6 @@ public class SqlInjectionLesson5b extends AssignmentEndpoint {
} else {
return trackProgress(failed().feedback("sql-injection.5b.no.results").output("Your query was: " + queryString.replace("?", login_count)).build());
// output.append(getLabelManager().get("NoResultsMatched"));
}
} catch (SQLException sqle) {

View File

@ -130,11 +130,11 @@ public class SqlInjectionLesson8 extends AssignmentEndpoint {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(cal.getTime());
String log_query = "INSERT INTO access_log (time, action) VALUES ('" + time + "', '" + action + "')";
String logQuery = "INSERT INTO access_log (time, action) VALUES ('" + time + "', '" + action + "')";
try {
Statement statement = connection.createStatement(TYPE_SCROLL_SENSITIVE, CONCUR_UPDATABLE);
statement.executeUpdate(log_query);
statement.executeUpdate(logQuery);
} catch (SQLException e) {
System.err.println(e.getMessage());
}

View File

@ -22,10 +22,10 @@
package org.owasp.webgoat.sql_injection.mitigation;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@ -33,6 +33,8 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
@ -41,6 +43,7 @@ import java.util.List;
*/
@RestController
@RequestMapping("SqlInjectionMitigations/servers")
@Slf4j
public class Servers {
private final DataSource dataSource;
@ -62,16 +65,19 @@ public class Servers {
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@SneakyThrows
@ResponseBody
public List<Server> sort(@RequestParam String column) {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select id, hostname, ip, mac, status, description from servers where status <> 'out of order' order by " + column);
ResultSet rs = preparedStatement.executeQuery();
List<Server> servers = Lists.newArrayList();
while (rs.next()) {
Server server = new Server(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6));
servers.add(server);
List<Server> servers = new ArrayList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select id, hostname, ip, mac, status, description from servers where status <> 'out of order' order by " + column)) {
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
Server server = new Server(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6));
servers.add(server);
}
} catch (SQLException e) {
log.error("Unable to get servers", e);
}
return servers;
}

View File

@ -49,21 +49,21 @@ public class SqlInjectionLesson10b extends AssignmentEndpoint {
editor = editor.replaceAll("\\<.*?>", "");
String regex_setsUpConnection = "(?=.*getConnection.*)";
String regex_usesPreparedStatement = "(?=.*PreparedStatement.*)";
String regex_usesPlaceholder = "(?=.*\\=\\?.*|.*\\=\\s\\?.*)";
String regex_usesSetString = "(?=.*setString.*)";
String regex_usesExecute = "(?=.*execute.*)";
String regex_usesExecuteUpdate = "(?=.*executeUpdate.*)";
String regexSetsUpConnection = "(?=.*getConnection.*)";
String regexUsesPreparedStatement = "(?=.*PreparedStatement.*)";
String regexUsesPlaceholder = "(?=.*\\=\\?.*|.*\\=\\s\\?.*)";
String regexUsesSetString = "(?=.*setString.*)";
String regexUsesExecute = "(?=.*execute.*)";
String regexUsesExecuteUpdate = "(?=.*executeUpdate.*)";
String codeline = editor.replace("\n", "").replace("\r", "");
boolean setsUpConnection = this.check_text(regex_setsUpConnection, codeline);
boolean usesPreparedStatement = this.check_text(regex_usesPreparedStatement, codeline);
boolean usesSetString = this.check_text(regex_usesSetString, codeline);
boolean usesPlaceholder = this.check_text(regex_usesPlaceholder, codeline);
boolean usesExecute = this.check_text(regex_usesExecute, codeline);
boolean usesExecuteUpdate = this.check_text(regex_usesExecuteUpdate, codeline);
boolean setsUpConnection = this.check_text(regexSetsUpConnection, codeline);
boolean usesPreparedStatement = this.check_text(regexUsesPreparedStatement, codeline);
boolean usesSetString = this.check_text(regexUsesSetString, codeline);
boolean usesPlaceholder = this.check_text(regexUsesPlaceholder, codeline);
boolean usesExecute = this.check_text(regexUsesExecute, codeline);
boolean usesExecuteUpdate = this.check_text(regexUsesExecuteUpdate, codeline);
boolean hasImportant = (setsUpConnection && usesPreparedStatement && usesPlaceholder && usesSetString && (usesExecute || usesExecuteUpdate));
List<Diagnostic> hasCompiled = this.compileFromString(editor);
@ -79,7 +79,7 @@ public class SqlInjectionLesson10b extends AssignmentEndpoint {
} else {
return trackProgress(failed().feedback("sql-injection.10b.failed").build());
}
} catch(Exception e) {
} catch (Exception e) {
return trackProgress(failed().output(e.getMessage()).build());
}
}
@ -87,7 +87,7 @@ public class SqlInjectionLesson10b extends AssignmentEndpoint {
private List<Diagnostic> compileFromString(String s) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector diagnosticsCollector = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null);
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null);
JavaFileObject javaObjectFromString = getJavaFileContentsAsString(s);
Iterable fileObjects = Arrays.asList(javaObjectFromString);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects);
@ -96,12 +96,12 @@ public class SqlInjectionLesson10b extends AssignmentEndpoint {
return diagnostics;
}
private SimpleJavaFileObject getJavaFileContentsAsString(String s){
private SimpleJavaFileObject getJavaFileContentsAsString(String s) {
StringBuilder javaFileContents = new StringBuilder("import java.sql.*; public class TestClass { static String DBUSER; static String DBPW; static String DBURL; public static void main(String[] args) {" + s + "}}");
JavaObjectFromString javaFileObject = null;
try{
try {
javaFileObject = new JavaObjectFromString("TestClass.java", javaFileContents.toString());
}catch(Exception exception){
} catch (Exception exception) {
exception.printStackTrace();
}
return javaFileObject;
@ -109,10 +109,12 @@ public class SqlInjectionLesson10b extends AssignmentEndpoint {
class JavaObjectFromString extends SimpleJavaFileObject {
private String contents = null;
public JavaObjectFromString(String className, String contents) throws Exception{
public JavaObjectFromString(String className, String contents) throws Exception {
super(new URI(className), Kind.SOURCE);
this.contents = contents;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return contents;
}
@ -121,7 +123,7 @@ public class SqlInjectionLesson10b extends AssignmentEndpoint {
private boolean check_text(String regex, String text) {
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
if(m.find())
if (m.find())
return true;
else return false;
}

View File

@ -36,6 +36,7 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@RestController
@AssignmentHints(value = {"SqlStringInjectionHint-mitigation-12a-1", "SqlStringInjectionHint-mitigation-12a-2", "SqlStringInjectionHint-mitigation-12a-3", "SqlStringInjectionHint-mitigation-12a-4"})
@ -50,10 +51,9 @@ public class SqlInjectionLesson12a extends AssignmentEndpoint {
@PostMapping("/SqlInjectionMitigations/attack12a")
@ResponseBody
@SneakyThrows
public AttackResult completed(@RequestParam String ip) {
try (Connection connection = dataSource.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement("select ip from servers where ip = ? and hostname = ?");
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select ip from servers where ip = ? and hostname = ?")) {
preparedStatement.setString(1, ip);
preparedStatement.setString(2, "webgoat-prd");
ResultSet resultSet = preparedStatement.executeQuery();
@ -61,6 +61,9 @@ public class SqlInjectionLesson12a extends AssignmentEndpoint {
return trackProgress(success().build());
}
return trackProgress(failed().build());
} catch (SQLException e) {
log.error("Failed", e);
return trackProgress(failed().build());
}
}
}