tls.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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 (phase == 0) {
  527. if (hdr[0] != 22 || len > TLS_SH_MAX) {
  528. err = 3;
  529. return -1;
  530. }
  531. if (raw_read(sh_buf, len, deadline) != 0)
  532. return -1;
  533. for (i = 0; i < len && !err; i++)
  534. hs_byte(sh_buf[i]);
  535. return 0;
  536. }
  537. if (hdr[0] != 23 || len < 17 || len > TLS_REC_PT_MAX) {
  538. err = 3;
  539. return -1;
  540. }
  541. {
  542. const unsigned char *key = (phase == 1) ? s_hs_key : s_ap_key;
  543. const unsigned char *iv = (phase == 1) ? s_hs_iv : s_ap_iv;
  544. struct aead_open_ctx a;
  545. unsigned char nonce[12];
  546. unsigned int ptlen = len - 16, off = 0;
  547. nonce_for(nonce, iv, rx_seq);
  548. aead_open_init(&a, key, nonce, hdr, 5);
  549. while (off < ptlen) {
  550. unsigned int n = ptlen - off;
  551. if (n > 1024)
  552. n = 1024;
  553. if (raw_read(rec_pt + off, n, deadline) != 0)
  554. return -1;
  555. aead_open_update(&a, rec_pt + off, rec_pt + off, n);
  556. off += n;
  557. }
  558. if (raw_read(tag, 16, deadline) != 0)
  559. return -1;
  560. aead_open_tag(&a, expect);
  561. for (i = 0; i < 16; i++) {
  562. if (tag[i] != expect[i]) {
  563. u_puts("tls: record authentication failed\n");
  564. err = 5;
  565. return -1;
  566. }
  567. }
  568. rx_seq++;
  569. inner_process(ptlen);
  570. }
  571. return 0;
  572. }
  573. /* ---- ClientHello ---- */
  574. static unsigned char ch_buf[512];
  575. static unsigned int ch_n;
  576. static int ch_over;
  577. static void ch_u8(unsigned int v)
  578. {
  579. if (ch_n < sizeof(ch_buf))
  580. ch_buf[ch_n++] = (unsigned char)v;
  581. else
  582. ch_over = 1;
  583. }
  584. static void ch_u16(unsigned int v)
  585. {
  586. ch_u8(v >> 8);
  587. ch_u8(v);
  588. }
  589. static void ch_u24(unsigned int v)
  590. {
  591. ch_u8(v >> 16);
  592. ch_u8(v >> 8);
  593. ch_u8(v);
  594. }
  595. static void ch_bytes(const void *p, unsigned int n)
  596. {
  597. const unsigned char *b = p;
  598. while (n--)
  599. ch_u8(*b++);
  600. }
  601. static int build_client_hello(const char *sni)
  602. {
  603. unsigned char cr[32], sid[32], pub[32];
  604. unsigned int hostlen = 0, ext_pos, ext_start;
  605. while (sni[hostlen])
  606. hostlen++;
  607. if (hostlen == 0 || hostlen > 200)
  608. return -1;
  609. ch_n = 0;
  610. ch_over = 0;
  611. ch_u8(1); /* client_hello */
  612. ch_u24(0); /* length (patched below) */
  613. ch_u16(0x0303); /* legacy_version */
  614. tls_random(cr, 32);
  615. ch_bytes(cr, 32);
  616. tls_random(sid, 32);
  617. ch_u8(32); /* legacy_session_id */
  618. ch_bytes(sid, 32);
  619. ch_u16(2); /* cipher suites */
  620. ch_u16(0x1303);
  621. ch_u8(1); /* compression */
  622. ch_u8(0);
  623. ext_pos = ch_n;
  624. ch_u16(0); /* extensions length (patched) */
  625. ext_start = ch_n;
  626. /* supported_versions */
  627. ch_u16(0x002b);
  628. ch_u16(3);
  629. ch_u8(2);
  630. ch_u16(0x0304);
  631. /* supported_groups */
  632. ch_u16(0x000a);
  633. ch_u16(4);
  634. ch_u16(2);
  635. ch_u16(0x001d);
  636. /* signature_algorithms (unused in phase A, syntactically required) */
  637. ch_u16(0x000d);
  638. ch_u16(6);
  639. ch_u16(4);
  640. ch_u16(0x0804);
  641. ch_u16(0x0403);
  642. /* key_share */
  643. tls_random(x_priv, 32);
  644. x25519(pub, x_priv, x25519_base_point);
  645. ch_u16(0x0033);
  646. ch_u16(38);
  647. ch_u16(36);
  648. ch_u16(0x001d);
  649. ch_u16(32);
  650. ch_bytes(pub, 32);
  651. /* server_name */
  652. ch_u16(0x0000);
  653. ch_u16(2 + 1 + 2 + hostlen);
  654. ch_u16(1 + 2 + hostlen);
  655. ch_u8(0);
  656. ch_u16(hostlen);
  657. ch_bytes(sni, hostlen);
  658. /* application_layer_protocol_negotiation: http/1.1 */
  659. ch_u16(0x0010);
  660. ch_u16(2 + 1 + 8);
  661. ch_u16(1 + 8);
  662. ch_u8(8);
  663. ch_bytes("http/1.1", 8);
  664. if (ch_over)
  665. return -1;
  666. ch_buf[ext_pos] = (unsigned char)((ch_n - ext_start) >> 8);
  667. ch_buf[ext_pos + 1] = (unsigned char)(ch_n - ext_start);
  668. ch_buf[1] = (unsigned char)((ch_n - 4) >> 16);
  669. ch_buf[2] = (unsigned char)((ch_n - 4) >> 8);
  670. ch_buf[3] = (unsigned char)(ch_n - 4);
  671. return (int)ch_n;
  672. }
  673. /* ---- public API ---- */
  674. int tls_connect(const char *sni)
  675. {
  676. unsigned int n;
  677. unsigned int deadline;
  678. int r;
  679. phase = 0;
  680. rx_seq = tx_seq = 0;
  681. raw_len = raw_pos = 0;
  682. app_off = app_len = 0;
  683. eof = err = 0;
  684. hm_got = 0;
  685. cert_stage = cert_seen = 0;
  686. cert_hdr_got = 0;
  687. peer_mss = (unsigned int)u_syscall0(SYS_TCP_PEER_MSS);
  688. if (peer_mss < 64 || peer_mss > 1460)
  689. peer_mss = 536;
  690. sha256_init(&transcript);
  691. r = build_client_hello(sni);
  692. if (r <= 0) {
  693. u_puts("tls: bad host name\n");
  694. return -1;
  695. }
  696. n = (unsigned int)r;
  697. sha256_update(&transcript, ch_buf, n);
  698. if (send_plain(22, ch_buf, n) != 0) {
  699. u_puts("tls: send failed\n");
  700. return -1;
  701. }
  702. {
  703. static const unsigned char ccs[1] = { 1 };
  704. send_plain(20, ccs, 1); /* middlebox compatibility */
  705. }
  706. u_puts("tls: client hello sent (");
  707. u_putdec(n);
  708. u_puts(" bytes)\n");
  709. deadline = u_ticks_ms() + TLS_HS_DEADLINE_MS;
  710. while (phase != 2 && !err && !eof) {
  711. if (pump_record(deadline) != 0)
  712. break;
  713. }
  714. if (phase != 2) {
  715. u_puts("tls: handshake failed");
  716. if (err == 4)
  717. u_puts(" (server does not support TLS 1.3)");
  718. else if (err == 2)
  719. u_puts(" (timeout)");
  720. else if (err == 1)
  721. u_puts(" (connection reset)");
  722. else if (eof)
  723. u_puts(" (connection closed)");
  724. u_putc('\n');
  725. return -1;
  726. }
  727. u_puts("tls: handshake done\n");
  728. return 0;
  729. }
  730. int tls_send(const void *buf, unsigned int len)
  731. {
  732. if (phase != 2 || len == 0 || len > TLS_APP_CHUNK)
  733. return -1;
  734. return send_record(23, buf, len, 0);
  735. }
  736. int tls_recv(void *buf, unsigned int max, unsigned int timeout_ms)
  737. {
  738. unsigned char *out = buf;
  739. unsigned int deadline = u_ticks_ms() + timeout_ms;
  740. for (;;) {
  741. unsigned int i, n;
  742. if (app_len) {
  743. n = app_len - app_off;
  744. if (n > max)
  745. n = max;
  746. for (i = 0; i < n; i++)
  747. out[i] = rec_pt[app_off + i];
  748. app_off += n;
  749. if (app_off == app_len)
  750. app_len = 0;
  751. return (int)n;
  752. }
  753. if (eof)
  754. return 0;
  755. if (err)
  756. return (err == 2) ? -1 : -2;
  757. if ((int)(u_ticks_ms() - deadline) >= 0)
  758. return -1;
  759. if (pump_record(deadline) != 0) {
  760. if (eof)
  761. return 0;
  762. return (err == 2) ? -1 : -2;
  763. }
  764. }
  765. }
  766. void tls_close(void)
  767. {
  768. static const unsigned char cn[2] = { 1, 0 };
  769. if (phase == 2 && !err && !eof)
  770. send_record(21, cn, 2, 0);
  771. }