tls.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  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. bad_record_die(tls, expected, sz);
  726. }
  727. dbg("xhdr type:%d ver:%d.%d len:%d\n",
  728. xhdr->type, xhdr->proto_maj, xhdr->proto_min,
  729. 0x100 * xhdr->len16_hi + xhdr->len16_lo
  730. );
  731. }
  732. /* if total >= target, we have a full packet (and possibly more)... */
  733. if (total - target >= 0)
  734. break;
  735. /* input buffer is grown only as needed */
  736. rem = tls->inbuf_size - total;
  737. if (rem == 0) {
  738. tls->inbuf_size += MAX_INBUF / 8;
  739. if (tls->inbuf_size > MAX_INBUF)
  740. tls->inbuf_size = MAX_INBUF;
  741. dbg("inbuf_size:%d\n", tls->inbuf_size);
  742. rem = tls->inbuf_size - total;
  743. tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
  744. }
  745. sz = safe_read(tls->ifd, tls->inbuf + total, rem);
  746. if (sz <= 0) {
  747. if (sz == 0 && total == 0) {
  748. /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
  749. dbg("EOF (without TLS shutdown) from peer\n");
  750. tls->buffered_size = 0;
  751. goto end;
  752. }
  753. bb_perror_msg_and_die("short read, have only %d", total);
  754. }
  755. dump_raw_in("<< %s\n", tls->inbuf + total, sz);
  756. total += sz;
  757. }
  758. tls->buffered_size = total - target;
  759. tls->ofs_to_buffered = target;
  760. //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
  761. //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
  762. sz = target - RECHDR_LEN;
  763. /* Needs to be decrypted? */
  764. if (tls->min_encrypted_len_on_read > tls->MAC_size) {
  765. uint8_t *p = tls->inbuf + RECHDR_LEN;
  766. int padding_len;
  767. if (sz & (AES_BLOCKSIZE-1)
  768. || sz < (int)tls->min_encrypted_len_on_read
  769. ) {
  770. bb_error_msg_and_die("bad encrypted len:%u < %u",
  771. sz, tls->min_encrypted_len_on_read);
  772. }
  773. /* Decrypt content+MAC+padding, moving it over IV in the process */
  774. sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
  775. aes_cbc_decrypt(
  776. tls->server_write_key, tls->key_size, /* selects 128/256 */
  777. p, /* IV */
  778. p + AES_BLOCKSIZE, sz, /* ciphertext */
  779. p /* plaintext */
  780. );
  781. padding_len = p[sz - 1];
  782. dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
  783. padding_len++;
  784. sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
  785. //if (sz < 0)
  786. // bb_error_msg_and_die("bad padding size:%u", padding_len);
  787. } else {
  788. /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
  789. /* else: no encryption yet on input, subtract zero = NOP */
  790. sz -= tls->min_encrypted_len_on_read;
  791. }
  792. if (sz < 0)
  793. bb_error_msg_and_die("encrypted data too short");
  794. //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
  795. xhdr = (void*)tls->inbuf;
  796. if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
  797. uint8_t *p = tls->inbuf + RECHDR_LEN;
  798. dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
  799. if (p[0] == 2) { /* fatal */
  800. bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
  801. "error",
  802. p[1], alert_text(p[1])
  803. );
  804. }
  805. if (p[0] == 1) { /* warning */
  806. if (p[1] == 0) { /* "close_notify" warning: it's EOF */
  807. dbg("EOF (TLS encoded) from peer\n");
  808. sz = 0;
  809. goto end;
  810. }
  811. //This possibly needs to be cached and shown only if
  812. //a fatal alert follows
  813. // bb_error_msg("TLS %s from peer (alert code %d): %s",
  814. // "warning",
  815. // p[1], alert_text(p[1])
  816. // );
  817. /* discard it, get next record */
  818. goto again;
  819. }
  820. /* p[0] not 1 or 2: not defined in protocol */
  821. sz = 0;
  822. goto end;
  823. }
  824. /* RFC 5246 is not saying it explicitly, but sha256 hash
  825. * in our FINISHED record must include data of incoming packets too!
  826. */
  827. if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
  828. && tls->MAC_size != 0 /* do we know which hash to use? (server_hello() does not!) */
  829. ) {
  830. hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
  831. }
  832. end:
  833. dbg("got block len:%u\n", sz);
  834. return sz;
  835. }
  836. /*
  837. * DER parsing routines
  838. */
  839. static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
  840. {
  841. unsigned len, len1;
  842. if (end - der < 2)
  843. xfunc_die();
  844. // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
  845. // xfunc_die();
  846. len = der[1]; /* maybe it's short len */
  847. if (len >= 0x80) {
  848. /* no, it's long */
  849. if (len == 0x80 || end - der < (int)(len - 0x7e)) {
  850. /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
  851. /* need 3 or 4 bytes for 81, 82 */
  852. xfunc_die();
  853. }
  854. len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
  855. if (len > 0x82) {
  856. /* >0x82 is "3+ bytes of len", should not happen realistically */
  857. xfunc_die();
  858. }
  859. if (len == 0x82) { /* it's "ii 82 xx yy" */
  860. len1 = 0x100*len1 + der[3];
  861. der += 1; /* skip [yy] */
  862. }
  863. der += 1; /* skip [xx] */
  864. len = len1;
  865. // if (len < 0x80)
  866. // xfunc_die(); /* invalid DER: must use short len if can */
  867. }
  868. der += 2; /* skip [code]+[1byte] */
  869. if (end - der < (int)len)
  870. xfunc_die();
  871. *bodyp = der;
  872. return len;
  873. }
  874. static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
  875. {
  876. uint8_t *new_der;
  877. unsigned len = get_der_len(&new_der, der, *endp);
  878. dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
  879. /* Move "end" position to cover only this item */
  880. *endp = new_der + len;
  881. return new_der;
  882. }
  883. static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
  884. {
  885. uint8_t *new_der;
  886. unsigned len = get_der_len(&new_der, der, end);
  887. /* Skip body */
  888. new_der += len;
  889. dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
  890. return new_der;
  891. }
  892. static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
  893. {
  894. uint8_t *bin_ptr;
  895. unsigned len = get_der_len(&bin_ptr, der, end);
  896. dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
  897. pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
  898. pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
  899. //return bin + len;
  900. }
  901. static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
  902. {
  903. /* Certificate is a DER-encoded data structure. Each DER element has a length,
  904. * which makes it easy to skip over large compound elements of any complexity
  905. * without parsing them. Example: partial decode of kernel.org certificate:
  906. * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
  907. * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
  908. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
  909. * INTEGER (version): 0201 02
  910. * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
  911. * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
  912. * SEQ 0x0d bytes (signatureAlgo): 300d
  913. * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
  914. * NULL: 0500
  915. * SEQ 0x5f bytes (issuer): 305f
  916. * SET 11 bytes: 310b
  917. * SEQ 9 bytes: 3009
  918. * OID 3 bytes: 0603 550406
  919. * Printable string "FR": 1302 4652
  920. * SET 14 bytes: 310e
  921. * SEQ 12 bytes: 300c
  922. * OID 3 bytes: 0603 550408
  923. * Printable string "Paris": 1305 5061726973
  924. * SET 14 bytes: 310e
  925. * SEQ 12 bytes: 300c
  926. * OID 3 bytes: 0603 550407
  927. * Printable string "Paris": 1305 5061726973
  928. * SET 14 bytes: 310e
  929. * SEQ 12 bytes: 300c
  930. * OID 3 bytes: 0603 55040a
  931. * Printable string "Gandi": 1305 47616e6469
  932. * SET 32 bytes: 3120
  933. * SEQ 30 bytes: 301e
  934. * OID 3 bytes: 0603 550403
  935. * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
  936. * SEQ 30 bytes (validity): 301e
  937. * TIME "161011000000Z": 170d 3136313031313030303030305a
  938. * TIME "191011235959Z": 170d 3139313031313233353935395a
  939. * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
  940. * 3121301f060355040b1318446f6d61696e20436f
  941. * 6e74726f6c2056616c6964617465643121301f06
  942. * 0355040b1318506f73697469766553534c204d75
  943. * 6c74692d446f6d61696e31133011060355040313
  944. * 0a6b65726e656c2e6f7267
  945. * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
  946. * SEQ 13 bytes (algorithm): 300d
  947. * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
  948. * NULL: 0500
  949. * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
  950. * ????: 00
  951. * //after the zero byte, it appears key itself uses DER encoding:
  952. * SEQ 0x018a/394 bytes: 3082018a
  953. * INTEGER 0x0181/385 bytes (modulus): 02820181
  954. * 00b1ab2fc727a3bef76780c9349bf3
  955. * ...24 more blocks of 15 bytes each...
  956. * 90e895291c6bc8693b65
  957. * INTEGER 3 bytes (exponent): 0203 010001
  958. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
  959. * SEQ 0x01e1 bytes: 308201e1
  960. * ...
  961. * Certificate is a sequence of three elements:
  962. * tbsCertificate (SEQ)
  963. * signatureAlgorithm (AlgorithmIdentifier)
  964. * signatureValue (BIT STRING)
  965. *
  966. * In turn, tbsCertificate is a sequence of:
  967. * version
  968. * serialNumber
  969. * signatureAlgo (AlgorithmIdentifier)
  970. * issuer (Name, has complex structure)
  971. * validity (Validity, SEQ of two Times)
  972. * subject (Name)
  973. * subjectPublicKeyInfo (SEQ)
  974. * ...
  975. *
  976. * subjectPublicKeyInfo is a sequence of:
  977. * algorithm (AlgorithmIdentifier)
  978. * publicKey (BIT STRING)
  979. *
  980. * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
  981. */
  982. uint8_t *end = der + len;
  983. uint8_t tag_class, pc, tag_number;
  984. int version_present;
  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. /*
  990. * Skip version field only if it is present. For a v1 certificate, the
  991. * version field won't be present since v1 is the default value for the
  992. * version field and fields with default values should be omitted (see
  993. * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
  994. * it will have a tag class of 2 (context-specific), bit 6 as 1
  995. * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
  996. * and 8.14).
  997. */
  998. tag_class = der[0] >> 6; /* bits 8-7 */
  999. pc = (der[0] & 32) >> 5; /* bit 6 */
  1000. tag_number = der[0] & 31; /* bits 5-1 */
  1001. version_present = tag_class == 2 && pc == 1 && tag_number == 0;
  1002. if (version_present) {
  1003. der = skip_der_item(der, end); /* version */
  1004. }
  1005. /* skip up to subjectPublicKeyInfo */
  1006. der = skip_der_item(der, end); /* serialNumber */
  1007. der = skip_der_item(der, end); /* signatureAlgo */
  1008. der = skip_der_item(der, end); /* issuer */
  1009. der = skip_der_item(der, end); /* validity */
  1010. der = skip_der_item(der, end); /* subject */
  1011. /* enter subjectPublicKeyInfo */
  1012. der = enter_der_item(der, &end);
  1013. { /* check subjectPublicKeyInfo.algorithm */
  1014. static const uint8_t expected[] = {
  1015. 0x30,0x0d, // SEQ 13 bytes
  1016. 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
  1017. //0x05,0x00, // NULL
  1018. };
  1019. if (memcmp(der, expected, sizeof(expected)) != 0)
  1020. bb_error_msg_and_die("not RSA key");
  1021. }
  1022. /* skip subjectPublicKeyInfo.algorithm */
  1023. der = skip_der_item(der, end);
  1024. /* enter subjectPublicKeyInfo.publicKey */
  1025. // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
  1026. der = enter_der_item(der, &end);
  1027. /* parse RSA key: */
  1028. //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
  1029. dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
  1030. if (end - der < 14) xfunc_die();
  1031. /* example format:
  1032. * ignore bits: 00
  1033. * SEQ 0x018a/394 bytes: 3082018a
  1034. * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
  1035. * INTEGER 3 bytes (exponent): 0203 010001
  1036. */
  1037. if (*der != 0) /* "ignore bits", should be 0 */
  1038. xfunc_die();
  1039. der++;
  1040. der = enter_der_item(der, &end); /* enter SEQ */
  1041. /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
  1042. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
  1043. der = skip_der_item(der, end);
  1044. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
  1045. tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
  1046. dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
  1047. }
  1048. /*
  1049. * TLS Handshake routines
  1050. */
  1051. static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
  1052. {
  1053. struct record_hdr *xhdr;
  1054. int len = tls_xread_record(tls, "handshake record");
  1055. xhdr = (void*)tls->inbuf;
  1056. if (len < min_len
  1057. || xhdr->type != RECORD_TYPE_HANDSHAKE
  1058. ) {
  1059. bad_record_die(tls, "handshake record", len);
  1060. }
  1061. dbg("got HANDSHAKE\n");
  1062. return len;
  1063. }
  1064. static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
  1065. {
  1066. struct handshake_hdr {
  1067. uint8_t type;
  1068. uint8_t len24_hi, len24_mid, len24_lo;
  1069. } *h = buf;
  1070. len -= 4;
  1071. h->type = type;
  1072. h->len24_hi = len >> 16;
  1073. h->len24_mid = len >> 8;
  1074. h->len24_lo = len & 0xff;
  1075. }
  1076. static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
  1077. {
  1078. struct client_hello {
  1079. uint8_t type;
  1080. uint8_t len24_hi, len24_mid, len24_lo;
  1081. uint8_t proto_maj, proto_min;
  1082. uint8_t rand32[32];
  1083. uint8_t session_id_len;
  1084. /* uint8_t session_id[]; */
  1085. uint8_t cipherid_len16_hi, cipherid_len16_lo;
  1086. uint8_t cipherid[2 * (2 + !!CIPHER_ID2)]; /* actually variable */
  1087. uint8_t comprtypes_len;
  1088. uint8_t comprtypes[1]; /* actually variable */
  1089. /* Extensions (SNI shown):
  1090. * hi,lo // len of all extensions
  1091. * 00,00 // extension_type: "Server Name"
  1092. * 00,0e // list len (there can be more than one SNI)
  1093. * 00,0c // len of 1st Server Name Indication
  1094. * 00 // name type: host_name
  1095. * 00,09 // name len
  1096. * "localhost" // name
  1097. */
  1098. // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
  1099. // 0055
  1100. // 0005 0005 0100000000 - status_request
  1101. // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
  1102. // ff01 0001 00 - renegotiation_info
  1103. // 0023 0000 - session_ticket
  1104. // 000a 0008 0006001700180019 - supported_groups
  1105. // 000b 0002 0100 - ec_point_formats
  1106. // 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
  1107. // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
  1108. // 0017 0000 - extended master secret
  1109. };
  1110. struct client_hello *record;
  1111. int len;
  1112. int sni_len = sni ? strnlen(sni, 127 - 9) : 0;
  1113. len = sizeof(*record);
  1114. if (sni_len)
  1115. len += 11 + sni_len;
  1116. record = tls_get_outbuf(tls, len);
  1117. memset(record, 0, len);
  1118. fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
  1119. record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
  1120. record->proto_min = TLS_MIN; /* can be higher than one in record headers */
  1121. tls_get_random(record->rand32, sizeof(record->rand32));
  1122. if (TLS_DEBUG_FIXED_SECRETS)
  1123. memset(record->rand32, 0x11, sizeof(record->rand32));
  1124. /* record->session_id_len = 0; - already is */
  1125. /* record->cipherid_len16_hi = 0; */
  1126. record->cipherid_len16_lo = sizeof(record->cipherid);
  1127. /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
  1128. /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
  1129. record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
  1130. if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
  1131. /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
  1132. #if CIPHER_ID2
  1133. if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
  1134. /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
  1135. #endif
  1136. record->comprtypes_len = 1;
  1137. /* record->comprtypes[0] = 0; */
  1138. if (sni_len) {
  1139. uint8_t *p = (void*)(record + 1);
  1140. //p[0] = 0; //
  1141. p[1] = sni_len + 9; //ext_len
  1142. //p[2] = 0; //
  1143. //p[3] = 0; //extension_type
  1144. //p[4] = 0; //
  1145. p[5] = sni_len + 5; //list len
  1146. //p[6] = 0; //
  1147. p[7] = sni_len + 3; //len of 1st SNI
  1148. //p[8] = 0; //name type
  1149. //p[9] = 0; //
  1150. p[10] = sni_len; //name len
  1151. memcpy(&p[11], sni, sni_len);
  1152. }
  1153. dbg(">> CLIENT_HELLO\n");
  1154. /* Can hash it only when we know which MAC hash to use */
  1155. /*xwrite_and_update_handshake_hash(tls, len); - WRONG! */
  1156. xwrite_handshake_record(tls, len);
  1157. tls->hsd = xzalloc(sizeof(*tls->hsd) + len);
  1158. tls->hsd->saved_client_hello_size = len;
  1159. memcpy(tls->hsd->saved_client_hello, record, len);
  1160. memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
  1161. }
  1162. static void get_server_hello(tls_state_t *tls)
  1163. {
  1164. struct server_hello {
  1165. struct record_hdr xhdr;
  1166. uint8_t type;
  1167. uint8_t len24_hi, len24_mid, len24_lo;
  1168. uint8_t proto_maj, proto_min;
  1169. uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
  1170. uint8_t session_id_len;
  1171. uint8_t session_id[32];
  1172. uint8_t cipherid_hi, cipherid_lo;
  1173. uint8_t comprtype;
  1174. /* extensions may follow, but only those which client offered in its Hello */
  1175. };
  1176. struct server_hello *hp;
  1177. uint8_t *cipherid;
  1178. unsigned cipher;
  1179. int len, len24;
  1180. len = tls_xread_handshake_block(tls, 74 - 32);
  1181. hp = (void*)tls->inbuf;
  1182. // 74 bytes:
  1183. // 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|
  1184. //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
  1185. if (hp->type != HANDSHAKE_SERVER_HELLO
  1186. || hp->len24_hi != 0
  1187. || hp->len24_mid != 0
  1188. /* hp->len24_lo checked later */
  1189. || hp->proto_maj != TLS_MAJ
  1190. || hp->proto_min != TLS_MIN
  1191. ) {
  1192. bad_record_die(tls, "'server hello'", len);
  1193. }
  1194. cipherid = &hp->cipherid_hi;
  1195. len24 = hp->len24_lo;
  1196. if (hp->session_id_len != 32) {
  1197. if (hp->session_id_len != 0)
  1198. bad_record_die(tls, "'server hello'", len);
  1199. // session_id_len == 0: no session id
  1200. // "The server
  1201. // may return an empty session_id to indicate that the session will
  1202. // not be cached and therefore cannot be resumed."
  1203. cipherid -= 32;
  1204. len24 += 32; /* what len would be if session id would be present */
  1205. }
  1206. if (len24 < 70
  1207. // || cipherid[0] != (CIPHER_ID >> 8)
  1208. // || cipherid[1] != (CIPHER_ID & 0xff)
  1209. // || cipherid[2] != 0 /* comprtype */
  1210. ) {
  1211. bad_record_die(tls, "'server hello'", len);
  1212. }
  1213. dbg("<< SERVER_HELLO\n");
  1214. memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
  1215. tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
  1216. dbg("server chose cipher %04x\n", cipher);
  1217. if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA) {
  1218. tls->key_size = AES128_KEYSIZE;
  1219. tls->MAC_size = SHA1_OUTSIZE;
  1220. }
  1221. else { /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
  1222. tls->key_size = AES256_KEYSIZE;
  1223. tls->MAC_size = SHA256_OUTSIZE;
  1224. }
  1225. /* Handshake hash eventually destined to FINISHED record
  1226. * is sha256 regardless of cipher
  1227. * (at least for all ciphers defined by RFC5246).
  1228. * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
  1229. */
  1230. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1231. hash_handshake(tls, ">> client hello hash:%s",
  1232. tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
  1233. );
  1234. hash_handshake(tls, "<< server hello hash:%s",
  1235. tls->inbuf + RECHDR_LEN, len
  1236. );
  1237. }
  1238. static void get_server_cert(tls_state_t *tls)
  1239. {
  1240. struct record_hdr *xhdr;
  1241. uint8_t *certbuf;
  1242. int len, len1;
  1243. len = tls_xread_handshake_block(tls, 10);
  1244. xhdr = (void*)tls->inbuf;
  1245. certbuf = (void*)(xhdr + 1);
  1246. if (certbuf[0] != HANDSHAKE_CERTIFICATE)
  1247. bad_record_die(tls, "certificate", len);
  1248. dbg("<< CERTIFICATE\n");
  1249. // 4392 bytes:
  1250. // 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...
  1251. //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
  1252. len1 = get24be(certbuf + 1);
  1253. if (len1 > len - 4) tls_error_die(tls);
  1254. len = len1;
  1255. len1 = get24be(certbuf + 4);
  1256. if (len1 > len - 3) tls_error_die(tls);
  1257. len = len1;
  1258. len1 = get24be(certbuf + 7);
  1259. if (len1 > len - 3) tls_error_die(tls);
  1260. len = len1;
  1261. if (len)
  1262. find_key_in_der_cert(tls, certbuf + 10, len);
  1263. }
  1264. static void send_empty_client_cert(tls_state_t *tls)
  1265. {
  1266. struct client_empty_cert {
  1267. uint8_t type;
  1268. uint8_t len24_hi, len24_mid, len24_lo;
  1269. uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
  1270. };
  1271. struct client_empty_cert *record;
  1272. record = tls_get_outbuf(tls, sizeof(*record));
  1273. //FIXME: can just memcpy a ready-made one.
  1274. fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
  1275. record->cert_chain_len24_hi = 0;
  1276. record->cert_chain_len24_mid = 0;
  1277. record->cert_chain_len24_lo = 0;
  1278. dbg(">> CERTIFICATE\n");
  1279. xwrite_and_update_handshake_hash(tls, sizeof(*record));
  1280. }
  1281. static void send_client_key_exchange(tls_state_t *tls)
  1282. {
  1283. struct client_key_exchange {
  1284. uint8_t type;
  1285. uint8_t len24_hi, len24_mid, len24_lo;
  1286. /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
  1287. uint8_t keylen16_hi, keylen16_lo;
  1288. uint8_t key[4 * 1024]; // size??
  1289. };
  1290. //FIXME: better size estimate
  1291. struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
  1292. uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
  1293. int len;
  1294. tls_get_random(rsa_premaster, sizeof(rsa_premaster));
  1295. if (TLS_DEBUG_FIXED_SECRETS)
  1296. memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
  1297. // RFC 5246
  1298. // "Note: The version number in the PreMasterSecret is the version
  1299. // offered by the client in the ClientHello.client_version, not the
  1300. // version negotiated for the connection."
  1301. rsa_premaster[0] = TLS_MAJ;
  1302. rsa_premaster[1] = TLS_MIN;
  1303. dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
  1304. len = psRsaEncryptPub(/*pool:*/ NULL,
  1305. /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
  1306. rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
  1307. record->key, sizeof(record->key),
  1308. data_param_ignored
  1309. );
  1310. record->keylen16_hi = len >> 8;
  1311. record->keylen16_lo = len & 0xff;
  1312. len += 2;
  1313. record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
  1314. record->len24_hi = 0;
  1315. record->len24_mid = len >> 8;
  1316. record->len24_lo = len & 0xff;
  1317. len += 4;
  1318. dbg(">> CLIENT_KEY_EXCHANGE\n");
  1319. xwrite_and_update_handshake_hash(tls, len);
  1320. // RFC 5246
  1321. // For all key exchange methods, the same algorithm is used to convert
  1322. // the pre_master_secret into the master_secret. The pre_master_secret
  1323. // should be deleted from memory once the master_secret has been
  1324. // computed.
  1325. // master_secret = PRF(pre_master_secret, "master secret",
  1326. // ClientHello.random + ServerHello.random)
  1327. // [0..47];
  1328. // The master secret is always exactly 48 bytes in length. The length
  1329. // of the premaster secret will vary depending on key exchange method.
  1330. prf_hmac_sha256(/*tls,*/
  1331. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1332. rsa_premaster, sizeof(rsa_premaster),
  1333. "master secret",
  1334. tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
  1335. );
  1336. dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1337. // RFC 5246
  1338. // 6.3. Key Calculation
  1339. //
  1340. // The Record Protocol requires an algorithm to generate keys required
  1341. // by the current connection state (see Appendix A.6) from the security
  1342. // parameters provided by the handshake protocol.
  1343. //
  1344. // The master secret is expanded into a sequence of secure bytes, which
  1345. // is then split to a client write MAC key, a server write MAC key, a
  1346. // client write encryption key, and a server write encryption key. Each
  1347. // of these is generated from the byte sequence in that order. Unused
  1348. // values are empty. Some AEAD ciphers may additionally require a
  1349. // client write IV and a server write IV (see Section 6.2.3.3).
  1350. //
  1351. // When keys and MAC keys are generated, the master secret is used as an
  1352. // entropy source.
  1353. //
  1354. // To generate the key material, compute
  1355. //
  1356. // key_block = PRF(SecurityParameters.master_secret,
  1357. // "key expansion",
  1358. // SecurityParameters.server_random +
  1359. // SecurityParameters.client_random);
  1360. //
  1361. // until enough output has been generated. Then, the key_block is
  1362. // partitioned as follows:
  1363. //
  1364. // client_write_MAC_key[SecurityParameters.mac_key_length]
  1365. // server_write_MAC_key[SecurityParameters.mac_key_length]
  1366. // client_write_key[SecurityParameters.enc_key_length]
  1367. // server_write_key[SecurityParameters.enc_key_length]
  1368. // client_write_IV[SecurityParameters.fixed_iv_length]
  1369. // server_write_IV[SecurityParameters.fixed_iv_length]
  1370. {
  1371. uint8_t tmp64[64];
  1372. /* make "server_rand32 + client_rand32" */
  1373. memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
  1374. memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
  1375. prf_hmac_sha256(/*tls,*/
  1376. tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size),
  1377. // also fills:
  1378. // server_write_MAC_key[]
  1379. // client_write_key[]
  1380. // server_write_key[]
  1381. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1382. "key expansion",
  1383. tmp64, 64
  1384. );
  1385. tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
  1386. tls->server_write_key = tls->client_write_key + tls->key_size;
  1387. dump_hex("client_write_MAC_key:%s\n",
  1388. tls->client_write_MAC_key, tls->MAC_size
  1389. );
  1390. dump_hex("client_write_key:%s\n",
  1391. tls->client_write_key, tls->key_size
  1392. );
  1393. }
  1394. }
  1395. static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
  1396. RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
  1397. 01
  1398. };
  1399. static void send_change_cipher_spec(tls_state_t *tls)
  1400. {
  1401. dbg(">> CHANGE_CIPHER_SPEC\n");
  1402. xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
  1403. }
  1404. // 7.4.9. Finished
  1405. // A Finished message is always sent immediately after a change
  1406. // cipher spec message to verify that the key exchange and
  1407. // authentication processes were successful. It is essential that a
  1408. // change cipher spec message be received between the other handshake
  1409. // messages and the Finished message.
  1410. //...
  1411. // The Finished message is the first one protected with the just
  1412. // negotiated algorithms, keys, and secrets. Recipients of Finished
  1413. // messages MUST verify that the contents are correct. Once a side
  1414. // has sent its Finished message and received and validated the
  1415. // Finished message from its peer, it may begin to send and receive
  1416. // application data over the connection.
  1417. //...
  1418. // struct {
  1419. // opaque verify_data[verify_data_length];
  1420. // } Finished;
  1421. //
  1422. // verify_data
  1423. // PRF(master_secret, finished_label, Hash(handshake_messages))
  1424. // [0..verify_data_length-1];
  1425. //
  1426. // finished_label
  1427. // For Finished messages sent by the client, the string
  1428. // "client finished". For Finished messages sent by the server,
  1429. // the string "server finished".
  1430. //
  1431. // Hash denotes a Hash of the handshake messages. For the PRF
  1432. // defined in Section 5, the Hash MUST be the Hash used as the basis
  1433. // for the PRF. Any cipher suite which defines a different PRF MUST
  1434. // also define the Hash to use in the Finished computation.
  1435. //
  1436. // In previous versions of TLS, the verify_data was always 12 octets
  1437. // long. In the current version of TLS, it depends on the cipher
  1438. // suite. Any cipher suite which does not explicitly specify
  1439. // verify_data_length has a verify_data_length equal to 12. This
  1440. // includes all existing cipher suites.
  1441. static void send_client_finished(tls_state_t *tls)
  1442. {
  1443. struct finished {
  1444. uint8_t type;
  1445. uint8_t len24_hi, len24_mid, len24_lo;
  1446. uint8_t prf_result[12];
  1447. };
  1448. struct finished *record = tls_get_outbuf(tls, sizeof(*record));
  1449. uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
  1450. unsigned len;
  1451. fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
  1452. len = get_handshake_hash(tls, handshake_hash);
  1453. prf_hmac_sha256(/*tls,*/
  1454. record->prf_result, sizeof(record->prf_result),
  1455. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1456. "client finished",
  1457. handshake_hash, len
  1458. );
  1459. dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1460. dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
  1461. dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
  1462. dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
  1463. dbg(">> FINISHED\n");
  1464. xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
  1465. }
  1466. void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
  1467. {
  1468. // Client RFC 5246 Server
  1469. // (*) - optional messages, not always sent
  1470. //
  1471. // ClientHello ------->
  1472. // ServerHello
  1473. // Certificate*
  1474. // ServerKeyExchange*
  1475. // CertificateRequest*
  1476. // <------- ServerHelloDone
  1477. // Certificate*
  1478. // ClientKeyExchange
  1479. // CertificateVerify*
  1480. // [ChangeCipherSpec]
  1481. // Finished ------->
  1482. // [ChangeCipherSpec]
  1483. // <------- Finished
  1484. // Application Data <------> Application Data
  1485. int len;
  1486. int got_cert_req;
  1487. send_client_hello_and_alloc_hsd(tls, sni);
  1488. get_server_hello(tls);
  1489. // RFC 5246
  1490. // The server MUST send a Certificate message whenever the agreed-
  1491. // upon key exchange method uses certificates for authentication
  1492. // (this includes all key exchange methods defined in this document
  1493. // except DH_anon). This message will always immediately follow the
  1494. // ServerHello message.
  1495. //
  1496. // IOW: in practice, Certificate *always* follows.
  1497. // (for example, kernel.org does not even accept DH_anon cipher id)
  1498. get_server_cert(tls);
  1499. len = tls_xread_handshake_block(tls, 4);
  1500. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
  1501. // 459 bytes:
  1502. // 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...
  1503. //SvKey len=455^
  1504. // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
  1505. // 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...
  1506. dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
  1507. //probably need to save it
  1508. len = tls_xread_handshake_block(tls, 4);
  1509. }
  1510. got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
  1511. if (got_cert_req) {
  1512. dbg("<< CERTIFICATE_REQUEST\n");
  1513. // RFC 5246: "If no suitable certificate is available,
  1514. // the client MUST send a certificate message containing no
  1515. // certificates. That is, the certificate_list structure has a
  1516. // length of zero. ...
  1517. // Client certificates are sent using the Certificate structure
  1518. // defined in Section 7.4.2."
  1519. // (i.e. the same format as server certs)
  1520. /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
  1521. /* need to hash _all_ server replies first, up to ServerHelloDone */
  1522. len = tls_xread_handshake_block(tls, 4);
  1523. }
  1524. if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
  1525. bad_record_die(tls, "'server hello done'", len);
  1526. }
  1527. // 0e 000000 (len:0)
  1528. dbg("<< SERVER_HELLO_DONE\n");
  1529. if (got_cert_req)
  1530. send_empty_client_cert(tls);
  1531. send_client_key_exchange(tls);
  1532. send_change_cipher_spec(tls);
  1533. /* from now on we should send encrypted */
  1534. /* tls->write_seq64_be = 0; - already is */
  1535. tls->encrypt_on_write = 1;
  1536. send_client_finished(tls);
  1537. /* Get CHANGE_CIPHER_SPEC */
  1538. len = tls_xread_record(tls, "switch to encrypted traffic");
  1539. if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
  1540. bad_record_die(tls, "switch to encrypted traffic", len);
  1541. dbg("<< CHANGE_CIPHER_SPEC\n");
  1542. if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
  1543. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  1544. ) {
  1545. tls->min_encrypted_len_on_read = tls->MAC_size;
  1546. } else {
  1547. unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCKSIZE-1) / AES_BLOCKSIZE;
  1548. /* all incoming packets now should be encrypted and have
  1549. * at least IV + (MAC padded to blocksize):
  1550. */
  1551. tls->min_encrypted_len_on_read = AES_BLOCKSIZE + (mac_blocks * AES_BLOCKSIZE);
  1552. dbg("min_encrypted_len_on_read: %u", tls->min_encrypted_len_on_read);
  1553. }
  1554. /* Get (encrypted) FINISHED from the server */
  1555. len = tls_xread_record(tls, "'server finished'");
  1556. if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
  1557. bad_record_die(tls, "'server finished'", len);
  1558. dbg("<< FINISHED\n");
  1559. /* application data can be sent/received */
  1560. /* free handshake data */
  1561. // if (PARANOIA)
  1562. // memset(tls->hsd, 0, tls->hsd->hsd_size);
  1563. free(tls->hsd);
  1564. tls->hsd = NULL;
  1565. }
  1566. static void tls_xwrite(tls_state_t *tls, int len)
  1567. {
  1568. dbg(">> DATA\n");
  1569. xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
  1570. }
  1571. // To run a test server using openssl:
  1572. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  1573. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
  1574. //
  1575. // Unencryped SHA256 example:
  1576. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  1577. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
  1578. // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
  1579. void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
  1580. {
  1581. int inbuf_size;
  1582. const int INBUF_STEP = 4 * 1024;
  1583. struct pollfd pfds[2];
  1584. pfds[0].fd = STDIN_FILENO;
  1585. pfds[0].events = POLLIN;
  1586. pfds[1].fd = tls->ifd;
  1587. pfds[1].events = POLLIN;
  1588. inbuf_size = INBUF_STEP;
  1589. for (;;) {
  1590. int nread;
  1591. if (safe_poll(pfds, 2, -1) < 0)
  1592. bb_perror_msg_and_die("poll");
  1593. if (pfds[0].revents) {
  1594. void *buf;
  1595. dbg("STDIN HAS DATA\n");
  1596. buf = tls_get_outbuf(tls, inbuf_size);
  1597. nread = safe_read(STDIN_FILENO, buf, inbuf_size);
  1598. if (nread < 1) {
  1599. /* We'd want to do this: */
  1600. /* Close outgoing half-connection so they get EOF,
  1601. * but leave incoming alone so we can see response
  1602. */
  1603. //shutdown(tls->ofd, SHUT_WR);
  1604. /* But TLS has no way to encode this,
  1605. * doubt it's ok to do it "raw"
  1606. */
  1607. pfds[0].fd = -1;
  1608. tls_free_outbuf(tls); /* mem usage optimization */
  1609. if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
  1610. break;
  1611. } else {
  1612. if (nread == inbuf_size) {
  1613. /* TLS has per record overhead, if input comes fast,
  1614. * read, encrypt and send bigger chunks
  1615. */
  1616. inbuf_size += INBUF_STEP;
  1617. if (inbuf_size > TLS_MAX_OUTBUF)
  1618. inbuf_size = TLS_MAX_OUTBUF;
  1619. }
  1620. tls_xwrite(tls, nread);
  1621. }
  1622. }
  1623. if (pfds[1].revents) {
  1624. dbg("NETWORK HAS DATA\n");
  1625. read_record:
  1626. nread = tls_xread_record(tls, "encrypted data");
  1627. if (nread < 1) {
  1628. /* TLS protocol has no real concept of one-sided shutdowns:
  1629. * if we get "TLS EOF" from the peer, writes will fail too
  1630. */
  1631. //pfds[1].fd = -1;
  1632. //close(STDOUT_FILENO);
  1633. //tls_free_inbuf(tls); /* mem usage optimization */
  1634. //continue;
  1635. break;
  1636. }
  1637. if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
  1638. bad_record_die(tls, "encrypted data", nread);
  1639. xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
  1640. /* We may already have a complete next record buffered,
  1641. * can process it without network reads (and possible blocking)
  1642. */
  1643. if (tls_has_buffered_record(tls))
  1644. goto read_record;
  1645. }
  1646. }
  1647. }