tls.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. /* Minimal TLS 1.3 client (RFC 8446) over the kernel TCP client:
  2. * X25519 key exchange, TLS_CHACHA20_POLY1305_SHA256, no certificate
  3. * verification (the leaf SHA-256 is printed for manual comparison).
  4. *
  5. * The record layer is a small state machine; incoming records are
  6. * decrypted in chunks straight from the TCP stream (SYS_TCP_RECV) so a
  7. * 16 KB record never needs more than one plaintext buffer. Handshake
  8. * messages are fed byte-wise through a transcript-hashing parser, so a
  9. * large Certificate message is hashed as it flows past.
  10. *
  11. * Phase A trade-off: this authenticates nothing. See tls.h. */
  12. #include "ucmd_lib.h"
  13. #include "tls.h"
  14. #include "tls_sha256.h"
  15. #include "tls_chacha20.h"
  16. #include "tls_x25519.h"
  17. #include "tls_rng.h"
  18. #define TLS_RAW_SIZE 2048
  19. #define TLS_REC_PT_MAX (16384 + 256)
  20. #define TLS_SH_MAX 1024
  21. #define TLS_TX_MAX 2048
  22. #define TLS_APP_CHUNK 1024
  23. #define TLS_HS_DEADLINE_MS 15000
  24. /* ---- state (one connection at a time) ---- */
  25. static unsigned char raw_buf[TLS_RAW_SIZE];
  26. static unsigned int raw_len, raw_pos;
  27. static unsigned char rec_pt[TLS_REC_PT_MAX]; /* decrypted record payload */
  28. static unsigned int app_off, app_len; /* pending app data in rec_pt */
  29. static unsigned char sh_buf[TLS_SH_MAX];
  30. static unsigned char tx_buf[TLS_TX_MAX];
  31. static unsigned int peer_mss = 536;
  32. static int phase; /* 0 clear, 1 hs keys, 2 app keys */
  33. static unsigned long long rx_seq, tx_seq;
  34. static unsigned char c_hs[32], s_hs[32], c_ap[32], s_ap[32];
  35. static unsigned char c_hs_key[32], s_hs_key[32], c_hs_iv[12], s_hs_iv[12];
  36. static unsigned char c_ap_key[32], s_ap_key[32], c_ap_iv[12], s_ap_iv[12];
  37. static unsigned char master_secret[32];
  38. static unsigned char x_priv[32];
  39. static struct sha256_ctx transcript;
  40. static unsigned char fin_data[32];
  41. static int eof, err;
  42. /* handshake message parser */
  43. static unsigned int hm_type, hm_len, hm_got;
  44. /* Certificate streaming parser */
  45. static unsigned int cert_stage; /* 0 ctx-len, 1 ctx, 2 list-len, 3 cert-len, 4 cert data, 5 ext-len, 6 ext data, 9 done */
  46. static unsigned int cert_ctx_left, cert_hdr_got, cert_list_left;
  47. static unsigned int cert_cur_left, cert_seen;
  48. static unsigned int cert_ext_got, cert_ext_left;
  49. static struct sha256_ctx cert_hash;
  50. static const unsigned char zeros32[32];
  51. static const unsigned char sha256_empty[32] = {
  52. 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14,
  53. 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
  54. 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
  55. 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55
  56. };
  57. /* ---- small helpers ---- */
  58. static int eq32(const unsigned char *a, const unsigned char *b)
  59. {
  60. unsigned int i, d = 0;
  61. for (i = 0; i < 32; i++)
  62. d |= a[i] ^ b[i];
  63. return d == 0;
  64. }
  65. static void transcript_hash(unsigned char out[32])
  66. {
  67. struct sha256_ctx t;
  68. sha256_copy(&t, &transcript);
  69. sha256_final(&t, out);
  70. }
  71. static void derive_secret_th(const unsigned char *secret, const char *label,
  72. const unsigned char th[32], unsigned char out[32])
  73. {
  74. hkdf_expand_label(secret, label, th, 32, out, 32);
  75. }
  76. static void derive_keys(const unsigned char *secret, unsigned char key[32],
  77. unsigned char iv[12])
  78. {
  79. hkdf_expand_label(secret, "key", 0, 0, key, 32);
  80. hkdf_expand_label(secret, "iv", 0, 0, iv, 12);
  81. }
  82. static void nonce_for(unsigned char nonce[12], const unsigned char iv[12],
  83. unsigned long long seq)
  84. {
  85. unsigned int i;
  86. for (i = 0; i < 12; i++)
  87. nonce[i] = iv[i];
  88. for (i = 0; i < 8; i++)
  89. nonce[11 - i] ^= (unsigned char)(seq >> (8 * i));
  90. }
  91. /* ---- raw TCP input ---- */
  92. static int raw_fill(unsigned int timeout)
  93. {
  94. int r = (int)u_syscall3(SYS_TCP_RECV, (int)raw_buf,
  95. (int)sizeof(raw_buf), (int)timeout);
  96. if (r > 0) {
  97. raw_len = (unsigned int)r;
  98. raw_pos = 0;
  99. return 0;
  100. }
  101. if (r == 0) {
  102. eof = 1;
  103. return -1;
  104. }
  105. err = (r == -2) ? 1 : 2;
  106. return -1;
  107. }
  108. static int raw_read(void *dst, unsigned int n, unsigned int deadline)
  109. {
  110. unsigned char *d = dst;
  111. while (n) {
  112. unsigned int avail = raw_len - raw_pos;
  113. unsigned int take, i;
  114. if (!avail) {
  115. int left;
  116. if (err || eof)
  117. return -1;
  118. left = (int)(deadline - u_ticks_ms());
  119. if (left <= 0) {
  120. err = 2;
  121. return -1;
  122. }
  123. if (raw_fill((unsigned int)left) != 0)
  124. return -1;
  125. continue;
  126. }
  127. take = avail < n ? avail : n;
  128. for (i = 0; i < take; i++)
  129. d[i] = raw_buf[raw_pos + i];
  130. raw_pos += take;
  131. d += take;
  132. n -= take;
  133. }
  134. return 0;
  135. }
  136. /* ---- record output ---- */
  137. static int tcp_send_all(const unsigned char *p, unsigned int n)
  138. {
  139. while (n) {
  140. unsigned int take = n < peer_mss ? n : peer_mss;
  141. if (u_syscall2(SYS_TCP_SEND, (int)p, (int)take) != 0)
  142. return -1;
  143. p += take;
  144. n -= take;
  145. }
  146. return 0;
  147. }
  148. static int send_plain(unsigned char type, const unsigned char *data,
  149. unsigned int len)
  150. {
  151. unsigned char hdr[5];
  152. hdr[0] = type;
  153. hdr[1] = 3;
  154. hdr[2] = 3;
  155. hdr[3] = (unsigned char)(len >> 8);
  156. hdr[4] = (unsigned char)len;
  157. if (tcp_send_all(hdr, 5) != 0)
  158. return -1;
  159. return tcp_send_all(data, len);
  160. }
  161. static int send_record(unsigned char inner, const unsigned char *data,
  162. unsigned int len, int use_hs)
  163. {
  164. const unsigned char *key = use_hs ? c_hs_key : c_ap_key;
  165. const unsigned char *iv = use_hs ? c_hs_iv : c_ap_iv;
  166. unsigned char nonce[12], aad[5], tag[16];
  167. unsigned int plen = len + 1, rl = plen + 16, i;
  168. if (5 + rl > TLS_TX_MAX)
  169. return -1;
  170. for (i = 0; i < len; i++)
  171. tx_buf[5 + i] = data[i];
  172. tx_buf[5 + len] = inner;
  173. aad[0] = 23;
  174. aad[1] = 3;
  175. aad[2] = 3;
  176. aad[3] = (unsigned char)(rl >> 8);
  177. aad[4] = (unsigned char)rl;
  178. for (i = 0; i < 5; i++)
  179. tx_buf[i] = aad[i]; /* the record header on the wire */
  180. nonce_for(nonce, iv, tx_seq);
  181. aead_seal(key, nonce, aad, 5, tx_buf + 5, plen, tx_buf + 5, tag);
  182. for (i = 0; i < 16; i++)
  183. tx_buf[5 + plen + i] = tag[i];
  184. tx_seq++;
  185. return tcp_send_all(tx_buf, 5 + rl);
  186. }
  187. /* ---- handshake: ServerHello ---- */
  188. static void sh_parse(unsigned int len)
  189. {
  190. const unsigned char *p = sh_buf;
  191. unsigned char shared[32], early[32], d1[32], d2[32], hs[32], th[32];
  192. unsigned char server_key[32];
  193. unsigned int o, sid, cipher, elen, i, j;
  194. int have_key = 0, have_ver = 0;
  195. if (err)
  196. return;
  197. if (len < 2 + 32 + 1 + 2 + 1 + 2) {
  198. err = 3;
  199. return;
  200. }
  201. o = 2 + 32;
  202. sid = p[o++];
  203. if (o + sid + 3 > len) {
  204. err = 3;
  205. return;
  206. }
  207. o += sid;
  208. cipher = ((unsigned int)p[o] << 8) | p[o + 1];
  209. o += 2;
  210. if (cipher != 0x1303) {
  211. u_puts("tls: server chose another cipher suite\n");
  212. err = 4;
  213. return;
  214. }
  215. o++; /* legacy_compression_method */
  216. elen = ((unsigned int)p[o] << 8) | p[o + 1];
  217. o += 2;
  218. if (o + elen != len) {
  219. err = 3;
  220. return;
  221. }
  222. for (i = 0; i + 4 <= elen; ) {
  223. unsigned int et = ((unsigned int)p[o + i] << 8) | p[o + i + 1];
  224. unsigned int el = ((unsigned int)p[o + i + 2] << 8) |
  225. p[o + i + 3];
  226. const unsigned char *d = p + o + i + 4;
  227. if (i + 4 + el > elen) {
  228. err = 3;
  229. return;
  230. }
  231. if (et == 0x0033 && el == 36 && d[0] == 0x00 && d[1] == 0x1d &&
  232. d[2] == 0x00 && d[3] == 32) {
  233. for (j = 0; j < 32; j++)
  234. server_key[j] = d[4 + j];
  235. have_key = 1;
  236. }
  237. if (et == 0x002b && el == 2 && d[0] == 3 && d[1] == 4)
  238. have_ver = 1;
  239. i += 4 + el;
  240. }
  241. if (!have_ver) {
  242. u_puts("tls: server did not agree on TLS 1.3\n");
  243. err = 4;
  244. return;
  245. }
  246. if (!have_key) {
  247. u_puts("tls: server sent no X25519 key share\n");
  248. err = 4;
  249. return;
  250. }
  251. x25519(shared, x_priv, server_key);
  252. hkdf_extract(0, 0, zeros32, 32, early);
  253. derive_secret_th(early, "derived", sha256_empty, d1);
  254. hkdf_extract(d1, 32, shared, 32, hs);
  255. transcript_hash(th);
  256. derive_secret_th(hs, "c hs traffic", th, c_hs);
  257. derive_secret_th(hs, "s hs traffic", th, s_hs);
  258. derive_keys(c_hs, c_hs_key, c_hs_iv);
  259. derive_keys(s_hs, s_hs_key, s_hs_iv);
  260. derive_secret_th(hs, "derived", sha256_empty, d2);
  261. hkdf_extract(d2, 32, zeros32, 32, master_secret);
  262. phase = 1;
  263. u_puts("tls: server hello, TLS_CHACHA20_POLY1305_SHA256 + X25519\n");
  264. }
  265. /* ---- handshake: Certificate (streamed, fingerprint only) ---- */
  266. static unsigned char cert_lenbuf[3];
  267. static void cert_msg_done(void)
  268. {
  269. unsigned char fp[32];
  270. unsigned int i;
  271. if (cert_stage != 9 || cert_seen == 0) {
  272. err = 3;
  273. return;
  274. }
  275. sha256_final(&cert_hash, fp);
  276. u_puts("tls: cert[0] sha256=");
  277. for (i = 0; i < 32; i++)
  278. u_put_hex2(fp[i]);
  279. u_putc('\n');
  280. u_puts("tls: chain has ");
  281. u_putdec(cert_seen);
  282. u_puts(" certificate(s), NOT verified\n");
  283. }
  284. static void cert_byte(unsigned char b)
  285. {
  286. switch (cert_stage) {
  287. case 0:
  288. sha256_init(&cert_hash);
  289. cert_ctx_left = b;
  290. cert_stage = cert_ctx_left ? 1 : 2;
  291. break;
  292. case 1:
  293. if (--cert_ctx_left == 0)
  294. cert_stage = 2;
  295. break;
  296. case 2:
  297. cert_lenbuf[cert_hdr_got++] = b;
  298. if (cert_hdr_got == 3) {
  299. cert_hdr_got = 0;
  300. cert_list_left = ((unsigned int)cert_lenbuf[0] << 16) |
  301. ((unsigned int)cert_lenbuf[1] << 8) |
  302. cert_lenbuf[2];
  303. cert_stage = cert_list_left ? 3 : 9;
  304. }
  305. break;
  306. case 3:
  307. cert_lenbuf[cert_hdr_got++] = b;
  308. cert_list_left--;
  309. if (cert_hdr_got == 3) {
  310. cert_hdr_got = 0;
  311. cert_cur_left = ((unsigned int)cert_lenbuf[0] << 16) |
  312. ((unsigned int)cert_lenbuf[1] << 8) |
  313. cert_lenbuf[2];
  314. if (cert_cur_left == 0) {
  315. cert_seen++;
  316. cert_ext_got = 0;
  317. cert_stage = 5;
  318. } else {
  319. cert_stage = 4;
  320. }
  321. }
  322. break;
  323. case 4:
  324. if (cert_seen == 0)
  325. sha256_update(&cert_hash, &b, 1);
  326. cert_cur_left--;
  327. cert_list_left--;
  328. if (cert_cur_left == 0) {
  329. cert_seen++;
  330. cert_ext_got = 0;
  331. cert_stage = 5;
  332. }
  333. break;
  334. case 5: /* per-entry extensions */
  335. cert_lenbuf[cert_ext_got++] = b;
  336. cert_list_left--;
  337. if (cert_ext_got == 2) {
  338. cert_ext_left = ((unsigned int)cert_lenbuf[0] << 8) |
  339. cert_lenbuf[1];
  340. cert_stage = cert_ext_left ? 6 :
  341. (cert_list_left ? 3 : 9);
  342. }
  343. break;
  344. case 6:
  345. cert_ext_left--;
  346. cert_list_left--;
  347. if (cert_ext_left == 0)
  348. cert_stage = cert_list_left ? 3 : 9;
  349. break;
  350. default:
  351. break;
  352. }
  353. }
  354. /* ---- handshake message parser ---- */
  355. static void hs_msg_complete(void);
  356. static void hs_byte(unsigned char b)
  357. {
  358. unsigned int body_pos;
  359. if (hm_got < 4) {
  360. if (hm_got == 0) {
  361. hm_type = b;
  362. hm_len = 0;
  363. } else {
  364. hm_len = (hm_len << 8) | b;
  365. }
  366. if (hm_type != 20)
  367. sha256_update(&transcript, &b, 1);
  368. hm_got++;
  369. if (hm_got == 4 && hm_len == 0)
  370. hs_msg_complete();
  371. return;
  372. }
  373. if (hm_got - 4 >= hm_len) { /* defensive */
  374. hs_msg_complete();
  375. return;
  376. }
  377. body_pos = hm_got - 4;
  378. if (hm_type != 20)
  379. sha256_update(&transcript, &b, 1);
  380. switch (hm_type) {
  381. case 2:
  382. if (body_pos < TLS_SH_MAX)
  383. sh_buf[body_pos] = b;
  384. else
  385. err = 3;
  386. break;
  387. case 11:
  388. cert_byte(b);
  389. break;
  390. case 15:
  391. break; /* CertificateVerify: not checked */
  392. case 20:
  393. if (body_pos < 32)
  394. fin_data[body_pos] = b;
  395. break;
  396. default:
  397. break; /* EE and post-handshake: skip */
  398. }
  399. hm_got++;
  400. if (hm_got - 4 == hm_len)
  401. hs_msg_complete();
  402. }
  403. static void hs_finish(unsigned int len);
  404. static void hs_msg_complete(void)
  405. {
  406. unsigned int type = hm_type, len = hm_len;
  407. hm_got = 0;
  408. switch (type) {
  409. case 2:
  410. sh_parse(len);
  411. break;
  412. case 11:
  413. cert_msg_done();
  414. break;
  415. case 20:
  416. hs_finish(len);
  417. break;
  418. default:
  419. break;
  420. }
  421. }
  422. static void hs_finish(unsigned int len)
  423. {
  424. unsigned char th[32], fk[32], expect[32], msg[36];
  425. if (err)
  426. return;
  427. if (len != 32 || phase != 1) {
  428. err = 3;
  429. return;
  430. }
  431. transcript_hash(th);
  432. hkdf_expand_label(s_hs, "finished", 0, 0, fk, 32);
  433. hmac_sha256(fk, 32, th, 32, expect);
  434. if (!eq32(expect, fin_data)) {
  435. u_puts("tls: bad server Finished (handshake mismatch)\n");
  436. err = 5;
  437. return;
  438. }
  439. /* Transcript += server Finished. */
  440. msg[0] = 20;
  441. msg[1] = 0;
  442. msg[2] = 0;
  443. msg[3] = 32;
  444. sha256_update(&transcript, msg, 4);
  445. sha256_update(&transcript, fin_data, 32);
  446. /* Application traffic secrets (context: CH .. server Finished). */
  447. transcript_hash(th);
  448. derive_secret_th(master_secret, "c ap traffic", th, c_ap);
  449. derive_secret_th(master_secret, "s ap traffic", th, s_ap);
  450. derive_keys(c_ap, c_ap_key, c_ap_iv);
  451. derive_keys(s_ap, s_ap_key, s_ap_iv);
  452. /* Our Finished, under the handshake keys. */
  453. hkdf_expand_label(c_hs, "finished", 0, 0, fk, 32);
  454. hmac_sha256(fk, 32, th, 32, expect);
  455. msg[0] = 20;
  456. msg[1] = 0;
  457. msg[2] = 0;
  458. msg[3] = 32;
  459. {
  460. unsigned int i;
  461. for (i = 0; i < 32; i++)
  462. msg[4 + i] = expect[i];
  463. }
  464. if (send_record(22, msg, 36, 1) != 0) {
  465. err = 1;
  466. return;
  467. }
  468. phase = 2;
  469. rx_seq = 0;
  470. tx_seq = 0;
  471. }
  472. /* ---- record input ---- */
  473. static void inner_process(unsigned int len)
  474. {
  475. unsigned int i = len;
  476. unsigned char type;
  477. while (i > 0 && rec_pt[i - 1] == 0)
  478. i--;
  479. if (i == 0) {
  480. err = 3;
  481. return;
  482. }
  483. type = rec_pt[i - 1];
  484. len = i - 1;
  485. switch (type) {
  486. case 22:
  487. for (i = 0; i < len && !err; i++)
  488. hs_byte(rec_pt[i]);
  489. break;
  490. case 23:
  491. app_off = 0;
  492. app_len = len;
  493. break;
  494. case 21:
  495. if (len >= 2) {
  496. if (rec_pt[1] == 0) {
  497. eof = 1; /* close_notify */
  498. } else {
  499. u_puts("tls: alert ");
  500. u_putdec(rec_pt[1]);
  501. u_putc('\n');
  502. err = 6;
  503. }
  504. }
  505. break;
  506. default:
  507. break; /* inner CCS etc. */
  508. }
  509. }
  510. static int pump_record(unsigned int deadline)
  511. {
  512. unsigned char hdr[5], tag[16], expect[16];
  513. unsigned int len, i;
  514. if (err || eof)
  515. return -1;
  516. if (raw_read(hdr, 5, deadline) != 0)
  517. return -1;
  518. len = ((unsigned int)hdr[3] << 8) | hdr[4];
  519. if (hdr[0] == 20) { /* CCS (middlebox mode) */
  520. if (len > 4 || raw_read(rec_pt, len, deadline) != 0) {
  521. err = 3;
  522. return -1;
  523. }
  524. return 0;
  525. }
  526. if (hdr[0] == 21) { /* plaintext alert */
  527. if (len != 2 || raw_read(rec_pt, 2, deadline) != 0) {
  528. err = 3;
  529. return -1;
  530. }
  531. u_puts("tls: server alert: ");
  532. switch (rec_pt[1]) {
  533. case 40:
  534. u_puts("handshake failure");
  535. break;
  536. case 47:
  537. u_puts("illegal parameter");
  538. break;
  539. case 70:
  540. u_puts("protocol version (the server may not support TLS 1.3)");
  541. break;
  542. case 80:
  543. u_puts("internal error");
  544. break;
  545. default:
  546. u_puts("description ");
  547. u_putdec(rec_pt[1]);
  548. break;
  549. }
  550. u_puts(" (level ");
  551. u_putdec(rec_pt[0]);
  552. u_puts(")\n");
  553. err = 4;
  554. return -1;
  555. }
  556. if (phase == 0) {
  557. if (hdr[0] != 22 || len > TLS_SH_MAX) {
  558. err = 3;
  559. return -1;
  560. }
  561. if (raw_read(sh_buf, len, deadline) != 0)
  562. return -1;
  563. for (i = 0; i < len && !err; i++)
  564. hs_byte(sh_buf[i]);
  565. return 0;
  566. }
  567. if (hdr[0] != 23 || len < 17 || len > TLS_REC_PT_MAX) {
  568. err = 3;
  569. return -1;
  570. }
  571. {
  572. const unsigned char *key = (phase == 1) ? s_hs_key : s_ap_key;
  573. const unsigned char *iv = (phase == 1) ? s_hs_iv : s_ap_iv;
  574. struct aead_open_ctx a;
  575. unsigned char nonce[12];
  576. unsigned int ptlen = len - 16, off = 0;
  577. nonce_for(nonce, iv, rx_seq);
  578. aead_open_init(&a, key, nonce, hdr, 5);
  579. while (off < ptlen) {
  580. unsigned int n = ptlen - off;
  581. if (n > 1024)
  582. n = 1024;
  583. if (raw_read(rec_pt + off, n, deadline) != 0)
  584. return -1;
  585. aead_open_update(&a, rec_pt + off, rec_pt + off, n);
  586. off += n;
  587. }
  588. if (raw_read(tag, 16, deadline) != 0)
  589. return -1;
  590. aead_open_tag(&a, expect);
  591. for (i = 0; i < 16; i++) {
  592. if (tag[i] != expect[i]) {
  593. u_puts("tls: record authentication failed\n");
  594. err = 5;
  595. return -1;
  596. }
  597. }
  598. rx_seq++;
  599. inner_process(ptlen);
  600. }
  601. return 0;
  602. }
  603. /* ---- ClientHello ---- */
  604. static unsigned char ch_buf[512];
  605. static unsigned int ch_n;
  606. static int ch_over;
  607. static void ch_u8(unsigned int v)
  608. {
  609. if (ch_n < sizeof(ch_buf))
  610. ch_buf[ch_n++] = (unsigned char)v;
  611. else
  612. ch_over = 1;
  613. }
  614. static void ch_u16(unsigned int v)
  615. {
  616. ch_u8(v >> 8);
  617. ch_u8(v);
  618. }
  619. static void ch_u24(unsigned int v)
  620. {
  621. ch_u8(v >> 16);
  622. ch_u8(v >> 8);
  623. ch_u8(v);
  624. }
  625. static void ch_bytes(const void *p, unsigned int n)
  626. {
  627. const unsigned char *b = p;
  628. while (n--)
  629. ch_u8(*b++);
  630. }
  631. static int build_client_hello(const char *sni)
  632. {
  633. unsigned char cr[32], sid[32], pub[32];
  634. unsigned int hostlen = 0, ext_pos, ext_start;
  635. while (sni[hostlen])
  636. hostlen++;
  637. if (hostlen == 0 || hostlen > 200)
  638. return -1;
  639. ch_n = 0;
  640. ch_over = 0;
  641. ch_u8(1); /* client_hello */
  642. ch_u24(0); /* length (patched below) */
  643. ch_u16(0x0303); /* legacy_version */
  644. tls_random(cr, 32);
  645. ch_bytes(cr, 32);
  646. tls_random(sid, 32);
  647. ch_u8(32); /* legacy_session_id */
  648. ch_bytes(sid, 32);
  649. ch_u16(2); /* cipher suites */
  650. ch_u16(0x1303);
  651. ch_u8(1); /* compression */
  652. ch_u8(0);
  653. ext_pos = ch_n;
  654. ch_u16(0); /* extensions length (patched) */
  655. ext_start = ch_n;
  656. /* supported_versions */
  657. ch_u16(0x002b);
  658. ch_u16(3);
  659. ch_u8(2);
  660. ch_u16(0x0304);
  661. /* supported_groups */
  662. ch_u16(0x000a);
  663. ch_u16(4);
  664. ch_u16(2);
  665. ch_u16(0x001d);
  666. /* signature_algorithms (unused in phase A, syntactically required) */
  667. ch_u16(0x000d);
  668. ch_u16(6);
  669. ch_u16(4);
  670. ch_u16(0x0804);
  671. ch_u16(0x0403);
  672. /* key_share */
  673. tls_random(x_priv, 32);
  674. x25519(pub, x_priv, x25519_base_point);
  675. ch_u16(0x0033);
  676. ch_u16(38);
  677. ch_u16(36);
  678. ch_u16(0x001d);
  679. ch_u16(32);
  680. ch_bytes(pub, 32);
  681. /* server_name */
  682. ch_u16(0x0000);
  683. ch_u16(2 + 1 + 2 + hostlen);
  684. ch_u16(1 + 2 + hostlen);
  685. ch_u8(0);
  686. ch_u16(hostlen);
  687. ch_bytes(sni, hostlen);
  688. /* application_layer_protocol_negotiation: http/1.1 */
  689. ch_u16(0x0010);
  690. ch_u16(2 + 1 + 8);
  691. ch_u16(1 + 8);
  692. ch_u8(8);
  693. ch_bytes("http/1.1", 8);
  694. if (ch_over)
  695. return -1;
  696. ch_buf[ext_pos] = (unsigned char)((ch_n - ext_start) >> 8);
  697. ch_buf[ext_pos + 1] = (unsigned char)(ch_n - ext_start);
  698. ch_buf[1] = (unsigned char)((ch_n - 4) >> 16);
  699. ch_buf[2] = (unsigned char)((ch_n - 4) >> 8);
  700. ch_buf[3] = (unsigned char)(ch_n - 4);
  701. return (int)ch_n;
  702. }
  703. /* ---- public API ---- */
  704. int tls_connect(const char *sni)
  705. {
  706. unsigned int n;
  707. unsigned int deadline;
  708. int r;
  709. phase = 0;
  710. rx_seq = tx_seq = 0;
  711. raw_len = raw_pos = 0;
  712. app_off = app_len = 0;
  713. eof = err = 0;
  714. hm_got = 0;
  715. cert_stage = cert_seen = 0;
  716. cert_hdr_got = 0;
  717. peer_mss = (unsigned int)u_syscall0(SYS_TCP_PEER_MSS);
  718. if (peer_mss < 64 || peer_mss > 1460)
  719. peer_mss = 536;
  720. sha256_init(&transcript);
  721. r = build_client_hello(sni);
  722. if (r <= 0) {
  723. u_puts("tls: bad host name\n");
  724. return -1;
  725. }
  726. n = (unsigned int)r;
  727. sha256_update(&transcript, ch_buf, n);
  728. if (send_plain(22, ch_buf, n) != 0) {
  729. u_puts("tls: send failed\n");
  730. return -1;
  731. }
  732. {
  733. static const unsigned char ccs[1] = { 1 };
  734. send_plain(20, ccs, 1); /* middlebox compatibility */
  735. }
  736. u_puts("tls: client hello sent (");
  737. u_putdec(n);
  738. u_puts(" bytes)\n");
  739. deadline = u_ticks_ms() + TLS_HS_DEADLINE_MS;
  740. while (phase != 2 && !err && !eof) {
  741. if (pump_record(deadline) != 0)
  742. break;
  743. }
  744. if (phase != 2) {
  745. u_puts("tls: handshake failed");
  746. if (err == 4)
  747. u_puts(" (server does not support TLS 1.3)");
  748. else if (err == 2)
  749. u_puts(" (timeout)");
  750. else if (err == 1)
  751. u_puts(" (connection reset)");
  752. else if (eof)
  753. u_puts(" (connection closed)");
  754. u_putc('\n');
  755. return -1;
  756. }
  757. u_puts("tls: handshake done\n");
  758. return 0;
  759. }
  760. int tls_send(const void *buf, unsigned int len)
  761. {
  762. if (phase != 2 || len == 0 || len > TLS_APP_CHUNK)
  763. return -1;
  764. return send_record(23, buf, len, 0);
  765. }
  766. int tls_recv(void *buf, unsigned int max, unsigned int timeout_ms)
  767. {
  768. unsigned char *out = buf;
  769. unsigned int deadline = u_ticks_ms() + timeout_ms;
  770. for (;;) {
  771. unsigned int i, n;
  772. if (app_len) {
  773. n = app_len - app_off;
  774. if (n > max)
  775. n = max;
  776. for (i = 0; i < n; i++)
  777. out[i] = rec_pt[app_off + i];
  778. app_off += n;
  779. if (app_off == app_len)
  780. app_len = 0;
  781. return (int)n;
  782. }
  783. if (eof)
  784. return 0;
  785. if (err)
  786. return (err == 2) ? -1 : -2;
  787. if ((int)(u_ticks_ms() - deadline) >= 0)
  788. return -1;
  789. if (pump_record(deadline) != 0) {
  790. if (eof)
  791. return 0;
  792. return (err == 2) ? -1 : -2;
  793. }
  794. }
  795. }
  796. void tls_close(void)
  797. {
  798. static const unsigned char cn[2] = { 1, 0 };
  799. if (phase == 2 && !err && !eof)
  800. send_record(21, cn, 2, 0);
  801. }