/** * A fake Cloud KMS, served by `zena:http` in the same program, for tests * of code that signs or encrypts through `google-cloud/kms`. It answers * asymmetricSign and getPublicKey for one secp256k1 key version, as Cloud * KMS may, with DER signatures whose s is high, and encrypt and decrypt * for one symmetric key, and refuses any token but `token`. * * Its encryption only has to be what the tests check: a ciphertext that * does not hold the plaintext, and that decrypts only with the same * additional data. It is a SHA-256 keystream, not a cipher to keep * anything with. */ import {Future} from 'zena:async'; import {Own} from 'zena:core'; import {secp256k1, sha256} from 'zena:crypto'; import {base64, hex} from 'zena:encoding'; import {App, Server} from 'zena:http'; import {JsonObject, parseJson, stringify} from 'zena:json'; /** The key version's name. */ export let FAKE_KMS_KEY = 'projects/p/locations/global/keyRings/r/cryptoKeys/rotation/cryptoKeyVersions/1'; /** Its private key. */ export let FAKE_KMS_PRIVATE_KEY = hex.decode('c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721'); /** The symmetric key's name. */ export let FAKE_KMS_CRYPTO_KEY = 'projects/p/locations/global/keyRings/r/cryptoKeys/signing-keys'; /** What the symmetric key's keystream and tags are made from. */ let SYMMETRIC_SECRET = hex.decode('5eb63bbbe01eeed093cb22bb8f5acdc35eb63bbbe01eeed093cb22bb8f5acdc3'); let ORDER = hex.decode('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); /** A secp256k1 SubjectPublicKeyInfo, up to the point. */ let SPKI_PREFIX = '3056301006072a8648ce3d020106052b8104000a034200'; /** `a` then `b`. */ function join(a: FixedArray, b: FixedArray) { let out = new FixedArray(a.length + b.length, 0 as u8); for (var i = 0; i < a.length; i += 1) { out[i] = a[i]; } for (var i = 0; i < b.length; i += 1) { out[a.length + i] = b[i]; } return out; } /** `n - x` for 32-byte big-endian numbers. */ function subtractFrom(n: FixedArray, x: FixedArray) { let out = new FixedArray(32, 0 as u8); var borrow = 0; for (var i = 31; i >= 0; i -= 1) { var d = (n[i] as i32) - (x[i] as i32) - borrow; borrow = if (d < 0) 1 else 0; if (d < 0) { d += 256; } out[i] = d as u8; } return out; } /** A DER INTEGER of a 32-byte number, with a leading zero byte always. */ function derInteger(value: FixedArray) { let head = new FixedArray(3, 0 as u8); head[0] = 0x02 as u8; head[1] = 33 as u8; return join(head, value); } /** The fake signs as Cloud KMS may: in DER, with the high-S twin of its signature. */ function highSDer(digest: FixedArray) { let signature = secp256k1.signDigest(FAKE_KMS_PRIVATE_KEY, digest); let body = join(derInteger(signature[0..32]), derInteger(subtractFrom(ORDER, signature[32..64]))); let head = new FixedArray(2, 0 as u8); head[0] = 0x30 as u8; head[1] = body.length as u8; return join(head, body); } /** `bytes` XORed with the keystream for `additionalData`. */ function keystreamed(bytes: FixedArray, additionalData: FixedArray) { let out = new FixedArray(bytes.length, 0 as u8); for (var block = 0; block * 32 < bytes.length; block += 1) { let counter = new FixedArray(1, block as u8); let stream = sha256(join(join(SYMMETRIC_SECRET, additionalData), counter)); for (var i = 0; i < 32 && block * 32 + i < bytes.length; i += 1) { out[block * 32 + i] = (bytes[block * 32 + i] ^ stream[i]) as u8; } } return out; } /** The tag that binds `plaintext` to `additionalData`. */ function tagOf(plaintext: FixedArray, additionalData: FixedArray) { let length = new FixedArray(1, additionalData.length as u8); return sha256(join(join(join(SYMMETRIC_SECRET, length), additionalData), plaintext)); } /** The tag, then the keystreamed plaintext. */ function fakeEncrypt(plaintext: FixedArray, additionalData: FixedArray) { return join(tagOf(plaintext, additionalData), keystreamed(plaintext, additionalData)); } /** The plaintext of `ciphertext`, or null when it was not encrypted with `additionalData`. */ function fakeDecrypt(ciphertext: FixedArray, additionalData: FixedArray): FixedArray | null { if (ciphertext.length < 32) { return null; } let plaintext = keystreamed(ciphertext[32..ciphertext.length], additionalData); return if (hex.encode(tagOf(plaintext, additionalData)) == hex.encode(ciphertext[0..32])) plaintext else null; } /** The base64 member `name` of `body`, decoded; empty when it is missing. */ function bytesMember(body: JsonObject, name: String) { let value = body[name]; return if (value is String) base64.decode(value) else new FixedArray(0, 0 as u8); } /** A started server for the keys; its origin is `http://127.0.0.1:`. */ export function startFakeKms(): Own { let app = new App(); app.use(async (req, res, next): Future => { res.type = 'application/json'; if (req.getHeader('authorization') != 'Bearer token') { res.statusCode = 403; res.body = '{"error":{"code":403,"message":"Permission denied on the key"}}'; return; } if (req.method == 'POST' && req.path == `/v1/${FAKE_KMS_KEY}:asymmetricSign`) { let body = parseJson(await req.text()) as JsonObject; let digest = base64.decode((body['digest'] as JsonObject)['sha256'] as String); let answer = new JsonObject(); answer['name'] = FAKE_KMS_KEY; answer['signature'] = base64.encode(highSDer(digest)); res.body = stringify(answer); return; } if (req.method == 'POST' && req.path == `/v1/${FAKE_KMS_CRYPTO_KEY}:encrypt`) { let body = parseJson(await req.text()) as JsonObject; let answer = new JsonObject(); answer['name'] = `${FAKE_KMS_CRYPTO_KEY}/cryptoKeyVersions/1`; answer['ciphertext'] = base64.encode(fakeEncrypt(bytesMember(body, 'plaintext'), bytesMember(body, 'additionalAuthenticatedData'))); res.body = stringify(answer); return; } if (req.method == 'POST' && req.path == `/v1/${FAKE_KMS_CRYPTO_KEY}:decrypt`) { let body = parseJson(await req.text()) as JsonObject; let plaintext = fakeDecrypt(bytesMember(body, 'ciphertext'), bytesMember(body, 'additionalAuthenticatedData')); if (plaintext == null) { res.statusCode = 400; res.body = '{"error":{"code":400,"message":"Decryption failed: the ciphertext is invalid."}}'; return; } let answer = new JsonObject(); answer['plaintext'] = base64.encode(plaintext); res.body = stringify(answer); return; } if (req.method == 'GET' && req.path == `/v1/${FAKE_KMS_KEY}/publicKey`) { let spki = join(hex.decode(SPKI_PREFIX), secp256k1.publicKey(FAKE_KMS_PRIVATE_KEY, false)); let encoded = base64.encode(spki); var pem = '-----BEGIN PUBLIC KEY-----\n'; var at = 0; while (at < encoded.length) { let end = if (at + 64 < encoded.length) at + 64 else encoded.length; pem = `${pem}${encoded.sliceBytes(at, end)}\n`; at = end; } pem = `${pem}-----END PUBLIC KEY-----\n`; let answer = new JsonObject(); answer['pem'] = pem; answer['algorithm'] = 'EC_SIGN_SECP256K1_SHA256'; res.body = stringify(answer); return; } res.statusCode = 404; res.body = '{"error":{"code":404,"message":"not found"}}'; }); let server = new Server(app, 0 as u16); server.start(); return server; }