| 1 |
// Copyright (C) 2018 ProtonTech AG |
| 2 |
|
| 3 |
package packet |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"crypto/rand" |
| 8 |
"encoding/hex" |
| 9 |
"io" |
| 10 |
mathrand "math/rand" |
| 11 |
"testing" |
| 12 |
|
| 13 |
"github.com/ProtonMail/go-crypto/openpgp/errors" |
| 14 |
) |
| 15 |
|
| 16 |
// Note: This implementation does not produce packets with chunk sizes over |
| 17 |
// 1<<27, but can parse packets with chunk size octets up to 56 and decrypt |
| 18 |
// them within limits of the running system. See RFC4880bis, sec 5.16. |
| 19 |
var maxChunkSizeExp = 62 |
| 20 |
|
| 21 |
const maxPlaintextLength = 1 << 18 |
| 22 |
|
| 23 |
func TestAeadRFCParse(t *testing.T) { |
| 24 |
for _, sample := range samplesAeadEncryptedDataPacket { |
| 25 |
key, _ := hex.DecodeString(sample.cek) |
| 26 |
packetBytes, _ := hex.DecodeString(sample.full) |
| 27 |
packetReader := bytes.NewBuffer(packetBytes) |
| 28 |
packet := new(AEADEncrypted) |
| 29 |
ptype, _, contentsReader, err := readHeader(packetReader) |
| 30 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 31 |
t.Error("Error reading packet header") |
| 32 |
} |
| 33 |
if err = packet.parse(contentsReader); err != nil { |
| 34 |
t.Error(err) |
| 35 |
} |
| 36 |
// decrypted plaintext can be read from 'rc' |
| 37 |
rc, err := packet.decrypt(key) |
| 38 |
if err != nil { |
| 39 |
t.Error(err) |
| 40 |
} |
| 41 |
got, err := readDecryptedStream(rc) |
| 42 |
if err != nil { |
| 43 |
t.Error(err) |
| 44 |
} |
| 45 |
|
| 46 |
want, _ := hex.DecodeString(sample.plaintext) |
| 47 |
if !bytes.Equal(got, want) { |
| 48 |
t.Errorf("Error opening:\ngot\n%s\nwant\n%s", got, want) |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
// Test if it is possible to stream an empty plaintext correctly. For |
| 54 |
// compatibility with OpenPGPjs, if the stream has no contents, it has two |
| 55 |
// authentication tags: One for the empty chunk, and the final auth. tag. This |
| 56 |
// test also checks if it cannot decrypt a corrupt stream of empty plaintext. |
| 57 |
func TestAeadEmptyStream(t *testing.T) { |
| 58 |
config := randomConfig() |
| 59 |
key := randomKey(config.Cipher().KeySize()) |
| 60 |
raw, _, err := randomStream(key, 0, config) |
| 61 |
if err != nil { |
| 62 |
t.Error(err) |
| 63 |
} |
| 64 |
// Packet is ready. |
| 65 |
corruptBytes := make([]byte, len(raw.Bytes())) |
| 66 |
copy(corruptBytes, raw.Bytes()) |
| 67 |
for bytes.Equal(corruptBytes, raw.Bytes()) { |
| 68 |
corruptBytes[mathrand.Intn(len(corruptBytes)-6)+6] = byte(mathrand.Intn(256)) |
| 69 |
} |
| 70 |
corrupt := bytes.NewBuffer(corruptBytes) |
| 71 |
|
| 72 |
// Decrypt correct stream |
| 73 |
packet := new(AEADEncrypted) |
| 74 |
ptype, _, contentsReader, err := readHeader(raw) |
| 75 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 76 |
t.Error("Error reading packet header") |
| 77 |
} |
| 78 |
if err = packet.parse(contentsReader); err != nil { |
| 79 |
t.Error(err) |
| 80 |
} |
| 81 |
// decrypted plaintext can be read from 'rc' |
| 82 |
rc, err := packet.decrypt(key) |
| 83 |
if err != nil { |
| 84 |
t.Error(err) |
| 85 |
} |
| 86 |
|
| 87 |
_, err = readDecryptedStream(rc) |
| 88 |
if err != nil { |
| 89 |
t.Error(err) |
| 90 |
} |
| 91 |
|
| 92 |
// Decrypt corrupt stream |
| 93 |
packet = new(AEADEncrypted) |
| 94 |
ptype, _, contentsReader, err = readHeader(corrupt) |
| 95 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 96 |
t.Error("Error reading packet header") |
| 97 |
} |
| 98 |
if err = packet.parse(contentsReader); err != nil { |
| 99 |
t.Error(err) |
| 100 |
} |
| 101 |
// decrypted plaintext can be read from 'rc' |
| 102 |
rc, err = packet.decrypt(key) |
| 103 |
if err != nil { |
| 104 |
t.Error(err) |
| 105 |
} |
| 106 |
|
| 107 |
_, err = readDecryptedStream(rc) |
| 108 |
if err == nil { |
| 109 |
t.Errorf("No error raised when reading corrupt stream with empty plaintext") |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
// Tests if encrypt/decrypt functions are callable and correct with a nil config |
| 114 |
func TestAeadNilConfigStream(t *testing.T) { |
| 115 |
// Sample key |
| 116 |
key := randomKey(16) |
| 117 |
randomLength := mathrand.Intn(maxPlaintextLength) + 1 |
| 118 |
raw, plain, err := randomStream(key, randomLength, nil) |
| 119 |
if err != nil { |
| 120 |
t.Error(err) |
| 121 |
} |
| 122 |
// Packet is ready in 'raw' |
| 123 |
|
| 124 |
packet := new(AEADEncrypted) |
| 125 |
|
| 126 |
ptype, _, contentsReader, err := readHeader(raw) |
| 127 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 128 |
t.Error("Error reading packet header") |
| 129 |
} |
| 130 |
|
| 131 |
if err = packet.parse(contentsReader); err != nil { |
| 132 |
t.Error(err) |
| 133 |
} |
| 134 |
// decrypted plaintext can be read from 'rc' |
| 135 |
rc, err := packet.decrypt(key) |
| 136 |
if err != nil { |
| 137 |
t.Error(err) |
| 138 |
} |
| 139 |
|
| 140 |
got, err := readDecryptedStream(rc) |
| 141 |
if err != nil { |
| 142 |
t.Error(err) |
| 143 |
} |
| 144 |
|
| 145 |
want := plain |
| 146 |
if !bytes.Equal(got, want) { |
| 147 |
t.Errorf("Error encrypting/decrypting random stream with nil config") |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
// Encrypts and decrypts a random stream, checking correctness and integrity |
| 152 |
func TestAeadStreamRandomizeSlow(t *testing.T) { |
| 153 |
config := randomConfig() |
| 154 |
key := randomKey(config.Cipher().KeySize()) |
| 155 |
randomLength := mathrand.Intn(maxPlaintextLength) + 1 |
| 156 |
raw, plain, err := randomStream(key, randomLength, config) |
| 157 |
if err != nil { |
| 158 |
t.Error(err) |
| 159 |
} |
| 160 |
// Packet is ready in 'raw' |
| 161 |
|
| 162 |
packet := new(AEADEncrypted) |
| 163 |
ptype, _, contentsReader, err := readHeader(raw) |
| 164 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 165 |
t.Error("Error reading packet header") |
| 166 |
} |
| 167 |
|
| 168 |
if err = packet.parse(contentsReader); err != nil { |
| 169 |
t.Error(err) |
| 170 |
} |
| 171 |
// decrypted plaintext can be read from 'rc' |
| 172 |
rc, err := packet.decrypt(key) |
| 173 |
if err != nil { |
| 174 |
t.Error(err) |
| 175 |
} |
| 176 |
|
| 177 |
got, err := readDecryptedStream(rc) |
| 178 |
if err != nil { |
| 179 |
t.Error(err) |
| 180 |
} |
| 181 |
// Close MUST be called - it checks if the final chunk was witnessed |
| 182 |
if err = rc.Close(); err != nil { |
| 183 |
t.Error(err) |
| 184 |
} |
| 185 |
want := plain |
| 186 |
if !bytes.Equal(got, want) { |
| 187 |
t.Errorf("Error encrypting/decrypting random stream") |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
// Encrypts a random stream, corrupt some bytes, and check if it fails |
| 192 |
func TestAeadCorruptStreamRandomizeSlow(t *testing.T) { |
| 193 |
config := randomConfig() |
| 194 |
key := randomKey(config.Cipher().KeySize()) |
| 195 |
randomLength := mathrand.Intn(maxPlaintextLength) + 1 |
| 196 |
raw, plain, err := randomStream(key, randomLength, config) |
| 197 |
if err != nil { |
| 198 |
t.Error(err) |
| 199 |
} |
| 200 |
|
| 201 |
// Corrupt some bytes of the stream |
| 202 |
for j := 0; j < 10; j++ { |
| 203 |
index := mathrand.Intn(len(raw.Bytes())) |
| 204 |
if index < 8 || len(plain) == 0 { |
| 205 |
// avoid corrupting header or nonce, that's useless |
| 206 |
continue |
| 207 |
} |
| 208 |
raw.Bytes()[index] = 255 - raw.Bytes()[index] |
| 209 |
} |
| 210 |
packet := new(AEADEncrypted) |
| 211 |
ptype, _, contentsReader, err := readHeader(raw) |
| 212 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 213 |
t.Error("Error reading packet header") |
| 214 |
} |
| 215 |
|
| 216 |
if err = packet.parse(contentsReader); err != nil { |
| 217 |
// Header was corrupted |
| 218 |
t.Error(err) |
| 219 |
return |
| 220 |
} |
| 221 |
rc, err := packet.decrypt(key) |
| 222 |
if err != nil { |
| 223 |
t.Error(err) |
| 224 |
} |
| 225 |
got, err := readDecryptedStream(rc) |
| 226 |
if err == nil || err == io.EOF { |
| 227 |
t.Errorf("No error raised when decrypting corrupt stream") |
| 228 |
} |
| 229 |
if bytes.Equal(got, plain) { |
| 230 |
t.Errorf("Error: Successfully decrypted corrupt stream") |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
// Encrypts a random stream, truncate the end, and check if it fails |
| 235 |
func TestAeadTruncatedStreamRandomizeSlow(t *testing.T) { |
| 236 |
config := randomConfig() |
| 237 |
key := randomKey(config.Cipher().KeySize()) |
| 238 |
randomLength := mathrand.Intn(maxPlaintextLength) |
| 239 |
if randomLength < 16 { |
| 240 |
return |
| 241 |
} |
| 242 |
|
| 243 |
raw, plain, err := randomStream(key, randomLength, config) |
| 244 |
if err != nil { |
| 245 |
t.Error(err) |
| 246 |
} |
| 247 |
|
| 248 |
// Truncate the packet by some bytes |
| 249 |
var truncatedRaw []byte |
| 250 |
cut := 0 |
| 251 |
for cut == 0 { |
| 252 |
cut = mathrand.Intn(randomLength / 2) |
| 253 |
} |
| 254 |
truncatedRaw = raw.Bytes()[:len(raw.Bytes())-cut] |
| 255 |
truncated := bytes.NewBuffer(truncatedRaw) |
| 256 |
|
| 257 |
packet := new(AEADEncrypted) |
| 258 |
ptype, _, truncatedContentsReader, err := readHeader(truncated) |
| 259 |
if ptype != packetTypeAEADEncrypted || err != nil { |
| 260 |
t.Error("Error reading packet header") |
| 261 |
} |
| 262 |
|
| 263 |
if err = packet.parse(truncatedContentsReader); err != nil { |
| 264 |
t.Error(err) |
| 265 |
} |
| 266 |
rc, err := packet.decrypt(key) |
| 267 |
if err != nil { |
| 268 |
return |
| 269 |
} |
| 270 |
got, err := readDecryptedStream(rc) |
| 271 |
if err == nil || err == io.EOF { |
| 272 |
t.Errorf("No truncate error raised when decrypting truncated stream") |
| 273 |
} |
| 274 |
if bytes.Equal(got, plain) { |
| 275 |
t.Errorf("Error: Successfully decrypted truncated stream") |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
// Encrypts a random stream, truncate the end, and check if it fails |
| 280 |
func TestAeadUnclosedStreamRandomizeSlow(t *testing.T) { |
| 281 |
config := randomConfig() |
| 282 |
key := randomKey(config.Cipher().KeySize()) |
| 283 |
ptLen := mathrand.Intn(maxPlaintextLength) |
| 284 |
// Sample random plaintext of given length |
| 285 |
plain := make([]byte, ptLen) |
| 286 |
_, err := rand.Read(plain) |
| 287 |
if err != nil { |
| 288 |
t.Error(err) |
| 289 |
} |
| 290 |
// 'writeCloser' encrypts and writes the plaintext bytes. |
| 291 |
rawCipher := bytes.NewBuffer(nil) |
| 292 |
writeCloser, err := SerializeAEADEncrypted(rawCipher, key, config) |
| 293 |
if err != nil { |
| 294 |
t.Error(err) |
| 295 |
} |
| 296 |
// Write the partial lengths packet into 'raw' |
| 297 |
if _, err = writeCloser.Write(plain); err != nil { |
| 298 |
t.Error(err) |
| 299 |
} |
| 300 |
// Don't call Close |
| 301 |
|
| 302 |
packet := new(AEADEncrypted) |
| 303 |
_, _, contentsReader, err := readHeader(rawCipher) |
| 304 |
if err != nil { |
| 305 |
return |
| 306 |
} |
| 307 |
|
| 308 |
if err = packet.parse(contentsReader); err != nil { |
| 309 |
return |
| 310 |
} |
| 311 |
rc, err := packet.decrypt(key) |
| 312 |
if err != nil { |
| 313 |
return |
| 314 |
} |
| 315 |
got, err := readDecryptedStream(rc) |
| 316 |
if err == nil || err == io.EOF { |
| 317 |
t.Errorf("No error raised when decrypting unclosed stream") |
| 318 |
} |
| 319 |
if bytes.Equal(got, plain) { |
| 320 |
t.Errorf("Error: Successfully decrypted unclosed stream") |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
// ----------------------------------- // |
| 325 |
// ------- UTILS --------- // |
| 326 |
// ----------------------------------- // |
| 327 |
|
| 328 |
func randomKey(length int) []byte { |
| 329 |
key := make([]byte, length) |
| 330 |
_, err := rand.Read(key) |
| 331 |
if err != nil { |
| 332 |
panic("can't read from rand") |
| 333 |
} |
| 334 |
return key |
| 335 |
} |
| 336 |
|
| 337 |
func randomConfig() *Config { |
| 338 |
var aeadCompatibleCiphers = []CipherFunction{ |
| 339 |
CipherAES128, |
| 340 |
CipherAES192, |
| 341 |
CipherAES256, |
| 342 |
} |
| 343 |
var modes = []AEADMode{ |
| 344 |
AEADModeEAX, |
| 345 |
AEADModeOCB, |
| 346 |
} |
| 347 |
|
| 348 |
// Random chunk size |
| 349 |
chunkSizeExp := 6 + mathrand.Intn(maxChunkSizeExp-5) |
| 350 |
chunkSize := uint64(1 << uint(chunkSizeExp)) |
| 351 |
// Random cipher and mode |
| 352 |
ciph := aeadCompatibleCiphers[mathrand.Intn(len(aeadCompatibleCiphers))] |
| 353 |
aeadConf := AEADConfig{ |
| 354 |
ChunkSize: uint64(chunkSize), |
| 355 |
DefaultMode: modes[mathrand.Intn(len(modes))], |
| 356 |
} |
| 357 |
config := &Config{ |
| 358 |
AEADConfig: &aeadConf, |
| 359 |
DefaultCipher: ciph, |
| 360 |
} |
| 361 |
return config |
| 362 |
} |
| 363 |
|
| 364 |
// Samples a random plaintext and gives the raw AEADEncrypted packet contents. |
| 365 |
// Returns said contents, the plaintext, and an error. |
| 366 |
func randomStream(key []byte, ptLen int, config *Config) (*bytes.Buffer, []byte, error) { |
| 367 |
// Sample random plaintext of given length |
| 368 |
plaintext := make([]byte, ptLen) |
| 369 |
_, err := rand.Read(plaintext) |
| 370 |
if err != nil { |
| 371 |
return nil, nil, err |
| 372 |
} |
| 373 |
|
| 374 |
// 'writeCloser' encrypts and writes the plaintext bytes. |
| 375 |
rawCipher := bytes.NewBuffer(nil) |
| 376 |
writeCloser, err := SerializeAEADEncrypted(rawCipher, key, config) |
| 377 |
if err != nil { |
| 378 |
return nil, nil, err |
| 379 |
} |
| 380 |
// Write the partial lengths packet into 'raw' |
| 381 |
_, err = writeCloser.Write(plaintext) |
| 382 |
if err != nil { |
| 383 |
return nil, nil, err |
| 384 |
} |
| 385 |
// Close MUST be called - it appends the final auth. tag |
| 386 |
if err = writeCloser.Close(); err != nil { |
| 387 |
return nil, nil, err |
| 388 |
} |
| 389 |
// Packet is ready. |
| 390 |
return rawCipher, plaintext, nil |
| 391 |
} |
| 392 |
|
| 393 |
func readDecryptedStream(rc io.ReadCloser) (got []byte, err error) { |
| 394 |
for { |
| 395 |
// Read a random number of bytes, until the end of the packet. |
| 396 |
decrypted := make([]byte, mathrand.Intn(200)) |
| 397 |
n, err := rc.Read(decrypted) |
| 398 |
decrypted = decrypted[:n] |
| 399 |
got = append(got, decrypted...) |
| 400 |
if err != nil { |
| 401 |
if err == io.EOF { |
| 402 |
// Finished reading |
| 403 |
break |
| 404 |
} else { |
| 405 |
// Something happened |
| 406 |
return nil, err |
| 407 |
} |
| 408 |
} |
| 409 |
} |
| 410 |
err = rc.Close() |
| 411 |
return got, err |
| 412 |
} |
| 413 |
|
| 414 |
// SerializeAEADEncrypted initializes the aeadCrypter and returns a writer. |
| 415 |
// This writer encrypts and writes bytes (see aeadEncrypter.Write()). |
| 416 |
// This funcion is moved to the test suite to prevent it from creating this deprecated package |
| 417 |
func SerializeAEADEncrypted(w io.Writer, key []byte, config *Config) (io.WriteCloser, error) { |
| 418 |
writeCloser := noOpCloser{w} |
| 419 |
writer, err := serializeStreamHeader(writeCloser, packetTypeAEADEncrypted) |
| 420 |
if err != nil { |
| 421 |
return nil, err |
| 422 |
} |
| 423 |
|
| 424 |
// Data for en/decryption: tag, version, cipher, aead mode, chunk size |
| 425 |
aeadConf := config.AEAD() |
| 426 |
prefix := []byte{ |
| 427 |
0xD4, |
| 428 |
aeadEncryptedVersion, |
| 429 |
byte(config.Cipher()), |
| 430 |
byte(aeadConf.Mode()), |
| 431 |
aeadConf.ChunkSizeByte(), |
| 432 |
} |
| 433 |
n, err := writer.Write(prefix[1:]) |
| 434 |
if err != nil || n < 4 { |
| 435 |
return nil, errors.AEADError("could not write AEAD headers") |
| 436 |
} |
| 437 |
// Sample nonce |
| 438 |
nonceLen := aeadConf.Mode().IvLength() |
| 439 |
nonce := make([]byte, nonceLen) |
| 440 |
_, err = rand.Read(nonce) |
| 441 |
if err != nil { |
| 442 |
panic("Could not sample random nonce") |
| 443 |
} |
| 444 |
_, err = writer.Write(nonce) |
| 445 |
if err != nil { |
| 446 |
return nil, err |
| 447 |
} |
| 448 |
blockCipher := CipherFunction(config.Cipher()).new(key) |
| 449 |
alg, err := aeadConf.Mode().new(blockCipher) |
| 450 |
if err != nil { |
| 451 |
return nil, err |
| 452 |
} |
| 453 |
|
| 454 |
chunkSize := decodeAEADChunkSize(aeadConf.ChunkSizeByte()) |
| 455 |
tagLen := alg.Overhead() |
| 456 |
chunkBytes := make([]byte, chunkSize+tagLen) |
| 457 |
return &aeadEncrypter{ |
| 458 |
aeadCrypter: aeadCrypter{ |
| 459 |
aead: alg, |
| 460 |
chunkSize: chunkSize, |
| 461 |
associatedData: prefix, |
| 462 |
chunkIndex: make([]byte, 8), |
| 463 |
nonce: nonce, |
| 464 |
packetTag: packetTypeAEADEncrypted, |
| 465 |
}, |
| 466 |
writer: writer, |
| 467 |
chunkBytes: chunkBytes, |
| 468 |
}, nil |
| 469 |
} |
| 470 |
|
| 471 |
// aeadEncryptedPacket builds a minimal AEAD Encrypted Data packet with an |
| 472 |
// all-zero OCB nonce and ciphertext. |
| 473 |
func aeadEncryptedPacket(cipher CipherFunction, chunkSizeByte byte) []byte { |
| 474 |
body := []byte{aeadEncryptedVersion, byte(cipher), byte(AEADModeOCB), chunkSizeByte} |
| 475 |
body = append(body, make([]byte, AEADModeOCB.IvLength()+64)...) |
| 476 |
return append([]byte{0xd4, byte(len(body))}, body...) |
| 477 |
} |