tls.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. /*
  2. * Copyright (C) 2017 Denys Vlasenko
  3. *
  4. * Licensed under GPLv2, see file LICENSE in this source tree.
  5. */
  6. //config:config TLS
  7. //config: bool #No description makes it a hidden option
  8. //config: default n
  9. //kbuild:lib-$(CONFIG_TLS) += tls.o
  10. //kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
  11. //kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
  12. //kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
  13. //kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
  14. //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
  15. //kbuild:lib-$(CONFIG_TLS) += tls_aes.o
  16. ////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
  17. #include "tls.h"
  18. //Tested against kernel.org:
  19. //TLS 1.2
  20. #define TLS_MAJ 3
  21. #define TLS_MIN 3
  22. //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
  23. //#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
  24. //#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
  25. //^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
  26. //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
  27. //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
  28. //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
  29. //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  30. //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
  31. //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
  32. //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
  33. //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
  34. //#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
  35. //#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE *** select this?
  36. // works against "openssl s_server -cipher NULL"
  37. // and against wolfssl-3.9.10-stable/examples/server/server.c:
  38. //#define CIPHER_ID1 TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
  39. // works against wolfssl-3.9.10-stable/examples/server/server.c
  40. // works for kernel.org
  41. // does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
  42. // getting alert 40 "handshake failure" at once
  43. // with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
  44. // fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-SHA256
  45. // fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-GCM-SHA384
  46. // fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA256
  47. // ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-GCM-SHA256
  48. // ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA
  49. // (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
  50. #define CIPHER_ID1 TLS_RSA_WITH_AES_256_CBC_SHA256 // no SERVER_KEY_EXCHANGE from peer
  51. // Works with "wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.5.tar.xz"
  52. #define CIPHER_ID2 TLS_RSA_WITH_AES_128_CBC_SHA
  53. #define TLS_DEBUG 0
  54. #define TLS_DEBUG_HASH 0
  55. #define TLS_DEBUG_DER 0
  56. #define TLS_DEBUG_FIXED_SECRETS 0
  57. #if 0
  58. # define dump_raw_out(...) dump_hex(__VA_ARGS__)
  59. #else
  60. # define dump_raw_out(...) ((void)0)
  61. #endif
  62. #if 0
  63. # define dump_raw_in(...) dump_hex(__VA_ARGS__)
  64. #else
  65. # define dump_raw_in(...) ((void)0)
  66. #endif
  67. #if TLS_DEBUG
  68. # define dbg(...) fprintf(stderr, __VA_ARGS__)
  69. #else
  70. # define dbg(...) ((void)0)
  71. #endif
  72. #if TLS_DEBUG_DER
  73. # define dbg_der(...) fprintf(stderr, __VA_ARGS__)
  74. #else
  75. # define dbg_der(...) ((void)0)
  76. #endif
  77. #define RECORD_TYPE_CHANGE_CIPHER_SPEC 20 /* 0x14 */
  78. #define RECORD_TYPE_ALERT 21 /* 0x15 */
  79. #define RECORD_TYPE_HANDSHAKE 22 /* 0x16 */
  80. #define RECORD_TYPE_APPLICATION_DATA 23 /* 0x17 */
  81. #define HANDSHAKE_HELLO_REQUEST 0 /* 0x00 */
  82. #define HANDSHAKE_CLIENT_HELLO 1 /* 0x01 */
  83. #define HANDSHAKE_SERVER_HELLO 2 /* 0x02 */
  84. #define HANDSHAKE_HELLO_VERIFY_REQUEST 3 /* 0x03 */
  85. #define HANDSHAKE_NEW_SESSION_TICKET 4 /* 0x04 */
  86. #define HANDSHAKE_CERTIFICATE 11 /* 0x0b */
  87. #define HANDSHAKE_SERVER_KEY_EXCHANGE 12 /* 0x0c */
  88. #define HANDSHAKE_CERTIFICATE_REQUEST 13 /* 0x0d */
  89. #define HANDSHAKE_SERVER_HELLO_DONE 14 /* 0x0e */
  90. #define HANDSHAKE_CERTIFICATE_VERIFY 15 /* 0x0f */
  91. #define HANDSHAKE_CLIENT_KEY_EXCHANGE 16 /* 0x10 */
  92. #define HANDSHAKE_FINISHED 20 /* 0x14 */
  93. #define SSL_NULL_WITH_NULL_NULL 0x0000
  94. #define SSL_RSA_WITH_NULL_MD5 0x0001
  95. #define SSL_RSA_WITH_NULL_SHA 0x0002
  96. #define SSL_RSA_WITH_RC4_128_MD5 0x0004
  97. #define SSL_RSA_WITH_RC4_128_SHA 0x0005
  98. #define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
  99. #define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /* 47 */
  100. #define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
  101. #define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
  102. #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF
  103. #define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
  104. #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
  105. #define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
  106. #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
  107. #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
  108. #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
  109. #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
  110. #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
  111. #define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
  112. #define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
  113. #define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
  114. #define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
  115. #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
  116. #define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
  117. #define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
  118. #define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
  119. #define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
  120. #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
  121. #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
  122. #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
  123. #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
  124. #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /* 49161 */
  125. #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /* 49162 */
  126. #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
  127. #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /* 49171 */
  128. #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /* 49172 */
  129. #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
  130. #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
  131. #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /* 49187 */
  132. #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /* 49188 */
  133. #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
  134. #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
  135. #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /* 49191 */
  136. #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /* 49192 */
  137. #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
  138. #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
  139. /* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
  140. #define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /* 156 */
  141. #define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /* 157 */
  142. #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /* 49195 */
  143. #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /* 49196 */
  144. #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
  145. #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
  146. #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /* 49199 */
  147. #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /* 49200 */
  148. #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
  149. #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
  150. /* Might go to libbb.h */
  151. #define TLS_MAX_CRYPTBLOCK_SIZE 16
  152. #define TLS_MAX_OUTBUF (1 << 14)
  153. enum {
  154. SHA_INSIZE = 64,
  155. SHA1_OUTSIZE = 20,
  156. SHA256_OUTSIZE = 32,
  157. AES_BLOCKSIZE = 16,
  158. AES128_KEYSIZE = 16,
  159. AES256_KEYSIZE = 32,
  160. RSA_PREMASTER_SIZE = 48,
  161. RECHDR_LEN = 5,
  162. /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
  163. OUTBUF_PFX = 8 + AES_BLOCKSIZE, /* header + IV */
  164. OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
  165. // RFC 5246
  166. // | 6.2.1. Fragmentation
  167. // | The record layer fragments information blocks into TLSPlaintext
  168. // | records carrying data in chunks of 2^14 bytes or less. Client
  169. // | message boundaries are not preserved in the record layer (i.e.,
  170. // | multiple client messages of the same ContentType MAY be coalesced
  171. // | into a single TLSPlaintext record, or a single message MAY be
  172. // | fragmented across several records)
  173. // |...
  174. // | length
  175. // | The length (in bytes) of the following TLSPlaintext.fragment.
  176. // | The length MUST NOT exceed 2^14.
  177. // |...
  178. // | 6.2.2. Record Compression and Decompression
  179. // |...
  180. // | Compression must be lossless and may not increase the content length
  181. // | by more than 1024 bytes. If the decompression function encounters a
  182. // | TLSCompressed.fragment that would decompress to a length in excess of
  183. // | 2^14 bytes, it MUST report a fatal decompression failure error.
  184. // |...
  185. // | length
  186. // | The length (in bytes) of the following TLSCompressed.fragment.
  187. // | The length MUST NOT exceed 2^14 + 1024.
  188. // |...
  189. // | 6.2.3. Record Payload Protection
  190. // | The encryption and MAC functions translate a TLSCompressed
  191. // | structure into a TLSCiphertext. The decryption functions reverse
  192. // | the process. The MAC of the record also includes a sequence
  193. // | number so that missing, extra, or repeated messages are
  194. // | detectable.
  195. // |...
  196. // | length
  197. // | The length (in bytes) of the following TLSCiphertext.fragment.
  198. // | The length MUST NOT exceed 2^14 + 2048.
  199. MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
  200. };
  201. struct record_hdr {
  202. uint8_t type;
  203. uint8_t proto_maj, proto_min;
  204. uint8_t len16_hi, len16_lo;
  205. };
  206. struct tls_handshake_data {
  207. /* In bbox, md5/sha1/sha256 ctx's are the same structure */
  208. md5sha_ctx_t handshake_hash_ctx;
  209. uint8_t client_and_server_rand32[2 * 32];
  210. uint8_t master_secret[48];
  211. //TODO: store just the DER key here, parse/use/delete it when sending client key
  212. //this way it will stay key type agnostic here.
  213. psRsaKey_t server_rsa_pub_key;
  214. unsigned saved_client_hello_size;
  215. uint8_t saved_client_hello[1];
  216. };
  217. static unsigned get24be(const uint8_t *p)
  218. {
  219. return 0x100*(0x100*p[0] + p[1]) + p[2];
  220. }
  221. #if TLS_DEBUG
  222. static void dump_hex(const char *fmt, const void *vp, int len)
  223. {
  224. char hexbuf[32 * 1024 + 4];
  225. const uint8_t *p = vp;
  226. bin2hex(hexbuf, (void*)p, len)[0] = '\0';
  227. dbg(fmt, hexbuf);
  228. }
  229. static void dump_tls_record(const void *vp, int len)
  230. {
  231. const uint8_t *p = vp;
  232. while (len > 0) {
  233. unsigned xhdr_len;
  234. if (len < RECHDR_LEN) {
  235. dump_hex("< |%s|\n", p, len);
  236. return;
  237. }
  238. xhdr_len = 0x100*p[3] + p[4];
  239. dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
  240. p += RECHDR_LEN;
  241. len -= RECHDR_LEN;
  242. if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
  243. unsigned len24 = get24be(p + 1);
  244. dbg(" type:%u len24:%u", p[0], len24);
  245. }
  246. if (xhdr_len > len)
  247. xhdr_len = len;
  248. dump_hex(" |%s|\n", p, xhdr_len);
  249. p += xhdr_len;
  250. len -= xhdr_len;
  251. }
  252. }
  253. #else
  254. # define dump_hex(...) ((void)0)
  255. # define dump_tls_record(...) ((void)0)
  256. #endif
  257. void tls_get_random(void *buf, unsigned len)
  258. {
  259. if (len != open_read_close("/dev/urandom", buf, len))
  260. xfunc_die();
  261. }
  262. /* Nondestructively see the current hash value */
  263. static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
  264. {
  265. md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
  266. return sha_end(&ctx_copy, buffer);
  267. }
  268. static ALWAYS_INLINE unsigned get_handshake_hash(tls_state_t *tls, void *buffer)
  269. {
  270. return sha_peek(&tls->hsd->handshake_hash_ctx, buffer);
  271. }
  272. #if !TLS_DEBUG_HASH
  273. # define hash_handshake(tls, fmt, buffer, len) \
  274. hash_handshake(tls, buffer, len)
  275. #endif
  276. static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
  277. {
  278. md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
  279. #if TLS_DEBUG_HASH
  280. {
  281. uint8_t h[TLS_MAX_MAC_SIZE];
  282. dump_hex(fmt, buffer, len);
  283. dbg(" (%u bytes) ", (int)len);
  284. len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
  285. if (len == SHA1_OUTSIZE)
  286. dump_hex("sha1:%s\n", h, len);
  287. else
  288. if (len == SHA256_OUTSIZE)
  289. dump_hex("sha256:%s\n", h, len);
  290. else
  291. dump_hex("sha???:%s\n", h, len);
  292. }
  293. #endif
  294. }
  295. // RFC 2104
  296. // HMAC(key, text) based on a hash H (say, sha256) is:
  297. // ipad = [0x36 x INSIZE]
  298. // opad = [0x5c x INSIZE]
  299. // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
  300. //
  301. // H(key XOR opad) and H(key XOR ipad) can be precomputed
  302. // if we often need HMAC hmac with the same key.
  303. //
  304. // text is often given in disjoint pieces.
  305. typedef struct hmac_precomputed {
  306. md5sha_ctx_t hashed_key_xor_ipad;
  307. md5sha_ctx_t hashed_key_xor_opad;
  308. } hmac_precomputed_t;
  309. static unsigned hmac_sha_precomputed_v(
  310. hmac_precomputed_t *pre,
  311. uint8_t *out,
  312. va_list va)
  313. {
  314. uint8_t *text;
  315. unsigned len;
  316. /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
  317. /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
  318. /* calculate out = H((key XOR ipad) + text) */
  319. while ((text = va_arg(va, uint8_t*)) != NULL) {
  320. unsigned text_size = va_arg(va, unsigned);
  321. md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
  322. }
  323. len = sha_end(&pre->hashed_key_xor_ipad, out);
  324. /* out = H((key XOR opad) + out) */
  325. md5sha_hash(&pre->hashed_key_xor_opad, out, len);
  326. return sha_end(&pre->hashed_key_xor_opad, out);
  327. }
  328. typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
  329. static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
  330. {
  331. uint8_t key_xor_ipad[SHA_INSIZE];
  332. uint8_t key_xor_opad[SHA_INSIZE];
  333. uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
  334. unsigned i;
  335. // "The authentication key can be of any length up to INSIZE, the
  336. // block length of the hash function. Applications that use keys longer
  337. // than INSIZE bytes will first hash the key using H and then use the
  338. // resultant OUTSIZE byte string as the actual key to HMAC."
  339. if (key_size > SHA_INSIZE) {
  340. md5sha_ctx_t ctx;
  341. begin(&ctx);
  342. md5sha_hash(&ctx, key, key_size);
  343. key_size = sha_end(&ctx, tempkey);
  344. }
  345. for (i = 0; i < key_size; i++) {
  346. key_xor_ipad[i] = key[i] ^ 0x36;
  347. key_xor_opad[i] = key[i] ^ 0x5c;
  348. }
  349. for (; i < SHA_INSIZE; i++) {
  350. key_xor_ipad[i] = 0x36;
  351. key_xor_opad[i] = 0x5c;
  352. }
  353. begin(&pre->hashed_key_xor_ipad);
  354. begin(&pre->hashed_key_xor_opad);
  355. md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
  356. md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
  357. }
  358. static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
  359. {
  360. hmac_precomputed_t pre;
  361. va_list va;
  362. unsigned len;
  363. va_start(va, key_size);
  364. hmac_begin(&pre, key, key_size,
  365. (tls->MAC_size == SHA256_OUTSIZE)
  366. ? sha256_begin
  367. : sha1_begin
  368. );
  369. len = hmac_sha_precomputed_v(&pre, out, va);
  370. va_end(va);
  371. return len;
  372. }
  373. static unsigned hmac_sha256(/*tls_state_t *tls,*/ uint8_t *out, uint8_t *key, unsigned key_size, ...)
  374. {
  375. hmac_precomputed_t pre;
  376. va_list va;
  377. unsigned len;
  378. va_start(va, key_size);
  379. hmac_begin(&pre, key, key_size, sha256_begin);
  380. len = hmac_sha_precomputed_v(&pre, out, va);
  381. va_end(va);
  382. return len;
  383. }
  384. // RFC 5246:
  385. // 5. HMAC and the Pseudorandom Function
  386. //...
  387. // In this section, we define one PRF, based on HMAC. This PRF with the
  388. // SHA-256 hash function is used for all cipher suites defined in this
  389. // document and in TLS documents published prior to this document when
  390. // TLS 1.2 is negotiated.
  391. // ^^^^^^^^^^^^^ IMPORTANT!
  392. // PRF uses sha256 regardless of cipher (at least for all ciphers
  393. // defined by RFC5246). It's not sha1 for AES_128_CBC_SHA!
  394. //...
  395. // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
  396. // HMAC_hash(secret, A(2) + seed) +
  397. // HMAC_hash(secret, A(3) + seed) + ...
  398. // where + indicates concatenation.
  399. // A() is defined as:
  400. // A(0) = seed
  401. // A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
  402. // A(i) = HMAC_hash(secret, A(i-1))
  403. // P_hash can be iterated as many times as necessary to produce the
  404. // required quantity of data. For example, if P_SHA256 is being used to
  405. // create 80 bytes of data, it will have to be iterated three times
  406. // (through A(3)), creating 96 bytes of output data; the last 16 bytes
  407. // of the final iteration will then be discarded, leaving 80 bytes of
  408. // output data.
  409. //
  410. // TLS's PRF is created by applying P_hash to the secret as:
  411. //
  412. // PRF(secret, label, seed) = P_<hash>(secret, label + seed)
  413. //
  414. // The label is an ASCII string.
  415. static void prf_hmac_sha256(/*tls_state_t *tls,*/
  416. uint8_t *outbuf, unsigned outbuf_size,
  417. uint8_t *secret, unsigned secret_size,
  418. const char *label,
  419. uint8_t *seed, unsigned seed_size)
  420. {
  421. uint8_t a[TLS_MAX_MAC_SIZE];
  422. uint8_t *out_p = outbuf;
  423. unsigned label_size = strlen(label);
  424. unsigned MAC_size = SHA256_OUTSIZE;
  425. /* In P_hash() calculation, "seed" is "label + seed": */
  426. #define SEED label, label_size, seed, seed_size
  427. #define SECRET secret, secret_size
  428. #define A a, MAC_size
  429. /* A(1) = HMAC_hash(secret, seed) */
  430. hmac_sha256(/*tls,*/ a, SECRET, SEED, NULL);
  431. //TODO: convert hmac to precomputed
  432. for (;;) {
  433. /* HMAC_hash(secret, A(1) + seed) */
  434. if (outbuf_size <= MAC_size) {
  435. /* Last, possibly incomplete, block */
  436. /* (use a[] as temp buffer) */
  437. hmac_sha256(/*tls,*/ a, SECRET, A, SEED, NULL);
  438. memcpy(out_p, a, outbuf_size);
  439. return;
  440. }
  441. /* Not last block. Store directly to result buffer */
  442. hmac_sha256(/*tls,*/ out_p, SECRET, A, SEED, NULL);
  443. out_p += MAC_size;
  444. outbuf_size -= MAC_size;
  445. /* A(2) = HMAC_hash(secret, A(1)) */
  446. hmac_sha256(/*tls,*/ a, SECRET, A, NULL);
  447. }
  448. #undef A
  449. #undef SECRET
  450. #undef SEED
  451. }
  452. static void bad_record_die(tls_state_t *tls, const char *expected, int len)
  453. {
  454. bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
  455. if (len > 0) {
  456. uint8_t *p = tls->inbuf;
  457. if (len > 99)
  458. len = 99; /* don't flood, a few lines should be enough */
  459. do {
  460. fprintf(stderr, " %02x", *p++);
  461. len--;
  462. } while (len != 0);
  463. fputc('\n', stderr);
  464. }
  465. xfunc_die();
  466. }
  467. static void tls_error_die(tls_state_t *tls, int line)
  468. {
  469. dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
  470. bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
  471. }
  472. #define tls_error_die(tls) tls_error_die(tls, __LINE__)
  473. #if 0 //UNUSED
  474. static void tls_free_inbuf(tls_state_t *tls)
  475. {
  476. if (tls->buffered_size == 0) {
  477. free(tls->inbuf);
  478. tls->inbuf_size = 0;
  479. tls->inbuf = NULL;
  480. }
  481. }
  482. #endif
  483. static void tls_free_outbuf(tls_state_t *tls)
  484. {
  485. free(tls->outbuf);
  486. tls->outbuf_size = 0;
  487. tls->outbuf = NULL;
  488. }
  489. static void *tls_get_outbuf(tls_state_t *tls, int len)
  490. {
  491. if (len > TLS_MAX_OUTBUF)
  492. xfunc_die();
  493. len += OUTBUF_PFX + OUTBUF_SFX;
  494. if (tls->outbuf_size < len) {
  495. tls->outbuf_size = len;
  496. tls->outbuf = xrealloc(tls->outbuf, len);
  497. }
  498. return tls->outbuf + OUTBUF_PFX;
  499. }
  500. static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
  501. {
  502. uint8_t *buf = tls->outbuf + OUTBUF_PFX;
  503. struct record_hdr *xhdr;
  504. uint8_t padding_length;
  505. xhdr = (void*)(buf - RECHDR_LEN);
  506. if (CIPHER_ID1 != TLS_RSA_WITH_NULL_SHA256 /* if "no encryption" can't be selected */
  507. || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
  508. ) {
  509. xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
  510. }
  511. xhdr->type = type;
  512. xhdr->proto_maj = TLS_MAJ;
  513. xhdr->proto_min = TLS_MIN;
  514. /* fake unencrypted record len for MAC calculation */
  515. xhdr->len16_hi = size >> 8;
  516. xhdr->len16_lo = size & 0xff;
  517. /* Calculate MAC signature */
  518. hmac(tls, buf + size, /* result */
  519. tls->client_write_MAC_key, tls->MAC_size,
  520. &tls->write_seq64_be, sizeof(tls->write_seq64_be),
  521. xhdr, RECHDR_LEN,
  522. buf, size,
  523. NULL
  524. );
  525. tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
  526. size += tls->MAC_size;
  527. // RFC 5246
  528. // 6.2.3.1. Null or Standard Stream Cipher
  529. //
  530. // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
  531. // convert TLSCompressed.fragment structures to and from stream
  532. // TLSCiphertext.fragment structures.
  533. //
  534. // stream-ciphered struct {
  535. // opaque content[TLSCompressed.length];
  536. // opaque MAC[SecurityParameters.mac_length];
  537. // } GenericStreamCipher;
  538. //
  539. // The MAC is generated as:
  540. // MAC(MAC_write_key, seq_num +
  541. // TLSCompressed.type +
  542. // TLSCompressed.version +
  543. // TLSCompressed.length +
  544. // TLSCompressed.fragment);
  545. // where "+" denotes concatenation.
  546. // seq_num
  547. // The sequence number for this record.
  548. // MAC
  549. // The MAC algorithm specified by SecurityParameters.mac_algorithm.
  550. //
  551. // Note that the MAC is computed before encryption. The stream cipher
  552. // encrypts the entire block, including the MAC.
  553. //...
  554. // Appendix C. Cipher Suite Definitions
  555. //...
  556. // MAC Algorithm mac_length mac_key_length
  557. // -------- ----------- ---------- --------------
  558. // SHA HMAC-SHA1 20 20
  559. // SHA256 HMAC-SHA256 32 32
  560. if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
  561. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  562. ) {
  563. /* No encryption, only signing */
  564. xhdr->len16_hi = size >> 8;
  565. xhdr->len16_lo = size & 0xff;
  566. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  567. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  568. dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
  569. return;
  570. }
  571. // 6.2.3.2. CBC Block Cipher
  572. // For block ciphers (such as 3DES or AES), the encryption and MAC
  573. // functions convert TLSCompressed.fragment structures to and from block
  574. // TLSCiphertext.fragment structures.
  575. // struct {
  576. // opaque IV[SecurityParameters.record_iv_length];
  577. // block-ciphered struct {
  578. // opaque content[TLSCompressed.length];
  579. // opaque MAC[SecurityParameters.mac_length];
  580. // uint8 padding[GenericBlockCipher.padding_length];
  581. // uint8 padding_length;
  582. // };
  583. // } GenericBlockCipher;
  584. //...
  585. // IV
  586. // The Initialization Vector (IV) SHOULD be chosen at random, and
  587. // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
  588. // there was no IV field (...). For block ciphers, the IV length is
  589. // of length SecurityParameters.record_iv_length, which is equal to the
  590. // SecurityParameters.block_size.
  591. // padding
  592. // Padding that is added to force the length of the plaintext to be
  593. // an integral multiple of the block cipher's block length.
  594. // padding_length
  595. // The padding length MUST be such that the total size of the
  596. // GenericBlockCipher structure is a multiple of the cipher's block
  597. // length. Legal values range from zero to 255, inclusive.
  598. //...
  599. // Appendix C. Cipher Suite Definitions
  600. //...
  601. // Key IV Block
  602. // Cipher Type Material Size Size
  603. // ------------ ------ -------- ---- -----
  604. // AES_128_CBC Block 16 16 16
  605. // AES_256_CBC Block 32 16 16
  606. tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
  607. dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
  608. size - tls->MAC_size, tls->MAC_size);
  609. /* Fill IV and padding in outbuf */
  610. // RFC is talking nonsense:
  611. // "Padding that is added to force the length of the plaintext to be
  612. // an integral multiple of the block cipher's block length."
  613. // WRONG. _padding+padding_length_, not just _padding_,
  614. // pads the data.
  615. // IOW: padding_length is the last byte of padding[] array,
  616. // contrary to what RFC depicts.
  617. //
  618. // What actually happens is that there is always padding.
  619. // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
  620. // If you need two bytes, they are both 0x01.
  621. // If you need three, they are 0x02,0x02,0x02. And so on.
  622. // If you need no bytes to reach BLOCKSIZE, you have to pad a full
  623. // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
  624. // It's ok to have more than minimum padding, but we do minimum.
  625. padding_length = (~size) & (AES_BLOCKSIZE - 1);
  626. do {
  627. buf[size++] = padding_length; /* padding */
  628. } while ((size & (AES_BLOCKSIZE - 1)) != 0);
  629. /* Encrypt content+MAC+padding in place */
  630. aes_cbc_encrypt(
  631. tls->client_write_key, tls->key_size, /* selects 128/256 */
  632. buf - AES_BLOCKSIZE, /* IV */
  633. buf, size, /* plaintext */
  634. buf /* ciphertext */
  635. );
  636. /* Write out */
  637. dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
  638. AES_BLOCKSIZE, size, padding_length);
  639. size += AES_BLOCKSIZE; /* + IV */
  640. xhdr->len16_hi = size >> 8;
  641. xhdr->len16_lo = size & 0xff;
  642. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  643. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  644. dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
  645. }
  646. static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
  647. {
  648. //if (!tls->encrypt_on_write) {
  649. uint8_t *buf = tls->outbuf + OUTBUF_PFX;
  650. struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
  651. xhdr->type = RECORD_TYPE_HANDSHAKE;
  652. xhdr->proto_maj = TLS_MAJ;
  653. xhdr->proto_min = TLS_MIN;
  654. xhdr->len16_hi = size >> 8;
  655. xhdr->len16_lo = size & 0xff;
  656. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  657. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  658. dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
  659. // return;
  660. //}
  661. //xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
  662. }
  663. static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
  664. {
  665. if (!tls->encrypt_on_write) {
  666. uint8_t *buf;
  667. xwrite_handshake_record(tls, size);
  668. /* Handshake hash does not include record headers */
  669. buf = tls->outbuf + OUTBUF_PFX;
  670. hash_handshake(tls, ">> hash:%s", buf, size);
  671. return;
  672. }
  673. xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
  674. }
  675. static int tls_has_buffered_record(tls_state_t *tls)
  676. {
  677. int buffered = tls->buffered_size;
  678. struct record_hdr *xhdr;
  679. int rec_size;
  680. if (buffered < RECHDR_LEN)
  681. return 0;
  682. xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
  683. rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  684. if (buffered < rec_size)
  685. return 0;
  686. return rec_size;
  687. }
  688. static const char *alert_text(int code)
  689. {
  690. switch (code) {
  691. case 20: return "bad MAC";
  692. case 50: return "decode error";
  693. case 51: return "decrypt error";
  694. case 40: return "handshake failure";
  695. case 112: return "unrecognized name";
  696. }
  697. return itoa(code);
  698. }
  699. static int tls_xread_record(tls_state_t *tls, const char *expected)
  700. {
  701. struct record_hdr *xhdr;
  702. int sz;
  703. int total;
  704. int target;
  705. again:
  706. dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
  707. total = tls->buffered_size;
  708. if (total != 0) {
  709. memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
  710. //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
  711. //dump_raw_in("<< %s\n", tls->inbuf, total);
  712. }
  713. errno = 0;
  714. target = MAX_INBUF;
  715. for (;;) {
  716. int rem;
  717. if (total >= RECHDR_LEN && target == MAX_INBUF) {
  718. xhdr = (void*)tls->inbuf;
  719. target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  720. if (target > MAX_INBUF /* malformed input (too long) */
  721. || xhdr->proto_maj != TLS_MAJ
  722. || xhdr->proto_min != TLS_MIN
  723. ) {
  724. sz = total < target ? total : target;
  725. if (sz > 24)
  726. sz = 24; /* don't flood */
  727. bad_record_die(tls, expected, sz);
  728. }
  729. dbg("xhdr type:%d ver:%d.%d len:%d\n",
  730. xhdr->type, xhdr->proto_maj, xhdr->proto_min,
  731. 0x100 * xhdr->len16_hi + xhdr->len16_lo
  732. );
  733. }
  734. /* if total >= target, we have a full packet (and possibly more)... */
  735. if (total - target >= 0)
  736. break;
  737. /* input buffer is grown only as needed */
  738. rem = tls->inbuf_size - total;
  739. if (rem == 0) {
  740. tls->inbuf_size += MAX_INBUF / 8;
  741. if (tls->inbuf_size > MAX_INBUF)
  742. tls->inbuf_size = MAX_INBUF;
  743. dbg("inbuf_size:%d\n", tls->inbuf_size);
  744. rem = tls->inbuf_size - total;
  745. tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
  746. }
  747. sz = safe_read(tls->ifd, tls->inbuf + total, rem);
  748. if (sz <= 0) {
  749. if (sz == 0 && total == 0) {
  750. /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
  751. dbg("EOF (without TLS shutdown) from peer\n");
  752. tls->buffered_size = 0;
  753. goto end;
  754. }
  755. bb_perror_msg_and_die("short read, have only %d", total);
  756. }
  757. dump_raw_in("<< %s\n", tls->inbuf + total, sz);
  758. total += sz;
  759. }
  760. tls->buffered_size = total - target;
  761. tls->ofs_to_buffered = target;
  762. //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
  763. //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
  764. sz = target - RECHDR_LEN;
  765. /* Needs to be decrypted? */
  766. if (tls->min_encrypted_len_on_read > tls->MAC_size) {
  767. uint8_t *p = tls->inbuf + RECHDR_LEN;
  768. int padding_len;
  769. if (sz & (AES_BLOCKSIZE-1)
  770. || sz < (int)tls->min_encrypted_len_on_read
  771. ) {
  772. bb_error_msg_and_die("bad encrypted len:%u < %u",
  773. sz, tls->min_encrypted_len_on_read);
  774. }
  775. /* Decrypt content+MAC+padding, moving it over IV in the process */
  776. sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
  777. aes_cbc_decrypt(
  778. tls->server_write_key, tls->key_size, /* selects 128/256 */
  779. p, /* IV */
  780. p + AES_BLOCKSIZE, sz, /* ciphertext */
  781. p /* plaintext */
  782. );
  783. padding_len = p[sz - 1];
  784. dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
  785. padding_len++;
  786. sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
  787. //if (sz < 0)
  788. // bb_error_msg_and_die("bad padding size:%u", padding_len);
  789. } else {
  790. /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
  791. /* else: no encryption yet on input, subtract zero = NOP */
  792. sz -= tls->min_encrypted_len_on_read;
  793. }
  794. if (sz < 0)
  795. bb_error_msg_and_die("encrypted data too short");
  796. //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
  797. xhdr = (void*)tls->inbuf;
  798. if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
  799. uint8_t *p = tls->inbuf + RECHDR_LEN;
  800. dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
  801. if (p[0] == 2) { /* fatal */
  802. bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
  803. "error",
  804. p[1], alert_text(p[1])
  805. );
  806. }
  807. if (p[0] == 1) { /* warning */
  808. if (p[1] == 0) { /* "close_notify" warning: it's EOF */
  809. dbg("EOF (TLS encoded) from peer\n");
  810. sz = 0;
  811. goto end;
  812. }
  813. //This possibly needs to be cached and shown only if
  814. //a fatal alert follows
  815. // bb_error_msg("TLS %s from peer (alert code %d): %s",
  816. // "warning",
  817. // p[1], alert_text(p[1])
  818. // );
  819. /* discard it, get next record */
  820. goto again;
  821. }
  822. /* p[0] not 1 or 2: not defined in protocol */
  823. sz = 0;
  824. goto end;
  825. }
  826. /* RFC 5246 is not saying it explicitly, but sha256 hash
  827. * in our FINISHED record must include data of incoming packets too!
  828. */
  829. if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
  830. && tls->MAC_size != 0 /* do we know which hash to use? (server_hello() does not!) */
  831. ) {
  832. hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
  833. }
  834. end:
  835. dbg("got block len:%u\n", sz);
  836. return sz;
  837. }
  838. /*
  839. * DER parsing routines
  840. */
  841. static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
  842. {
  843. unsigned len, len1;
  844. if (end - der < 2)
  845. xfunc_die();
  846. // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
  847. // xfunc_die();
  848. len = der[1]; /* maybe it's short len */
  849. if (len >= 0x80) {
  850. /* no, it's long */
  851. if (len == 0x80 || end - der < (int)(len - 0x7e)) {
  852. /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
  853. /* need 3 or 4 bytes for 81, 82 */
  854. xfunc_die();
  855. }
  856. len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
  857. if (len > 0x82) {
  858. /* >0x82 is "3+ bytes of len", should not happen realistically */
  859. xfunc_die();
  860. }
  861. if (len == 0x82) { /* it's "ii 82 xx yy" */
  862. len1 = 0x100*len1 + der[3];
  863. der += 1; /* skip [yy] */
  864. }
  865. der += 1; /* skip [xx] */
  866. len = len1;
  867. // if (len < 0x80)
  868. // xfunc_die(); /* invalid DER: must use short len if can */
  869. }
  870. der += 2; /* skip [code]+[1byte] */
  871. if (end - der < (int)len)
  872. xfunc_die();
  873. *bodyp = der;
  874. return len;
  875. }
  876. static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
  877. {
  878. uint8_t *new_der;
  879. unsigned len = get_der_len(&new_der, der, *endp);
  880. dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
  881. /* Move "end" position to cover only this item */
  882. *endp = new_der + len;
  883. return new_der;
  884. }
  885. static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
  886. {
  887. uint8_t *new_der;
  888. unsigned len = get_der_len(&new_der, der, end);
  889. /* Skip body */
  890. new_der += len;
  891. dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
  892. return new_der;
  893. }
  894. static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
  895. {
  896. uint8_t *bin_ptr;
  897. unsigned len = get_der_len(&bin_ptr, der, end);
  898. dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
  899. pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
  900. pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
  901. //return bin + len;
  902. }
  903. static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
  904. {
  905. /* Certificate is a DER-encoded data structure. Each DER element has a length,
  906. * which makes it easy to skip over large compound elements of any complexity
  907. * without parsing them. Example: partial decode of kernel.org certificate:
  908. * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
  909. * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
  910. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
  911. * INTEGER (version): 0201 02
  912. * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
  913. * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
  914. * SEQ 0x0d bytes (signatureAlgo): 300d
  915. * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
  916. * NULL: 0500
  917. * SEQ 0x5f bytes (issuer): 305f
  918. * SET 11 bytes: 310b
  919. * SEQ 9 bytes: 3009
  920. * OID 3 bytes: 0603 550406
  921. * Printable string "FR": 1302 4652
  922. * SET 14 bytes: 310e
  923. * SEQ 12 bytes: 300c
  924. * OID 3 bytes: 0603 550408
  925. * Printable string "Paris": 1305 5061726973
  926. * SET 14 bytes: 310e
  927. * SEQ 12 bytes: 300c
  928. * OID 3 bytes: 0603 550407
  929. * Printable string "Paris": 1305 5061726973
  930. * SET 14 bytes: 310e
  931. * SEQ 12 bytes: 300c
  932. * OID 3 bytes: 0603 55040a
  933. * Printable string "Gandi": 1305 47616e6469
  934. * SET 32 bytes: 3120
  935. * SEQ 30 bytes: 301e
  936. * OID 3 bytes: 0603 550403
  937. * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
  938. * SEQ 30 bytes (validity): 301e
  939. * TIME "161011000000Z": 170d 3136313031313030303030305a
  940. * TIME "191011235959Z": 170d 3139313031313233353935395a
  941. * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
  942. * 3121301f060355040b1318446f6d61696e20436f
  943. * 6e74726f6c2056616c6964617465643121301f06
  944. * 0355040b1318506f73697469766553534c204d75
  945. * 6c74692d446f6d61696e31133011060355040313
  946. * 0a6b65726e656c2e6f7267
  947. * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
  948. * SEQ 13 bytes (algorithm): 300d
  949. * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
  950. * NULL: 0500
  951. * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
  952. * ????: 00
  953. * //after the zero byte, it appears key itself uses DER encoding:
  954. * SEQ 0x018a/394 bytes: 3082018a
  955. * INTEGER 0x0181/385 bytes (modulus): 02820181
  956. * 00b1ab2fc727a3bef76780c9349bf3
  957. * ...24 more blocks of 15 bytes each...
  958. * 90e895291c6bc8693b65
  959. * INTEGER 3 bytes (exponent): 0203 010001
  960. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
  961. * SEQ 0x01e1 bytes: 308201e1
  962. * ...
  963. * Certificate is a sequence of three elements:
  964. * tbsCertificate (SEQ)
  965. * signatureAlgorithm (AlgorithmIdentifier)
  966. * signatureValue (BIT STRING)
  967. *
  968. * In turn, tbsCertificate is a sequence of:
  969. * version
  970. * serialNumber
  971. * signatureAlgo (AlgorithmIdentifier)
  972. * issuer (Name, has complex structure)
  973. * validity (Validity, SEQ of two Times)
  974. * subject (Name)
  975. * subjectPublicKeyInfo (SEQ)
  976. * ...
  977. *
  978. * subjectPublicKeyInfo is a sequence of:
  979. * algorithm (AlgorithmIdentifier)
  980. * publicKey (BIT STRING)
  981. *
  982. * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
  983. */
  984. uint8_t *end = der + len;
  985. /* enter "Certificate" item: [der, end) will be only Cert */
  986. der = enter_der_item(der, &end);
  987. /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
  988. der = enter_der_item(der, &end);
  989. /* skip up to subjectPublicKeyInfo */
  990. der = skip_der_item(der, end); /* version */
  991. der = skip_der_item(der, end); /* serialNumber */
  992. der = skip_der_item(der, end); /* signatureAlgo */
  993. der = skip_der_item(der, end); /* issuer */
  994. der = skip_der_item(der, end); /* validity */
  995. der = skip_der_item(der, end); /* subject */
  996. /* enter subjectPublicKeyInfo */
  997. der = enter_der_item(der, &end);
  998. { /* check subjectPublicKeyInfo.algorithm */
  999. static const uint8_t expected[] = {
  1000. 0x30,0x0d, // SEQ 13 bytes
  1001. 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
  1002. //0x05,0x00, // NULL
  1003. };
  1004. if (memcmp(der, expected, sizeof(expected)) != 0)
  1005. bb_error_msg_and_die("not RSA key");
  1006. }
  1007. /* skip subjectPublicKeyInfo.algorithm */
  1008. der = skip_der_item(der, end);
  1009. /* enter subjectPublicKeyInfo.publicKey */
  1010. // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
  1011. der = enter_der_item(der, &end);
  1012. /* parse RSA key: */
  1013. //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
  1014. dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
  1015. if (end - der < 14) xfunc_die();
  1016. /* example format:
  1017. * ignore bits: 00
  1018. * SEQ 0x018a/394 bytes: 3082018a
  1019. * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
  1020. * INTEGER 3 bytes (exponent): 0203 010001
  1021. */
  1022. if (*der != 0) /* "ignore bits", should be 0 */
  1023. xfunc_die();
  1024. der++;
  1025. der = enter_der_item(der, &end); /* enter SEQ */
  1026. /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
  1027. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
  1028. der = skip_der_item(der, end);
  1029. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
  1030. tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
  1031. dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
  1032. }
  1033. /*
  1034. * TLS Handshake routines
  1035. */
  1036. static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
  1037. {
  1038. struct record_hdr *xhdr;
  1039. int len = tls_xread_record(tls, "handshake record");
  1040. xhdr = (void*)tls->inbuf;
  1041. if (len < min_len
  1042. || xhdr->type != RECORD_TYPE_HANDSHAKE
  1043. ) {
  1044. bad_record_die(tls, "handshake record", len);
  1045. }
  1046. dbg("got HANDSHAKE\n");
  1047. return len;
  1048. }
  1049. static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
  1050. {
  1051. struct handshake_hdr {
  1052. uint8_t type;
  1053. uint8_t len24_hi, len24_mid, len24_lo;
  1054. } *h = buf;
  1055. len -= 4;
  1056. h->type = type;
  1057. h->len24_hi = len >> 16;
  1058. h->len24_mid = len >> 8;
  1059. h->len24_lo = len & 0xff;
  1060. }
  1061. static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
  1062. {
  1063. struct client_hello {
  1064. uint8_t type;
  1065. uint8_t len24_hi, len24_mid, len24_lo;
  1066. uint8_t proto_maj, proto_min;
  1067. uint8_t rand32[32];
  1068. uint8_t session_id_len;
  1069. /* uint8_t session_id[]; */
  1070. uint8_t cipherid_len16_hi, cipherid_len16_lo;
  1071. uint8_t cipherid[2 * (2 + !!CIPHER_ID2)]; /* actually variable */
  1072. uint8_t comprtypes_len;
  1073. uint8_t comprtypes[1]; /* actually variable */
  1074. /* Extensions (SNI shown):
  1075. * hi,lo // len of all extensions
  1076. * 00,00 // extension_type: "Server Name"
  1077. * 00,0e // list len (there can be more than one SNI)
  1078. * 00,0c // len of 1st Server Name Indication
  1079. * 00 // name type: host_name
  1080. * 00,09 // name len
  1081. * "localhost" // name
  1082. */
  1083. // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
  1084. // 0055
  1085. // 0005 0005 0100000000 - status_request
  1086. // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
  1087. // ff01 0001 00 - renegotiation_info
  1088. // 0023 0000 - session_ticket
  1089. // 000a 0008 0006001700180019 - supported_groups
  1090. // 000b 0002 0100 - ec_point_formats
  1091. // 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
  1092. // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
  1093. // 0017 0000 - extended master secret
  1094. };
  1095. struct client_hello *record;
  1096. int len;
  1097. int sni_len = sni ? strnlen(sni, 127 - 9) : 0;
  1098. len = sizeof(*record);
  1099. if (sni_len)
  1100. len += 11 + sni_len;
  1101. record = tls_get_outbuf(tls, len);
  1102. memset(record, 0, len);
  1103. fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
  1104. record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
  1105. record->proto_min = TLS_MIN; /* can be higher than one in record headers */
  1106. tls_get_random(record->rand32, sizeof(record->rand32));
  1107. if (TLS_DEBUG_FIXED_SECRETS)
  1108. memset(record->rand32, 0x11, sizeof(record->rand32));
  1109. /* record->session_id_len = 0; - already is */
  1110. /* record->cipherid_len16_hi = 0; */
  1111. record->cipherid_len16_lo = sizeof(record->cipherid);
  1112. /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
  1113. /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
  1114. record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
  1115. if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
  1116. /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
  1117. #if CIPHER_ID2
  1118. if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
  1119. /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
  1120. #endif
  1121. record->comprtypes_len = 1;
  1122. /* record->comprtypes[0] = 0; */
  1123. if (sni_len) {
  1124. uint8_t *p = (void*)(record + 1);
  1125. //p[0] = 0; //
  1126. p[1] = sni_len + 9; //ext_len
  1127. //p[2] = 0; //
  1128. //p[3] = 0; //extension_type
  1129. //p[4] = 0; //
  1130. p[5] = sni_len + 5; //list len
  1131. //p[6] = 0; //
  1132. p[7] = sni_len + 3; //len of 1st SNI
  1133. //p[8] = 0; //name type
  1134. //p[9] = 0; //
  1135. p[10] = sni_len; //name len
  1136. memcpy(&p[11], sni, sni_len);
  1137. }
  1138. dbg(">> CLIENT_HELLO\n");
  1139. /* Can hash it only when we know which MAC hash to use */
  1140. /*xwrite_and_update_handshake_hash(tls, len); - WRONG! */
  1141. xwrite_handshake_record(tls, len);
  1142. tls->hsd = xzalloc(sizeof(*tls->hsd) + len);
  1143. tls->hsd->saved_client_hello_size = len;
  1144. memcpy(tls->hsd->saved_client_hello, record, len);
  1145. memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
  1146. }
  1147. static void get_server_hello(tls_state_t *tls)
  1148. {
  1149. struct server_hello {
  1150. struct record_hdr xhdr;
  1151. uint8_t type;
  1152. uint8_t len24_hi, len24_mid, len24_lo;
  1153. uint8_t proto_maj, proto_min;
  1154. uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
  1155. uint8_t session_id_len;
  1156. uint8_t session_id[32];
  1157. uint8_t cipherid_hi, cipherid_lo;
  1158. uint8_t comprtype;
  1159. /* extensions may follow, but only those which client offered in its Hello */
  1160. };
  1161. struct server_hello *hp;
  1162. uint8_t *cipherid;
  1163. unsigned cipher;
  1164. int len, len24;
  1165. len = tls_xread_handshake_block(tls, 74 - 32);
  1166. hp = (void*)tls->inbuf;
  1167. // 74 bytes:
  1168. // 02 000046 03|03 58|78|cf|c1 50|a5|49|ee|7e|29|48|71|fe|97|fa|e8|2d|19|87|72|90|84|9d|37|a3|f0|cb|6f|5f|e3|3c|2f |20 |d8|1a|78|96|52|d6|91|01|24|b3|d6|5b|b7|d0|6c|b3|e1|78|4e|3c|95|de|74|a0|ba|eb|a7|3a|ff|bd|a2|bf |00|9c |00|
  1169. //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
  1170. if (hp->type != HANDSHAKE_SERVER_HELLO
  1171. || hp->len24_hi != 0
  1172. || hp->len24_mid != 0
  1173. /* hp->len24_lo checked later */
  1174. || hp->proto_maj != TLS_MAJ
  1175. || hp->proto_min != TLS_MIN
  1176. ) {
  1177. bad_record_die(tls, "'server hello'", len);
  1178. }
  1179. cipherid = &hp->cipherid_hi;
  1180. len24 = hp->len24_lo;
  1181. if (hp->session_id_len != 32) {
  1182. if (hp->session_id_len != 0)
  1183. bad_record_die(tls, "'server hello'", len);
  1184. // session_id_len == 0: no session id
  1185. // "The server
  1186. // may return an empty session_id to indicate that the session will
  1187. // not be cached and therefore cannot be resumed."
  1188. cipherid -= 32;
  1189. len24 += 32; /* what len would be if session id would be present */
  1190. }
  1191. if (len24 < 70
  1192. // || cipherid[0] != (CIPHER_ID >> 8)
  1193. // || cipherid[1] != (CIPHER_ID & 0xff)
  1194. // || cipherid[2] != 0 /* comprtype */
  1195. ) {
  1196. bad_record_die(tls, "'server hello'", len);
  1197. }
  1198. dbg("<< SERVER_HELLO\n");
  1199. memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
  1200. tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
  1201. dbg("server chose cipher %04x\n", cipher);
  1202. if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA) {
  1203. tls->key_size = AES128_KEYSIZE;
  1204. tls->MAC_size = SHA1_OUTSIZE;
  1205. }
  1206. else { /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
  1207. tls->key_size = AES256_KEYSIZE;
  1208. tls->MAC_size = SHA256_OUTSIZE;
  1209. }
  1210. /* Handshake hash eventually destined to FINISHED record
  1211. * is sha256 regardless of cipher
  1212. * (at least for all ciphers defined by RFC5246).
  1213. * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
  1214. */
  1215. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1216. hash_handshake(tls, ">> client hello hash:%s",
  1217. tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
  1218. );
  1219. hash_handshake(tls, "<< server hello hash:%s",
  1220. tls->inbuf + RECHDR_LEN, len
  1221. );
  1222. }
  1223. static void get_server_cert(tls_state_t *tls)
  1224. {
  1225. struct record_hdr *xhdr;
  1226. uint8_t *certbuf;
  1227. int len, len1;
  1228. len = tls_xread_handshake_block(tls, 10);
  1229. xhdr = (void*)tls->inbuf;
  1230. certbuf = (void*)(xhdr + 1);
  1231. if (certbuf[0] != HANDSHAKE_CERTIFICATE)
  1232. bad_record_die(tls, "certificate", len);
  1233. dbg("<< CERTIFICATE\n");
  1234. // 4392 bytes:
  1235. // 0b 00|11|24 00|11|21 00|05|b0 30|82|05|ac|30|82|04|94|a0|03|02|01|02|02|11|00|9f|85|bf|66|4b|0c|dd|af|ca|50|86|79|50|1b|2b|e4|30|0d...
  1236. //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
  1237. len1 = get24be(certbuf + 1);
  1238. if (len1 > len - 4) tls_error_die(tls);
  1239. len = len1;
  1240. len1 = get24be(certbuf + 4);
  1241. if (len1 > len - 3) tls_error_die(tls);
  1242. len = len1;
  1243. len1 = get24be(certbuf + 7);
  1244. if (len1 > len - 3) tls_error_die(tls);
  1245. len = len1;
  1246. if (len)
  1247. find_key_in_der_cert(tls, certbuf + 10, len);
  1248. }
  1249. static void send_empty_client_cert(tls_state_t *tls)
  1250. {
  1251. struct client_empty_cert {
  1252. uint8_t type;
  1253. uint8_t len24_hi, len24_mid, len24_lo;
  1254. uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
  1255. };
  1256. struct client_empty_cert *record;
  1257. record = tls_get_outbuf(tls, sizeof(*record));
  1258. //FIXME: can just memcpy a ready-made one.
  1259. fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
  1260. record->cert_chain_len24_hi = 0;
  1261. record->cert_chain_len24_mid = 0;
  1262. record->cert_chain_len24_lo = 0;
  1263. dbg(">> CERTIFICATE\n");
  1264. xwrite_and_update_handshake_hash(tls, sizeof(*record));
  1265. }
  1266. static void send_client_key_exchange(tls_state_t *tls)
  1267. {
  1268. struct client_key_exchange {
  1269. uint8_t type;
  1270. uint8_t len24_hi, len24_mid, len24_lo;
  1271. /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
  1272. uint8_t keylen16_hi, keylen16_lo;
  1273. uint8_t key[4 * 1024]; // size??
  1274. };
  1275. //FIXME: better size estimate
  1276. struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
  1277. uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
  1278. int len;
  1279. tls_get_random(rsa_premaster, sizeof(rsa_premaster));
  1280. if (TLS_DEBUG_FIXED_SECRETS)
  1281. memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
  1282. // RFC 5246
  1283. // "Note: The version number in the PreMasterSecret is the version
  1284. // offered by the client in the ClientHello.client_version, not the
  1285. // version negotiated for the connection."
  1286. rsa_premaster[0] = TLS_MAJ;
  1287. rsa_premaster[1] = TLS_MIN;
  1288. dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
  1289. len = psRsaEncryptPub(/*pool:*/ NULL,
  1290. /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
  1291. rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
  1292. record->key, sizeof(record->key),
  1293. data_param_ignored
  1294. );
  1295. record->keylen16_hi = len >> 8;
  1296. record->keylen16_lo = len & 0xff;
  1297. len += 2;
  1298. record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
  1299. record->len24_hi = 0;
  1300. record->len24_mid = len >> 8;
  1301. record->len24_lo = len & 0xff;
  1302. len += 4;
  1303. dbg(">> CLIENT_KEY_EXCHANGE\n");
  1304. xwrite_and_update_handshake_hash(tls, len);
  1305. // RFC 5246
  1306. // For all key exchange methods, the same algorithm is used to convert
  1307. // the pre_master_secret into the master_secret. The pre_master_secret
  1308. // should be deleted from memory once the master_secret has been
  1309. // computed.
  1310. // master_secret = PRF(pre_master_secret, "master secret",
  1311. // ClientHello.random + ServerHello.random)
  1312. // [0..47];
  1313. // The master secret is always exactly 48 bytes in length. The length
  1314. // of the premaster secret will vary depending on key exchange method.
  1315. prf_hmac_sha256(/*tls,*/
  1316. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1317. rsa_premaster, sizeof(rsa_premaster),
  1318. "master secret",
  1319. tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
  1320. );
  1321. dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1322. // RFC 5246
  1323. // 6.3. Key Calculation
  1324. //
  1325. // The Record Protocol requires an algorithm to generate keys required
  1326. // by the current connection state (see Appendix A.6) from the security
  1327. // parameters provided by the handshake protocol.
  1328. //
  1329. // The master secret is expanded into a sequence of secure bytes, which
  1330. // is then split to a client write MAC key, a server write MAC key, a
  1331. // client write encryption key, and a server write encryption key. Each
  1332. // of these is generated from the byte sequence in that order. Unused
  1333. // values are empty. Some AEAD ciphers may additionally require a
  1334. // client write IV and a server write IV (see Section 6.2.3.3).
  1335. //
  1336. // When keys and MAC keys are generated, the master secret is used as an
  1337. // entropy source.
  1338. //
  1339. // To generate the key material, compute
  1340. //
  1341. // key_block = PRF(SecurityParameters.master_secret,
  1342. // "key expansion",
  1343. // SecurityParameters.server_random +
  1344. // SecurityParameters.client_random);
  1345. //
  1346. // until enough output has been generated. Then, the key_block is
  1347. // partitioned as follows:
  1348. //
  1349. // client_write_MAC_key[SecurityParameters.mac_key_length]
  1350. // server_write_MAC_key[SecurityParameters.mac_key_length]
  1351. // client_write_key[SecurityParameters.enc_key_length]
  1352. // server_write_key[SecurityParameters.enc_key_length]
  1353. // client_write_IV[SecurityParameters.fixed_iv_length]
  1354. // server_write_IV[SecurityParameters.fixed_iv_length]
  1355. {
  1356. uint8_t tmp64[64];
  1357. /* make "server_rand32 + client_rand32" */
  1358. memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
  1359. memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
  1360. prf_hmac_sha256(/*tls,*/
  1361. tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size),
  1362. // also fills:
  1363. // server_write_MAC_key[]
  1364. // client_write_key[]
  1365. // server_write_key[]
  1366. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1367. "key expansion",
  1368. tmp64, 64
  1369. );
  1370. tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
  1371. tls->server_write_key = tls->client_write_key + tls->key_size;
  1372. dump_hex("client_write_MAC_key:%s\n",
  1373. tls->client_write_MAC_key, tls->MAC_size
  1374. );
  1375. dump_hex("client_write_key:%s\n",
  1376. tls->client_write_key, tls->key_size
  1377. );
  1378. }
  1379. }
  1380. static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
  1381. RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
  1382. 01
  1383. };
  1384. static void send_change_cipher_spec(tls_state_t *tls)
  1385. {
  1386. dbg(">> CHANGE_CIPHER_SPEC\n");
  1387. xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
  1388. }
  1389. // 7.4.9. Finished
  1390. // A Finished message is always sent immediately after a change
  1391. // cipher spec message to verify that the key exchange and
  1392. // authentication processes were successful. It is essential that a
  1393. // change cipher spec message be received between the other handshake
  1394. // messages and the Finished message.
  1395. //...
  1396. // The Finished message is the first one protected with the just
  1397. // negotiated algorithms, keys, and secrets. Recipients of Finished
  1398. // messages MUST verify that the contents are correct. Once a side
  1399. // has sent its Finished message and received and validated the
  1400. // Finished message from its peer, it may begin to send and receive
  1401. // application data over the connection.
  1402. //...
  1403. // struct {
  1404. // opaque verify_data[verify_data_length];
  1405. // } Finished;
  1406. //
  1407. // verify_data
  1408. // PRF(master_secret, finished_label, Hash(handshake_messages))
  1409. // [0..verify_data_length-1];
  1410. //
  1411. // finished_label
  1412. // For Finished messages sent by the client, the string
  1413. // "client finished". For Finished messages sent by the server,
  1414. // the string "server finished".
  1415. //
  1416. // Hash denotes a Hash of the handshake messages. For the PRF
  1417. // defined in Section 5, the Hash MUST be the Hash used as the basis
  1418. // for the PRF. Any cipher suite which defines a different PRF MUST
  1419. // also define the Hash to use in the Finished computation.
  1420. //
  1421. // In previous versions of TLS, the verify_data was always 12 octets
  1422. // long. In the current version of TLS, it depends on the cipher
  1423. // suite. Any cipher suite which does not explicitly specify
  1424. // verify_data_length has a verify_data_length equal to 12. This
  1425. // includes all existing cipher suites.
  1426. static void send_client_finished(tls_state_t *tls)
  1427. {
  1428. struct finished {
  1429. uint8_t type;
  1430. uint8_t len24_hi, len24_mid, len24_lo;
  1431. uint8_t prf_result[12];
  1432. };
  1433. struct finished *record = tls_get_outbuf(tls, sizeof(*record));
  1434. uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
  1435. unsigned len;
  1436. fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
  1437. len = get_handshake_hash(tls, handshake_hash);
  1438. prf_hmac_sha256(/*tls,*/
  1439. record->prf_result, sizeof(record->prf_result),
  1440. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1441. "client finished",
  1442. handshake_hash, len
  1443. );
  1444. dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1445. dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
  1446. dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
  1447. dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
  1448. dbg(">> FINISHED\n");
  1449. xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
  1450. }
  1451. void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
  1452. {
  1453. // Client RFC 5246 Server
  1454. // (*) - optional messages, not always sent
  1455. //
  1456. // ClientHello ------->
  1457. // ServerHello
  1458. // Certificate*
  1459. // ServerKeyExchange*
  1460. // CertificateRequest*
  1461. // <------- ServerHelloDone
  1462. // Certificate*
  1463. // ClientKeyExchange
  1464. // CertificateVerify*
  1465. // [ChangeCipherSpec]
  1466. // Finished ------->
  1467. // [ChangeCipherSpec]
  1468. // <------- Finished
  1469. // Application Data <------> Application Data
  1470. int len;
  1471. int got_cert_req;
  1472. send_client_hello_and_alloc_hsd(tls, sni);
  1473. get_server_hello(tls);
  1474. // RFC 5246
  1475. // The server MUST send a Certificate message whenever the agreed-
  1476. // upon key exchange method uses certificates for authentication
  1477. // (this includes all key exchange methods defined in this document
  1478. // except DH_anon). This message will always immediately follow the
  1479. // ServerHello message.
  1480. //
  1481. // IOW: in practice, Certificate *always* follows.
  1482. // (for example, kernel.org does not even accept DH_anon cipher id)
  1483. get_server_cert(tls);
  1484. len = tls_xread_handshake_block(tls, 4);
  1485. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
  1486. // 459 bytes:
  1487. // 0c 00|01|c7 03|00|17|41|04|87|94|2e|2f|68|d0|c9|f4|97|a8|2d|ef|ed|67|ea|c6|f3|b3|56|47|5d|27|b6|bd|ee|70|25|30|5e|b0|8e|f6|21|5a...
  1488. //SvKey len=455^
  1489. // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
  1490. // 0c 00|01|c9 03|00|17|41|04|cd|9b|b4|29|1f|f6|b0|c2|84|82|7f|29|6a|47|4e|ec|87|0b|c1|9c|69|e1|f8|c6|d0|53|e9|27|90|a5|c8|02|15|75...
  1491. dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
  1492. //probably need to save it
  1493. len = tls_xread_handshake_block(tls, 4);
  1494. }
  1495. got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
  1496. if (got_cert_req) {
  1497. dbg("<< CERTIFICATE_REQUEST\n");
  1498. // RFC 5246: "If no suitable certificate is available,
  1499. // the client MUST send a certificate message containing no
  1500. // certificates. That is, the certificate_list structure has a
  1501. // length of zero. ...
  1502. // Client certificates are sent using the Certificate structure
  1503. // defined in Section 7.4.2."
  1504. // (i.e. the same format as server certs)
  1505. /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
  1506. /* need to hash _all_ server replies first, up to ServerHelloDone */
  1507. len = tls_xread_handshake_block(tls, 4);
  1508. }
  1509. if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
  1510. bad_record_die(tls, "'server hello done'", len);
  1511. }
  1512. // 0e 000000 (len:0)
  1513. dbg("<< SERVER_HELLO_DONE\n");
  1514. if (got_cert_req)
  1515. send_empty_client_cert(tls);
  1516. send_client_key_exchange(tls);
  1517. send_change_cipher_spec(tls);
  1518. /* from now on we should send encrypted */
  1519. /* tls->write_seq64_be = 0; - already is */
  1520. tls->encrypt_on_write = 1;
  1521. send_client_finished(tls);
  1522. /* Get CHANGE_CIPHER_SPEC */
  1523. len = tls_xread_record(tls, "switch to encrypted traffic");
  1524. if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
  1525. bad_record_die(tls, "switch to encrypted traffic", len);
  1526. dbg("<< CHANGE_CIPHER_SPEC\n");
  1527. if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
  1528. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  1529. ) {
  1530. tls->min_encrypted_len_on_read = tls->MAC_size;
  1531. } else {
  1532. unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCKSIZE-1) / AES_BLOCKSIZE;
  1533. /* all incoming packets now should be encrypted and have
  1534. * at least IV + (MAC padded to blocksize):
  1535. */
  1536. tls->min_encrypted_len_on_read = AES_BLOCKSIZE + (mac_blocks * AES_BLOCKSIZE);
  1537. dbg("min_encrypted_len_on_read: %u", tls->min_encrypted_len_on_read);
  1538. }
  1539. /* Get (encrypted) FINISHED from the server */
  1540. len = tls_xread_record(tls, "'server finished'");
  1541. if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
  1542. bad_record_die(tls, "'server finished'", len);
  1543. dbg("<< FINISHED\n");
  1544. /* application data can be sent/received */
  1545. /* free handshake data */
  1546. // if (PARANOIA)
  1547. // memset(tls->hsd, 0, tls->hsd->hsd_size);
  1548. free(tls->hsd);
  1549. tls->hsd = NULL;
  1550. }
  1551. static void tls_xwrite(tls_state_t *tls, int len)
  1552. {
  1553. dbg(">> DATA\n");
  1554. xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
  1555. }
  1556. // To run a test server using openssl:
  1557. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  1558. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
  1559. //
  1560. // Unencryped SHA256 example:
  1561. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  1562. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
  1563. // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
  1564. void FAST_FUNC tls_run_copy_loop(tls_state_t *tls)
  1565. {
  1566. int inbuf_size;
  1567. const int INBUF_STEP = 4 * 1024;
  1568. struct pollfd pfds[2];
  1569. pfds[0].fd = STDIN_FILENO;
  1570. pfds[0].events = POLLIN;
  1571. pfds[1].fd = tls->ifd;
  1572. pfds[1].events = POLLIN;
  1573. inbuf_size = INBUF_STEP;
  1574. for (;;) {
  1575. int nread;
  1576. if (safe_poll(pfds, 2, -1) < 0)
  1577. bb_perror_msg_and_die("poll");
  1578. if (pfds[0].revents) {
  1579. void *buf;
  1580. dbg("STDIN HAS DATA\n");
  1581. buf = tls_get_outbuf(tls, inbuf_size);
  1582. nread = safe_read(STDIN_FILENO, buf, inbuf_size);
  1583. if (nread < 1) {
  1584. /* We'd want to do this: */
  1585. /* Close outgoing half-connection so they get EOF,
  1586. * but leave incoming alone so we can see response
  1587. */
  1588. //shutdown(tls->ofd, SHUT_WR);
  1589. /* But TLS has no way to encode this,
  1590. * doubt it's ok to do it "raw"
  1591. */
  1592. pfds[0].fd = -1;
  1593. tls_free_outbuf(tls); /* mem usage optimization */
  1594. } else {
  1595. if (nread == inbuf_size) {
  1596. /* TLS has per record overhead, if input comes fast,
  1597. * read, encrypt and send bigger chunks
  1598. */
  1599. inbuf_size += INBUF_STEP;
  1600. if (inbuf_size > TLS_MAX_OUTBUF)
  1601. inbuf_size = TLS_MAX_OUTBUF;
  1602. }
  1603. tls_xwrite(tls, nread);
  1604. }
  1605. }
  1606. if (pfds[1].revents) {
  1607. dbg("NETWORK HAS DATA\n");
  1608. read_record:
  1609. nread = tls_xread_record(tls, "encrypted data");
  1610. if (nread < 1) {
  1611. /* TLS protocol has no real concept of one-sided shutdowns:
  1612. * if we get "TLS EOF" from the peer, writes will fail too
  1613. */
  1614. //pfds[1].fd = -1;
  1615. //close(STDOUT_FILENO);
  1616. //tls_free_inbuf(tls); /* mem usage optimization */
  1617. //continue;
  1618. break;
  1619. }
  1620. if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
  1621. bad_record_die(tls, "encrypted data", nread);
  1622. xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
  1623. /* We may already have a complete next record buffered,
  1624. * can process it without network reads (and possible blocking)
  1625. */
  1626. if (tls_has_buffered_record(tls))
  1627. goto read_record;
  1628. }
  1629. }
  1630. }