Debian Codegraph @

age/internal/testkit/testkit.go

raw symbols SCIP
1 // Copyright 2022 The age Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package testkit
6
7 import (
8 "bytes"
9 "compress/zlib"
10 "crypto/hmac"
11 "crypto/mlkem"
12 "crypto/sha256"
13 "crypto/sha3"
14 "encoding/base64"
15 "encoding/binary"
16 "fmt"
17 "io"
18 "os"
19 "strconv"
20 "strings"
21
22 "c2sp.org/CCTV/age/internal/bech32"
23 "c2sp.org/CCTV/age/internal/mlkemtest"
24 "golang.org/x/crypto/chacha20"
25 "golang.org/x/crypto/chacha20poly1305"
26 "golang.org/x/crypto/curve25519"
27 "golang.org/x/crypto/hkdf"
28 "golang.org/x/crypto/scrypt"
29 )
30
31 var TestFileKey = []byte("YELLOW SUBMARINE")
32
33 var _, TestX25519Identity, _ = bech32.Decode(
34 "AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0")
35
36 var TestX25519Recipient, _ = curve25519.X25519(TestX25519Identity, curve25519.Basepoint)
37
38 var _, TestHybridIdentity, _ = bech32.Decode(
39 "AGE-SECRET-KEY-PQ-1HZLGZUPT4ETPKDEV8HSGFDCYZ4E522W0A7PU2LHT8EH9W6YLNC3SW78XKG")
40
41 var TestHybridRecipient = func() []byte {
42 dkPQ, dkT := hybridKeysFromSeed(TestHybridIdentity)
43 return append(dkPQ.EncapsulationKey().Bytes(), x25519(dkT, curve25519.Basepoint)...)
44 }()
45
46 const ChunkSize = 64 * 1024
47
48 func NotCanonicalBase64(s string) string {
49 // Assuming there are spare zero bits at the end of the encoded bitstring,
50 // the character immediately after in the alphabet compared to the last one
51 // in the encoding will only flip the last bit to one, making the string a
52 // non-canonical encoding of the same value.
53 alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
54 idx := strings.IndexByte(alphabet, s[len(s)-1])
55 return s[:len(s)-1] + string(alphabet[idx+1])
56 }
57
58 type TestFile struct {
59 Buf bytes.Buffer
60 Rand func(n int) []byte
61
62 fileKey []byte
63 streamKey []byte
64 nonce [12]byte
65 payload bytes.Buffer
66 expect string
67 comment string
68 identities []string
69 passphrases []string
70 armor bool
71 }
72
73 func NewTestFile() *TestFile {
74 c, _ := chacha20.NewUnauthenticatedCipher(
75 []byte("TEST RANDOMNESS TEST RANDOMNESS!"), make([]byte, chacha20.NonceSize))
76 rand := func(n int) []byte {
77 out := make([]byte, n)
78 c.XORKeyStream(out, out)
79 return out
80 }
81 return &TestFile{Rand: rand, expect: "success", fileKey: TestFileKey}
82 }
83
84 func (f *TestFile) FileKey(key []byte) {
85 f.fileKey = key
86 }
87
88 func (f *TestFile) TextLine(s string) {
89 f.Buf.WriteString(s)
90 f.Buf.WriteString("\n")
91 }
92
93 func (f *TestFile) UnreadLine() string {
94 buf := bytes.TrimSuffix(f.Buf.Bytes(), []byte("\n"))
95 idx := bytes.LastIndex(buf, []byte("\n")) + 1
96 f.Buf.Reset()
97 f.Buf.Write(buf[:idx])
98 return string(buf[idx:])
99 }
100
101 func (f *TestFile) VersionLine(v string) {
102 f.TextLine("age-encryption.org/" + v)
103 }
104
105 func (f *TestFile) ArgsLine(args ...string) {
106 f.TextLine(strings.Join(append([]string{"->"}, args...), " "))
107 }
108
109 func (f *TestFile) UnreadArgsLine() []string {
110 line := strings.TrimPrefix(f.UnreadLine(), "-> ")
111 return strings.Split(line, " ")
112 }
113
114 var b64 = base64.RawStdEncoding.EncodeToString
115
116 func (f *TestFile) Body(body []byte) {
117 for {
118 line := body
119 if len(line) > 48 {
120 line = line[:48]
121 }
122 f.TextLine(b64(line))
123 body = body[len(line):]
124 if len(line) < 48 {
125 break
126 }
127 }
128 }
129
130 func (f *TestFile) Base64Padding() {
131 line := f.UnreadLine()
132 paddingLen := 4 - len(line)%4
133 if paddingLen == 4 {
134 paddingLen = 0
135 }
136 padding := strings.Repeat("=", paddingLen)
137 f.TextLine(line + padding)
138 }
139
140 func (f *TestFile) AEADBody(key, body []byte) {
141 aead, _ := chacha20poly1305.New(key)
142 f.Body(aead.Seal(nil, make([]byte, chacha20poly1305.NonceSize), body, nil))
143 }
144
145 func x25519(scalar, point []byte) []byte {
146 secret, err := curve25519.X25519(scalar, point)
147 if err != nil {
148 if strings.Contains(err.Error(), "low order point") {
149 return make([]byte, 32)
150 }
151 panic(err)
152 }
153 return secret
154 }
155
156 func (f *TestFile) X25519(identity []byte) {
157 f.X25519RecordIdentity(identity)
158 f.X25519NoRecordIdentity(identity)
159 }
160
161 func (f *TestFile) X25519RecordIdentity(identity []byte) {
162 id, _ := bech32.Encode("AGE-SECRET-KEY-", identity)
163 f.identities = append(f.identities, id)
164 }
165
166 func (f *TestFile) X25519NoRecordIdentity(identity []byte) {
167 share := x25519(f.Rand(32), curve25519.Basepoint)
168 f.X25519Stanza(share, identity)
169 }
170
171 func (f *TestFile) X25519Stanza(share, identity []byte) {
172 recipient := x25519(identity, curve25519.Basepoint)
173 f.ArgsLine("X25519", b64(share))
174 // This would be ordinarily done as [ephemeral]recipient rather than
175 // [identity]share, but for some tests we don't have the dlog of share.
176 secret := x25519(identity, share)
177 key := make([]byte, 32)
178 hkdf.New(sha256.New, secret, append(share, recipient...),
179 []byte("age-encryption.org/v1/X25519")).Read(key)
180 f.AEADBody(key, f.fileKey)
181 }
182
183 func (f *TestFile) Hybrid(identity []byte) {
184 f.HybridRecordIdentity(identity)
185 f.HybridNoRecordIdentity(identity)
186 }
187
188 func (f *TestFile) HybridRecordIdentity(identity []byte) {
189 id, _ := bech32.Encode("AGE-SECRET-KEY-PQ-", identity)
190 f.identities = append(f.identities, id)
191 }
192
193 func (f *TestFile) HybridNoRecordIdentity(identity []byte) {
194 share := x25519(f.Rand(32), curve25519.Basepoint)
195 f.HybridStanza(share, f.Rand(32), identity)
196 }
197
198 func (f *TestFile) HybridStanza(ctT, pqRandom, identity []byte) {
199 dkPQ, dkT := hybridKeysFromSeed(identity)
200
201 // Calculate shared secret as [dkT]ctT instead of [ephemeral]ekT
202 ssT := x25519(dkT, ctT)
203
204 // ML-KEM-768 deterministic encapsulation
205 ssPQ, ctPQ, _ := mlkemtest.Encapsulate768(dkPQ.EncapsulationKey(), pqRandom)
206
207 // Combined shared secret (X-Wing style)
208 h := sha3.New256()
209 h.Write(ssPQ)
210 h.Write(ssT)
211 h.Write(ctT)
212 h.Write(x25519(dkT, curve25519.Basepoint))
213 h.Write([]byte(`\./` + `/^\`))
214 sharedSecret := h.Sum(nil)
215
216 // HPKE key schedule with HKDF-SHA256
217 // suiteID = "HPKE" || kemID || kdfID || aeadID
218 // = "HPKE" || 0x647a || 0x0001 || 0x0003
219 suiteID := []byte("HPKE\x64\x7a\x00\x01\x00\x03")
220 info := []byte("age-encryption.org/mlkem768x25519")
221
222 pskIDHash := hpkeLabeledExtract(suiteID, nil, "psk_id_hash", nil)
223 infoHash := hpkeLabeledExtract(suiteID, nil, "info_hash", info)
224 ksContext := append([]byte{0}, pskIDHash...) // mode = 0
225 ksContext = append(ksContext, infoHash...)
226
227 secret := hpkeLabeledExtract(suiteID, sharedSecret, "secret", nil)
228 key := hpkeLabeledExpand(suiteID, secret, "key", ksContext, 32)
229 baseNonce := hpkeLabeledExpand(suiteID, secret, "base_nonce", ksContext, 12)
230
231 // Seal with ChaCha20-Poly1305 (seqNum=0, so nonce = baseNonce)
232 aead, _ := chacha20poly1305.New(key)
233 ciphertext := aead.Seal(nil, baseNonce, f.fileKey, nil)
234
235 // enc = ctPQ || ctT
236 enc := append(ctPQ, ctT...)
237 f.ArgsLine("mlkem768x25519", b64(enc))
238 f.Body(ciphertext)
239 }
240
241 func hybridKeysFromSeed(seed []byte) (dkPQ *mlkem.DecapsulationKey768, dkT []byte) {
242 s := sha3.NewSHAKE256()
243 s.Write(seed)
244
245 seedPQ := make([]byte, mlkem.SeedSize)
246 s.Read(seedPQ)
247 dkPQ, _ = mlkem.NewDecapsulationKey768(seedPQ)
248
249 dkT = make([]byte, 32)
250 s.Read(dkT)
251
252 return dkPQ, dkT
253 }
254
255 func hpkeLabeledExtract(suiteID, salt []byte, label string, ikm []byte) []byte {
256 labeledIKM := make([]byte, 0, 7+len(suiteID)+len(label)+len(ikm))
257 labeledIKM = append(labeledIKM, []byte("HPKE-v1")...)
258 labeledIKM = append(labeledIKM, suiteID...)
259 labeledIKM = append(labeledIKM, label...)
260 labeledIKM = append(labeledIKM, ikm...)
261 return hkdf.Extract(sha256.New, labeledIKM, salt)
262 }
263
264 func hpkeLabeledExpand(suiteID, prk []byte, label string, info []byte, length int) []byte {
265 labeledInfo := make([]byte, 0, 2+7+len(suiteID)+len(label)+len(info))
266 labeledInfo = binary.BigEndian.AppendUint16(labeledInfo, uint16(length))
267 labeledInfo = append(labeledInfo, []byte("HPKE-v1")...)
268 labeledInfo = append(labeledInfo, suiteID...)
269 labeledInfo = append(labeledInfo, label...)
270 labeledInfo = append(labeledInfo, info...)
271 out := make([]byte, length)
272 hkdf.Expand(sha256.New, prk, labeledInfo).Read(out)
273 return out
274 }
275
276 func (f *TestFile) Scrypt(passphrase string, workFactor int) {
277 f.ScryptRecordPassphrase(passphrase)
278 f.ScryptNoRecordPassphrase(passphrase, workFactor)
279 }
280
281 func (f *TestFile) ScryptRecordPassphrase(passphrase string) {
282 f.passphrases = append(f.passphrases, passphrase)
283 }
284
285 func (f *TestFile) ScryptNoRecordPassphrase(passphrase string, workFactor int) {
286 salt := f.Rand(16)
287 f.ScryptNoRecordPassphraseWithSalt(passphrase, workFactor, salt)
288 }
289
290 func (f *TestFile) ScryptNoRecordPassphraseWithSalt(passphrase string, workFactor int, salt []byte) {
291 f.ArgsLine("scrypt", b64(salt), strconv.Itoa(workFactor))
292 key, err := scrypt.Key([]byte(passphrase), append([]byte("age-encryption.org/v1/scrypt"), salt...),
293 1<<workFactor, 8, 1, 32)
294 if err != nil {
295 panic(err)
296 }
297 f.AEADBody(key, f.fileKey)
298 }
299
300 func (f *TestFile) HMACLine(h []byte) {
301 f.TextLine("--- " + b64(h))
302 }
303
304 func (f *TestFile) HMAC() {
305 key := make([]byte, 32)
306 hkdf.New(sha256.New, f.fileKey, nil, []byte("header")).Read(key)
307 h := hmac.New(sha256.New, key)
308 h.Write(f.Buf.Bytes())
309 h.Write([]byte("---"))
310 f.HMACLine(h.Sum(nil))
311 }
312
313 func (f *TestFile) Nonce() {
314 nonce := f.Rand(16)
315 f.streamKey = make([]byte, 32)
316 hkdf.New(sha256.New, f.fileKey, nonce, []byte("payload")).Read(f.streamKey)
317 f.Buf.Write(nonce)
318 }
319
320 func (f *TestFile) PayloadChunk(size int) {
321 plaintext := bytes.Repeat([]byte{0}, size)
322 s, _ := chacha20.NewUnauthenticatedCipher(f.streamKey, f.nonce[:])
323 s.SetCounter(1)
324 s.XORKeyStream(plaintext, plaintext)
325 f.payloadChunk(plaintext)
326 }
327
328 func (f *TestFile) payloadChunk(plaintext []byte) {
329 f.payload.Write(plaintext)
330 aead, _ := chacha20poly1305.New(f.streamKey)
331 f.Buf.Write(aead.Seal(nil, f.nonce[:], plaintext, nil))
332
333 for i := 10; i >= 0; i-- {
334 f.nonce[i]++
335 if f.nonce[i] != 0 {
336 break
337 }
338 }
339 }
340
341 func (f *TestFile) PayloadChunkFinal(size int) {
342 f.nonce[11] = 1
343 f.PayloadChunk(size)
344 }
345
346 func (f *TestFile) Payload(plaintext string) {
347 f.Nonce()
348 f.nonce[11] = 1
349 f.payloadChunk([]byte(plaintext))
350 }
351
352 func (f *TestFile) ExpectHeaderFailure() {
353 f.expect = "header failure"
354 }
355
356 func (f *TestFile) ExpectArmorFailure() {
357 f.armor = true
358 f.expect = "armor failure"
359 }
360
361 func (f *TestFile) ExpectPayloadFailure() {
362 f.expect = "payload failure"
363 f.payload.Reset()
364 }
365
366 func (f *TestFile) ExpectPartialPayload(goodBytes int) {
367 f.expect = "payload failure"
368 payload := f.payload.Bytes()
369 f.payload.Reset()
370 f.payload.Write(payload[:goodBytes])
371 }
372
373 func (f *TestFile) ExpectHMACFailure() {
374 f.expect = "HMAC failure"
375 }
376
377 func (f *TestFile) ExpectNoMatch() {
378 f.expect = "no match"
379 }
380
381 func (f *TestFile) Comment(c string) {
382 f.comment = c
383 }
384
385 func (f *TestFile) BeginArmor(t string) {
386 f.armor = true
387 f.TextLine("-----BEGIN " + t + "-----")
388 }
389
390 func (f *TestFile) EndArmor(t string) {
391 f.armor = true
392 f.TextLine("-----END " + t + "-----")
393 }
394
395 func (f *TestFile) Bytes() []byte {
396 out := make([]byte, f.Buf.Len())
397 copy(out, f.Buf.Bytes())
398 return out
399 }
400
401 func (f *TestFile) Generate() {
402 fmt.Printf("expect: %s\n", f.expect)
403 if f.expect == "success" || f.expect == "payload failure" {
404 fmt.Printf("payload: %x\n", sha256.Sum256(f.payload.Bytes()))
405 }
406 fmt.Printf("file key: %x\n", f.fileKey)
407 for _, id := range f.identities {
408 fmt.Printf("identity: %s\n", id)
409 }
410 for _, p := range f.passphrases {
411 fmt.Printf("passphrase: %s\n", p)
412 }
413 if f.armor {
414 fmt.Printf("armored: yes\n")
415 }
416 if f.comment != "" {
417 fmt.Printf("comment: %s\n", f.comment)
418 }
419 out := io.Writer(os.Stdout)
420 if f.Buf.Len() > 2048 {
421 fmt.Printf("compressed: zlib\n")
422 out, _ = zlib.NewWriterLevel(os.Stdout, zlib.BestCompression)
423 defer out.(*zlib.Writer).Close()
424 }
425 fmt.Println()
426 io.Copy(out, &f.Buf)
427 }