Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-crypto

Source of release 0.6.1

0.6.1 / tests / gcm / main.lucb

## AES and AES-GCM vectors: BearSSL's AES block, Monte Carlo and CTR known
## answers, GHASH known answers plus a cross-check against a bit-serial GHASH,
## GCM known answers with tampering and tag truncation, the complete Wycheproof
## aes_gcm file, NIST CAVP gcmEncryptExtIV/gcmDecrypt cases and OpenSSL's
## AES-GCM stanzas.
import aes
import chacha
import gcm
import vector_file

## FIPS 197 block known answers (BearSSL KAT_AES; encryption direction).
func block_kats(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/aes_ecb.txt")
    defer lines.close()
    var key: u8[32]
    var plain: u8[16]
    var cipher: u8[16]
    var out: u8[16]
    var count: usize = 0
    while lines.next():
        let k = try lines.decode(0, key)
        _ = try lines.decode(1, plain)
        _ = try lines.decode(2, cipher)
        var schedule = try aes.expand(key[..<k])
        try aes.encrypt_block(&schedule, plain, out)
        schedule.wipe()
        assert(out == cipher, "AES block mismatch")
        count += 1
    return count

## BearSSL monte_carlo_AES_encrypt: 100 keys, each 1000 chained encryptions.
func monte_carlo(directory: str, out_of_scope: usize*) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/aes_monte_carlo.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        if try lines.is(0, "decrypt"):
            *out_of_scope += 1
            continue
        var key: u8[32]
        var buf: u8[16]
        var previous: u8[16]
        var expected: u8[16]
        let k = try lines.decode(1, key)
        _ = try lines.decode(2, buf)
        _ = try lines.decode(3, expected)
        for _ in 0..<(usize)100:
            var schedule = try aes.expand(key[..<k])
            for _ in 0..<(usize)1000:
                previous = buf
                try aes.encrypt_block(&schedule, previous, buf)
            schedule.wipe()
            if k == 16:
                for i in 0..<(usize)16: key[i] ^= buf[i]
            elif k == 24:
                for i in 0..<(usize)8: key[i] ^= previous[8 + i]
                for i in 0..<(usize)16: key[8 + i] ^= buf[i]
            else:
                for i in 0..<(usize)16:
                    key[i] ^= previous[i]
                    key[16 + i] ^= buf[i]
        assert(buf == expected, "AES Monte Carlo mismatch")
        count += 1
    return count

## BearSSL KAT_AES_CTR (RFC 3686): whole runs and counter-continued chunks.
func ctr_kats(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/aes_ctr.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var key: u8[32]
        var iv: u8[12]
        var plain: u8[200]
        var cipher: u8[200]
        var buf: u8[200]
        let k = try lines.decode(0, key)
        _ = try lines.decode(1, iv)
        let n = try lines.decode(2, plain)
        _ = try lines.decode(3, cipher)
        var schedule = try aes.expand(key[..<k])
        defer schedule.wipe()
        _ = try aes.ctr32(&schedule, iv, 1, plain[..<n], buf[..<n])
        assert(buf[..<n] == cipher[..<n], "AES-CTR mismatch (1)")
        _ = try aes.ctr32(&schedule, iv, 1, buf[..<n], buf[..<n])
        assert(buf[..<n] == plain[..<n], "AES-CTR mismatch (2)")
        for step in [(usize)32, 16]:
            var counter: u32 = 1
            var at: usize = 0
            while at < n:
                let take = n - at if n - at < step else step
                counter = try aes.ctr32(&schedule, iv, counter, plain[at..<at + take], buf[at..<at + take])
                at += take
            assert(buf[..<n] == cipher[..<n], "AES-CTR chunked mismatch")
        count += 1
    return count

## GF(2^128) multiplication, bit by bit (SP 800-38D Algorithm 1).
func slow_multiply(x: u8[], h: const u8[]):
    var z: u8[16]
    var v: u8[16]
    for i in 0..<(usize)16: v[i] = h[i]
    for i in 0..<(usize)128:
        if ((x[i // 8] >> (u8)(7 - i % 8)) & 1) == 1:
            for j in 0..<(usize)16: z[j] ^= v[j]
        let low = v[15] & 1
        var j: usize = 15
        while j > 0:
            v[j] = (v[j] >> 1) | (v[j - 1] << 7)
            j -= 1
        v[0] >>= 1
        if low == 1: v[0] ^= 0xe1
    for i in 0..<(usize)16: x[i] = z[i]

func slow_ghash(y: u8[], h: const u8[], data: const u8[]):
    var at: usize = 0
    while at < data.length:
        for i in 0..<(usize)16:
            if at + i < data.length: y[i] ^= data[at + i]
        slow_multiply(y, h)
        at += 16

## BearSSL test_GHASH: known answers, then lengths 0 to 1024 against the
## bit-serial reference on ChaCha20-generated data.
func ghash_kats(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/ghash.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var h: u8[16]
        var a: u8[100]
        var c: u8[100]
        var expected: u8[16]
        var y: u8[16]
        _ = try lines.decode(0, h)
        let a_size = try lines.decode(1, a)
        let c_size = try lines.decode(2, c)
        _ = try lines.decode(3, expected)
        try gcm.ghash(y, h, a[..<a_size])
        try gcm.ghash(y, h, c[..<c_size])
        var lengths: u8[16]
        let a_bits = (u32)a_size << 3
        let c_bits = (u32)c_size << 3
        for i in 0..<(usize)4:
            lengths[4 + i] = (u8)((a_bits >> (u32)(24 - 8 * i)) & 0xff)
            lengths[12 + i] = (u8)((c_bits >> (u32)(24 - 8 * i)) & 0xff)
        try gcm.ghash(y, h, lengths)
        assert(y == expected, "GHASH known answer mismatch")
        count += 1
    for u in 0..<(usize)1025:
        var key: u8[32]
        var nonce: u8[12]
        key[0] = (u8)(u >> 24)
        key[1] = (u8)((u >> 16) & 0xff)
        key[2] = (u8)((u >> 8) & 0xff)
        key[3] = (u8)(u & 0xff)
        var zeros: u8[1056]
        var buf: u8[1056]
        _ = try chacha.xor(key, nonce, 1, zeros, buf)
        var y0: u8[16]
        var y1: u8[16]
        for i in 0..<(usize)16:
            y0[i] = buf[i]
            y1[i] = buf[i]
        slow_ghash(y0, buf[16..<32], buf[32..<32 + u])
        try gcm.ghash(y1, buf[16..<32], buf[32..<32 + u])
        assert(y0 == y1, "GHASH cross-check mismatch")
    return count + 1025

## Seal and open in place and out of place; true when the tag verifies.
func round_trip(key: const u8[], iv: const u8[], aad: const u8[], plain: const u8[], cipher: const u8[], tag: const u8[]) -> !:
    var out: u8[600]
    var out_tag: u8[16]
    let n = plain.length
    try gcm.seal(key, iv, aad, plain, out[..<n], out_tag[..<tag.length])
    assert(out[..<n] == cipher and out_tag[..<tag.length] == tag, "GCM seal mismatch")
    for i in 0..<n: out[i] = 0x54
    try gcm.open(key, iv, aad, cipher, tag, out[..<n])
    assert(out[..<n] == plain, "GCM open mismatch")
    for i in 0..<n: out[i] = plain[i]
    try gcm.seal(key, iv, aad, out[..<n], out[..<n], out_tag[..<tag.length])
    assert(out[..<n] == cipher, "GCM in-place seal mismatch")
    try gcm.open(key, iv, aad, out[..<n], out_tag[..<tag.length], out[..<n])
    assert(out[..<n] == plain, "GCM in-place open mismatch")

func forged(key: const u8[], iv: const u8[], aad: const u8[], cipher: const u8[], tag: const u8[]) -> bool:
    var out: u8[600]
    var refused = false
    gcm.open(key, iv, aad, cipher, tag, out[..<cipher.length]) catch failure:
        assert(failure.code == gcm.forged or failure.code == gcm.invalid)
        refused = true
        recover ()
    return refused

## BearSSL test_GCM: known answers (all IV lengths), AAD tampering, and tags
## truncated to every SP 800-38D length (other lengths must be refused).
func gcm_kats(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/gcm.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var key: u8[32]
        var plain: u8[100]
        var aad: u8[100]
        var iv: u8[100]
        var cipher: u8[100]
        var tag: u8[16]
        let k = try lines.decode(0, key)
        let n = try lines.decode(1, plain)
        let a = try lines.decode(2, aad)
        let v = try lines.decode(3, iv)
        _ = try lines.decode(4, cipher)
        _ = try lines.decode(5, tag)
        try round_trip(key[..<k], iv[..<v], aad[..<a], plain[..<n], cipher[..<n], tag)
        for i in 0..<a:
            aad[i] ^= 0x04
            assert(forged(key[..<k], iv[..<v], aad[..<a], cipher[..<n], tag), "AAD change not detected")
            aad[i] ^= 0x04
        for size in 1..<(usize)17:
            var out: u8[100]
            var out_tag: u8[16]
            if gcm.valid_tag_length(size):
                try gcm.seal(key[..<k], iv[..<v], aad[..<a], plain[..<n], out[..<n], out_tag[..<size])
                assert(out_tag[..<size] == tag[..<size], "truncated GCM tag mismatch")
                try gcm.open(key[..<k], iv[..<v], aad[..<a], cipher[..<n], tag[..<size], out[..<n])
            else:
                var refused = false
                gcm.seal(key[..<k], iv[..<v], aad[..<a], plain[..<n], out[..<n], out_tag[..<size]) catch failure:
                    assert(failure.code == gcm.invalid)
                    refused = true
                    recover ()
                assert(refused, "GCM tag length outside SP 800-38D accepted")
        count += 1
    return count

## The complete Wycheproof aes_gcm file.
func wycheproof(directory: str, valid: usize*, invalid: usize*) -> !:
    var lines = try vector_file.Lines.open(directory, "wycheproof/aes_gcm.txt")
    defer lines.close()
    var key: u8[32]
    var iv: u8[300]
    var aad: u8[600]
    var msg: u8[600]
    var ct: u8[600]
    var tag: u8[16]
    while lines.next():
        let k = try lines.decode(1, key)
        let v = try lines.decode(2, iv)
        let a = try lines.decode(3, aad)
        let n = try lines.decode(4, msg)
        _ = try lines.decode(5, ct)
        let t = try lines.decode(6, tag)
        if try lines.is(0, "valid"):
            try round_trip(key[..<k], iv[..<v], aad[..<a], msg[..<n], ct[..<n], tag[..<t])
            *valid += 1
        else:
            assert(forged(key[..<k], iv[..<v], aad[..<a], ct[..<n], tag[..<t]), "invalid Wycheproof GCM case accepted")
            *invalid += 1

## NIST CAVP gcmEncryptExtIV and gcmDecrypt cases. The committed files are a
## subset; tools/cavp_vectors.py --full writes more parts for a local run, so
## a missing part ends the list.
func cavp(directory: str, name: str, valid: usize*, invalid: usize*) -> !:
    var lines = vector_file.Lines.open(directory, name) catch failure:
        _ = failure
        return
    defer lines.close()
    var key: u8[32]
    var iv: u8[128]
    var aad: u8[128]
    var pt: u8[64]
    var ct: u8[64]
    var tag: u8[16]
    while lines.next():
        let k = try lines.decode(1, key)
        let v = try lines.decode(2, iv)
        let a = try lines.decode(3, aad)
        let p = try lines.decode(4, pt)
        let c = try lines.decode(5, ct)
        let t = try lines.decode(6, tag)
        if try lines.is(0, "valid"):
            assert(p == c, "CAVP GCM plaintext and ciphertext lengths differ")
            try round_trip(key[..<k], iv[..<v], aad[..<a], pt[..<p], ct[..<c], tag[..<t])
            *valid += 1
        else:
            assert(forged(key[..<k], iv[..<v], aad[..<a], ct[..<c], tag[..<t]), "failing CAVP GCM case accepted")
            *invalid += 1

## OpenSSL evpciph_aes_common.txt AES-GCM stanzas. Tags shorter than 12
## bytes other than 4 and 8 are accepted by OpenSSL's default provider (its
## FIPS provider marks them unapproved); this package follows SP 800-38D and
## refuses them, which is counted separately.
func openssl(directory: str, passed: usize*, failing: usize*, refused: usize*) -> !:
    var lines = try vector_file.Lines.open(directory, "openssl/cipher.txt")
    defer lines.close()
    var key: u8[32]
    var iv: u8[64]
    var aad: u8[512]
    var plain: u8[512]
    var cipher: u8[512]
    var tag: u8[16]
    while lines.next():
        let kind = try lines.field(0)
        if kind.length < 4 or kind[0] != 'a':
            continue
        let k = try lines.decode(3, key)
        let v = try lines.decode(4, iv)
        let a = 0 if try lines.is(5, "absent") else try lines.decode(5, aad)
        let p = try lines.decode(6, plain)
        let c = try lines.decode(7, cipher)
        let t = try lines.decode(8, tag)
        assert(p == c)
        if not gcm.valid_tag_length(t):
            var out: u8[512]
            var out_tag: u8[16]
            var rejected = false
            gcm.seal(key[..<k], iv[..<v], aad[..<a], plain[..<p], out[..<p], out_tag[..<t]) catch failure:
                assert(failure.code == gcm.invalid)
                rejected = true
                recover ()
            assert(rejected, "GCM tag length outside SP 800-38D accepted")
            *refused += 1
        elif try lines.is(2, "ok"):
            if try lines.is(1, "decrypt"):
                var out: u8[512]
                try gcm.open(key[..<k], iv[..<v], aad[..<a], cipher[..<c], tag[..<t], out[..<c])
                assert(out[..<c] == plain[..<p], "OpenSSL GCM decrypt mismatch")
            else:
                try round_trip(key[..<k], iv[..<v], aad[..<a], plain[..<p], cipher[..<c], tag[..<t])
            *passed += 1
        else:
            assert(forged(key[..<k], iv[..<v], aad[..<a], cipher[..<c], tag[..<t]), "failing OpenSSL GCM case accepted")
            *failing += 1

## Optional argument: the vector directory (default tests/vectors).
pub func main(arguments: str[]) -> i32!:
    let directory = arguments[1] if arguments.length > 1 else "tests/vectors"
    var out_of_scope: usize = 0
    let blocks = try block_kats(directory)
    let carlo = try monte_carlo(directory, &out_of_scope)
    let ctr = try ctr_kats(directory)
    let ghash_count = try ghash_kats(directory)
    let kats = try gcm_kats(directory)
    var cbc = try vector_file.Lines.open(directory, "bearssl/aes_cbc.txt")
    while cbc.next(): out_of_scope += 1
    cbc.close()
    var valid: usize = 0
    var invalid: usize = 0
    try wycheproof(directory, &valid, &invalid)
    assert(valid == 229 and invalid == 87, "unexpected Wycheproof AES-GCM counts")
    var cavp_valid: usize = 0
    var cavp_invalid: usize = 0
    let parts = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    for i in 0..<parts.length:
        var name: u8[64]
        for kind in ["cavp/gcm_encryptextiv_", "cavp/gcm_decrypt_"]:
            for j in 0..<kind.length: name[j] = kind.bytes[j]
            name[kind.length] = parts[i].bytes[0]
            let suffix = ".txt"
            for j in 0..<suffix.length: name[kind.length + 1 + j] = suffix.bytes[j]
            try cavp(directory, (str)name[..<kind.length + 5], &cavp_valid, &cavp_invalid)
    assert(cavp_valid + cavp_invalid >= 9641, "CAVP GCM files are missing")
    var ossl_passed: usize = 0
    var ossl_failing: usize = 0
    var ossl_refused: usize = 0
    try openssl(directory, &ossl_passed, &ossl_failing, &ossl_refused)
    assert(ossl_passed == 161 and ossl_failing == 3 and ossl_refused == 9, "unexpected OpenSSL GCM counts")
    assert(blocks == 387 and carlo == 3 and ctr == 9 and ghash_count == 1041 and kats == 18, "unexpected BearSSL AES/GCM counts")
    assert(out_of_scope == 33, "unexpected BearSSL AES out-of-scope count")
    print(f"PASS AES/GCM: BearSSL {blocks} block, {carlo} Monte Carlo, {ctr} CTR, {ghash_count} GHASH, {kats} GCM (+{out_of_scope} CBC/decrypt out of scope); Wycheproof {valid} valid, {invalid} invalid; CAVP {cavp_valid} valid, {cavp_invalid} failing; OpenSSL {ossl_passed} ok, {ossl_failing} failing, {ossl_refused} short tags refused")
    return 0