diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Totp.java b/src/main/java/io/github/hectorvent/floci/core/common/Totp.java new file mode 100644 index 0000000000..60a1a9279d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/Totp.java @@ -0,0 +1,153 @@ +package io.github.hectorvent.floci.core.common; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Instant; +import java.util.Locale; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * Time-based one-time passwords as specified in RFC 6238: HMAC-SHA1 over the number of 30-second + * steps since the epoch, truncated to six digits by RFC 4226's dynamic truncation. + * + *
Lifted out of {@code CognitoTotp}, which is now a thin view over it, because the same + * arithmetic is needed wherever a service hands a secret to an authenticator app and then verifies + * what the app produces. Cognito's software-token MFA is the only caller today; IAM's virtual MFA + * devices are the reason it lives here rather than inside Cognito. + * + *
The secret is real randomness and the codes are really derived from it, so a caller that does + * not hold the secret cannot produce an accepted code. Secrets cross the wire as RFC 4648 base32, + * which is the form authenticator apps accept. + * + *
Everything here is JDK-only: {@link SecureRandom} for the secret and {@code javax.crypto}'s + * HMAC-SHA1 for the codes. + */ +public final class Totp { + + /** The RFC 6238 time step. A code is valid for the 30-second window it was generated in. */ + static final int STEP_SECONDS = 30; + + /** RFC 4648 base32, the alphabet authenticator apps expect. */ + private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + /** 160 bits, the secret size RFC 4226 recommends for HMAC-SHA1. */ + private static final int SECRET_BYTES = 20; + private static final int DIGITS = 6; + private static final int DIGITS_MODULUS = 1_000_000; + + private static final SecureRandom RANDOM = new SecureRandom(); + + private Totp() { + } + + /** A fresh base32-encoded secret, the form handed to an authenticator app. */ + public static String newSecret() { + byte[] secret = new byte[SECRET_BYTES]; + RANDOM.nextBytes(secret); + return base32Encode(secret); + } + + /** The step counter current at {@code now}, which is what {@link #codeAt} is keyed on. */ + public static long stepAt(Instant now) { + return Math.floorDiv(now.getEpochSecond(), STEP_SECONDS); + } + + /** The six-digit password for a given step counter. */ + public static String codeAt(String base32Secret, long counter) { + byte[] hash; + try { + Mac mac = Mac.getInstance("HmacSHA1"); + mac.init(new SecretKeySpec(base32Decode(base32Secret), "HmacSHA1")); + hash = mac.doFinal(ByteBuffer.allocate(Long.BYTES).putLong(counter).array()); + } catch (GeneralSecurityException e) { + // HmacSHA1 is required of every JDK, so this is not a runtime condition. + throw new IllegalStateException("HMAC-SHA1 is unavailable", e); + } + int offset = hash[hash.length - 1] & 0x0F; + int binary = ((hash[offset] & 0x7F) << 24) + | ((hash[offset + 1] & 0xFF) << 16) + | ((hash[offset + 2] & 0xFF) << 8) + | (hash[offset + 3] & 0xFF); + return String.format(Locale.ROOT, "%06d", binary % DIGITS_MODULUS); + } + + /** + * Whether {@code code} is the password for {@code base32Secret} at any step within + * {@code driftSteps} either side of the one current at {@code now}, which absorbs clock skew + * between the authenticator and this process. + */ + public static boolean matchesCode(String base32Secret, String code, int driftSteps, Instant now) { + if (base32Secret == null || !isSixDigits(code)) { + return false; + } + long current = stepAt(now); + for (long counter = current - driftSteps; counter <= current + driftSteps; counter++) { + if (codeEquals(codeAt(base32Secret, counter), code)) { + return true; + } + } + return false; + } + + /** Whether the value has the shape of a code at all, before any secret is touched. */ + static boolean isSixDigits(String code) { + if (code == null || code.length() != DIGITS) { + return false; + } + for (int i = 0; i < code.length(); i++) { + if (code.charAt(i) < '0' || code.charAt(i) > '9') { + return false; + } + } + return true; + } + + /** Length-independent comparison, so a wrong code does not leak its prefix through timing. */ + static boolean codeEquals(String expected, String actual) { + return MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII), + actual.getBytes(StandardCharsets.US_ASCII)); + } + + static String base32Encode(byte[] data) { + StringBuilder encoded = new StringBuilder(); + int buffer = 0; + int bitsLeft = 0; + for (byte b : data) { + buffer = (buffer << 8) | (b & 0xFF); + bitsLeft += 8; + while (bitsLeft >= 5) { + encoded.append(BASE32.charAt((buffer >> (bitsLeft - 5)) & 0x1F)); + bitsLeft -= 5; + } + } + if (bitsLeft > 0) { + encoded.append(BASE32.charAt((buffer << (5 - bitsLeft)) & 0x1F)); + } + // No '=' padding: authenticator apps accept the unpadded form, and AWS's own secrets + // carry none. + return encoded.toString(); + } + + static byte[] base32Decode(String encoded) { + int buffer = 0; + int bitsLeft = 0; + byte[] decoded = new byte[encoded.length() * 5 / 8]; + int written = 0; + for (int i = 0; i < encoded.length(); i++) { + int value = BASE32.indexOf(Character.toUpperCase(encoded.charAt(i))); + if (value < 0) { + throw new IllegalArgumentException("Not a base32 character: " + encoded.charAt(i)); + } + buffer = (buffer << 5) | value; + bitsLeft += 5; + if (bitsLeft >= 8) { + decoded[written++] = (byte) ((buffer >> (bitsLeft - 8)) & 0xFF); + bitsLeft -= 8; + } + } + return decoded; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java index 54b243a7fd..1701c8c26c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java @@ -1,92 +1,30 @@ package io.github.hectorvent.floci.services.cognito; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.time.Instant; -import java.util.Locale; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; +import io.github.hectorvent.floci.core.common.Totp; +import java.time.Instant; + +/** + * Cognito's software-token MFA view of {@link Totp}: a single code, accepted one step either side + * of the current window, plus the attempt budget a challenge gets. + */ final class CognitoTotp { // Match verification-code emulation; AWS does not publish an exact attempt threshold. static final int MAX_FAILED_ATTEMPTS = 5; - private static final char[] BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".toCharArray(); - private static final SecureRandom RANDOM = new SecureRandom(); + /** Cognito accepts the adjacent windows as well as the current one. */ + private static final int DRIFT_STEPS = 1; private CognitoTotp() {} static String newSecret() { - byte[] bytes = new byte[20]; - RANDOM.nextBytes(bytes); - StringBuilder encoded = new StringBuilder(32); - int buffer = 0; - int bits = 0; - for (byte value : bytes) { - buffer = (buffer << 8) | (value & 0xff); - bits += 8; - while (bits >= 5) { - encoded.append(BASE32[(buffer >>> (bits - 5)) & 31]); - bits -= 5; - } - } - return encoded.toString(); + return Totp.newSecret(); } static boolean validCode(String secret, String code, Instant now) { - if (secret == null || code == null || !code.matches("[0-9]{6}")) { - return false; - } - byte[] key = decode(secret); - long step = Math.floorDiv(now.getEpochSecond(), 30); - for (long candidate = step - 1; candidate <= step + 1; candidate++) { - byte[] expected = codeAt(key, candidate).getBytes(StandardCharsets.US_ASCII); - if (MessageDigest.isEqual(expected, code.getBytes(StandardCharsets.US_ASCII))) { - return true; - } - } - return false; + return Totp.matchesCode(secret, code, DRIFT_STEPS, now); } static String code(String secret, Instant now) { - return codeAt(decode(secret), Math.floorDiv(now.getEpochSecond(), 30)); - } - - private static String codeAt(byte[] key, long counter) { - try { - Mac mac = Mac.getInstance("HmacSHA1"); - mac.init(new SecretKeySpec(key, "HmacSHA1")); - byte[] digest = mac.doFinal(ByteBuffer.allocate(Long.BYTES).putLong(counter).array()); - int offset = digest[digest.length - 1] & 15; - int binary = ((digest[offset] & 127) << 24) - | ((digest[offset + 1] & 255) << 16) - | ((digest[offset + 2] & 255) << 8) - | (digest[offset + 3] & 255); - return String.format(Locale.ROOT, "%06d", binary % 1_000_000); - } catch (GeneralSecurityException e) { - throw new IllegalStateException("TOTP HMAC is unavailable", e); - } - } - - private static byte[] decode(String secret) { - byte[] decoded = new byte[secret.length() * 5 / 8]; - int buffer = 0; - int bits = 0; - int index = 0; - for (int i = 0; i < secret.length(); i++) { - int value = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(secret.charAt(i)); - if (value < 0) { - throw new IllegalArgumentException("Invalid TOTP secret"); - } - buffer = (buffer << 5) | value; - bits += 5; - if (bits >= 8) { - decoded[index++] = (byte) (buffer >>> (bits - 8)); - bits -= 8; - } - } - return decoded; + return Totp.codeAt(secret, Totp.stepAt(now)); } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ecfe91838b..58f04c66a0 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -100,7 +100,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.acm.CertificateGenerator - --initialize-at-run-time=io.github.hectorvent.floci.config.TlsConfigSource - --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoSrpHelper - - --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoTotp + - --initialize-at-run-time=io.github.hectorvent.floci.core.common.Totp - --initialize-at-run-time=io.github.hectorvent.floci.services.route53.Route53Service - --initialize-at-run-time=io.github.hectorvent.floci.services.kms.KmsService - --initialize-at-run-time=io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreEventService diff --git a/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.java b/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.java new file mode 100644 index 0000000000..94ca2017a4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.java @@ -0,0 +1,105 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The point of these is that the codes are interoperable, not merely self-consistent: a secret + * Floci hands out has to produce the same six digits an authenticator app would, or verifying a + * code is only checking this implementation against itself. + */ +class TotpTest { + + /** + * RFC 6238's test secret, the ASCII string {@code 12345678901234567890}, in base32. The + * expectations below come from that document's published table, not from this implementation. + */ + private static final String RFC6238_SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; + + @Test + void base32EncodesTheRfc6238TestSecret() { + assertEquals(RFC6238_SECRET, + Totp.base32Encode("12345678901234567890".getBytes(StandardCharsets.UTF_8))); + } + + @Test + void base32DecodeIsTheInverseOfEncode() { + byte[] original = "12345678901234567890".getBytes(StandardCharsets.UTF_8); + assertArrayEquals(original, Totp.base32Decode(Totp.base32Encode(original))); + } + + /** + * RFC 6238 Appendix B, the SHA-1 rows, truncated to the six digits AWS asks for: at T=59 the + * document gives 94287082, at T=1111111109 07081804, and so on. + */ + @Test + void codesMatchTheRfc6238TestVectors() { + assertEquals("287082", Totp.codeAt(RFC6238_SECRET, Totp.stepAt(Instant.ofEpochSecond(59)))); + assertEquals("081804", Totp.codeAt(RFC6238_SECRET, Totp.stepAt(Instant.ofEpochSecond(1111111109L)))); + assertEquals("050471", Totp.codeAt(RFC6238_SECRET, Totp.stepAt(Instant.ofEpochSecond(1111111111L)))); + assertEquals("005924", Totp.codeAt(RFC6238_SECRET, Totp.stepAt(Instant.ofEpochSecond(1234567890L)))); + assertEquals("279037", Totp.codeAt(RFC6238_SECRET, Totp.stepAt(Instant.ofEpochSecond(2000000000L)))); + assertEquals("353130", Totp.codeAt(RFC6238_SECRET, Totp.stepAt(Instant.ofEpochSecond(20000000000L)))); + } + + @Test + void generatedSecretsAreDistinctAndDecodeToAFullLengthKey() { + String first = Totp.newSecret(); + String second = Totp.newSecret(); + assertNotEquals(first, second); + assertTrue(first.matches("[A-Z2-7]{32}")); + assertEquals(20, Totp.base32Decode(first).length, "a 160-bit HMAC-SHA1 secret"); + } + + @Test + void matchesCodeAcceptsTheCurrentWindow() { + Instant now = Instant.ofEpochSecond(1_700_000_000L); + assertTrue(Totp.matchesCode(RFC6238_SECRET, Totp.codeAt(RFC6238_SECRET, Totp.stepAt(now)), 0, now)); + } + + /** The drift window's edges, so a widening or narrowing of it cannot pass unnoticed. */ + @Test + void matchesCodeHonoursTheDriftWindowExactly() { + Instant now = Instant.ofEpochSecond(1_700_000_000L); + String twoStepsBack = Totp.codeAt(RFC6238_SECRET, Totp.stepAt(now) - 2); + + assertFalse(Totp.matchesCode(RFC6238_SECRET, twoStepsBack, 1, now), + "two steps back is outside a one-step allowance"); + assertTrue(Totp.matchesCode(RFC6238_SECRET, twoStepsBack, 2, now), + "and inside a two-step one"); + } + + @Test + void matchesCodeRejectsACodeFromADifferentSecret() { + Instant now = Instant.ofEpochSecond(1_700_000_000L); + String other = Totp.newSecret(); + assertFalse(Totp.matchesCode(RFC6238_SECRET, Totp.codeAt(other, Totp.stepAt(now)), 1, now)); + } + + @Test + void anythingThatIsNotSixDigitsIsNotACode() { + assertTrue(Totp.isSixDigits("000000")); + assertFalse(Totp.isSixDigits(null)); + assertFalse(Totp.isSixDigits("12345")); + assertFalse(Totp.isSixDigits("1234567")); + assertFalse(Totp.isSixDigits("12345a")); + assertFalse(Totp.isSixDigits("12 456")); + } + + /** A negative epoch must floor rather than truncate toward zero, or codes shift by a step. */ + @Test + void stepAtFloorsBelowTheEpoch() { + assertEquals(-1, Totp.stepAt(Instant.ofEpochSecond(-1))); + assertEquals(-1, Totp.stepAt(Instant.ofEpochSecond(-30))); + assertEquals(-2, Totp.stepAt(Instant.ofEpochSecond(-31))); + assertEquals(0, Totp.stepAt(Instant.EPOCH)); + } +}