| 1 |
// Copyright (C) 2019 ProtonTech AG |
| 2 |
|
| 3 |
package v2 |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"crypto" |
| 8 |
"encoding/json" |
| 9 |
"io" |
| 10 |
"os" |
| 11 |
"strings" |
| 12 |
"testing" |
| 13 |
"time" |
| 14 |
|
| 15 |
"github.com/ProtonMail/go-crypto/openpgp/armor" |
| 16 |
"github.com/ProtonMail/go-crypto/openpgp/packet" |
| 17 |
openpgp "github.com/ProtonMail/go-crypto/openpgp/v2" |
| 18 |
) |
| 19 |
|
| 20 |
///////////////////////////////////////////////////////////////////////////// |
| 21 |
// TODO: |
| 22 |
// |
| 23 |
// - Move signature line endings test to packet unit tests. |
| 24 |
// |
| 25 |
///////////////////////////////////////////////////////////////////////////// |
| 26 |
|
| 27 |
type testVector struct { |
| 28 |
Message string |
| 29 |
Name string |
| 30 |
PrivateKey string |
| 31 |
PublicKey string |
| 32 |
Password string |
| 33 |
EncryptedSignedMessage string |
| 34 |
config *packet.Config |
| 35 |
} |
| 36 |
|
| 37 |
var allowAllAlgorithmsConfig = packet.Config{ |
| 38 |
RejectMessageHashAlgorithms: map[crypto.Hash]bool{}, |
| 39 |
RejectPublicKeyAlgorithms: map[packet.PublicKeyAlgorithm]bool{}, |
| 40 |
RejectCurves: map[packet.Curve]bool{}, |
| 41 |
MinRSABits: 512, |
| 42 |
} |
| 43 |
|
| 44 |
// Takes a set of different keys (some external, some generated here) and test |
| 45 |
// interactions between them: encrypt, sign, decrypt, verify random messages. |
| 46 |
func TestEndToEnd(t *testing.T) { |
| 47 |
// Fetch foreign test vectors from JSON file |
| 48 |
file, err := os.Open("testdata/test_vectors.json") |
| 49 |
if err != nil { |
| 50 |
panic(err) |
| 51 |
} |
| 52 |
raw, err := io.ReadAll(file) |
| 53 |
if err != nil { |
| 54 |
panic(err) |
| 55 |
} |
| 56 |
var foreignTestVectors []testVector |
| 57 |
err = json.Unmarshal(raw, &foreignTestVectors) |
| 58 |
if err != nil { |
| 59 |
panic(err) |
| 60 |
} |
| 61 |
|
| 62 |
for i := 0; i < len(foreignTestVectors); i++ { |
| 63 |
foreignTestVectors[i].Name += "_foreign" |
| 64 |
config := allowAllAlgorithmsConfig |
| 65 |
foreignTestVectors[i].config = &config |
| 66 |
} |
| 67 |
|
| 68 |
// Generate random test vectors |
| 69 |
freshTestVectors, err := generateFreshTestVectors(20) |
| 70 |
if err != nil { |
| 71 |
t.Fatal("Cannot proceed without generated keys: " + err.Error()) |
| 72 |
} |
| 73 |
testVectors := append(foreignTestVectors, freshTestVectors...) |
| 74 |
|
| 75 |
// For each testVector in testVectors, (1) Decrypt an already existing message, |
| 76 |
// (2) Sign and verify random messages, and (3) Encrypt random messages for |
| 77 |
// each of the other keys and then decrypt on the other end. |
| 78 |
for _, from := range testVectors { |
| 79 |
skFrom := readArmoredSk(t, from.PrivateKey, from.Password) |
| 80 |
pkFrom := readArmoredPk(t, from.PublicKey) |
| 81 |
t.Run(from.Name, func(t *testing.T) { |
| 82 |
|
| 83 |
// 1. Decrypt the existing message of the given test vector |
| 84 |
t.Run("DecryptPreparedMessage", |
| 85 |
func(t *testing.T) { |
| 86 |
decryptionTest(t, from, skFrom) |
| 87 |
}) |
| 88 |
// 2. Sign a message and verify the signature. |
| 89 |
t.Run("signVerify", func(t *testing.T) { |
| 90 |
t.Run("binary", func(t *testing.T) { |
| 91 |
signVerifyTest(t, from, skFrom, pkFrom, true) |
| 92 |
}) |
| 93 |
t.Run("text", func(t *testing.T) { |
| 94 |
signVerifyTest(t, from, skFrom, pkFrom, false) |
| 95 |
}) |
| 96 |
}) |
| 97 |
// 3. Encrypt, decrypt and verify a random message for |
| 98 |
// every other key. |
| 99 |
t.Run("encryptDecrypt", |
| 100 |
func(t *testing.T) { |
| 101 |
encDecTest(t, from, testVectors) |
| 102 |
}) |
| 103 |
}) |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
// This subtest decrypts the existing encrypted and signed message of each |
| 108 |
// testVector. |
| 109 |
func decryptionTest(t *testing.T, vector testVector, sk openpgp.EntityList) { |
| 110 |
if vector.EncryptedSignedMessage == "" { |
| 111 |
return |
| 112 |
} |
| 113 |
prompt := func(keys []openpgp.Key, symmetric bool) ([]byte, error) { |
| 114 |
err := keys[0].PrivateKey.Decrypt([]byte(vector.Password)) |
| 115 |
if err != nil { |
| 116 |
t.Errorf("prompt: error decrypting key: %s", err) |
| 117 |
return nil, err |
| 118 |
} |
| 119 |
return nil, nil |
| 120 |
} |
| 121 |
sig, err := armor.Decode(strings.NewReader(vector.EncryptedSignedMessage)) |
| 122 |
if err != nil { |
| 123 |
t.Fatal(err) |
| 124 |
} |
| 125 |
md, err := openpgp.ReadMessage(sig.Body, sk, prompt, vector.config) |
| 126 |
if err != nil { |
| 127 |
t.Fatal(err) |
| 128 |
} |
| 129 |
|
| 130 |
body, err := io.ReadAll(md.UnverifiedBody) |
| 131 |
if err != nil { |
| 132 |
t.Fatal(err) |
| 133 |
} |
| 134 |
if !md.IsVerified { |
| 135 |
t.Errorf("not verified despite all data read") |
| 136 |
} |
| 137 |
|
| 138 |
stringBody := string(body) |
| 139 |
if stringBody != vector.Message { |
| 140 |
t.Fatal("Decrypted body did not match expected body") |
| 141 |
} |
| 142 |
|
| 143 |
// We'll see a sig error here after reading in the UnverifiedBody above, |
| 144 |
// if there was one to see. |
| 145 |
if err = md.SignatureError; err != nil { |
| 146 |
t.Fatal(err) |
| 147 |
} |
| 148 |
|
| 149 |
if md.Signature == nil { |
| 150 |
t.Fatal("Expected a signature to be valid") |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
// Given a testVector, encrypts random messages for all given testVectors |
| 155 |
// (including self) and verifies on the other end. |
| 156 |
func encDecTest(t *testing.T, from testVector, testVectors []testVector) { |
| 157 |
skFrom := readArmoredSk(t, from.PrivateKey, from.Password) |
| 158 |
// Decrypt private key if necessary |
| 159 |
for _, entity := range skFrom { |
| 160 |
if err := entity.DecryptPrivateKeys([]byte(from.Password)); err != nil { |
| 161 |
t.Error(err) |
| 162 |
} |
| 163 |
} |
| 164 |
pkFrom := readArmoredPk(t, from.PublicKey) |
| 165 |
for _, to := range testVectors { |
| 166 |
t.Run(to.Name, func(t *testing.T) { |
| 167 |
pkTo := readArmoredPk(t, to.PublicKey) |
| 168 |
skTo := readArmoredSk(t, to.PrivateKey, to.Password) |
| 169 |
message := randMessage() |
| 170 |
hints := randFileHints() |
| 171 |
|
| 172 |
// Encrypt message |
| 173 |
signer := skFrom[0] |
| 174 |
errDec := signer.PrivateKey.Decrypt([]byte(from.Password)) |
| 175 |
if errDec != nil { |
| 176 |
t.Error(errDec) |
| 177 |
} |
| 178 |
buf := new(bytes.Buffer) |
| 179 |
w, err := openpgp.Encrypt(buf, pkTo[:1], nil, []*openpgp.Entity{signer}, hints, from.config) |
| 180 |
if err != nil { |
| 181 |
t.Fatalf("Error in Encrypt: %s", err) |
| 182 |
} |
| 183 |
_, err = w.Write([]byte(message)) |
| 184 |
if err != nil { |
| 185 |
t.Fatalf("Error writing plaintext: %s", err) |
| 186 |
} |
| 187 |
err = w.Close() |
| 188 |
if err != nil { |
| 189 |
t.Fatalf("Error closing WriteCloser: %s", err) |
| 190 |
} |
| 191 |
|
| 192 |
// ----------------- |
| 193 |
// On the other end: |
| 194 |
// ----------------- |
| 195 |
|
| 196 |
// Decrypt recipient key |
| 197 |
prompt := func(keys []openpgp.Key, symm bool) ([]byte, error) { |
| 198 |
err := keys[0].PrivateKey.Decrypt([]byte(to.Password)) |
| 199 |
if err != nil { |
| 200 |
t.Errorf("Prompt: error decrypting key: %s", err) |
| 201 |
return nil, err |
| 202 |
} |
| 203 |
return nil, nil |
| 204 |
} |
| 205 |
|
| 206 |
// Read message with recipient key |
| 207 |
keyring := append(skTo, pkFrom[:]...) |
| 208 |
md, err := openpgp.ReadMessage(buf, keyring, prompt, to.config) |
| 209 |
if err != nil { |
| 210 |
t.Fatalf("Error reading message: %s", err) |
| 211 |
} |
| 212 |
|
| 213 |
// Test message details |
| 214 |
if !md.IsEncrypted { |
| 215 |
t.Fatal("The message should be encrypted") |
| 216 |
} |
| 217 |
signKey, _ := signer.SigningKey(time.Now(), &allowAllAlgorithmsConfig) |
| 218 |
expectedKeyID := signKey.PublicKey.KeyId |
| 219 |
expectedFingerprint := signKey.PublicKey.Fingerprint |
| 220 |
if len(md.SignatureCandidates) != 1 { |
| 221 |
t.Fatal("No signature candidate found") |
| 222 |
} |
| 223 |
if signKey.PublicKey.Version != 6 && md.SignatureCandidates[0].IssuerKeyId != expectedKeyID { |
| 224 |
t.Fatalf( |
| 225 |
"Message signed by wrong key id, got: %v, want: %v", |
| 226 |
*md.SignatureCandidates[0].SignedBy, expectedKeyID) |
| 227 |
} |
| 228 |
if signKey.PublicKey.Version == 6 && !bytes.Equal(md.SignatureCandidates[0].IssuerFingerprint, expectedFingerprint) { |
| 229 |
t.Fatalf( |
| 230 |
"Message signed by wrong key id, got: %x, want: %x", |
| 231 |
md.SignatureCandidates[0].IssuerFingerprint, expectedFingerprint) |
| 232 |
} |
| 233 |
if md.SignatureCandidates[0] == nil { |
| 234 |
t.Fatalf("Failed to find the signing Entity") |
| 235 |
} |
| 236 |
|
| 237 |
plaintext, err := io.ReadAll(md.UnverifiedBody) |
| 238 |
if err != nil { |
| 239 |
t.Fatalf("Error reading encrypted contents: %s", err) |
| 240 |
} |
| 241 |
if !md.IsVerified { |
| 242 |
t.Errorf("not verified despite all data read") |
| 243 |
} |
| 244 |
encryptKey, _ := pkTo[0].EncryptionKey(time.Now(), &allowAllAlgorithmsConfig) |
| 245 |
expectedEncKeyID := encryptKey.PublicKey.KeyId |
| 246 |
if len(md.EncryptedToKeyIds) != 1 || |
| 247 |
md.EncryptedToKeyIds[0] != expectedEncKeyID { |
| 248 |
t.Errorf("Expected message to be encrypted to %v, but got %#v", |
| 249 |
expectedKeyID, md.EncryptedToKeyIds) |
| 250 |
} |
| 251 |
// Test decrypted message |
| 252 |
if string(plaintext) != message { |
| 253 |
t.Error("decrypted and expected message do not match") |
| 254 |
} |
| 255 |
|
| 256 |
if md.SignatureError != nil { |
| 257 |
t.Fatalf("Signature error: %s", md.SignatureError) |
| 258 |
} |
| 259 |
if md.Signature == nil { |
| 260 |
t.Error("Expected valid signature") |
| 261 |
} |
| 262 |
}) |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
// Sign a random message and verify signature against the original message, |
| 267 |
// another message with same body but different line endings, and a corrupt |
| 268 |
// message. |
| 269 |
func signVerifyTest( |
| 270 |
t *testing.T, |
| 271 |
from testVector, |
| 272 |
skFrom, pkFrom openpgp.EntityList, |
| 273 |
binary bool, |
| 274 |
) { |
| 275 |
if err := skFrom[0].PrivateKey.Decrypt([]byte(from.Password)); err != nil { |
| 276 |
t.Error(err) |
| 277 |
} |
| 278 |
|
| 279 |
messageBody := randMessage() |
| 280 |
|
| 281 |
// ================================================ |
| 282 |
// TODO: Move the line ending checks to unit tests |
| 283 |
// ================================================ |
| 284 |
// Add line endings to test whether the non-binary version of this |
| 285 |
// signature normalizes the final line endings, see RFC4880bis, sec 5.2.1. |
| 286 |
lineEnding := " \r\n \n \r\n" |
| 287 |
otherLineEnding := " \n \r\n \n" |
| 288 |
message := bytes.NewReader([]byte(messageBody + lineEnding)) |
| 289 |
otherMessage := bytes.NewReader([]byte(messageBody + otherLineEnding)) |
| 290 |
|
| 291 |
corruptMessage := bytes.NewReader([]byte(corrupt(messageBody) + lineEnding)) |
| 292 |
|
| 293 |
// Sign the message |
| 294 |
buf := new(bytes.Buffer) |
| 295 |
errSign := openpgp.ArmoredDetachSign(buf, skFrom[:1], message, &openpgp.SignParams{ |
| 296 |
TextSig: !binary, |
| 297 |
Config: &allowAllAlgorithmsConfig, |
| 298 |
}) |
| 299 |
if errSign != nil { |
| 300 |
t.Error(errSign) |
| 301 |
} |
| 302 |
|
| 303 |
// Verify the signature against the corrupt message first |
| 304 |
signatureReader := bytes.NewReader(buf.Bytes()) |
| 305 |
_, wrongsigner, err := openpgp.VerifyArmoredDetachedSignature( |
| 306 |
pkFrom, corruptMessage, signatureReader, &allowAllAlgorithmsConfig) |
| 307 |
if err == nil || wrongsigner != nil { |
| 308 |
t.Fatal("Expected the signature to not verify") |
| 309 |
} |
| 310 |
|
| 311 |
// Reset the reader and verify against the message with different line |
| 312 |
// endings (should pass in the non-binary case) |
| 313 |
var errSeek error |
| 314 |
_, errSeek = signatureReader.Seek(0, io.SeekStart) |
| 315 |
if errSeek != nil { |
| 316 |
t.Error(errSeek) |
| 317 |
} |
| 318 |
|
| 319 |
_, otherSigner, err := openpgp.VerifyArmoredDetachedSignature( |
| 320 |
pkFrom, otherMessage, signatureReader, &allowAllAlgorithmsConfig) |
| 321 |
if binary { |
| 322 |
if err == nil || otherSigner != nil { |
| 323 |
t.Fatal("Expected the signature to not verify") |
| 324 |
return |
| 325 |
} |
| 326 |
} else { |
| 327 |
if err != nil { |
| 328 |
t.Fatalf("signature error: %s", err) |
| 329 |
} |
| 330 |
if otherSigner == nil { |
| 331 |
t.Fatalf("signer is nil") |
| 332 |
} |
| 333 |
if otherSigner.PrimaryKey.KeyId != skFrom[0].PrimaryKey.KeyId { |
| 334 |
t.Errorf( |
| 335 |
"wrong signer: got %x, expected %x", otherSigner.PrimaryKey.KeyId, 0) |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
// Reset the readers and verify against the exact first message. |
| 340 |
_, errSeek = message.Seek(0, io.SeekStart) |
| 341 |
if errSeek != nil { |
| 342 |
t.Error(errSeek) |
| 343 |
} |
| 344 |
_, errSeek = signatureReader.Seek(0, io.SeekStart) |
| 345 |
if errSeek != nil { |
| 346 |
t.Error(errSeek) |
| 347 |
} |
| 348 |
|
| 349 |
_, otherSigner, err = openpgp.VerifyArmoredDetachedSignature( |
| 350 |
pkFrom, message, signatureReader, &allowAllAlgorithmsConfig) |
| 351 |
|
| 352 |
if err != nil { |
| 353 |
t.Fatalf("signature error: %s", err) |
| 354 |
} |
| 355 |
if otherSigner == nil { |
| 356 |
t.Fatalf("signer is nil") |
| 357 |
} |
| 358 |
if otherSigner.PrimaryKey.KeyId != skFrom[0].PrimaryKey.KeyId { |
| 359 |
t.Errorf( |
| 360 |
"wrong signer: got %x, expected %x", |
| 361 |
skFrom[0].PrimaryKey.KeyId, |
| 362 |
skFrom[0].PrimaryKey.KeyId, |
| 363 |
) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
func readArmoredPk(t *testing.T, publicKey string) openpgp.EntityList { |
| 368 |
keys, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(publicKey)) |
| 369 |
if err != nil { |
| 370 |
t.Fatal(err) |
| 371 |
} |
| 372 |
if len(keys) < 1 { |
| 373 |
t.Errorf("Failed to read key with good cross signature, %d", len(keys)) |
| 374 |
} |
| 375 |
if len(keys[0].Subkeys) < 1 { |
| 376 |
t.Errorf("Failed to read good subkey, %d", len(keys[0].Subkeys)) |
| 377 |
} |
| 378 |
return keys |
| 379 |
} |
| 380 |
|
| 381 |
func readArmoredSk(t *testing.T, sk string, pass string) openpgp.EntityList { |
| 382 |
keys, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(sk)) |
| 383 |
if err != nil { |
| 384 |
t.Fatal(err) |
| 385 |
} |
| 386 |
if len(keys) != 1 { |
| 387 |
t.Errorf("Failed to read key with good cross signature, %d", len(keys)) |
| 388 |
} |
| 389 |
if len(keys[0].Subkeys) < 1 { |
| 390 |
t.Errorf("Failed to read good subkey, %d", len(keys[0].Subkeys)) |
| 391 |
} |
| 392 |
keyObject := keys[0].PrivateKey |
| 393 |
if pass != "" { |
| 394 |
corruptPassword := corrupt(pass) |
| 395 |
if err := keyObject.Decrypt([]byte(corruptPassword)); err == nil { |
| 396 |
t.Fatal("Decrypted key with invalid password") |
| 397 |
} |
| 398 |
} |
| 399 |
return keys |
| 400 |
} |