diff --git a/pom.xml b/pom.xml index e0e19bd08a..0e49146b8b 100644 --- a/pom.xml +++ b/pom.xml @@ -87,6 +87,7 @@ 7.0.6 1.5 3.2.0 + 3.53.4.0 2.1.8 1.10.0 1.21.4 @@ -218,6 +219,11 @@ KeePassJava2 ${KeePassJava2.version} + + org.xerial + sqlite-jdbc + ${sqlite-jdbc.version} + org.asciidoctor asciidoctorj-api diff --git a/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77.java b/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77.java new file mode 100644 index 0000000000..a026fabdad --- /dev/null +++ b/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77.java @@ -0,0 +1,141 @@ +package org.owasp.wrongsecrets.challenges.docker; + +import static org.owasp.wrongsecrets.Challenges.ErrorResponses.DECRYPTION_ERROR; +import static org.owasp.wrongsecrets.Challenges.ErrorResponses.FILE_MOUNT_ERROR; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.security.GeneralSecurityException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Base64; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import lombok.extern.slf4j.Slf4j; +import org.owasp.wrongsecrets.challenges.FixedAnswerChallenge; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +/** + * Challenge about intentionally vulnerable password storage in a shipped SQLite user database. The + * database holds ~2000 synthetic user records whose passwords are stored twice: as an unsalted MD5 + * hash and as AES-128-ECB ciphertext produced with a key that ships together with this source code. + * At runtime one database user is selected as the target: its username is displayed in the + * explanation and the recovered password of that exact user is the answer of this challenge. + */ +@Slf4j +@Component +public class Challenge77 extends FixedAnswerChallenge { + + static final String ENCRYPTION_KEY = "SqliteWeakKey76!"; + + private static final String TARGET_USER_QUERY = + "SELECT username, password_encrypted FROM users ORDER BY RANDOM() LIMIT 1"; + + private final Resource databaseFile; + + private volatile DatabaseUser targetUser; + + /** + * Constructor for creating a new Challenge77 object. + * + * @param databaseFile the SQLite database containing the synthetic user records. + */ + public Challenge77( + @Value("classpath:challenges/challenge-77/wrongsecrets-users.sqlite") Resource databaseFile) { + this.databaseFile = databaseFile; + } + + /** + * Gives the username of the user that is dynamically selected as the target of this challenge, + * this is the username that gets displayed in the explanation. + * + * @return the username of the selected target user. + */ + public String getTargetUsername() { + return targetUser().username(); + } + + @Override + public String getAnswer() { + return targetUser().password(); + } + + private DatabaseUser targetUser() { + DatabaseUser user = targetUser; + if (user == null) { + synchronized (this) { + if (targetUser == null) { + targetUser = loadTargetUser(); + } + user = targetUser; + } + } + return user; + } + + private DatabaseUser loadTargetUser() { + Path temporaryDatabase = null; + try { + temporaryDatabase = Files.createTempFile("wrongsecrets-challenge77", ".sqlite"); + try (var inputStream = databaseFile.getInputStream()) { + Files.copy(inputStream, temporaryDatabase, StandardCopyOption.REPLACE_EXISTING); + } + try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + temporaryDatabase); + var statement = connection.createStatement(); + var resultSet = statement.executeQuery(TARGET_USER_QUERY)) { + if (resultSet.next()) { + return new DatabaseUser( + resultSet.getString("username"), decrypt(resultSet.getString("password_encrypted"))); + } + log.warn("No users found in the user database of challenge 77"); + } + } catch (IOException | SQLException e) { + log.warn("Could not read the user database of challenge 77", e); + } catch (GeneralSecurityException | IllegalArgumentException e) { + log.warn("Could not decrypt the password of the target user of challenge 77", e); + return DatabaseUser.error(DECRYPTION_ERROR); + } finally { + deleteTemporaryDatabase(temporaryDatabase); + } + return DatabaseUser.error(FILE_MOUNT_ERROR); + } + + @SuppressFBWarnings( + value = {"CIPHER_INTEGRITY", "ECB_MODE"}, + justification = "Intentionally weak ECB mode so every stored password stays recoverable") + private String decrypt(String cipherText) throws GeneralSecurityException { + SecretKey secretKey = new SecretKeySpec(ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8), "AES"); + // codeql[java/weak-cryptographic-algorithm] Intentionally weak ECB mode for educational + // challenge about vulnerable password storage + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.DECRYPT_MODE, secretKey); + byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(cipherText)); + return new String(decryptedData, StandardCharsets.UTF_8); + } + + private void deleteTemporaryDatabase(Path temporaryDatabase) { + if (temporaryDatabase == null) { + return; + } + try { + Files.deleteIfExists(temporaryDatabase); + } catch (IOException e) { + log.debug("Could not delete the temporary database copy of challenge 77", e); + } + } + + private record DatabaseUser(String username, String password) { + + private static DatabaseUser error(String password) { + return new DatabaseUser("unknown", password); + } + } +} diff --git a/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77Controller.java b/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77Controller.java new file mode 100644 index 0000000000..0b1ac94c02 --- /dev/null +++ b/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77Controller.java @@ -0,0 +1,46 @@ +package org.owasp.wrongsecrets.challenges.docker; + +import java.io.IOException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Serves the SQLite user database of challenge 77 straight from the resource folder, so + * participants can download it and crack the stored password hashes and ciphertexts offline. + */ +@Slf4j +@RestController +public class Challenge77Controller { + + private final Resource databaseFile; + + /** + * Constructor for creating a new Challenge77Controller object. + * + * @param databaseFile the SQLite database containing the synthetic user records. + */ + public Challenge77Controller( + @Value("classpath:challenges/challenge-77/wrongsecrets-users.sqlite") Resource databaseFile) { + this.databaseFile = databaseFile; + } + + /** Returns the SQLite user database of challenge 77. */ + @GetMapping("/challenges/challenge-77/wrongsecrets-users.sqlite") + public ResponseEntity userDatabase() { + try { + var databaseContent = databaseFile.getContentAsByteArray(); + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .body(databaseContent); + } catch (IOException e) { + log.warn("Unable to serve the user database of challenge 77", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } +} diff --git a/src/main/resources/challenges/challenge-77/wrongsecrets-users.sqlite b/src/main/resources/challenges/challenge-77/wrongsecrets-users.sqlite new file mode 100644 index 0000000000..e8a48c5b51 Binary files /dev/null and b/src/main/resources/challenges/challenge-77/wrongsecrets-users.sqlite differ diff --git a/src/main/resources/explanations/challenge77.adoc b/src/main/resources/explanations/challenge77.adoc new file mode 100644 index 0000000000..b52da1c81b --- /dev/null +++ b/src/main/resources/explanations/challenge77.adoc @@ -0,0 +1,24 @@ +=== Challenge 77: Crack the Leaked User Database + +A web application kept its user accounts in a SQLite database and "protected" every password twice: an unsalted https://en.wikipedia.org/wiki/MD5[MD5] hash was stored in the `password_hash` column and an https://en.wikipedia.org/wiki/Advanced_Encryption_Standard[AES-128-ECB] ciphertext was stored in the `password_encrypted` column. The same developer who built the database also shipped it together with the application source code. + +This application ships such a database: 2000 entirely synthetic user records with usernames and passwords that were generated for this challenge only. Your target user for this challenge is: + +++++ +

