tls.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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
  78. #define RECORD_TYPE_ALERT 21
  79. #define RECORD_TYPE_HANDSHAKE 22
  80. #define RECORD_TYPE_APPLICATION_DATA 23
  81. #define HANDSHAKE_HELLO_REQUEST 0
  82. #define HANDSHAKE_CLIENT_HELLO 1
  83. #define HANDSHAKE_SERVER_HELLO 2
  84. #define HANDSHAKE_HELLO_VERIFY_REQUEST 3
  85. #define HANDSHAKE_NEW_SESSION_TICKET 4
  86. #define HANDSHAKE_CERTIFICATE 11
  87. #define HANDSHAKE_SERVER_KEY_EXCHANGE 12
  88. #define HANDSHAKE_CERTIFICATE_REQUEST 13
  89. #define HANDSHAKE_SERVER_HELLO_DONE 14
  90. #define HANDSHAKE_CERTIFICATE_VERIFY 15
  91. #define HANDSHAKE_CLIENT_KEY_EXCHANGE 16
  92. #define HANDSHAKE_FINISHED 20
  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. while (len > 0) {
  458. fprintf(stderr, " %02x", *p++);
  459. len--;
  460. }
  461. fputc('\n', stderr);
  462. }
  463. xfunc_die();
  464. }
  465. static void tls_error_die(tls_state_t *tls, int line)
  466. {
  467. dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
  468. bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
  469. }
  470. #define tls_error_die(tls) tls_error_die(tls, __LINE__)
  471. #if 0 //UNUSED
  472. static void tls_free_inbuf(tls_state_t *tls)
  473. {
  474. if (tls->buffered_size == 0) {
  475. free(tls->inbuf);
  476. tls->inbuf_size = 0;
  477. tls->inbuf = NULL;
  478. }
  479. }
  480. #endif
  481. static void tls_free_outbuf(tls_state_t *tls)
  482. {
  483. free(tls->outbuf);
  484. tls->outbuf_size = 0;
  485. tls->outbuf = NULL;
  486. }
  487. static void *tls_get_outbuf(tls_state_t *tls, int len)
  488. {
  489. if (len > TLS_MAX_OUTBUF)
  490. xfunc_die();
  491. len += OUTBUF_PFX + OUTBUF_SFX;
  492. if (tls->outbuf_size < len) {
  493. tls->outbuf_size = len;
  494. tls->outbuf = xrealloc(tls->outbuf, len);
  495. }
  496. return tls->outbuf + OUTBUF_PFX;
  497. }
  498. static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
  499. {
  500. uint8_t *buf = tls->outbuf + OUTBUF_PFX;
  501. struct record_hdr *xhdr;
  502. uint8_t padding_length;
  503. xhdr = (void*)(buf - RECHDR_LEN);
  504. if (CIPHER_ID1 != TLS_RSA_WITH_NULL_SHA256 /* if "no encryption" can't be selected */
  505. || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
  506. ) {
  507. xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
  508. }
  509. xhdr->type = type;
  510. xhdr->proto_maj = TLS_MAJ;
  511. xhdr->proto_min = TLS_MIN;
  512. /* fake unencrypted record len for MAC calculation */
  513. xhdr->len16_hi = size >> 8;
  514. xhdr->len16_lo = size & 0xff;
  515. /* Calculate MAC signature */
  516. hmac(tls, buf + size, /* result */
  517. tls->client_write_MAC_key, tls->MAC_size,
  518. &tls->write_seq64_be, sizeof(tls->write_seq64_be),
  519. xhdr, RECHDR_LEN,
  520. buf, size,
  521. NULL
  522. );
  523. tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
  524. size += tls->MAC_size;
  525. // RFC 5246
  526. // 6.2.3.1. Null or Standard Stream Cipher
  527. //
  528. // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
  529. // convert TLSCompressed.fragment structures to and from stream
  530. // TLSCiphertext.fragment structures.
  531. //
  532. // stream-ciphered struct {
  533. // opaque content[TLSCompressed.length];
  534. // opaque MAC[SecurityParameters.mac_length];
  535. // } GenericStreamCipher;
  536. //
  537. // The MAC is generated as:
  538. // MAC(MAC_write_key, seq_num +
  539. // TLSCompressed.type +
  540. // TLSCompressed.version +
  541. // TLSCompressed.length +
  542. // TLSCompressed.fragment);
  543. // where "+" denotes concatenation.
  544. // seq_num
  545. // The sequence number for this record.
  546. // MAC
  547. // The MAC algorithm specified by SecurityParameters.mac_algorithm.
  548. //
  549. // Note that the MAC is computed before encryption. The stream cipher
  550. // encrypts the entire block, including the MAC.
  551. //...
  552. // Appendix C. Cipher Suite Definitions
  553. //...
  554. // MAC Algorithm mac_length mac_key_length
  555. // -------- ----------- ---------- --------------
  556. // SHA HMAC-SHA1 20 20
  557. // SHA256 HMAC-SHA256 32 32
  558. if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
  559. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  560. ) {
  561. /* No encryption, only signing */
  562. xhdr->len16_hi = size >> 8;
  563. xhdr->len16_lo = size & 0xff;
  564. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  565. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  566. dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
  567. return;
  568. }
  569. // 6.2.3.2. CBC Block Cipher
  570. // For block ciphers (such as 3DES or AES), the encryption and MAC
  571. // functions convert TLSCompressed.fragment structures to and from block
  572. // TLSCiphertext.fragment structures.
  573. // struct {
  574. // opaque IV[SecurityParameters.record_iv_length];
  575. // block-ciphered struct {
  576. // opaque content[TLSCompressed.length];
  577. // opaque MAC[SecurityParameters.mac_length];
  578. // uint8 padding[GenericBlockCipher.padding_length];
  579. // uint8 padding_length;
  580. // };
  581. // } GenericBlockCipher;
  582. //...
  583. // IV
  584. // The Initialization Vector (IV) SHOULD be chosen at random, and
  585. // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
  586. // there was no IV field (...). For block ciphers, the IV length is
  587. // of length SecurityParameters.record_iv_length, which is equal to the
  588. // SecurityParameters.block_size.
  589. // padding
  590. // Padding that is added to force the length of the plaintext to be
  591. // an integral multiple of the block cipher's block length.
  592. // padding_length
  593. // The padding length MUST be such that the total size of the
  594. // GenericBlockCipher structure is a multiple of the cipher's block
  595. // length. Legal values range from zero to 255, inclusive.
  596. //...
  597. // Appendix C. Cipher Suite Definitions
  598. //...
  599. // Key IV Block
  600. // Cipher Type Material Size Size
  601. // ------------ ------ -------- ---- -----
  602. // AES_128_CBC Block 16 16 16
  603. // AES_256_CBC Block 32 16 16
  604. /* Fill IV and padding in outbuf */
  605. tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
  606. dbg("before crypt: 5 hdr + %u data + %u hash bytes\n", size, tls->MAC_size);
  607. // RFC is talking nonsense:
  608. // "Padding that is added to force the length of the plaintext to be
  609. // an integral multiple of the block cipher's block length."
  610. // WRONG. _padding+padding_length_, not just _padding_,
  611. // pads the data.
  612. // IOW: padding_length is the last byte of padding[] array,
  613. // contrary to what RFC depicts.
  614. //
  615. // What actually happens is that there is always padding.
  616. // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
  617. // If you need two bytes, they are both 0x01.
  618. // If you need three, they are 0x02,0x02,0x02. And so on.
  619. // If you need no bytes to reach BLOCKSIZE, you have to pad a full
  620. // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
  621. // It's ok to have more than minimum padding, but we do minimum.
  622. padding_length = (~size) & (AES_BLOCKSIZE - 1);
  623. do {
  624. buf[size++] = padding_length; /* padding */
  625. } while ((size & (AES_BLOCKSIZE - 1)) != 0);
  626. /* Encrypt content+MAC+padding in place */
  627. aes_cbc_encrypt(
  628. tls->client_write_key, tls->key_size, /* selects 128/256 */
  629. buf - AES_BLOCKSIZE, /* IV */
  630. buf, size, /* plaintext */
  631. buf /* ciphertext */
  632. );
  633. /* Write out */
  634. dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
  635. AES_BLOCKSIZE, size, padding_length);
  636. size += AES_BLOCKSIZE; /* + IV */
  637. xhdr->len16_hi = size >> 8;
  638. xhdr->len16_lo = size & 0xff;
  639. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  640. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  641. dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
  642. }
  643. static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
  644. {
  645. //if (!tls->encrypt_on_write) {
  646. uint8_t *buf = tls->outbuf + OUTBUF_PFX;
  647. struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
  648. xhdr->type = RECORD_TYPE_HANDSHAKE;
  649. xhdr->proto_maj = TLS_MAJ;
  650. xhdr->proto_min = TLS_MIN;
  651. xhdr->len16_hi = size >> 8;
  652. xhdr->len16_lo = size & 0xff;
  653. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  654. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  655. dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
  656. // return;
  657. //}
  658. //xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
  659. }
  660. static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
  661. {
  662. if (!tls->encrypt_on_write) {
  663. uint8_t *buf;
  664. xwrite_handshake_record(tls, size);
  665. /* Handshake hash does not include record headers */
  666. buf = tls->outbuf + OUTBUF_PFX;
  667. hash_handshake(tls, ">> hash:%s", buf, size);
  668. return;
  669. }
  670. xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
  671. }
  672. static int tls_has_buffered_record(tls_state_t *tls)
  673. {
  674. int buffered = tls->buffered_size;
  675. struct record_hdr *xhdr;
  676. int rec_size;
  677. if (buffered < RECHDR_LEN)
  678. return 0;
  679. xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
  680. rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  681. if (buffered < rec_size)
  682. return 0;
  683. return rec_size;
  684. }
  685. static const char *alert_text(int code)
  686. {
  687. switch (code) {
  688. case 20: return "bad MAC";
  689. case 50: return "decode error";
  690. case 51: return "decrypt error";
  691. case 40: return "handshake failure";
  692. case 112: return "unrecognized name";
  693. }
  694. return itoa(code);
  695. }
  696. static int tls_xread_record(tls_state_t *tls)
  697. {
  698. struct record_hdr *xhdr;
  699. int sz;
  700. int total;
  701. int target;
  702. again:
  703. dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
  704. total = tls->buffered_size;
  705. if (total != 0) {
  706. memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
  707. //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
  708. //dump_raw_in("<< %s\n", tls->inbuf, total);
  709. }
  710. errno = 0;
  711. target = MAX_INBUF;
  712. for (;;) {
  713. int rem;
  714. if (total >= RECHDR_LEN && target == MAX_INBUF) {
  715. xhdr = (void*)tls->inbuf;
  716. target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  717. if (target > MAX_INBUF) {
  718. /* malformed input (too long): yell and die */
  719. tls->buffered_size = 0;
  720. tls->ofs_to_buffered = total;
  721. tls_error_die(tls);
  722. }
  723. /* can also check type/proto_maj/proto_min here */
  724. dbg("xhdr type:%d ver:%d.%d len:%d\n",
  725. xhdr->type, xhdr->proto_maj, xhdr->proto_min,
  726. 0x100 * xhdr->len16_hi + xhdr->len16_lo
  727. );
  728. }
  729. /* if total >= target, we have a full packet (and possibly more)... */
  730. if (total - target >= 0)
  731. break;
  732. /* input buffer is grown only as needed */
  733. rem = tls->inbuf_size - total;
  734. if (rem == 0) {
  735. tls->inbuf_size += MAX_INBUF / 8;
  736. if (tls->inbuf_size > MAX_INBUF)
  737. tls->inbuf_size = MAX_INBUF;
  738. dbg("inbuf_size:%d\n", tls->inbuf_size);
  739. rem = tls->inbuf_size - total;
  740. tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
  741. }
  742. sz = safe_read(tls->ifd, tls->inbuf + total, rem);
  743. if (sz <= 0) {
  744. if (sz == 0 && total == 0) {
  745. /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
  746. dbg("EOF (without TLS shutdown) from peer\n");
  747. tls->buffered_size = 0;
  748. goto end;
  749. }
  750. bb_perror_msg_and_die("short read, have only %d", total);
  751. }
  752. dump_raw_in("<< %s\n", tls->inbuf + total, sz);
  753. total += sz;
  754. }
  755. tls->buffered_size = total - target;
  756. tls->ofs_to_buffered = target;
  757. //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
  758. //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
  759. sz = target - RECHDR_LEN;
  760. /* Needs to be decrypted? */
  761. if (tls->min_encrypted_len_on_read > tls->MAC_size) {
  762. uint8_t *p = tls->inbuf + RECHDR_LEN;
  763. int padding_len;
  764. if (sz & (AES_BLOCKSIZE-1)
  765. || sz < (int)tls->min_encrypted_len_on_read
  766. ) {
  767. bb_error_msg_and_die("bad encrypted len:%u < %u",
  768. sz, tls->min_encrypted_len_on_read);
  769. }
  770. /* Decrypt content+MAC+padding, moving it over IV in the process */
  771. sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
  772. aes_cbc_decrypt(
  773. tls->server_write_key, tls->key_size, /* selects 128/256 */
  774. p, /* IV */
  775. p + AES_BLOCKSIZE, sz, /* ciphertext */
  776. p /* plaintext */
  777. );
  778. padding_len = p[sz - 1];
  779. dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
  780. padding_len++;
  781. sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
  782. //if (sz < 0)
  783. // bb_error_msg_and_die("bad padding size:%u", padding_len);
  784. } else {
  785. /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
  786. /* else: no encryption yet on input, subtract zero = NOP */
  787. sz -= tls->min_encrypted_len_on_read;
  788. }
  789. if (sz < 0)
  790. bb_error_msg_and_die("encrypted data too short");
  791. //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
  792. xhdr = (void*)tls->inbuf;
  793. if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
  794. uint8_t *p = tls->inbuf + RECHDR_LEN;
  795. dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
  796. if (p[0] == 2) { /* fatal */
  797. bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
  798. "error",
  799. p[1], alert_text(p[1])
  800. );
  801. }
  802. if (p[0] == 1) { /* warning */
  803. if (p[1] == 0) { /* "close_notify" warning: it's EOF */
  804. dbg("EOF (TLS encoded) from peer\n");
  805. sz = 0;
  806. goto end;
  807. }
  808. //This possibly needs to be cached and shown only if
  809. //a fatal alert follows
  810. // bb_error_msg("TLS %s from peer (alert code %d): %s",
  811. // "warning",
  812. // p[1], alert_text(p[1])
  813. // );
  814. /* discard it, get next record */
  815. goto again;
  816. }
  817. /* p[0] not 1 or 2: not defined in protocol */
  818. sz = 0;
  819. goto end;
  820. }
  821. /* RFC 5246 is not saying it explicitly, but sha256 hash
  822. * in our FINISHED record must include data of incoming packets too!
  823. */
  824. if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
  825. && tls->MAC_size != 0 /* do we know which hash to use? (server_hello() does not!) */
  826. ) {
  827. hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
  828. }
  829. end:
  830. dbg("got block len:%u\n", sz);
  831. return sz;
  832. }
  833. /*
  834. * DER parsing routines
  835. */
  836. static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
  837. {
  838. unsigned len, len1;
  839. if (end - der < 2)
  840. xfunc_die();
  841. // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
  842. // xfunc_die();
  843. len = der[1]; /* maybe it's short len */
  844. if (len >= 0x80) {
  845. /* no, it's long */
  846. if (len == 0x80 || end - der < (int)(len - 0x7e)) {
  847. /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
  848. /* need 3 or 4 bytes for 81, 82 */
  849. xfunc_die();
  850. }
  851. len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
  852. if (len > 0x82) {
  853. /* >0x82 is "3+ bytes of len", should not happen realistically */
  854. xfunc_die();
  855. }
  856. if (len == 0x82) { /* it's "ii 82 xx yy" */
  857. len1 = 0x100*len1 + der[3];
  858. der += 1; /* skip [yy] */
  859. }
  860. der += 1; /* skip [xx] */
  861. len = len1;
  862. // if (len < 0x80)
  863. // xfunc_die(); /* invalid DER: must use short len if can */
  864. }
  865. der += 2; /* skip [code]+[1byte] */
  866. if (end - der < (int)len)
  867. xfunc_die();
  868. *bodyp = der;
  869. return len;
  870. }
  871. static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
  872. {
  873. uint8_t *new_der;
  874. unsigned len = get_der_len(&new_der, der, *endp);
  875. dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
  876. /* Move "end" position to cover only this item */
  877. *endp = new_der + len;
  878. return new_der;
  879. }
  880. static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
  881. {
  882. uint8_t *new_der;
  883. unsigned len = get_der_len(&new_der, der, end);
  884. /* Skip body */
  885. new_der += len;
  886. dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
  887. return new_der;
  888. }
  889. static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
  890. {
  891. uint8_t *bin_ptr;
  892. unsigned len = get_der_len(&bin_ptr, der, end);
  893. dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
  894. pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
  895. pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
  896. //return bin + len;
  897. }
  898. static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
  899. {
  900. /* Certificate is a DER-encoded data structure. Each DER element has a length,
  901. * which makes it easy to skip over large compound elements of any complexity
  902. * without parsing them. Example: partial decode of kernel.org certificate:
  903. * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
  904. * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
  905. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
  906. * INTEGER (version): 0201 02
  907. * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
  908. * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
  909. * SEQ 0x0d bytes (signatureAlgo): 300d
  910. * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
  911. * NULL: 0500
  912. * SEQ 0x5f bytes (issuer): 305f
  913. * SET 11 bytes: 310b
  914. * SEQ 9 bytes: 3009
  915. * OID 3 bytes: 0603 550406
  916. * Printable string "FR": 1302 4652
  917. * SET 14 bytes: 310e
  918. * SEQ 12 bytes: 300c
  919. * OID 3 bytes: 0603 550408
  920. * Printable string "Paris": 1305 5061726973
  921. * SET 14 bytes: 310e
  922. * SEQ 12 bytes: 300c
  923. * OID 3 bytes: 0603 550407
  924. * Printable string "Paris": 1305 5061726973
  925. * SET 14 bytes: 310e
  926. * SEQ 12 bytes: 300c
  927. * OID 3 bytes: 0603 55040a
  928. * Printable string "Gandi": 1305 47616e6469
  929. * SET 32 bytes: 3120
  930. * SEQ 30 bytes: 301e
  931. * OID 3 bytes: 0603 550403
  932. * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
  933. * SEQ 30 bytes (validity): 301e
  934. * TIME "161011000000Z": 170d 3136313031313030303030305a
  935. * TIME "191011235959Z": 170d 3139313031313233353935395a
  936. * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
  937. * 3121301f060355040b1318446f6d61696e20436f
  938. * 6e74726f6c2056616c6964617465643121301f06
  939. * 0355040b1318506f73697469766553534c204d75
  940. * 6c74692d446f6d61696e31133011060355040313
  941. * 0a6b65726e656c2e6f7267
  942. * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
  943. * SEQ 13 bytes (algorithm): 300d
  944. * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
  945. * NULL: 0500
  946. * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
  947. * ????: 00
  948. * //after the zero byte, it appears key itself uses DER encoding:
  949. * SEQ 0x018a/394 bytes: 3082018a
  950. * INTEGER 0x0181/385 bytes (modulus): 02820181
  951. * 00b1ab2fc727a3bef76780c9349bf3
  952. * ...24 more blocks of 15 bytes each...
  953. * 90e895291c6bc8693b65
  954. * INTEGER 3 bytes (exponent): 0203 010001
  955. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
  956. * SEQ 0x01e1 bytes: 308201e1
  957. * ...
  958. * Certificate is a sequence of three elements:
  959. * tbsCertificate (SEQ)
  960. * signatureAlgorithm (AlgorithmIdentifier)
  961. * signatureValue (BIT STRING)
  962. *
  963. * In turn, tbsCertificate is a sequence of:
  964. * version
  965. * serialNumber
  966. * signatureAlgo (AlgorithmIdentifier)
  967. * issuer (Name, has complex structure)
  968. * validity (Validity, SEQ of two Times)
  969. * subject (Name)
  970. * subjectPublicKeyInfo (SEQ)
  971. * ...
  972. *
  973. * subjectPublicKeyInfo is a sequence of:
  974. * algorithm (AlgorithmIdentifier)
  975. * publicKey (BIT STRING)
  976. *
  977. * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
  978. */
  979. uint8_t *end = der + len;
  980. /* enter "Certificate" item: [der, end) will be only Cert */
  981. der = enter_der_item(der, &end);
  982. /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
  983. der = enter_der_item(der, &end);
  984. /* skip up to subjectPublicKeyInfo */
  985. der = skip_der_item(der, end); /* version */
  986. der = skip_der_item(der, end); /* serialNumber */
  987. der = skip_der_item(der, end); /* signatureAlgo */
  988. der = skip_der_item(der, end); /* issuer */
  989. der = skip_der_item(der, end); /* validity */
  990. der = skip_der_item(der, end); /* subject */
  991. /* enter subjectPublicKeyInfo */
  992. der = enter_der_item(der, &end);
  993. { /* check subjectPublicKeyInfo.algorithm */
  994. static const uint8_t expected[] = {
  995. 0x30,0x0d, // SEQ 13 bytes
  996. 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
  997. //0x05,0x00, // NULL
  998. };
  999. if (memcmp(der, expected, sizeof(expected)) != 0)
  1000. bb_error_msg_and_die("not RSA key");
  1001. }
  1002. /* skip subjectPublicKeyInfo.algorithm */
  1003. der = skip_der_item(der, end);
  1004. /* enter subjectPublicKeyInfo.publicKey */
  1005. // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
  1006. der = enter_der_item(der, &end);
  1007. /* parse RSA key: */
  1008. //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
  1009. dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
  1010. if (end - der < 14) xfunc_die();
  1011. /* example format:
  1012. * ignore bits: 00
  1013. * SEQ 0x018a/394 bytes: 3082018a
  1014. * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
  1015. * INTEGER 3 bytes (exponent): 0203 010001
  1016. */
  1017. if (*der != 0) /* "ignore bits", should be 0 */
  1018. xfunc_die();
  1019. der++;
  1020. der = enter_der_item(der, &end); /* enter SEQ */
  1021. /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
  1022. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
  1023. der = skip_der_item(der, end);
  1024. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
  1025. tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
  1026. dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
  1027. }
  1028. /*
  1029. * TLS Handshake routines
  1030. */
  1031. static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
  1032. {
  1033. struct record_hdr *xhdr;
  1034. int len = tls_xread_record(tls);
  1035. xhdr = (void*)tls->inbuf;
  1036. if (len < min_len
  1037. || xhdr->type != RECORD_TYPE_HANDSHAKE
  1038. || xhdr->proto_maj != TLS_MAJ
  1039. || xhdr->proto_min != TLS_MIN
  1040. ) {
  1041. bad_record_die(tls, "handshake record", len);
  1042. }
  1043. dbg("got HANDSHAKE\n");
  1044. return len;
  1045. }
  1046. static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
  1047. {
  1048. struct handshake_hdr {
  1049. uint8_t type;
  1050. uint8_t len24_hi, len24_mid, len24_lo;
  1051. } *h = buf;
  1052. len -= 4;
  1053. h->type = type;
  1054. h->len24_hi = len >> 16;
  1055. h->len24_mid = len >> 8;
  1056. h->len24_lo = len & 0xff;
  1057. }
  1058. static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
  1059. {
  1060. struct client_hello {
  1061. uint8_t type;
  1062. uint8_t len24_hi, len24_mid, len24_lo;
  1063. uint8_t proto_maj, proto_min;
  1064. uint8_t rand32[32];
  1065. uint8_t session_id_len;
  1066. /* uint8_t session_id[]; */
  1067. uint8_t cipherid_len16_hi, cipherid_len16_lo;
  1068. uint8_t cipherid[2 * (2 + !!CIPHER_ID2)]; /* actually variable */
  1069. uint8_t comprtypes_len;
  1070. uint8_t comprtypes[1]; /* actually variable */
  1071. /* Extensions (SNI shown):
  1072. * hi,lo // len of all extensions
  1073. * 00,00 // extension_type: "Server Name"
  1074. * 00,0e // list len (there can be more than one SNI)
  1075. * 00,0c // len of 1st Server Name Indication
  1076. * 00 // name type: host_name
  1077. * 00,09 // name len
  1078. * "localhost" // name
  1079. */
  1080. // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
  1081. // 0055
  1082. // 0005 0005 0100000000 - status_request
  1083. // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
  1084. // ff01 0001 00 - renegotiation_info
  1085. // 0023 0000 - session_ticket
  1086. // 000a 0008 0006001700180019 - supported_groups
  1087. // 000b 0002 0100 - ec_point_formats
  1088. // 000d 0016 00140401040305010503060106030301030302010203 - signature_algorithms
  1089. };
  1090. struct client_hello *record;
  1091. int len;
  1092. int sni_len = sni ? strnlen(sni, 127 - 9) : 0;
  1093. len = sizeof(*record);
  1094. if (sni_len)
  1095. len += 11 + sni_len;
  1096. record = tls_get_outbuf(tls, len);
  1097. memset(record, 0, len);
  1098. fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
  1099. record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
  1100. record->proto_min = TLS_MIN; /* can be higher than one in record headers */
  1101. tls_get_random(record->rand32, sizeof(record->rand32));
  1102. if (TLS_DEBUG_FIXED_SECRETS)
  1103. memset(record->rand32, 0x11, sizeof(record->rand32));
  1104. /* record->session_id_len = 0; - already is */
  1105. /* record->cipherid_len16_hi = 0; */
  1106. record->cipherid_len16_lo = sizeof(record->cipherid);
  1107. /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
  1108. /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
  1109. record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
  1110. if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
  1111. /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
  1112. #if CIPHER_ID2
  1113. if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
  1114. /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
  1115. #endif
  1116. record->comprtypes_len = 1;
  1117. /* record->comprtypes[0] = 0; */
  1118. if (sni_len) {
  1119. uint8_t *p = (void*)(record + 1);
  1120. //p[0] = 0; //
  1121. p[1] = sni_len + 9; //ext_len
  1122. //p[2] = 0; //
  1123. //p[3] = 0; //extension_type
  1124. //p[4] = 0; //
  1125. p[5] = sni_len + 5; //list len
  1126. //p[6] = 0; //
  1127. p[7] = sni_len + 3; //len of 1st SNI
  1128. //p[8] = 0; //name type
  1129. //p[9] = 0; //
  1130. p[10] = sni_len; //name len
  1131. memcpy(&p[11], sni, sni_len);
  1132. }
  1133. dbg(">> CLIENT_HELLO\n");
  1134. /* Can hash it only when we know which MAC hash to use */
  1135. /*xwrite_and_update_handshake_hash(tls, len); - WRONG! */
  1136. xwrite_handshake_record(tls, len);
  1137. tls->hsd = xzalloc(sizeof(*tls->hsd) + len);
  1138. tls->hsd->saved_client_hello_size = len;
  1139. memcpy(tls->hsd->saved_client_hello, record, len);
  1140. memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
  1141. }
  1142. static void get_server_hello(tls_state_t *tls)
  1143. {
  1144. struct server_hello {
  1145. struct record_hdr xhdr;
  1146. uint8_t type;
  1147. uint8_t len24_hi, len24_mid, len24_lo;
  1148. uint8_t proto_maj, proto_min;
  1149. uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
  1150. uint8_t session_id_len;
  1151. uint8_t session_id[32];
  1152. uint8_t cipherid_hi, cipherid_lo;
  1153. uint8_t comprtype;
  1154. /* extensions may follow, but only those which client offered in its Hello */
  1155. };
  1156. struct server_hello *hp;
  1157. uint8_t *cipherid;
  1158. unsigned cipher;
  1159. int len, len24;
  1160. len = tls_xread_handshake_block(tls, 74 - 32);
  1161. hp = (void*)tls->inbuf;
  1162. // 74 bytes:
  1163. // 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|
  1164. //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
  1165. if (hp->type != HANDSHAKE_SERVER_HELLO
  1166. || hp->len24_hi != 0
  1167. || hp->len24_mid != 0
  1168. /* hp->len24_lo checked later */
  1169. || hp->proto_maj != TLS_MAJ
  1170. || hp->proto_min != TLS_MIN
  1171. ) {
  1172. bad_record_die(tls, "'server hello'", len);
  1173. }
  1174. cipherid = &hp->cipherid_hi;
  1175. len24 = hp->len24_lo;
  1176. if (hp->session_id_len != 32) {
  1177. if (hp->session_id_len != 0)
  1178. bad_record_die(tls, "'server hello'", len);
  1179. // session_id_len == 0: no session id
  1180. // "The server
  1181. // may return an empty session_id to indicate that the session will
  1182. // not be cached and therefore cannot be resumed."
  1183. cipherid -= 32;
  1184. len24 += 32; /* what len would be if session id would be present */
  1185. }
  1186. if (len24 < 70
  1187. // || cipherid[0] != (CIPHER_ID >> 8)
  1188. // || cipherid[1] != (CIPHER_ID & 0xff)
  1189. // || cipherid[2] != 0 /* comprtype */
  1190. ) {
  1191. bad_record_die(tls, "'server hello'", len);
  1192. }
  1193. dbg("<< SERVER_HELLO\n");
  1194. memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
  1195. tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
  1196. dbg("server chose cipher %04x\n", cipher);
  1197. if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA) {
  1198. tls->key_size = AES128_KEYSIZE;
  1199. tls->MAC_size = SHA1_OUTSIZE;
  1200. }
  1201. else { /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
  1202. tls->key_size = AES256_KEYSIZE;
  1203. tls->MAC_size = SHA256_OUTSIZE;
  1204. }
  1205. /* Handshake hash eventually destined to FINISHED record
  1206. * is sha256 regardless of cipher
  1207. * (at least for all ciphers defined by RFC5246).
  1208. * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
  1209. */
  1210. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1211. hash_handshake(tls, ">> client hello hash:%s",
  1212. tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
  1213. );
  1214. hash_handshake(tls, "<< server hello hash:%s",
  1215. tls->inbuf + RECHDR_LEN, len
  1216. );
  1217. }
  1218. static void get_server_cert(tls_state_t *tls)
  1219. {
  1220. struct record_hdr *xhdr;
  1221. uint8_t *certbuf;
  1222. int len, len1;
  1223. len = tls_xread_handshake_block(tls, 10);
  1224. xhdr = (void*)tls->inbuf;
  1225. certbuf = (void*)(xhdr + 1);
  1226. if (certbuf[0] != HANDSHAKE_CERTIFICATE)
  1227. tls_error_die(tls);
  1228. dbg("<< CERTIFICATE\n");
  1229. // 4392 bytes:
  1230. // 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...
  1231. //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
  1232. len1 = get24be(certbuf + 1);
  1233. if (len1 > len - 4) tls_error_die(tls);
  1234. len = len1;
  1235. len1 = get24be(certbuf + 4);
  1236. if (len1 > len - 3) tls_error_die(tls);
  1237. len = len1;
  1238. len1 = get24be(certbuf + 7);
  1239. if (len1 > len - 3) tls_error_die(tls);
  1240. len = len1;
  1241. if (len)
  1242. find_key_in_der_cert(tls, certbuf + 10, len);
  1243. }
  1244. static void send_empty_client_cert(tls_state_t *tls)
  1245. {
  1246. struct client_empty_cert {
  1247. uint8_t type;
  1248. uint8_t len24_hi, len24_mid, len24_lo;
  1249. uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
  1250. };
  1251. struct client_empty_cert *record;
  1252. record = tls_get_outbuf(tls, sizeof(*record));
  1253. //FIXME: can just memcpy a ready-made one.
  1254. fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
  1255. record->cert_chain_len24_hi = 0;
  1256. record->cert_chain_len24_mid = 0;
  1257. record->cert_chain_len24_lo = 0;
  1258. dbg(">> CERTIFICATE\n");
  1259. xwrite_and_update_handshake_hash(tls, sizeof(*record));
  1260. }
  1261. static void send_client_key_exchange(tls_state_t *tls)
  1262. {
  1263. struct client_key_exchange {
  1264. uint8_t type;
  1265. uint8_t len24_hi, len24_mid, len24_lo;
  1266. /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
  1267. uint8_t keylen16_hi, keylen16_lo;
  1268. uint8_t key[4 * 1024]; // size??
  1269. };
  1270. //FIXME: better size estimate
  1271. struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
  1272. uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
  1273. int len;
  1274. tls_get_random(rsa_premaster, sizeof(rsa_premaster));
  1275. if (TLS_DEBUG_FIXED_SECRETS)
  1276. memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
  1277. // RFC 5246
  1278. // "Note: The version number in the PreMasterSecret is the version
  1279. // offered by the client in the ClientHello.client_version, not the
  1280. // version negotiated for the connection."
  1281. rsa_premaster[0] = TLS_MAJ;
  1282. rsa_premaster[1] = TLS_MIN;
  1283. dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
  1284. len = psRsaEncryptPub(/*pool:*/ NULL,
  1285. /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
  1286. rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
  1287. record->key, sizeof(record->key),
  1288. data_param_ignored
  1289. );
  1290. record->keylen16_hi = len >> 8;
  1291. record->keylen16_lo = len & 0xff;
  1292. len += 2;
  1293. record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
  1294. record->len24_hi = 0;
  1295. record->len24_mid = len >> 8;
  1296. record->len24_lo = len & 0xff;
  1297. len += 4;
  1298. dbg(">> CLIENT_KEY_EXCHANGE\n");
  1299. xwrite_and_update_handshake_hash(tls, len);
  1300. // RFC 5246
  1301. // For all key exchange methods, the same algorithm is used to convert
  1302. // the pre_master_secret into the master_secret. The pre_master_secret
  1303. // should be deleted from memory once the master_secret has been
  1304. // computed.
  1305. // master_secret = PRF(pre_master_secret, "master secret",
  1306. // ClientHello.random + ServerHello.random)
  1307. // [0..47];
  1308. // The master secret is always exactly 48 bytes in length. The length
  1309. // of the premaster secret will vary depending on key exchange method.
  1310. prf_hmac_sha256(/*tls,*/
  1311. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1312. rsa_premaster, sizeof(rsa_premaster),
  1313. "master secret",
  1314. tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
  1315. );
  1316. dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1317. // RFC 5246
  1318. // 6.3. Key Calculation
  1319. //
  1320. // The Record Protocol requires an algorithm to generate keys required
  1321. // by the current connection state (see Appendix A.6) from the security
  1322. // parameters provided by the handshake protocol.
  1323. //
  1324. // The master secret is expanded into a sequence of secure bytes, which
  1325. // is then split to a client write MAC key, a server write MAC key, a
  1326. // client write encryption key, and a server write encryption key. Each
  1327. // of these is generated from the byte sequence in that order. Unused
  1328. // values are empty. Some AEAD ciphers may additionally require a
  1329. // client write IV and a server write IV (see Section 6.2.3.3).
  1330. //
  1331. // When keys and MAC keys are generated, the master secret is used as an
  1332. // entropy source.
  1333. //
  1334. // To generate the key material, compute
  1335. //
  1336. // key_block = PRF(SecurityParameters.master_secret,
  1337. // "key expansion",
  1338. // SecurityParameters.server_random +
  1339. // SecurityParameters.client_random);
  1340. //
  1341. // until enough output has been generated. Then, the key_block is
  1342. // partitioned as follows:
  1343. //
  1344. // client_write_MAC_key[SecurityParameters.mac_key_length]
  1345. // server_write_MAC_key[SecurityParameters.mac_key_length]
  1346. // client_write_key[SecurityParameters.enc_key_length]
  1347. // server_write_key[SecurityParameters.enc_key_length]
  1348. // client_write_IV[SecurityParameters.fixed_iv_length]
  1349. // server_write_IV[SecurityParameters.fixed_iv_length]
  1350. {
  1351. uint8_t tmp64[64];
  1352. /* make "server_rand32 + client_rand32" */
  1353. memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
  1354. memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
  1355. prf_hmac_sha256(/*tls,*/
  1356. tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size),
  1357. // also fills:
  1358. // server_write_MAC_key[]
  1359. // client_write_key[]
  1360. // server_write_key[]
  1361. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1362. "key expansion",
  1363. tmp64, 64
  1364. );
  1365. tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
  1366. tls->server_write_key = tls->client_write_key + tls->key_size;
  1367. dump_hex("client_write_MAC_key:%s\n",
  1368. tls->client_write_MAC_key, tls->MAC_size
  1369. );
  1370. dump_hex("client_write_key:%s\n",
  1371. tls->client_write_key, tls->key_size
  1372. );
  1373. }
  1374. }
  1375. static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
  1376. RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
  1377. 01
  1378. };
  1379. static void send_change_cipher_spec(tls_state_t *tls)
  1380. {
  1381. dbg(">> CHANGE_CIPHER_SPEC\n");
  1382. xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
  1383. }
  1384. // 7.4.9. Finished
  1385. // A Finished message is always sent immediately after a change
  1386. // cipher spec message to verify that the key exchange and
  1387. // authentication processes were successful. It is essential that a
  1388. // change cipher spec message be received between the other handshake
  1389. // messages and the Finished message.
  1390. //...
  1391. // The Finished message is the first one protected with the just
  1392. // negotiated algorithms, keys, and secrets. Recipients of Finished
  1393. // messages MUST verify that the contents are correct. Once a side
  1394. // has sent its Finished message and received and validated the
  1395. // Finished message from its peer, it may begin to send and receive
  1396. // application data over the connection.
  1397. //...
  1398. // struct {
  1399. // opaque verify_data[verify_data_length];
  1400. // } Finished;
  1401. //
  1402. // verify_data
  1403. // PRF(master_secret, finished_label, Hash(handshake_messages))
  1404. // [0..verify_data_length-1];
  1405. //
  1406. // finished_label
  1407. // For Finished messages sent by the client, the string
  1408. // "client finished". For Finished messages sent by the server,
  1409. // the string "server finished".
  1410. //
  1411. // Hash denotes a Hash of the handshake messages. For the PRF
  1412. // defined in Section 5, the Hash MUST be the Hash used as the basis
  1413. // for the PRF. Any cipher suite which defines a different PRF MUST
  1414. // also define the Hash to use in the Finished computation.
  1415. //
  1416. // In previous versions of TLS, the verify_data was always 12 octets
  1417. // long. In the current version of TLS, it depends on the cipher
  1418. // suite. Any cipher suite which does not explicitly specify
  1419. // verify_data_length has a verify_data_length equal to 12. This
  1420. // includes all existing cipher suites.
  1421. static void send_client_finished(tls_state_t *tls)
  1422. {
  1423. struct finished {
  1424. uint8_t type;
  1425. uint8_t len24_hi, len24_mid, len24_lo;
  1426. uint8_t prf_result[12];
  1427. };
  1428. struct finished *record = tls_get_outbuf(tls, sizeof(*record));
  1429. uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
  1430. unsigned len;
  1431. fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
  1432. len = get_handshake_hash(tls, handshake_hash);
  1433. prf_hmac_sha256(/*tls,*/
  1434. record->prf_result, sizeof(record->prf_result),
  1435. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1436. "client finished",
  1437. handshake_hash, len
  1438. );
  1439. dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1440. dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
  1441. dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
  1442. dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
  1443. dbg(">> FINISHED\n");
  1444. xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
  1445. }
  1446. void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
  1447. {
  1448. // Client RFC 5246 Server
  1449. // (*) - optional messages, not always sent
  1450. //
  1451. // ClientHello ------->
  1452. // ServerHello
  1453. // Certificate*
  1454. // ServerKeyExchange*
  1455. // CertificateRequest*
  1456. // <------- ServerHelloDone
  1457. // Certificate*
  1458. // ClientKeyExchange
  1459. // CertificateVerify*
  1460. // [ChangeCipherSpec]
  1461. // Finished ------->
  1462. // [ChangeCipherSpec]
  1463. // <------- Finished
  1464. // Application Data <------> Application Data
  1465. int len;
  1466. send_client_hello_and_alloc_hsd(tls, sni);
  1467. get_server_hello(tls);
  1468. // RFC 5246
  1469. // The server MUST send a Certificate message whenever the agreed-
  1470. // upon key exchange method uses certificates for authentication
  1471. // (this includes all key exchange methods defined in this document
  1472. // except DH_anon). This message will always immediately follow the
  1473. // ServerHello message.
  1474. //
  1475. // IOW: in practice, Certificate *always* follows.
  1476. // (for example, kernel.org does not even accept DH_anon cipher id)
  1477. get_server_cert(tls);
  1478. len = tls_xread_handshake_block(tls, 4);
  1479. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
  1480. // 459 bytes:
  1481. // 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...
  1482. //SvKey len=455^
  1483. // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
  1484. // 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...
  1485. dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
  1486. //probably need to save it
  1487. len = tls_xread_handshake_block(tls, 4);
  1488. }
  1489. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST) {
  1490. dbg("<< CERTIFICATE_REQUEST\n");
  1491. // RFC 5246: "If no suitable certificate is available,
  1492. // the client MUST send a certificate message containing no
  1493. // certificates. That is, the certificate_list structure has a
  1494. // length of zero. ...
  1495. // Client certificates are sent using the Certificate structure
  1496. // defined in Section 7.4.2."
  1497. // (i.e. the same format as server certs)
  1498. send_empty_client_cert(tls);
  1499. len = tls_xread_handshake_block(tls, 4);
  1500. }
  1501. if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
  1502. bad_record_die(tls, "'server hello done'", len);
  1503. }
  1504. // 0e 000000 (len:0)
  1505. dbg("<< SERVER_HELLO_DONE\n");
  1506. send_client_key_exchange(tls);
  1507. send_change_cipher_spec(tls);
  1508. /* from now on we should send encrypted */
  1509. /* tls->write_seq64_be = 0; - already is */
  1510. tls->encrypt_on_write = 1;
  1511. send_client_finished(tls);
  1512. /* Get CHANGE_CIPHER_SPEC */
  1513. len = tls_xread_record(tls);
  1514. if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
  1515. bad_record_die(tls, "switch to encrypted traffic", len);
  1516. dbg("<< CHANGE_CIPHER_SPEC\n");
  1517. if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
  1518. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  1519. ) {
  1520. tls->min_encrypted_len_on_read = tls->MAC_size;
  1521. } else {
  1522. unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCKSIZE-1) / AES_BLOCKSIZE;
  1523. /* all incoming packets now should be encrypted and have
  1524. * at least IV + (MAC padded to blocksize):
  1525. */
  1526. tls->min_encrypted_len_on_read = AES_BLOCKSIZE + (mac_blocks * AES_BLOCKSIZE);
  1527. dbg("min_encrypted_len_on_read: %u", tls->min_encrypted_len_on_read);
  1528. }
  1529. /* Get (encrypted) FINISHED from the server */
  1530. len = tls_xread_record(tls);
  1531. if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
  1532. tls_error_die(tls);
  1533. dbg("<< FINISHED\n");
  1534. /* application data can be sent/received */
  1535. /* free handshake data */
  1536. // if (PARANOIA)
  1537. // memset(tls->hsd, 0, tls->hsd->hsd_size);
  1538. free(tls->hsd);
  1539. tls->hsd = NULL;
  1540. }
  1541. static void tls_xwrite(tls_state_t *tls, int len)
  1542. {
  1543. dbg(">> DATA\n");
  1544. xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
  1545. }
  1546. // To run a test server using openssl:
  1547. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  1548. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
  1549. //
  1550. // Unencryped SHA256 example:
  1551. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  1552. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
  1553. // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
  1554. void FAST_FUNC tls_run_copy_loop(tls_state_t *tls)
  1555. {
  1556. int inbuf_size;
  1557. const int INBUF_STEP = 4 * 1024;
  1558. struct pollfd pfds[2];
  1559. pfds[0].fd = STDIN_FILENO;
  1560. pfds[0].events = POLLIN;
  1561. pfds[1].fd = tls->ifd;
  1562. pfds[1].events = POLLIN;
  1563. inbuf_size = INBUF_STEP;
  1564. for (;;) {
  1565. int nread;
  1566. if (safe_poll(pfds, 2, -1) < 0)
  1567. bb_perror_msg_and_die("poll");
  1568. if (pfds[0].revents) {
  1569. void *buf;
  1570. dbg("STDIN HAS DATA\n");
  1571. buf = tls_get_outbuf(tls, inbuf_size);
  1572. nread = safe_read(STDIN_FILENO, buf, inbuf_size);
  1573. if (nread < 1) {
  1574. /* We'd want to do this: */
  1575. /* Close outgoing half-connection so they get EOF,
  1576. * but leave incoming alone so we can see response
  1577. */
  1578. //shutdown(tls->ofd, SHUT_WR);
  1579. /* But TLS has no way to encode this,
  1580. * doubt it's ok to do it "raw"
  1581. */
  1582. pfds[0].fd = -1;
  1583. tls_free_outbuf(tls); /* mem usage optimization */
  1584. } else {
  1585. if (nread == inbuf_size) {
  1586. /* TLS has per record overhead, if input comes fast,
  1587. * read, encrypt and send bigger chunks
  1588. */
  1589. inbuf_size += INBUF_STEP;
  1590. if (inbuf_size > TLS_MAX_OUTBUF)
  1591. inbuf_size = TLS_MAX_OUTBUF;
  1592. }
  1593. tls_xwrite(tls, nread);
  1594. }
  1595. }
  1596. if (pfds[1].revents) {
  1597. dbg("NETWORK HAS DATA\n");
  1598. read_record:
  1599. nread = tls_xread_record(tls);
  1600. if (nread < 1) {
  1601. /* TLS protocol has no real concept of one-sided shutdowns:
  1602. * if we get "TLS EOF" from the peer, writes will fail too
  1603. */
  1604. //pfds[1].fd = -1;
  1605. //close(STDOUT_FILENO);
  1606. //tls_free_inbuf(tls); /* mem usage optimization */
  1607. //continue;
  1608. break;
  1609. }
  1610. if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
  1611. bb_error_msg_and_die("unexpected record type %d", tls->inbuf[0]);
  1612. xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
  1613. /* We may already have a complete next record buffered,
  1614. * can process it without network reads (and possible blocking)
  1615. */
  1616. if (tls_has_buffered_record(tls))
  1617. goto read_record;
  1618. }
  1619. }
  1620. }