bad_dtls_test.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. /*
  2. * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /*
  10. * Unit test for Cisco DTLS1_BAD_VER session resume, as used by
  11. * AnyConnect VPN protocol.
  12. *
  13. * This is designed to exercise the code paths in
  14. * http://git.infradead.org/users/dwmw2/openconnect.git/blob/HEAD:/dtls.c
  15. * which have frequently been affected by regressions in DTLS1_BAD_VER
  16. * support.
  17. *
  18. * Note that unlike other SSL tests, we don't test against our own SSL
  19. * server method. Firstly because we don't have one; we *only* support
  20. * DTLS1_BAD_VER as a client. And secondly because even if that were
  21. * fixed up it's the wrong thing to test against — because if changes
  22. * are made in generic DTLS code which don't take DTLS1_BAD_VER into
  23. * account, there's plenty of scope for making those changes such that
  24. * they break *both* the client and the server in the same way.
  25. *
  26. * So we handle the server side manually. In a session resume there isn't
  27. * much to be done anyway.
  28. */
  29. #include <string.h>
  30. /* On Windows this will include <winsock2.h> and thus it needs to be
  31. * included *before* anything that includes <windows.h>. Ick. */
  32. #include "e_os.h" /* for 'inline' */
  33. #include <openssl/bio.h>
  34. #include <openssl/crypto.h>
  35. #include <openssl/evp.h>
  36. #include <openssl/ssl.h>
  37. #include <openssl/err.h>
  38. #include <openssl/rand.h>
  39. /* PACKET functions lifted from OpenSSL 1.1's ssl/packet_locl.h */
  40. typedef struct {
  41. /* Pointer to where we are currently reading from */
  42. const unsigned char *curr;
  43. /* Number of bytes remaining */
  44. size_t remaining;
  45. } PACKET;
  46. /* Internal unchecked shorthand; don't use outside this file. */
  47. static inline void packet_forward(PACKET *pkt, size_t len)
  48. {
  49. pkt->curr += len;
  50. pkt->remaining -= len;
  51. }
  52. /*
  53. * Returns the number of bytes remaining to be read in the PACKET
  54. */
  55. static inline size_t PACKET_remaining(const PACKET *pkt)
  56. {
  57. return pkt->remaining;
  58. }
  59. /*
  60. * Initialise a PACKET with |len| bytes held in |buf|. This does not make a
  61. * copy of the data so |buf| must be present for the whole time that the PACKET
  62. * is being used.
  63. */
  64. static inline int PACKET_buf_init(PACKET *pkt,
  65. const unsigned char *buf,
  66. size_t len)
  67. {
  68. /* Sanity check for negative values. */
  69. if (len > (size_t)65536)
  70. return 0;
  71. pkt->curr = buf;
  72. pkt->remaining = len;
  73. return 1;
  74. }
  75. /*
  76. * Returns 1 if the packet has length |num| and its contents equal the |num|
  77. * bytes read from |ptr|. Returns 0 otherwise (lengths or contents not equal).
  78. * If lengths are equal, performs the comparison in constant time.
  79. */
  80. static inline int PACKET_equal(const PACKET *pkt, const void *ptr,
  81. size_t num)
  82. {
  83. if (PACKET_remaining(pkt) != num)
  84. return 0;
  85. return CRYPTO_memcmp(pkt->curr, ptr, num) == 0;
  86. }
  87. /*
  88. * Peek ahead at 2 bytes in network order from |pkt| and store the value in
  89. * |*data|
  90. */
  91. static inline int PACKET_peek_net_2(const PACKET *pkt,
  92. unsigned int *data)
  93. {
  94. if (PACKET_remaining(pkt) < 2)
  95. return 0;
  96. *data = ((unsigned int)(*pkt->curr)) << 8;
  97. *data |= *(pkt->curr + 1);
  98. return 1;
  99. }
  100. /* Equivalent of n2s */
  101. /* Get 2 bytes in network order from |pkt| and store the value in |*data| */
  102. static inline int PACKET_get_net_2(PACKET *pkt,
  103. unsigned int *data)
  104. {
  105. if (!PACKET_peek_net_2(pkt, data))
  106. return 0;
  107. packet_forward(pkt, 2);
  108. return 1;
  109. }
  110. /* Peek ahead at 1 byte from |pkt| and store the value in |*data| */
  111. static inline int PACKET_peek_1(const PACKET *pkt,
  112. unsigned int *data)
  113. {
  114. if (!PACKET_remaining(pkt))
  115. return 0;
  116. *data = *pkt->curr;
  117. return 1;
  118. }
  119. /* Get 1 byte from |pkt| and store the value in |*data| */
  120. static inline int PACKET_get_1(PACKET *pkt, unsigned int *data)
  121. {
  122. if (!PACKET_peek_1(pkt, data))
  123. return 0;
  124. packet_forward(pkt, 1);
  125. return 1;
  126. }
  127. /*
  128. * Peek ahead at |len| bytes from the |pkt| and store a pointer to them in
  129. * |*data|. This just points at the underlying buffer that |pkt| is using. The
  130. * caller should not free this data directly (it will be freed when the
  131. * underlying buffer gets freed
  132. */
  133. static inline int PACKET_peek_bytes(const PACKET *pkt,
  134. const unsigned char **data,
  135. size_t len)
  136. {
  137. if (PACKET_remaining(pkt) < len)
  138. return 0;
  139. *data = pkt->curr;
  140. return 1;
  141. }
  142. /*
  143. * Read |len| bytes from the |pkt| and store a pointer to them in |*data|. This
  144. * just points at the underlying buffer that |pkt| is using. The caller should
  145. * not free this data directly (it will be freed when the underlying buffer gets
  146. * freed
  147. */
  148. static inline int PACKET_get_bytes(PACKET *pkt,
  149. const unsigned char **data,
  150. size_t len)
  151. {
  152. if (!PACKET_peek_bytes(pkt, data, len))
  153. return 0;
  154. packet_forward(pkt, len);
  155. return 1;
  156. }
  157. /* Peek ahead at |len| bytes from |pkt| and copy them to |data| */
  158. static inline int PACKET_peek_copy_bytes(const PACKET *pkt,
  159. unsigned char *data,
  160. size_t len)
  161. {
  162. if (PACKET_remaining(pkt) < len)
  163. return 0;
  164. memcpy(data, pkt->curr, len);
  165. return 1;
  166. }
  167. /*
  168. * Read |len| bytes from |pkt| and copy them to |data|.
  169. * The caller is responsible for ensuring that |data| can hold |len| bytes.
  170. */
  171. static inline int PACKET_copy_bytes(PACKET *pkt,
  172. unsigned char *data,
  173. size_t len)
  174. {
  175. if (!PACKET_peek_copy_bytes(pkt, data, len))
  176. return 0;
  177. packet_forward(pkt, len);
  178. return 1;
  179. }
  180. /* Move the current reading position forward |len| bytes */
  181. static inline int PACKET_forward(PACKET *pkt, size_t len)
  182. {
  183. if (PACKET_remaining(pkt) < len)
  184. return 0;
  185. packet_forward(pkt, len);
  186. return 1;
  187. }
  188. /*
  189. * Reads a variable-length vector prefixed with a one-byte length, and stores
  190. * the contents in |subpkt|. |pkt| can equal |subpkt|.
  191. * Data is not copied: the |subpkt| packet will share its underlying buffer with
  192. * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
  193. * Upon failure, the original |pkt| and |subpkt| are not modified.
  194. */
  195. static inline int PACKET_get_length_prefixed_1(PACKET *pkt,
  196. PACKET *subpkt)
  197. {
  198. unsigned int length;
  199. const unsigned char *data;
  200. PACKET tmp = *pkt;
  201. if (!PACKET_get_1(&tmp, &length) ||
  202. !PACKET_get_bytes(&tmp, &data, (size_t)length)) {
  203. return 0;
  204. }
  205. *pkt = tmp;
  206. subpkt->curr = data;
  207. subpkt->remaining = length;
  208. return 1;
  209. }
  210. #define OSSL_NELEM(x) (sizeof(x)/sizeof(x[0]))
  211. /* For DTLS1_BAD_VER packets the MAC doesn't include the handshake header */
  212. #define MAC_OFFSET (DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH)
  213. static unsigned char client_random[SSL3_RANDOM_SIZE];
  214. static unsigned char server_random[SSL3_RANDOM_SIZE];
  215. /* These are all generated locally, sized purely according to our own whim */
  216. static unsigned char session_id[32];
  217. static unsigned char master_secret[48];
  218. static unsigned char cookie[20];
  219. /* We've hard-coded the cipher suite; we know it's 104 bytes */
  220. static unsigned char key_block[104];
  221. #define mac_key (key_block + 20)
  222. #define dec_key (key_block + 40)
  223. #define enc_key (key_block + 56)
  224. static EVP_MD_CTX handshake_md5;
  225. static EVP_MD_CTX handshake_sha1;
  226. /* PRF lifted from ssl/t1_enc.c since we can't easily use it directly */
  227. static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
  228. int sec_len,
  229. const void *seed1, int seed1_len,
  230. const void *seed2, int seed2_len,
  231. const void *seed3, int seed3_len,
  232. unsigned char *out, int olen)
  233. {
  234. int chunk;
  235. size_t j;
  236. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  237. EVP_PKEY *prf_mac_key;
  238. unsigned char A1[EVP_MAX_MD_SIZE];
  239. size_t A1_len;
  240. int ret = 0;
  241. chunk = EVP_MD_size(md);
  242. OPENSSL_assert(chunk >= 0);
  243. EVP_MD_CTX_init(&ctx);
  244. EVP_MD_CTX_init(&ctx_tmp);
  245. EVP_MD_CTX_init(&ctx_init);
  246. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  247. prf_mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
  248. if (!prf_mac_key)
  249. goto err;
  250. if (!EVP_DigestSignInit(&ctx_init, NULL, md, NULL, prf_mac_key))
  251. goto err;
  252. if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
  253. goto err;
  254. if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
  255. goto err;
  256. if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
  257. goto err;
  258. if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
  259. goto err;
  260. if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
  261. goto err;
  262. for (;;) {
  263. /* Reinit mac contexts */
  264. if (!EVP_MD_CTX_copy_ex(&ctx, &ctx_init))
  265. goto err;
  266. if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
  267. goto err;
  268. if (olen > chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx))
  269. goto err;
  270. if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
  271. goto err;
  272. if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
  273. goto err;
  274. if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
  275. goto err;
  276. if (olen > chunk) {
  277. if (!EVP_DigestSignFinal(&ctx, out, &j))
  278. goto err;
  279. out += j;
  280. olen -= j;
  281. /* calc the next A1 value */
  282. if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len))
  283. goto err;
  284. } else { /* last one */
  285. if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
  286. goto err;
  287. memcpy(out, A1, olen);
  288. break;
  289. }
  290. }
  291. ret = 1;
  292. err:
  293. EVP_PKEY_free(prf_mac_key);
  294. EVP_MD_CTX_cleanup(&ctx);
  295. EVP_MD_CTX_cleanup(&ctx_tmp);
  296. EVP_MD_CTX_cleanup(&ctx_init);
  297. OPENSSL_cleanse(A1, sizeof(A1));
  298. return ret;
  299. }
  300. /* seed1 through seed5 are virtually concatenated */
  301. static int do_PRF(const void *seed1, int seed1_len,
  302. const void *seed2, int seed2_len,
  303. const void *seed3, int seed3_len,
  304. unsigned char *out, int olen)
  305. {
  306. unsigned char out2[104];
  307. int i, len;
  308. if (olen > (int)sizeof(out2))
  309. return 0;
  310. len = sizeof(master_secret) / 2;
  311. if (!tls1_P_hash(EVP_md5(), master_secret, len,
  312. seed1, seed1_len, seed2, seed2_len, seed3,
  313. seed3_len, out, olen))
  314. return 0;
  315. if (!tls1_P_hash(EVP_sha1(), master_secret + len, len,
  316. seed1, seed1_len, seed2, seed2_len, seed3,
  317. seed3_len, out2, olen))
  318. return 0;
  319. for (i = 0; i < olen; i++) {
  320. out[i] ^= out2[i];
  321. }
  322. return 1;
  323. }
  324. static SSL_SESSION *client_session(void)
  325. {
  326. static unsigned char session_asn1[] = {
  327. 0x30, 0x5F, /* SEQUENCE, length 0x5F */
  328. 0x02, 0x01, 0x01, /* INTEGER, SSL_SESSION_ASN1_VERSION */
  329. 0x02, 0x02, 0x01, 0x00, /* INTEGER, DTLS1_BAD_VER */
  330. 0x04, 0x02, 0x00, 0x2F, /* OCTET_STRING, AES128-SHA */
  331. 0x04, 0x20, /* OCTET_STRING, session id */
  332. #define SS_SESSID_OFS 15 /* Session ID goes here */
  333. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  334. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  335. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  336. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  337. 0x04, 0x30, /* OCTET_STRING, master secret */
  338. #define SS_SECRET_OFS 49 /* Master secret goes here */
  339. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  340. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  341. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  342. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  343. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  344. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  345. };
  346. const unsigned char *p = session_asn1;
  347. /* Copy the randomly-generated fields into the above ASN1 */
  348. memcpy(session_asn1 + SS_SESSID_OFS, session_id, sizeof(session_id));
  349. memcpy(session_asn1 + SS_SECRET_OFS, master_secret, sizeof(master_secret));
  350. return d2i_SSL_SESSION(NULL, &p, sizeof(session_asn1));
  351. }
  352. /* Returns 1 for initial ClientHello, 2 for ClientHello with cookie */
  353. static int validate_client_hello(BIO *wbio)
  354. {
  355. PACKET pkt, pkt2;
  356. long len;
  357. unsigned char *data;
  358. int cookie_found = 0;
  359. unsigned int u;
  360. len = BIO_get_mem_data(wbio, (char **)&data);
  361. if (!PACKET_buf_init(&pkt, data, len))
  362. return 0;
  363. /* Check record header type */
  364. if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
  365. return 0;
  366. /* Version */
  367. if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
  368. return 0;
  369. /* Skip the rest of the record header */
  370. if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
  371. return 0;
  372. /* Check it's a ClientHello */
  373. if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CLIENT_HELLO)
  374. return 0;
  375. /* Skip the rest of the handshake message header */
  376. if (!PACKET_forward(&pkt, DTLS1_HM_HEADER_LENGTH - 1))
  377. return 0;
  378. /* Check client version */
  379. if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
  380. return 0;
  381. /* Store random */
  382. if (!PACKET_copy_bytes(&pkt, client_random, SSL3_RANDOM_SIZE))
  383. return 0;
  384. /* Check session id length and content */
  385. if (!PACKET_get_length_prefixed_1(&pkt, &pkt2) ||
  386. !PACKET_equal(&pkt2, session_id, sizeof(session_id)))
  387. return 0;
  388. /* Check cookie */
  389. if (!PACKET_get_length_prefixed_1(&pkt, &pkt2))
  390. return 0;
  391. if (PACKET_remaining(&pkt2)) {
  392. if (!PACKET_equal(&pkt2, cookie, sizeof(cookie)))
  393. return 0;
  394. cookie_found = 1;
  395. }
  396. /* Skip ciphers */
  397. if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
  398. return 0;
  399. /* Skip compression */
  400. if (!PACKET_get_1(&pkt, &u) || !PACKET_forward(&pkt, u))
  401. return 0;
  402. /* Skip extensions */
  403. if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
  404. return 0;
  405. /* Now we are at the end */
  406. if (PACKET_remaining(&pkt))
  407. return 0;
  408. /* Update handshake MAC for second ClientHello (with cookie) */
  409. if (cookie_found && (!EVP_DigestUpdate(&handshake_md5, data + MAC_OFFSET,
  410. len - MAC_OFFSET) ||
  411. !EVP_DigestUpdate(&handshake_sha1, data + MAC_OFFSET,
  412. len - MAC_OFFSET)))
  413. printf("EVP_DigestUpdate() failed\n");
  414. (void)BIO_reset(wbio);
  415. return 1 + cookie_found;
  416. }
  417. static int send_hello_verify(BIO *rbio)
  418. {
  419. static unsigned char hello_verify[] = {
  420. 0x16, /* Handshake */
  421. 0x01, 0x00, /* DTLS1_BAD_VER */
  422. 0x00, 0x00, /* Epoch 0 */
  423. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Seq# 0 */
  424. 0x00, 0x23, /* Length */
  425. 0x03, /* Hello Verify */
  426. 0x00, 0x00, 0x17, /* Length */
  427. 0x00, 0x00, /* Seq# 0 */
  428. 0x00, 0x00, 0x00, /* Fragment offset */
  429. 0x00, 0x00, 0x17, /* Fragment length */
  430. 0x01, 0x00, /* DTLS1_BAD_VER */
  431. 0x14, /* Cookie length */
  432. #define HV_COOKIE_OFS 28 /* Cookie goes here */
  433. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  434. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  435. 0x00, 0x00, 0x00, 0x00,
  436. };
  437. memcpy(hello_verify + HV_COOKIE_OFS, cookie, sizeof(cookie));
  438. BIO_write(rbio, hello_verify, sizeof(hello_verify));
  439. return 1;
  440. }
  441. static int send_server_hello(BIO *rbio)
  442. {
  443. static unsigned char server_hello[] = {
  444. 0x16, /* Handshake */
  445. 0x01, 0x00, /* DTLS1_BAD_VER */
  446. 0x00, 0x00, /* Epoch 0 */
  447. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* Seq# 1 */
  448. 0x00, 0x52, /* Length */
  449. 0x02, /* Server Hello */
  450. 0x00, 0x00, 0x46, /* Length */
  451. 0x00, 0x01, /* Seq# */
  452. 0x00, 0x00, 0x00, /* Fragment offset */
  453. 0x00, 0x00, 0x46, /* Fragment length */
  454. 0x01, 0x00, /* DTLS1_BAD_VER */
  455. #define SH_RANDOM_OFS 27 /* Server random goes here */
  456. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  457. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  458. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  459. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  460. 0x20, /* Session ID length */
  461. #define SH_SESSID_OFS 60 /* Session ID goes here */
  462. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  463. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  464. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  465. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  466. 0x00, 0x2f, /* Cipher suite AES128-SHA */
  467. 0x00, /* Compression null */
  468. };
  469. static unsigned char change_cipher_spec[] = {
  470. 0x14, /* Change Cipher Spec */
  471. 0x01, 0x00, /* DTLS1_BAD_VER */
  472. 0x00, 0x00, /* Epoch 0 */
  473. 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, /* Seq# 2 */
  474. 0x00, 0x03, /* Length */
  475. 0x01, 0x00, 0x02, /* Message */
  476. };
  477. memcpy(server_hello + SH_RANDOM_OFS, server_random, sizeof(server_random));
  478. memcpy(server_hello + SH_SESSID_OFS, session_id, sizeof(session_id));
  479. if (!EVP_DigestUpdate(&handshake_md5, server_hello + MAC_OFFSET,
  480. sizeof(server_hello) - MAC_OFFSET) ||
  481. !EVP_DigestUpdate(&handshake_sha1, server_hello + MAC_OFFSET,
  482. sizeof(server_hello) - MAC_OFFSET))
  483. printf("EVP_DigestUpdate() failed\n");
  484. BIO_write(rbio, server_hello, sizeof(server_hello));
  485. BIO_write(rbio, change_cipher_spec, sizeof(change_cipher_spec));
  486. return 1;
  487. }
  488. /* Create header, HMAC, pad, encrypt and send a record */
  489. static int send_record(BIO *rbio, unsigned char type, unsigned long seqnr,
  490. const void *msg, size_t len)
  491. {
  492. /* Note that the order of the record header fields on the wire,
  493. * and in the HMAC, is different. So we just keep them in separate
  494. * variables and handle them individually. */
  495. static unsigned char epoch[2] = { 0x00, 0x01 };
  496. static unsigned char seq[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  497. static unsigned char ver[2] = { 0x01, 0x00 }; /* DTLS1_BAD_VER */
  498. unsigned char lenbytes[2];
  499. HMAC_CTX ctx;
  500. EVP_CIPHER_CTX enc_ctx;
  501. unsigned char iv[16];
  502. unsigned char pad;
  503. unsigned char *enc;
  504. #ifdef SIXTY_FOUR_BIT_LONG
  505. seq[0] = (seqnr >> 40) & 0xff;
  506. seq[1] = (seqnr >> 32) & 0xff;
  507. #endif
  508. seq[2] = (seqnr >> 24) & 0xff;
  509. seq[3] = (seqnr >> 16) & 0xff;
  510. seq[4] = (seqnr >> 8) & 0xff;
  511. seq[5] = seqnr & 0xff;
  512. pad = 15 - ((len + SHA_DIGEST_LENGTH) % 16);
  513. enc = OPENSSL_malloc(len + SHA_DIGEST_LENGTH + 1 + pad);
  514. if (enc == NULL)
  515. return 0;
  516. /* Copy record to encryption buffer */
  517. memcpy(enc, msg, len);
  518. /* Append HMAC to data */
  519. HMAC_Init(&ctx, mac_key, 20, EVP_sha1());
  520. HMAC_Update(&ctx, epoch, 2);
  521. HMAC_Update(&ctx, seq, 6);
  522. HMAC_Update(&ctx, &type, 1);
  523. HMAC_Update(&ctx, ver, 2); /* Version */
  524. lenbytes[0] = len >> 8;
  525. lenbytes[1] = len & 0xff;
  526. HMAC_Update(&ctx, lenbytes, 2); /* Length */
  527. HMAC_Update(&ctx, enc, len); /* Finally the data itself */
  528. HMAC_Final(&ctx, enc + len, NULL);
  529. HMAC_CTX_cleanup(&ctx);
  530. /* Append padding bytes */
  531. len += SHA_DIGEST_LENGTH;
  532. do {
  533. enc[len++] = pad;
  534. } while (len % 16);
  535. /* Generate IV, and encrypt */
  536. RAND_bytes(iv, sizeof(iv));
  537. EVP_CIPHER_CTX_init(&enc_ctx);
  538. EVP_CipherInit_ex(&enc_ctx, EVP_aes_128_cbc(), NULL, enc_key, iv, 1);
  539. EVP_Cipher(&enc_ctx, enc, enc, len);
  540. EVP_CIPHER_CTX_cleanup(&enc_ctx);
  541. /* Finally write header (from fragmented variables), IV and encrypted record */
  542. BIO_write(rbio, &type, 1);
  543. BIO_write(rbio, ver, 2);
  544. BIO_write(rbio, epoch, 2);
  545. BIO_write(rbio, seq, 6);
  546. lenbytes[0] = (len + sizeof(iv)) >> 8;
  547. lenbytes[1] = (len + sizeof(iv)) & 0xff;
  548. BIO_write(rbio, lenbytes, 2);
  549. BIO_write(rbio, iv, sizeof(iv));
  550. BIO_write(rbio, enc, len);
  551. OPENSSL_free(enc);
  552. return 1;
  553. }
  554. static int send_finished(SSL *s, BIO *rbio)
  555. {
  556. static unsigned char finished_msg[DTLS1_HM_HEADER_LENGTH +
  557. TLS1_FINISH_MAC_LENGTH] = {
  558. 0x14, /* Finished */
  559. 0x00, 0x00, 0x0c, /* Length */
  560. 0x00, 0x03, /* Seq# 3 */
  561. 0x00, 0x00, 0x00, /* Fragment offset */
  562. 0x00, 0x00, 0x0c, /* Fragment length */
  563. /* Finished MAC (12 bytes) */
  564. };
  565. unsigned char handshake_hash[EVP_MAX_MD_SIZE * 2];
  566. /* Derive key material */
  567. do_PRF(TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
  568. server_random, SSL3_RANDOM_SIZE,
  569. client_random, SSL3_RANDOM_SIZE,
  570. key_block, sizeof(key_block));
  571. /* Generate Finished MAC */
  572. if (!EVP_DigestFinal_ex(&handshake_md5, handshake_hash, NULL) ||
  573. !EVP_DigestFinal_ex(&handshake_sha1, handshake_hash + EVP_MD_CTX_size(&handshake_md5), NULL))
  574. printf("EVP_DigestFinal_ex() failed\n");
  575. do_PRF(TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
  576. handshake_hash, EVP_MD_CTX_size(&handshake_md5) + EVP_MD_CTX_size(&handshake_sha1),
  577. NULL, 0,
  578. finished_msg + DTLS1_HM_HEADER_LENGTH, TLS1_FINISH_MAC_LENGTH);
  579. return send_record(rbio, SSL3_RT_HANDSHAKE, 0,
  580. finished_msg, sizeof(finished_msg));
  581. }
  582. static int validate_ccs(BIO *wbio)
  583. {
  584. PACKET pkt;
  585. long len;
  586. unsigned char *data;
  587. unsigned int u;
  588. len = BIO_get_mem_data(wbio, (char **)&data);
  589. if (!PACKET_buf_init(&pkt, data, len))
  590. return 0;
  591. /* Check record header type */
  592. if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_CHANGE_CIPHER_SPEC)
  593. return 0;
  594. /* Version */
  595. if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
  596. return 0;
  597. /* Skip the rest of the record header */
  598. if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
  599. return 0;
  600. /* Check ChangeCipherSpec message */
  601. if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CCS)
  602. return 0;
  603. /* A DTLS1_BAD_VER ChangeCipherSpec also contains the
  604. * handshake sequence number (which is 2 here) */
  605. if (!PACKET_get_net_2(&pkt, &u) || u != 0x0002)
  606. return 0;
  607. /* Now check the Finished packet */
  608. if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
  609. return 0;
  610. if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
  611. return 0;
  612. /* Check epoch is now 1 */
  613. if (!PACKET_get_net_2(&pkt, &u) || u != 0x0001)
  614. return 0;
  615. /* That'll do for now. If OpenSSL accepted *our* Finished packet
  616. * then it's evidently remembered that DTLS1_BAD_VER doesn't
  617. * include the handshake header in the MAC. There's not a lot of
  618. * point in implementing decryption here, just to check that it
  619. * continues to get it right for one more packet. */
  620. return 1;
  621. }
  622. #define NODROP(x) { x##UL, 0 }
  623. #define DROP(x) { x##UL, 1 }
  624. static struct {
  625. unsigned long seq;
  626. int drop;
  627. } tests[] = {
  628. NODROP(1), NODROP(3), NODROP(2),
  629. NODROP(0x1234), NODROP(0x1230), NODROP(0x1235),
  630. NODROP(0xffff), NODROP(0x10001), NODROP(0xfffe), NODROP(0x10000),
  631. DROP(0x10001), DROP(0xff), NODROP(0x100000), NODROP(0x800000), NODROP(0x7fffe1),
  632. NODROP(0xffffff), NODROP(0x1000000), NODROP(0xfffffe), DROP(0xffffff), NODROP(0x1000010),
  633. NODROP(0xfffffd), NODROP(0x1000011), DROP(0x12), NODROP(0x1000012),
  634. NODROP(0x1ffffff), NODROP(0x2000000), DROP(0x1ff00fe), NODROP(0x2000001),
  635. NODROP(0x20fffff), NODROP(0x2105500), DROP(0x20ffffe), NODROP(0x21054ff),
  636. NODROP(0x211ffff), DROP(0x2110000), NODROP(0x2120000)
  637. /* The last test should be NODROP, because a DROP wouldn't get tested. */
  638. };
  639. int main(int argc, char *argv[])
  640. {
  641. SSL_SESSION *sess;
  642. SSL_CTX *ctx;
  643. SSL *con;
  644. BIO *rbio;
  645. BIO *wbio;
  646. BIO *err;
  647. time_t now = 0;
  648. int testresult = 0;
  649. int ret;
  650. int i;
  651. SSL_library_init();
  652. SSL_load_error_strings();
  653. err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
  654. CRYPTO_malloc_debug_init();
  655. CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
  656. CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
  657. RAND_bytes(session_id, sizeof(session_id));
  658. RAND_bytes(master_secret, sizeof(master_secret));
  659. RAND_bytes(cookie, sizeof(cookie));
  660. RAND_bytes(server_random + 4, sizeof(server_random) - 4);
  661. now = time(NULL);
  662. memcpy(server_random, &now, sizeof(now));
  663. sess = client_session();
  664. if (sess == NULL) {
  665. printf("Failed to generate SSL_SESSION\n");
  666. goto end;
  667. }
  668. if (!EVP_DigestInit_ex(&handshake_md5, EVP_md5(), NULL) ||
  669. !EVP_DigestInit_ex(&handshake_sha1, EVP_sha1(), NULL)) {
  670. printf("Failed to initialise handshake_md\n");
  671. goto end;
  672. }
  673. ctx = SSL_CTX_new(DTLSv1_client_method());
  674. if (ctx == NULL) {
  675. printf("Failed to allocate SSL_CTX\n");
  676. goto end_md;
  677. }
  678. SSL_CTX_set_options(ctx, SSL_OP_CISCO_ANYCONNECT);
  679. if (!SSL_CTX_set_cipher_list(ctx, "AES128-SHA")) {
  680. printf("SSL_CTX_set_cipher_list() failed\n");
  681. goto end_ctx;
  682. }
  683. con = SSL_new(ctx);
  684. if (!SSL_set_session(con, sess)) {
  685. printf("SSL_set_session() failed\n");
  686. goto end_con;
  687. }
  688. SSL_SESSION_free(sess);
  689. rbio = BIO_new(BIO_s_mem());
  690. wbio = BIO_new(BIO_s_mem());
  691. BIO_set_nbio(rbio, 1);
  692. BIO_set_nbio(wbio, 1);
  693. SSL_set_bio(con, rbio, wbio);
  694. SSL_set_connect_state(con);
  695. /* Send initial ClientHello */
  696. ret = SSL_do_handshake(con);
  697. if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) {
  698. printf("Unexpected handshake result at initial call!\n");
  699. goto end_con;
  700. }
  701. if (validate_client_hello(wbio) != 1) {
  702. printf("Initial ClientHello failed validation\n");
  703. goto end_con;
  704. }
  705. if (send_hello_verify(rbio) != 1) {
  706. printf("Failed to send HelloVerify\n");
  707. goto end_con;
  708. }
  709. ret = SSL_do_handshake(con);
  710. if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) {
  711. printf("Unexpected handshake result after HelloVerify!\n");
  712. goto end_con;
  713. }
  714. if (validate_client_hello(wbio) != 2) {
  715. printf("Second ClientHello failed validation\n");
  716. goto end_con;
  717. }
  718. if (send_server_hello(rbio) != 1) {
  719. printf("Failed to send ServerHello\n");
  720. goto end_con;
  721. }
  722. ret = SSL_do_handshake(con);
  723. if (ret > 0 || SSL_get_error(con, ret) != SSL_ERROR_WANT_READ) {
  724. printf("Unexpected handshake result after ServerHello!\n");
  725. goto end_con;
  726. }
  727. if (send_finished(con, rbio) != 1) {
  728. printf("Failed to send Finished\n");
  729. goto end_con;
  730. }
  731. ret = SSL_do_handshake(con);
  732. if (ret < 1) {
  733. printf("Handshake not successful after Finished!\n");
  734. goto end_con;
  735. }
  736. if (validate_ccs(wbio) != 1) {
  737. printf("Failed to validate client CCS/Finished\n");
  738. goto end_con;
  739. }
  740. /* While we're here and crafting packets by hand, we might as well do a
  741. bit of a stress test on the DTLS record replay handling. Not Cisco-DTLS
  742. specific but useful anyway for the general case. It's been broken
  743. before, and in fact was broken even for a basic 0, 2, 1 test case
  744. when this test was first added.... */
  745. for (i = 0; i < (int)OSSL_NELEM(tests); i++) {
  746. unsigned long recv_buf[2];
  747. if (send_record(rbio, SSL3_RT_APPLICATION_DATA, tests[i].seq,
  748. &tests[i].seq, sizeof(unsigned long)) != 1) {
  749. printf("Failed to send data seq #0x%lx (%d)\n",
  750. tests[i].seq, i);
  751. goto end_con;
  752. }
  753. if (tests[i].drop)
  754. continue;
  755. ret = SSL_read(con, recv_buf, 2 * sizeof(unsigned long));
  756. if (ret != sizeof(unsigned long)) {
  757. printf("SSL_read failed or wrong size on seq#0x%lx (%d)\n",
  758. tests[i].seq, i);
  759. goto end_con;
  760. }
  761. if (recv_buf[0] != tests[i].seq) {
  762. printf("Wrong data packet received (0x%lx not 0x%lx) at packet %d\n",
  763. recv_buf[0], tests[i].seq, i);
  764. goto end_con;
  765. }
  766. }
  767. if (tests[i-1].drop) {
  768. printf("Error: last test cannot be DROP()\n");
  769. goto end_con;
  770. }
  771. testresult=1;
  772. end_con:
  773. SSL_free(con);
  774. end_ctx:
  775. SSL_CTX_free(ctx);
  776. end_md:
  777. EVP_MD_CTX_cleanup(&handshake_md5);
  778. EVP_MD_CTX_cleanup(&handshake_sha1);
  779. end:
  780. ERR_print_errors_fp(stderr);
  781. if (!testresult) {
  782. printf("Cisco BadDTLS test: FAILED\n");
  783. }
  784. ERR_free_strings();
  785. ERR_remove_thread_state(NULL);
  786. EVP_cleanup();
  787. CRYPTO_cleanup_all_ex_data();
  788. CRYPTO_mem_leaks(err);
  789. BIO_free(err);
  790. return testresult?0:1;
  791. }