Your target user: user_0000

+++++ + +Download the database from link:/challenges/challenge-77/wrongsecrets-users.sqlite[`/challenges/challenge-77/wrongsecrets-users.sqlite`] and recover the plaintext password that belongs to that user: + +.... +sqlite3 wrongsecrets-users.sqlite "SELECT hash_algorithm, password_hash, cipher_algorithm, password_encrypted FROM users WHERE username = 'YOUR_TARGET_USER';" +.... + +Submit the recovered plaintext password as the answer. It is not the hash and it is not the ciphertext: the whole point of this challenge is that both stored representations can be turned back into the original password, completely offline. + +The same file is part of the source tree at link:https://github.com/OWASP/wrongsecrets/blob/master/src/main/resources/challenges/challenge-77/wrongsecrets-users.sqlite[`src/main/resources/challenges/challenge-77/wrongsecrets-users.sqlite`]. + +[NOTE] +==== +All 2000 users can be recovered the same way, but only the password of the target user listed above is accepted as the answer. +==== diff --git a/src/main/resources/explanations/challenge77_hint.adoc b/src/main/resources/explanations/challenge77_hint.adoc new file mode 100644 index 0000000000..db53c6a9b9 --- /dev/null +++ b/src/main/resources/explanations/challenge77_hint.adoc @@ -0,0 +1,14 @@ +The answer is the plaintext password of the target user displayed on this page - not the MD5 hash and not the ciphertext. + +1. Download the database: `curl -sO http://localhost:8080/challenges/challenge-77/wrongsecrets-users.sqlite` +2. Dump the stored values of your target user: `sqlite3 wrongsecrets-users.sqlite "SELECT hash_algorithm, password_hash, cipher_algorithm, password_encrypted FROM users WHERE username = 'YOUR_TARGET_USER';"` +3. `password_encrypted` is a base64 encoded AES-128-ECB ciphertext. The database does not contain the key: it is hardcoded in the application source code, in the `ENCRYPTION_KEY` constant of `src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge77.java`, which you can read from the link:https://github.com/OWASP/wrongsecrets[WrongSecrets repository]. +4. Base64 decode the ciphertext and decrypt it with that 16 character key. +5. Verify your result against the weak hash: `printf '%s' 'THE_RECOVERED_PASSWORD' | md5sum` has to match `password_hash`. Since the hash is plain MD5 without a salt, this check works for every user in the database and also for any other password candidate you want to test offline. + +An example of step 4 with `openssl`, fill in the two values you collected in the steps above: + +.... +key=$(printf '%s' 'THE_VALUE_OF_ENCRYPTION_KEY' | xxd -p -c 256) +printf '%s' 'THE_PASSWORD_ENCRYPTED_VALUE' | base64 -d | openssl enc -d -aes-128-ecb -K "$key" -nosalt +.... diff --git a/src/main/resources/explanations/challenge77_reason.adoc b/src/main/resources/explanations/challenge77_reason.adoc new file mode 100644 index 0000000000..ecb17c41b5 --- /dev/null +++ b/src/main/resources/explanations/challenge77_reason.adoc @@ -0,0 +1,24 @@ +*Why is storing passwords like this dangerous?* + +This challenge used two storage techniques that are commonly found in legacy applications, and both of them fail in the same way: as soon as the database ends up in the wrong hands, every single password can be read back without guessing anything. + +**Unsalted MD5 is not password hashing.** MD5 was designed to be fast, and that is exactly the wrong property for a password hash. A single GPU can try billions of MD5 candidates per second, and because no salt is stored, identical passwords produce identical hashes, which allows precomputed https://en.wikipedia.org/wiki/Rainbow_table[rainbow tables] to be reused across the whole database. The `hash_algorithm` column in this database even documents the algorithm that was used, so an attacker knows exactly which table to reach for. + +**Encryption with a key that sits next to the data is not protection.** The ciphertext was produced with AES in ECB mode, which means identical plaintext blocks turn into identical ciphertext blocks and patterns in the data stay visible. On top of that the key is a fixed 16 character constant that ships inside the application source code. Whoever has the database and the repository - which is everyone in this challenge - has the key, so the encryption only ever protected the data against someone who has neither. + +**Only one of the 2000 records had to be correct.** The application selected your target user at runtime, displayed its username, and expected exactly that user's password. Because both stored representations are fully reversible for every record, every possible target could be recovered with the same offline procedure. + +---- +What to do instead: + +- Hash passwords with a dedicated, slow algorithm such as Argon2id, bcrypt or scrypt, with a unique random salt per user and a work factor tuned to your hardware. +- Keep verification cheap but guessing expensive: never use MD5, SHA-1 or plain SHA-256 on passwords. +- If you also need to encrypt data at rest, use a proper mode such as AES-GCM and keep the key in a KMS, HSM or secret manager where it is separated from the data, scoped per tenant and rotatable. +- Never hardcode cryptographic keys in source code, and never deploy the key together with the ciphertext it protects. +- Treat a leaked password database as a credential breach: force a reset of every affected password. +---- + +[NOTE] +==== +Both failures are silent: nothing in the database tells a user that their password was only ever "protected" by a hash that can be reversed and a key that was shipped along with it. +==== diff --git a/src/main/resources/wrong-secrets-configuration.yaml b/src/main/resources/wrong-secrets-configuration.yaml index 76af63a442..1225d7495b 100644 --- a/src/main/resources/wrong-secrets-configuration.yaml +++ b/src/main/resources/wrong-secrets-configuration.yaml @@ -1145,3 +1145,16 @@ configurations: category: *ci_cd ctf: enabled: true + + - name: Challenge 77 + short-name: "challenge-77" + sources: + - class-name: "org.owasp.wrongsecrets.challenges.docker.Challenge77" + explanation: "explanations/challenge77.adoc" + hint: "explanations/challenge77_hint.adoc" + reason: "explanations/challenge77_reason.adoc" + environments: *all_envs + difficulty: *normal + category: *crypto + ctf: + enabled: true diff --git a/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77ControllerTest.java b/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77ControllerTest.java new file mode 100644 index 0000000000..fe02b422e9 --- /dev/null +++ b/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77ControllerTest.java @@ -0,0 +1,47 @@ +package org.owasp.wrongsecrets.challenges.docker; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; + +class Challenge77ControllerTest { + + private static final String DATABASE_LOCATION = + "challenges/challenge-77/wrongsecrets-users.sqlite"; + + @Test + void shouldServeTheUserDatabaseAsDownload() { + var controller = new Challenge77Controller(new ClassPathResource(DATABASE_LOCATION)); + + var response = controller.userDatabase(); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getContentType()).hasToString("application/octet-stream"); + assertThat(response.getBody()).isNotNull(); + assertThat(response.getBody()) + .startsWith("SQLite format 3".getBytes(StandardCharsets.US_ASCII)); + } + + @Test + void servedUserDatabaseShouldContainTheAnswerOfEveryTargetUser() { + var controller = new Challenge77Controller(new ClassPathResource(DATABASE_LOCATION)); + var challenge = new Challenge77(new ClassPathResource(DATABASE_LOCATION)); + + assertThat(challenge.getTargetUsername()).isNotBlank(); + assertThat(controller.userDatabase().getBody()).isNotNull(); + assertThat(challenge.answerCorrect(challenge.spoiler().solution())).isTrue(); + } + + @Test + void shouldReturnServerErrorWhenTheDatabaseIsMissing() { + var controller = + new Challenge77Controller( + new ClassPathResource("challenges/challenge-77/does-not-exist.sqlite")); + + assertThat(controller.userDatabase().getStatusCode()) + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77RegistrationTest.java b/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77RegistrationTest.java new file mode 100644 index 0000000000..bb2b37a9db --- /dev/null +++ b/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77RegistrationTest.java @@ -0,0 +1,62 @@ +package org.owasp.wrongsecrets.challenges.docker; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; +import org.owasp.wrongsecrets.Challenges; +import org.owasp.wrongsecrets.WrongSecretsApplication; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest( + properties = {"K8S_ENV=DOCKER"}, + classes = WrongSecretsApplication.class) +@AutoConfigureMockMvc +class Challenge77RegistrationTest { + + @Autowired private Challenges challenges; + + @Autowired private MockMvc mvc; + + @Test + void challenge77ShouldBeRegisteredAndDiscoverable() { + var definition = challenges.findByShortName("challenge-77"); + + assertThat(definition).isPresent(); + assertThat(challenges.getChallenge(definition.get())).hasSize(1); + assertThat(challenges.getChallenge(definition.get()).getFirst()) + .isInstanceOf(Challenge77.class); + } + + @Test + void challengePageShouldDisplayTheSelectedTargetUsername() throws Exception { + var challenge = challenge77(); + + mvc.perform(get("/challenge/challenge-77")) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString(challenge.getTargetUsername()))); + } + + @Test + void spoilShouldContainThePasswordOfTheDisplayedTargetUser() throws Exception { + var challenge = challenge77(); + + mvc.perform(get("/spoil/challenge-77")) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString(challenge.spoiler().solution()))); + + assertThat(challenge.answerCorrect(challenge.spoiler().solution())).isTrue(); + assertThat(challenge.answerCorrect("not-the-password-of-the-target-user")).isFalse(); + } + + private Challenge77 challenge77() { + var definition = challenges.findByShortName("challenge-77").orElseThrow(); + return (Challenge77) challenges.getChallenge(definition).getFirst(); + } +} diff --git a/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77Test.java b/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77Test.java new file mode 100644 index 0000000000..f60d218098 --- /dev/null +++ b/src/test/java/org/owasp/wrongsecrets/challenges/docker/Challenge77Test.java @@ -0,0 +1,108 @@ +package org.owasp.wrongsecrets.challenges.docker; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.owasp.wrongsecrets.Challenges.ErrorResponses.DECRYPTION_ERROR; +import static org.owasp.wrongsecrets.Challenges.ErrorResponses.FILE_MOUNT_ERROR; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.DriverManager; +import java.util.Base64; +import java.util.HexFormat; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; + +class Challenge77Test { + + private static final String DATABASE_LOCATION = + "challenges/challenge-77/wrongsecrets-users.sqlite"; + + @Test + void spoilerShouldGiveThePasswordOfTheSelectedTargetUser() { + var challenge = new Challenge77(new ClassPathResource(DATABASE_LOCATION)); + + assertThat(challenge.spoiler().solution()) + .isNotEmpty() + .isNotEqualTo(DECRYPTION_ERROR) + .isNotEqualTo(FILE_MOUNT_ERROR); + assertThat(challenge.answerCorrect(challenge.spoiler().solution())).isTrue(); + assertThat(challenge.answerCorrect("not-the-password-of-the-target-user")).isFalse(); + } + + @Test + void displayedUsernameAndAnswerShouldStayConsistent() { + var challenge = new Challenge77(new ClassPathResource(DATABASE_LOCATION)); + + var targetUsername = challenge.getTargetUsername(); + + assertThat(targetUsername).isNotBlank(); + assertThat(challenge.getTargetUsername()).isEqualTo(targetUsername); + assertThat(challenge.getAnswer()).isEqualTo(challenge.spoiler().solution()); + } + + @Test + void targetUsernameShouldExistInTheShippedDatabase() throws Exception { + var challenge = new Challenge77(new ClassPathResource(DATABASE_LOCATION)); + var targetUsername = challenge.getTargetUsername(); + + try (var connection = DriverManager.getConnection(databaseUrl()); + var statement = + connection.prepareStatement("SELECT COUNT(*) FROM users WHERE username = ?")) { + statement.setString(1, targetUsername); + try (var resultSet = statement.executeQuery()) { + assertThat(resultSet.next()).isTrue(); + assertThat(resultSet.getInt(1)).isEqualTo(1); + } + } + } + + @Test + void everyUserInTheShippedDatabaseShouldBeRecoverableOffline() throws Exception { + var userCount = 0; + + try (var connection = DriverManager.getConnection(databaseUrl()); + var statement = connection.createStatement(); + var resultSet = + statement.executeQuery( + "SELECT username, password_hash, password_encrypted FROM users")) { + while (resultSet.next()) { + var password = decrypt(resultSet.getString("password_encrypted")); + var md5 = MessageDigest.getInstance("MD5"); + var hash = HexFormat.of().formatHex(md5.digest(password.getBytes(StandardCharsets.UTF_8))); + + assertThat(resultSet.getString("username")).isNotBlank(); + assertThat(password).isNotBlank(); + assertThat(hash).isEqualTo(resultSet.getString("password_hash")); + userCount++; + } + } + + assertThat(userCount).isBetween(1900, 2100); + } + + @Test + void shouldReportAnErrorWhenTheDatabaseIsMissing() { + var challenge = + new Challenge77(new ClassPathResource("challenges/challenge-77/does-not-exist.sqlite")); + + assertThat(challenge.spoiler().solution()).isEqualTo(FILE_MOUNT_ERROR); + assertThat(challenge.answerCorrect(FILE_MOUNT_ERROR)).isTrue(); + } + + private String databaseUrl() throws Exception { + var databasePath = Path.of(new ClassPathResource(DATABASE_LOCATION).getURL().toURI()); + return "jdbc:sqlite:" + databasePath; + } + + private String decrypt(String cipherText) throws Exception { + var cipher = Cipher.getInstance("AES"); + cipher.init( + Cipher.DECRYPT_MODE, + new SecretKeySpec(Challenge77.ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8), "AES")); + return new String( + cipher.doFinal(Base64.getDecoder().decode(cipherText)), StandardCharsets.UTF_8); + } +}