1 /* t-stutter.c - Test the stutter exploit.
2 * Copyright (C) 2016 g10 Code GmbH
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20 /* This test is based on the paper: "An Attack on CFB Mode Encryption
21 * as Used by OpenPGP." This attack uses a padding oracle to decrypt
22 * the first two bytes of each block (which are normally 16 bytes
23 * large). Concretely, if an attacker can use this attack if it can
24 * sense whether the quick integrity check failed. See RFC 4880,
25 * Section 5.7 for an explanation of this quick check.
27 * The concrete attack, as described in the paper, only works for
28 * PKT_ENCRYPTED packets; it does not work for PKT_ENCRYPTED_MDC
29 * packets, which use a slightly different CFB mode (they don't
30 * include a sync after the IV). But, small modifications should
31 * allow the attack to work for PKT_ENCRYPTED_MDC packets.
33 * The cost of this attack is 2^15 + i * 2^15 oracle queries, where i
34 * is the number of blocks the attack wants to decrypt. This attack
35 * is completely unfeasible when gpg is used interactively, but it
36 * could work when used as a service.
38 * How to generate a test message:
40 * $ echo 0123456789abcdefghijklmnopqrstuvwxyz | \
41 * gpg --disable-mdc -z 0 -c > msg.asc
42 * $ gpg --list-packets msg.asc
43 * # Make sure the encryption packet contains a literal packet (without
46 * $ gpg --show-session-key -d msg.asc
47 * $ ./t-stutter --debug SESSION_KEY 000002-009.encrypted
56 #include "../common/types.h"
59 #include "../common/logging.h"
62 log_hexdump (byte *buffer, int length)
66 fprintf (stderr, "%d bytes:\n", length);
69 int have = length > 16 ? 16 : length;
71 char formatted[2 * have + 1];
74 fprintf (stderr, "%-8d ", written);
75 bin2hex (buffer, have, formatted);
76 for (i = 0; i < 16; i ++)
84 fwrite (&formatted[2 * i], 2, 1, stderr);
86 fwrite (" ", 2, 1, stderr);
89 for (i = 0; i < have; i ++)
90 if (isprint (buffer[i]))
96 fprintf (stderr, " ");
97 if (strlen (text) > 8)
99 fwrite (text, 8, 1, stderr);
101 fwrite (&text[8], strlen (text) - 8, 1, stderr);
104 fwrite (text, strlen (text), 1, stderr);
105 fputc ('\n', stderr);
116 hexstr (const byte *bytes)
119 static char bufs[100][7];
125 sprintf (bufs[i], "0x%02X%02X", bytes[0], bytes[1]);
129 /* xor the two bytes starting at A with the two bytes starting at B
130 and return the result. */
132 bufxor2 (const byte *a, const byte *b)
135 static char bufs[100][2];
141 bufs[i][0] = a[0] ^ b[0];
142 bufs[i][1] = a[1] ^ b[1];
146 /* The session key stays constant. */
150 /* Decode the session key, which is in the format output by gpg
151 --show-session-key. */
153 parse_session_key (char *session_key)
156 char *p = session_key;
159 dek.algo = strtol (p, &tail, 10);
160 if (errno || (tail && *tail != ':'))
161 log_fatal ("Invalid session key specification. "
162 "Expected: cipher-id:HEXADECIMAL-CHRACTERS\n");
167 if (strlen (p) % 2 != 0)
168 log_fatal ("Session key must consist of an even number of hexadecimal characters.\n");
170 dek.keylen = strlen (p) / 2;
171 log_assert (dek.keylen <= sizeof (dek.key));
173 if (hex2bin (p, dek.key, dek.keylen) == -1)
174 log_fatal ("Session key must only contain hexadecimal characters\n");
176 blocksize = openpgp_cipher_get_algo_blklen (dek.algo);
177 if ( !blocksize || blocksize > 16 )
178 log_fatal ("unsupported blocksize %u\n", blocksize );
183 /* The ciphertext, the plaintext as decrypted by the good session key,
184 and the cfb stream (derived from the ciphertext and the
188 static byte *msg_plaintext;
189 static byte *msg_cfb;
191 /* Whether we need to resynchronize the CFB after writing the random
192 data (this is the case for encrypted packets, but not encrypted and
193 integrity protected packets). */
202 /* Make sure blocksize has been initialized. */
203 log_assert (blocksize);
208 extra = blocksize + 2;
210 return (i - 1) * blocksize + extra;
213 /* Return the ith block from TEXT. The first block is labeled 1.
214 Note: consistent with the OpenPGP message format, the second block
215 (i=2) is just 2 bytes. */
217 block (byte *text, int len, int i)
219 int offset = block_offset (i);
221 log_assert (offset < len);
222 return &text[offset];
225 /* Return true if the quick integrity check passes. Also, if
226 PLAINTEXTP is not NULL, return the decrypted plaintext in
227 *PLAINTEXTP. If CFBP is not NULL, return the CFB byte stream in
230 oracle (int debug, byte *ciphertext, int len, byte **plaintextp, byte **cfbp)
234 gcry_cipher_hd_t cipher_hd = NULL;
235 byte *plaintext = NULL;
238 /* Make sure DEK was initialized. */
239 log_assert (dek.algo);
240 log_assert (dek.keylen);
241 log_assert (blocksize);
244 if (len < nprefix + 2)
246 /* An invalid message. We can't check that during parsing
247 because we may not know the used cipher then. */
248 rc = gpg_error (GPG_ERR_INV_PACKET);
252 rc = openpgp_cipher_open (&cipher_hd, dek.algo,
253 GCRY_CIPHER_MODE_CFB,
254 (! sync /* ed->mdc_method || dek.algo >= 100 */ ?
255 0 : GCRY_CIPHER_ENABLE_SYNC));
257 log_fatal ("Failed to open cipher: %s\n", gpg_strerror (rc));
259 rc = gcry_cipher_setkey (cipher_hd, dek.key, dek.keylen);
260 if (gpg_err_code (rc) == GPG_ERR_WEAK_KEY)
262 log_info ("WARNING: message was encrypted with"
263 " a weak key in the symmetric cipher.\n");
267 log_fatal ("key setup failed: %s\n", gpg_strerror (rc));
269 gcry_cipher_setiv (cipher_hd, NULL, 0);
273 log_debug ("Encrypted data:\n");
274 log_hexdump(ciphertext, len);
276 plaintext = xmalloc_clear (len);
277 gcry_cipher_decrypt (cipher_hd, plaintext, blocksize + 2,
278 ciphertext, blocksize + 2);
279 gcry_cipher_sync (cipher_hd);
280 if (len > blocksize+2)
281 gcry_cipher_decrypt (cipher_hd,
282 &plaintext[blocksize+2], len-(blocksize+2),
283 &ciphertext[blocksize+2], len-(blocksize+2));
287 log_debug ("Decrypted data:\n");
288 log_hexdump (plaintext, len);
289 log_debug ("R_{b-1,b} = %s\n", hexstr (&plaintext[blocksize - 2]));
290 log_debug ("R_{b+1,b+2} = %s\n", hexstr (&plaintext[blocksize]));
297 for (i = 0; i < len; i ++)
298 cfb[i] = plaintext[i] ^ ciphertext[i];
300 log_assert (len >= blocksize + 2);
304 log_debug ("cfb:\n");
305 log_hexdump (cfb, len);
307 log_debug ("E_k([C_1]_{1,2}) = C_2 xor R (%s xor %s) = %s\n",
308 hexstr (&ciphertext[blocksize]),
309 hexstr (&plaintext[blocksize]),
310 hexstr (bufxor2 (&ciphertext[blocksize],
311 &plaintext[blocksize])));
312 if (len >= blocksize + 4)
313 log_debug ("D = Ek([C1]_{3-b} || C_2)_{1-2} (%s) xor C2 (%s) xor E_k(0)_{b-1,b} (%s) = %s\n",
314 hexstr (&cfb[blocksize + 2]),
315 hexstr (&ciphertext[blocksize]),
316 hexstr (&cfb[blocksize - 2]),
317 hexstr (bufxor2 (bufxor2 (&cfb[blocksize + 2],
318 &ciphertext[blocksize]),
319 &cfb[blocksize - 2])));
323 if (plaintext[nprefix-2] != plaintext[nprefix]
324 || plaintext[nprefix-1] != plaintext[nprefix+1])
326 rc = gpg_error (GPG_ERR_BAD_KEY);
331 if (! rc && plaintextp)
332 *plaintextp = plaintext;
342 gcry_cipher_close (cipher_hd);
346 /* Query the oracle with D=D for block B. */
348 oracle_test (unsigned int d, int b, int debug)
350 byte probe[blocksize + 2];
352 log_assert (d < 256 * 256);
355 memcpy (probe, &msg[2], blocksize);
357 memcpy (probe, block (msg, msg_len, b), blocksize);
359 probe[blocksize] = d >> 8;
360 probe[blocksize + 1] = d & 0xff;
363 log_debug ("oracle (0x%04X):\n", d);
365 return oracle (debug, probe, blocksize + 2, NULL, NULL) == 0;
369 main (int argc, char *argv[])
373 char *filename = NULL;
381 for (i = 1; i < argc; i ++)
383 if (strcmp (argv[i], "--debug") == 0)
385 else if (! blocksize)
386 parse_session_key (argv[i]);
396 if (! blocksize && ! filename && (filename = getenv ("srcdir")))
399 parse_session_key ("9:9274A8EC128E850C6DDDF9EAC68BFA84FC7BC05F340DA41D78C93D0640C7C503");
400 filename = xasprintf ("%s/t-stutter-data.asc", filename);
403 if (help || ! blocksize || ! filename)
404 log_fatal ("Usage: %s [--debug] SESSION_KEY ENCRYPTED_PKT\n", argv[0]);
406 /* Don't read more than a KB. */
408 raw_data = xmalloc (raw_data_len);
414 fp = fopen (filename, "r");
416 log_fatal ("Opening %s: %s\n", filename, strerror (errno));
417 r = fread (raw_data, 1, raw_data_len, fp);
420 /* We need at least the random data, the encrypted and literal
421 packets' headers and some body. */
422 if (r < (blocksize + 2 /* Random data. */
423 + 2 * blocksize /* Header + some plaintext. */))
424 log_fatal ("Not enough data (need at least %d bytes of plain text): %s.\n",
425 blocksize + 2, strerror (errno));
430 log_debug ("First few bytes of the raw data:\n");
431 log_hexdump (raw_data, raw_data_len > 8 ? 8 : raw_data_len);
435 /* Parse the packet's header. */
437 int ctb = raw_data[0];
438 int new_format = ctb & (1 << 7);
439 int pkttype = (ctb & ((1 << 5) - 1)) >> (new_format ? 0 : 2);
445 log_debug ("len encoded: 0x%x (%d)\n", raw_data[1], raw_data[1]);
446 if (raw_data[1] < 192)
448 else if (raw_data[1] < 224)
450 else if (raw_data[1] == 255)
457 int lentype = ctb & 0x3;
460 else if (lentype == 1)
462 else if (lentype == 2)
470 log_debug ("ctb = %x; %s format, hdrlen: %d, packet: %s\n",
471 ctb, new_format ? "new" : "old",
473 pkttype_str (pkttype));
475 if (! (pkttype == PKT_ENCRYPTED || pkttype == PKT_ENCRYPTED_MDC))
476 log_fatal ("%s does not contain an encrypted packet, but a %s.\n",
477 filename, pkttype_str (pkttype));
479 if (pkttype == PKT_ENCRYPTED_MDC)
481 /* The first byte following the header is the version, which
483 log_assert (raw_data[hdrlen] == 1);
490 msg = &raw_data[hdrlen];
491 msg_len = raw_data_len - hdrlen;
494 log_assert (msg_len >= blocksize + 2);
497 /* This can at least partially be guessed. So we just assume that
504 if (oracle (debug, msg, msg_len, &msg_plaintext, &msg_cfb) == 0)
507 log_debug ("Session key appears to be good.\n");
510 log_fatal ("Session key is bad!\n");
512 m1 = &msg_plaintext[blocksize + 2];
514 log_debug ("First two bytes of plaintext are: %02X (%c) %02X (%c)\n",
515 m1[0], isprint (m1[0]) ? m1[0] : '?',
516 m1[1], isprint (m1[1]) ? m1[1] : '?');
518 for (d = 0; d < 256 * 256; d ++)
519 if ((found = oracle_test (d, 1, 0)))
523 log_fatal ("Failed to find d!\n");
526 oracle_test (d, 1, 1);
529 log_debug ("D = %d (%x) looks good.\n", d, d);
532 byte *c2 = block (msg, msg_len, 2);
533 byte D[2] = { d >> 8, d & 0xFF };
534 byte *c3 = block (msg, msg_len, 3);
537 bufxor2 (bufxor2 (c2, D),
543 log_debug ("C2 = %s\n", hexstr (c2));
544 log_debug ("D = %s\n", hexstr (D));
545 log_debug ("C3 = %s\n", hexstr (c3));
546 log_debug ("M = %s\n", hexstr (m1));
547 log_debug ("E_k([C1]_{3-b} || C_2) = C3 xor M1 = %s\n",
548 hexstr (bufxor2 (c3, m1)));
549 log_debug ("E_k(0)_{b-1,b} = %s\n", hexstr (e_k_zero));
553 /* Figure out the first 2 bytes of M2... (offset 16 & 17 of the
554 plain text assuming the blocksize == 16 or bytes 34 & 35 of the
555 decrypted cipher text, i.e., C4). */
556 for (i = 1; block_offset (i + 3) + 2 <= msg_len; i ++)
560 byte *ct = block (msg, msg_len, i + 2);
561 byte *pt = block (msg_plaintext, msg_len, 2 + i + 1);
563 for (d = 0; d < 256 * 256; d ++)
564 if (oracle_test (d, i + 2, 0))
571 log_fatal ("Failed to find a valid d for block %d\n", i);
574 log_debug ("Block %d: oracle: D = %04X passes integrity check\n",
578 byte D[2] = { d >> 8, d & 0xFF };
580 bufxor2 (bufxor2 (&ct[blocksize - 2], D), e_k_zero),
583 memcpy (m, bufxor2 (e_k_prime, block (msg, msg_len, i + 3)),
588 log_debug ("=> block %d starting at %zd starts with: "
590 i, (size_t) pt - (size_t) msg_plaintext,
592 isprint (m[0]) ? m[0] : '?', isprint (m[1]) ? m[1] : '?');
594 if (m[0] != pt[0] || m[1] != pt[1])
596 log_debug ("oracle attack failed! Expected %s (%c%c), got %s\n",
598 isprint (pt[0]) ? pt[0] : '?',
599 isprint (pt[1]) ? pt[1] : '?',
606 log_fatal ("Message is too short, nothing to test.\n");