tls.c 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483
  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. //Note:
  10. //Config.src also defines FEATURE_TLS_SHA1 option
  11. //kbuild:lib-$(CONFIG_TLS) += tls.o
  12. //kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
  13. //kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
  14. //kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
  15. //kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
  16. //kbuild:lib-$(CONFIG_TLS) += tls_aes.o
  17. //kbuild:lib-$(CONFIG_TLS) += tls_aesgcm.o
  18. //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
  19. //kbuild:lib-$(CONFIG_TLS) += tls_fe.o
  20. //kbuild:lib-$(CONFIG_TLS) += tls_sp_c32.o
  21. #include "tls.h"
  22. // Usually enabled. You can disable some of them to force only
  23. // specific ciphers to be advertized to server.
  24. // (this would not exclude code to handle disabled ciphers, no code size win)
  25. #define ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 1
  26. #define ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 1
  27. #define ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 1
  28. #define ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 1
  29. #define ALLOW_RSA_WITH_AES_128_CBC_SHA256 1
  30. #define ALLOW_RSA_WITH_AES_256_CBC_SHA256 1
  31. #define ALLOW_RSA_WITH_AES_128_GCM_SHA256 1
  32. #define ALLOW_CURVE_P256 1
  33. #define ALLOW_CURVE_X25519 1
  34. // For testing (does everything except encrypting).
  35. // works against "openssl s_server -cipher NULL"
  36. // and against wolfssl-3.9.10-stable/examples/server/server.c:
  37. #define ALLOW_RSA_NULL_SHA256 0
  38. #define TLS_DEBUG 0
  39. #define TLS_DEBUG_HASH 0
  40. #define TLS_DEBUG_DER 0
  41. #define TLS_DEBUG_FIXED_SECRETS 0
  42. #if 0
  43. # define dump_raw_out(...) dump_hex(__VA_ARGS__)
  44. #else
  45. # define dump_raw_out(...) ((void)0)
  46. #endif
  47. #if 0
  48. # define dump_raw_in(...) dump_hex(__VA_ARGS__)
  49. #else
  50. # define dump_raw_in(...) ((void)0)
  51. #endif
  52. #if TLS_DEBUG
  53. # define dbg(...) fprintf(stderr, __VA_ARGS__)
  54. #else
  55. # define dbg(...) ((void)0)
  56. #endif
  57. #if TLS_DEBUG_DER
  58. # define dbg_der(...) fprintf(stderr, __VA_ARGS__)
  59. #else
  60. # define dbg_der(...) ((void)0)
  61. #endif
  62. //TLS 1.2
  63. #define TLS_MAJ 3
  64. #define TLS_MIN 3
  65. #define RECORD_TYPE_CHANGE_CIPHER_SPEC 20 /* 0x14 */
  66. #define RECORD_TYPE_ALERT 21 /* 0x15 */
  67. #define RECORD_TYPE_HANDSHAKE 22 /* 0x16 */
  68. #define RECORD_TYPE_APPLICATION_DATA 23 /* 0x17 */
  69. #define HANDSHAKE_HELLO_REQUEST 0 /* 0x00 */
  70. #define HANDSHAKE_CLIENT_HELLO 1 /* 0x01 */
  71. #define HANDSHAKE_SERVER_HELLO 2 /* 0x02 */
  72. #define HANDSHAKE_HELLO_VERIFY_REQUEST 3 /* 0x03 */
  73. #define HANDSHAKE_NEW_SESSION_TICKET 4 /* 0x04 */
  74. #define HANDSHAKE_CERTIFICATE 11 /* 0x0b */
  75. #define HANDSHAKE_SERVER_KEY_EXCHANGE 12 /* 0x0c */
  76. #define HANDSHAKE_CERTIFICATE_REQUEST 13 /* 0x0d */
  77. #define HANDSHAKE_SERVER_HELLO_DONE 14 /* 0x0e */
  78. #define HANDSHAKE_CERTIFICATE_VERIFY 15 /* 0x0f */
  79. #define HANDSHAKE_CLIENT_KEY_EXCHANGE 16 /* 0x10 */
  80. #define HANDSHAKE_FINISHED 20 /* 0x14 */
  81. #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF /* not a real cipher id... */
  82. #define SSL_NULL_WITH_NULL_NULL 0x0000
  83. #define SSL_RSA_WITH_NULL_MD5 0x0001
  84. #define SSL_RSA_WITH_NULL_SHA 0x0002
  85. #define SSL_RSA_WITH_RC4_128_MD5 0x0004
  86. #define SSL_RSA_WITH_RC4_128_SHA 0x0005
  87. #define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
  88. #define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
  89. #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
  90. #define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
  91. #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
  92. #define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /*SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA1 */
  93. #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
  94. #define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
  95. #define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
  96. #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
  97. #define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
  98. #define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
  99. #define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
  100. #define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
  101. #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
  102. #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
  103. #define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
  104. #define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
  105. #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
  106. #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
  107. #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
  108. #define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(128) Mac=AEAD */
  109. #define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(256) Mac=AEAD */
  110. #define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x009E /*TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(128) Mac=AEAD */
  111. #define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 0x009F /*TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(256) Mac=AEAD */
  112. #define TLS_DH_anon_WITH_AES_128_GCM_SHA256 0x00A6 /* RFC 5288 */
  113. #define TLS_DH_anon_WITH_AES_256_GCM_SHA384 0x00A7 /* RFC 5288 */
  114. #define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
  115. #define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
  116. #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
  117. #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
  118. #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA1 */
  119. #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA1 */
  120. #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
  121. #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
  122. #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
  123. #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA1 */
  124. #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA1 */
  125. #define TLS_ECDH_anon_WITH_AES_128_CBC_SHA 0xC018 /* RFC 4492 */
  126. #define TLS_ECDH_anon_WITH_AES_256_CBC_SHA 0xC019 /* RFC 4492 */
  127. #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256 */
  128. #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA384 */
  129. #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
  130. #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
  131. #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256 */
  132. #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384 */
  133. #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
  134. #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
  135. /* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
  136. #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(128) Mac=AEAD */
  137. #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(256) Mac=AEAD */
  138. #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
  139. #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
  140. #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD */
  141. #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD */
  142. #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
  143. #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
  144. #define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA 0xC035
  145. #define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA 0xC036
  146. #define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0xC037
  147. #define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0xC038
  148. /* From http://wiki.mozilla.org/Security/Server_Side_TLS */
  149. /* and 'openssl ciphers -V -stdname' */
  150. #define TLS_RSA_WITH_AES_128_CCM 0xC09C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(128) Mac=AEAD */
  151. #define TLS_RSA_WITH_AES_256_CCM 0xC09D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(256) Mac=AEAD */
  152. #define TLS_DHE_RSA_WITH_AES_128_CCM 0xC09E /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM(128) Mac=AEAD */
  153. #define TLS_DHE_RSA_WITH_AES_256_CCM 0xC09F /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM(256) Mac=AEAD */
  154. #define TLS_RSA_WITH_AES_128_CCM_8 0xC0A0 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(128) Mac=AEAD */
  155. #define TLS_RSA_WITH_AES_256_CCM_8 0xC0A1 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(256) Mac=AEAD */
  156. #define TLS_DHE_RSA_WITH_AES_128_CCM_8 0xC0A2 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(128) Mac=AEAD */
  157. #define TLS_DHE_RSA_WITH_AES_256_CCM_8 0xC0A3 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(256) Mac=AEAD */
  158. #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(128) Mac=AEAD */
  159. #define TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(256) Mac=AEAD */
  160. #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(128) Mac=AEAD */
  161. #define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(256) Mac=AEAD */
  162. #define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /*TLSv1.2 Kx=ECDH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
  163. #define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
  164. #define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /*TLSv1.2 Kx=DH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
  165. #define TLS_AES_128_GCM_SHA256 0x1301 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(128) Mac=AEAD */
  166. #define TLS_AES_256_GCM_SHA384 0x1302 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(256) Mac=AEAD */
  167. #define TLS_CHACHA20_POLY1305_SHA256 0x1303 /*TLSv1.3 Kx=any Au=any Enc=CHACHA20/POLY1305(256) Mac=AEAD */
  168. #define TLS_AES_128_CCM_SHA256 0x1304 /*TLSv1.3 Kx=any Au=any Enc=AESCCM(128) Mac=AEAD */
  169. /* Might go to libbb.h */
  170. #define TLS_MAX_CRYPTBLOCK_SIZE 16
  171. #define TLS_MAX_OUTBUF (1 << 14)
  172. enum {
  173. SHA_INSIZE = 64,
  174. AES128_KEYSIZE = 16,
  175. AES256_KEYSIZE = 32,
  176. RSA_PREMASTER_SIZE = 48,
  177. RECHDR_LEN = 5,
  178. /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
  179. OUTBUF_PFX = 8 + AES_BLOCK_SIZE, /* header + IV */
  180. OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
  181. // RFC 5246:
  182. // | 6.2.1. Fragmentation
  183. // | The record layer fragments information blocks into TLSPlaintext
  184. // | records carrying data in chunks of 2^14 bytes or less. Client
  185. // | message boundaries are not preserved in the record layer (i.e.,
  186. // | multiple client messages of the same ContentType MAY be coalesced
  187. // | into a single TLSPlaintext record, or a single message MAY be
  188. // | fragmented across several records)
  189. // |...
  190. // | length
  191. // | The length (in bytes) of the following TLSPlaintext.fragment.
  192. // | The length MUST NOT exceed 2^14.
  193. // |...
  194. // | 6.2.2. Record Compression and Decompression
  195. // |...
  196. // | Compression must be lossless and may not increase the content length
  197. // | by more than 1024 bytes. If the decompression function encounters a
  198. // | TLSCompressed.fragment that would decompress to a length in excess of
  199. // | 2^14 bytes, it MUST report a fatal decompression failure error.
  200. // |...
  201. // | length
  202. // | The length (in bytes) of the following TLSCompressed.fragment.
  203. // | The length MUST NOT exceed 2^14 + 1024.
  204. // |...
  205. // | 6.2.3. Record Payload Protection
  206. // | The encryption and MAC functions translate a TLSCompressed
  207. // | structure into a TLSCiphertext. The decryption functions reverse
  208. // | the process. The MAC of the record also includes a sequence
  209. // | number so that missing, extra, or repeated messages are
  210. // | detectable.
  211. // |...
  212. // | length
  213. // | The length (in bytes) of the following TLSCiphertext.fragment.
  214. // | The length MUST NOT exceed 2^14 + 2048.
  215. MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
  216. /* Bits for tls->flags */
  217. NEED_EC_KEY = 1 << 0,
  218. GOT_CERT_RSA_KEY_ALG = 1 << 1,
  219. GOT_CERT_ECDSA_KEY_ALG = 1 << 2, // so far unused
  220. GOT_EC_KEY = 1 << 3,
  221. GOT_EC_CURVE_X25519 = 1 << 4, // else P256
  222. ENCRYPTION_AESGCM = 1 << 5, // else AES-SHA (or NULL-SHA if ALLOW_RSA_NULL_SHA256=1)
  223. ENCRYPT_ON_WRITE = 1 << 6,
  224. };
  225. struct record_hdr {
  226. uint8_t type;
  227. uint8_t proto_maj, proto_min;
  228. uint8_t len16_hi, len16_lo;
  229. };
  230. struct tls_handshake_data {
  231. /* In bbox, md5/sha1/sha256 ctx's are the same structure */
  232. md5sha_ctx_t handshake_hash_ctx;
  233. uint8_t client_and_server_rand32[2 * 32];
  234. uint8_t master_secret[48];
  235. //TODO: store just the DER key here, parse/use/delete it when sending client key
  236. //this way it will stay key type agnostic here.
  237. psRsaKey_t server_rsa_pub_key;
  238. /* peer's elliptic curve key data */
  239. /* for x25519, it contains one point in first 32 bytes */
  240. /* for P256, it contains x,y point pair, each 32 bytes long */
  241. uint8_t ecc_pub_key32[2 * 32];
  242. /* HANDSHAKE HASH: */
  243. //unsigned saved_client_hello_size;
  244. //uint8_t saved_client_hello[1];
  245. };
  246. static unsigned get24be(const uint8_t *p)
  247. {
  248. return 0x100*(0x100*p[0] + p[1]) + p[2];
  249. }
  250. #if TLS_DEBUG
  251. /* Nondestructively see the current hash value */
  252. # if TLS_DEBUG_HASH
  253. static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
  254. {
  255. md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
  256. return sha_end(&ctx_copy, buffer);
  257. }
  258. # endif
  259. static void dump_hex(const char *fmt, const void *vp, int len)
  260. {
  261. char hexbuf[32 * 1024 + 4];
  262. const uint8_t *p = vp;
  263. bin2hex(hexbuf, (void*)p, len)[0] = '\0';
  264. dbg(fmt, hexbuf);
  265. }
  266. static void dump_tls_record(const void *vp, int len)
  267. {
  268. const uint8_t *p = vp;
  269. while (len > 0) {
  270. unsigned xhdr_len;
  271. if (len < RECHDR_LEN) {
  272. dump_hex("< |%s|\n", p, len);
  273. return;
  274. }
  275. xhdr_len = 0x100*p[3] + p[4];
  276. dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
  277. p += RECHDR_LEN;
  278. len -= RECHDR_LEN;
  279. if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
  280. unsigned len24 = get24be(p + 1);
  281. dbg(" type:%u len24:%u", p[0], len24);
  282. }
  283. if (xhdr_len > len)
  284. xhdr_len = len;
  285. dump_hex(" |%s|\n", p, xhdr_len);
  286. p += xhdr_len;
  287. len -= xhdr_len;
  288. }
  289. }
  290. #else
  291. # define dump_hex(...) ((void)0)
  292. # define dump_tls_record(...) ((void)0)
  293. #endif
  294. void FAST_FUNC tls_get_random(void *buf, unsigned len)
  295. {
  296. if (len != open_read_close("/dev/urandom", buf, len))
  297. xfunc_die();
  298. }
  299. static void xorbuf3(void *dst, const void *src1, const void *src2, unsigned count)
  300. {
  301. uint8_t *d = dst;
  302. const uint8_t *s1 = src1;
  303. const uint8_t* s2 = src2;
  304. while (count--)
  305. *d++ = *s1++ ^ *s2++;
  306. }
  307. void FAST_FUNC xorbuf(void *dst, const void *src, unsigned count)
  308. {
  309. xorbuf3(dst, dst, src, count);
  310. }
  311. void FAST_FUNC xorbuf_aligned_AES_BLOCK_SIZE(void *dst, const void *src)
  312. {
  313. unsigned long *d = dst;
  314. const unsigned long *s = src;
  315. d[0] ^= s[0];
  316. #if ULONG_MAX <= 0xffffffffffffffff
  317. d[1] ^= s[1];
  318. #if ULONG_MAX == 0xffffffff
  319. d[2] ^= s[2];
  320. d[3] ^= s[3];
  321. #endif
  322. #endif
  323. }
  324. #if !TLS_DEBUG_HASH
  325. # define hash_handshake(tls, fmt, buffer, len) \
  326. hash_handshake(tls, buffer, len)
  327. #endif
  328. static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
  329. {
  330. md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
  331. #if TLS_DEBUG_HASH
  332. {
  333. uint8_t h[TLS_MAX_MAC_SIZE];
  334. dump_hex(fmt, buffer, len);
  335. dbg(" (%u bytes) ", (int)len);
  336. len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
  337. if (ENABLE_FEATURE_TLS_SHA1 && len == SHA1_OUTSIZE)
  338. dump_hex("sha1:%s\n", h, len);
  339. else
  340. if (len == SHA256_OUTSIZE)
  341. dump_hex("sha256:%s\n", h, len);
  342. else
  343. dump_hex("sha???:%s\n", h, len);
  344. }
  345. #endif
  346. }
  347. #if !ENABLE_FEATURE_TLS_SHA1
  348. # define TLS_MAC_SIZE(tls) SHA256_OUTSIZE
  349. #else
  350. # define TLS_MAC_SIZE(tls) (tls)->MAC_size
  351. #endif
  352. // RFC 2104:
  353. // HMAC(key, text) based on a hash H (say, sha256) is:
  354. // ipad = [0x36 x INSIZE]
  355. // opad = [0x5c x INSIZE]
  356. // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
  357. //
  358. // H(key XOR opad) and H(key XOR ipad) can be precomputed
  359. // if we often need HMAC hmac with the same key.
  360. //
  361. // text is often given in disjoint pieces.
  362. typedef struct hmac_precomputed {
  363. md5sha_ctx_t hashed_key_xor_ipad;
  364. md5sha_ctx_t hashed_key_xor_opad;
  365. } hmac_precomputed_t;
  366. typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
  367. #if !ENABLE_FEATURE_TLS_SHA1
  368. #define hmac_begin(pre,key,key_size,begin) \
  369. hmac_begin(pre,key,key_size)
  370. #define begin sha256_begin
  371. #endif
  372. static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
  373. {
  374. uint8_t key_xor_ipad[SHA_INSIZE];
  375. uint8_t key_xor_opad[SHA_INSIZE];
  376. // uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
  377. unsigned i;
  378. // "The authentication key can be of any length up to INSIZE, the
  379. // block length of the hash function. Applications that use keys longer
  380. // than INSIZE bytes will first hash the key using H and then use the
  381. // resultant OUTSIZE byte string as the actual key to HMAC."
  382. if (key_size > SHA_INSIZE) {
  383. bb_simple_error_msg_and_die("HMAC key>64"); //does not happen (yet?)
  384. // md5sha_ctx_t ctx;
  385. // begin(&ctx);
  386. // md5sha_hash(&ctx, key, key_size);
  387. // key_size = sha_end(&ctx, tempkey);
  388. // //key = tempkey; - right? RIGHT? why does it work without this?
  389. // // because SHA_INSIZE is 64, but hmac() is always called with
  390. // // key_size = tls->MAC_size = SHA1/256_OUTSIZE (20 or 32),
  391. // // and prf_hmac_sha256() -> hmac_sha256() key sizes are:
  392. // // - RSA_PREMASTER_SIZE is 48
  393. // // - CURVE25519_KEYSIZE is 32
  394. // // - master_secret[] is 48
  395. }
  396. for (i = 0; i < key_size; i++) {
  397. key_xor_ipad[i] = key[i] ^ 0x36;
  398. key_xor_opad[i] = key[i] ^ 0x5c;
  399. }
  400. for (; i < SHA_INSIZE; i++) {
  401. key_xor_ipad[i] = 0x36;
  402. key_xor_opad[i] = 0x5c;
  403. }
  404. begin(&pre->hashed_key_xor_ipad);
  405. begin(&pre->hashed_key_xor_opad);
  406. md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
  407. md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
  408. }
  409. #undef begin
  410. static unsigned hmac_sha_precomputed_v(
  411. hmac_precomputed_t *pre,
  412. uint8_t *out,
  413. va_list va)
  414. {
  415. uint8_t *text;
  416. unsigned len;
  417. /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
  418. /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
  419. /* calculate out = H((key XOR ipad) + text) */
  420. while ((text = va_arg(va, uint8_t*)) != NULL) {
  421. unsigned text_size = va_arg(va, unsigned);
  422. md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
  423. }
  424. len = sha_end(&pre->hashed_key_xor_ipad, out);
  425. /* out = H((key XOR opad) + out) */
  426. md5sha_hash(&pre->hashed_key_xor_opad, out, len);
  427. return sha_end(&pre->hashed_key_xor_opad, out);
  428. }
  429. static unsigned hmac_sha_precomputed(hmac_precomputed_t *pre_init, uint8_t *out, ...)
  430. {
  431. hmac_precomputed_t pre;
  432. va_list va;
  433. unsigned len;
  434. va_start(va, out);
  435. pre = *pre_init; /* struct copy */
  436. len = hmac_sha_precomputed_v(&pre, out, va);
  437. va_end(va);
  438. return len;
  439. }
  440. #if !ENABLE_FEATURE_TLS_SHA1
  441. #define hmac(tls,out,key,key_size,...) \
  442. hmac(out,key,key_size, __VA_ARGS__)
  443. #endif
  444. static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
  445. {
  446. hmac_precomputed_t pre;
  447. va_list va;
  448. unsigned len;
  449. va_start(va, key_size);
  450. hmac_begin(&pre, key, key_size,
  451. (ENABLE_FEATURE_TLS_SHA1 && tls->MAC_size == SHA1_OUTSIZE)
  452. ? sha1_begin
  453. : sha256_begin
  454. );
  455. len = hmac_sha_precomputed_v(&pre, out, va);
  456. va_end(va);
  457. return len;
  458. }
  459. // RFC 5246:
  460. // 5. HMAC and the Pseudorandom Function
  461. //...
  462. // In this section, we define one PRF, based on HMAC. This PRF with the
  463. // SHA-256 hash function is used for all cipher suites defined in this
  464. // document and in TLS documents published prior to this document when
  465. // TLS 1.2 is negotiated.
  466. // ^^^^^^^^^^^^^ IMPORTANT!
  467. // PRF uses sha256 regardless of cipher for all ciphers
  468. // defined by RFC 5246. It's not sha1 for AES_128_CBC_SHA!
  469. // However, for _SHA384 ciphers, it's sha384. See RFC 5288,5289.
  470. //...
  471. // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
  472. // HMAC_hash(secret, A(2) + seed) +
  473. // HMAC_hash(secret, A(3) + seed) + ...
  474. // where + indicates concatenation.
  475. // A() is defined as:
  476. // A(0) = seed
  477. // A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
  478. // A(i) = HMAC_hash(secret, A(i-1))
  479. // P_hash can be iterated as many times as necessary to produce the
  480. // required quantity of data. For example, if P_SHA256 is being used to
  481. // create 80 bytes of data, it will have to be iterated three times
  482. // (through A(3)), creating 96 bytes of output data; the last 16 bytes
  483. // of the final iteration will then be discarded, leaving 80 bytes of
  484. // output data.
  485. //
  486. // TLS's PRF is created by applying P_hash to the secret as:
  487. //
  488. // PRF(secret, label, seed) = P_<hash>(secret, label + seed)
  489. //
  490. // The label is an ASCII string.
  491. //
  492. // RFC 5288:
  493. // For cipher suites ending with _SHA256, the PRF is the TLS PRF
  494. // with SHA-256 as the hash function.
  495. // For cipher suites ending with _SHA384, the PRF is the TLS PRF
  496. // with SHA-384 as the hash function.
  497. static void prf_hmac_sha256(/*tls_state_t *tls,*/
  498. uint8_t *outbuf, unsigned outbuf_size,
  499. uint8_t *secret, unsigned secret_size,
  500. const char *label,
  501. uint8_t *seed, unsigned seed_size)
  502. {
  503. hmac_precomputed_t pre;
  504. uint8_t a[TLS_MAX_MAC_SIZE];
  505. uint8_t *out_p = outbuf;
  506. unsigned label_size = strlen(label);
  507. unsigned MAC_size = SHA256_OUTSIZE;
  508. /* In P_hash() calculation, "seed" is "label + seed": */
  509. #define SEED label, label_size, seed, seed_size
  510. #define A a, MAC_size
  511. hmac_begin(&pre, secret, secret_size, sha256_begin);
  512. /* A(1) = HMAC_hash(secret, seed) */
  513. hmac_sha_precomputed(&pre, a, SEED, NULL);
  514. for (;;) {
  515. /* HMAC_hash(secret, A(1) + seed) */
  516. if (outbuf_size <= MAC_size) {
  517. /* Last, possibly incomplete, block */
  518. /* (use a[] as temp buffer) */
  519. hmac_sha_precomputed(&pre, a, A, SEED, NULL);
  520. memcpy(out_p, a, outbuf_size);
  521. return;
  522. }
  523. /* Not last block. Store directly to result buffer */
  524. hmac_sha_precomputed(&pre, out_p, A, SEED, NULL);
  525. out_p += MAC_size;
  526. outbuf_size -= MAC_size;
  527. /* A(2) = HMAC_hash(secret, A(1)) */
  528. hmac_sha_precomputed(&pre, a, A, NULL);
  529. }
  530. #undef A
  531. #undef SECRET
  532. #undef SEED
  533. }
  534. static void bad_record_die(tls_state_t *tls, const char *expected, int len)
  535. {
  536. bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
  537. if (len > 0) {
  538. uint8_t *p = tls->inbuf;
  539. if (len > 99)
  540. len = 99; /* don't flood, a few lines should be enough */
  541. do {
  542. fprintf(stderr, " %02x", *p++);
  543. len--;
  544. } while (len != 0);
  545. fputc('\n', stderr);
  546. }
  547. xfunc_die();
  548. }
  549. static void tls_error_die(tls_state_t *tls, int line)
  550. {
  551. dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
  552. bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
  553. }
  554. #define tls_error_die(tls) tls_error_die(tls, __LINE__)
  555. #if 0 //UNUSED
  556. static void tls_free_inbuf(tls_state_t *tls)
  557. {
  558. if (tls->buffered_size == 0) {
  559. free(tls->inbuf);
  560. tls->inbuf_size = 0;
  561. tls->inbuf = NULL;
  562. }
  563. }
  564. #endif
  565. static void tls_free_outbuf(tls_state_t *tls)
  566. {
  567. free(tls->outbuf);
  568. tls->outbuf_size = 0;
  569. tls->outbuf = NULL;
  570. }
  571. static void *tls_get_outbuf(tls_state_t *tls, int len)
  572. {
  573. if (len > TLS_MAX_OUTBUF)
  574. xfunc_die();
  575. len += OUTBUF_PFX + OUTBUF_SFX;
  576. if (tls->outbuf_size < len) {
  577. tls->outbuf_size = len;
  578. tls->outbuf = xrealloc(tls->outbuf, len);
  579. }
  580. return tls->outbuf + OUTBUF_PFX;
  581. }
  582. static void *tls_get_zeroed_outbuf(tls_state_t *tls, int len)
  583. {
  584. void *record = tls_get_outbuf(tls, len);
  585. memset(record, 0, len);
  586. return record;
  587. }
  588. static void xwrite_encrypted_and_hmac_signed(tls_state_t *tls, unsigned size, unsigned type)
  589. {
  590. uint8_t *buf = tls->outbuf + OUTBUF_PFX;
  591. struct record_hdr *xhdr;
  592. uint8_t padding_length;
  593. xhdr = (void*)(buf - RECHDR_LEN);
  594. if (!ALLOW_RSA_NULL_SHA256 /* if "no encryption" can't be selected */
  595. || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
  596. ) {
  597. xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCK_SIZE); /* place for IV */
  598. }
  599. xhdr->type = type;
  600. xhdr->proto_maj = TLS_MAJ;
  601. xhdr->proto_min = TLS_MIN;
  602. /* fake unencrypted record len for MAC calculation */
  603. xhdr->len16_hi = size >> 8;
  604. xhdr->len16_lo = size & 0xff;
  605. /* Calculate MAC signature */
  606. hmac(tls, buf + size, /* result */
  607. tls->client_write_MAC_key, TLS_MAC_SIZE(tls),
  608. &tls->write_seq64_be, sizeof(tls->write_seq64_be),
  609. xhdr, RECHDR_LEN,
  610. buf, size,
  611. NULL
  612. );
  613. tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
  614. size += TLS_MAC_SIZE(tls);
  615. // RFC 5246:
  616. // 6.2.3.1. Null or Standard Stream Cipher
  617. //
  618. // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
  619. // convert TLSCompressed.fragment structures to and from stream
  620. // TLSCiphertext.fragment structures.
  621. //
  622. // stream-ciphered struct {
  623. // opaque content[TLSCompressed.length];
  624. // opaque MAC[SecurityParameters.mac_length];
  625. // } GenericStreamCipher;
  626. //
  627. // The MAC is generated as:
  628. // MAC(MAC_write_key, seq_num +
  629. // TLSCompressed.type +
  630. // TLSCompressed.version +
  631. // TLSCompressed.length +
  632. // TLSCompressed.fragment);
  633. // where "+" denotes concatenation.
  634. // seq_num
  635. // The sequence number for this record.
  636. // MAC
  637. // The MAC algorithm specified by SecurityParameters.mac_algorithm.
  638. //
  639. // Note that the MAC is computed before encryption. The stream cipher
  640. // encrypts the entire block, including the MAC.
  641. //...
  642. // Appendix C. Cipher Suite Definitions
  643. //...
  644. // MAC Algorithm mac_length mac_key_length
  645. // -------- ----------- ---------- --------------
  646. // SHA HMAC-SHA1 20 20
  647. // SHA256 HMAC-SHA256 32 32
  648. if (ALLOW_RSA_NULL_SHA256
  649. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  650. ) {
  651. /* No encryption, only signing */
  652. xhdr->len16_hi = size >> 8;
  653. xhdr->len16_lo = size & 0xff;
  654. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  655. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  656. dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
  657. return;
  658. }
  659. // 6.2.3.2. CBC Block Cipher
  660. // For block ciphers (such as 3DES or AES), the encryption and MAC
  661. // functions convert TLSCompressed.fragment structures to and from block
  662. // TLSCiphertext.fragment structures.
  663. // struct {
  664. // opaque IV[SecurityParameters.record_iv_length];
  665. // block-ciphered struct {
  666. // opaque content[TLSCompressed.length];
  667. // opaque MAC[SecurityParameters.mac_length];
  668. // uint8 padding[GenericBlockCipher.padding_length];
  669. // uint8 padding_length;
  670. // };
  671. // } GenericBlockCipher;
  672. //...
  673. // IV
  674. // The Initialization Vector (IV) SHOULD be chosen at random, and
  675. // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
  676. // there was no IV field (...). For block ciphers, the IV length is
  677. // of length SecurityParameters.record_iv_length, which is equal to the
  678. // SecurityParameters.block_size.
  679. // padding
  680. // Padding that is added to force the length of the plaintext to be
  681. // an integral multiple of the block cipher's block length.
  682. // padding_length
  683. // The padding length MUST be such that the total size of the
  684. // GenericBlockCipher structure is a multiple of the cipher's block
  685. // length. Legal values range from zero to 255, inclusive.
  686. //...
  687. // Appendix C. Cipher Suite Definitions
  688. //...
  689. // Key IV Block
  690. // Cipher Type Material Size Size
  691. // ------------ ------ -------- ---- -----
  692. // AES_128_CBC Block 16 16 16
  693. // AES_256_CBC Block 32 16 16
  694. tls_get_random(buf - AES_BLOCK_SIZE, AES_BLOCK_SIZE); /* IV */
  695. dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
  696. size - TLS_MAC_SIZE(tls), TLS_MAC_SIZE(tls));
  697. /* Fill IV and padding in outbuf */
  698. // RFC is talking nonsense:
  699. // "Padding that is added to force the length of the plaintext to be
  700. // an integral multiple of the block cipher's block length."
  701. // WRONG. _padding+padding_length_, not just _padding_,
  702. // pads the data.
  703. // IOW: padding_length is the last byte of padding[] array,
  704. // contrary to what RFC depicts.
  705. //
  706. // What actually happens is that there is always padding.
  707. // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
  708. // If you need two bytes, they are both 0x01.
  709. // If you need three, they are 0x02,0x02,0x02. And so on.
  710. // If you need no bytes to reach BLOCKSIZE, you have to pad a full
  711. // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
  712. // It's ok to have more than minimum padding, but we do minimum.
  713. padding_length = (~size) & (AES_BLOCK_SIZE - 1);
  714. do {
  715. buf[size++] = padding_length; /* padding */
  716. } while ((size & (AES_BLOCK_SIZE - 1)) != 0);
  717. /* Encrypt content+MAC+padding in place */
  718. aes_cbc_encrypt(
  719. &tls->aes_encrypt, /* selects 128/256 */
  720. buf - AES_BLOCK_SIZE, /* IV */
  721. buf, size, /* plaintext */
  722. buf /* ciphertext */
  723. );
  724. /* Write out */
  725. dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
  726. AES_BLOCK_SIZE, size, padding_length);
  727. size += AES_BLOCK_SIZE; /* + IV */
  728. xhdr->len16_hi = size >> 8;
  729. xhdr->len16_lo = size & 0xff;
  730. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  731. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  732. dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
  733. }
  734. /* Example how GCM encryption combines nonce, aad, input and generates
  735. * "header | exp_nonce | encrypted output | tag":
  736. * nonce:0d 6a 26 31 00 00 00 00 00 00 00 01 (implicit 4 bytes (derived from master secret), then explicit 8 bytes)
  737. * aad: 00 00 00 00 00 00 00 01 17 03 03 00 1c
  738. * in: 47 45 54 20 2f 69 6e 64 65 78 2e 68 74 6d 6c 20 48 54 54 50 2f 31 2e 30 0d 0a 0d 0a "GET /index.html HTTP/1.0\r\n\r\n" (0x1c bytes)
  739. * out: f7 8a b2 8f 78 0e f6 d5 76 17 2e b5 6d 46 59 56 8b 46 9f 0b d9 2c 35 28 13 66 19 be
  740. * tag: c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
  741. * sent: 17 03 03 00 34|00 00 00 00 00 00 00 01|f7 8a b2 8f 78 0e f6 d5 76 17 2e b5 6d 46 59 56 8b 46 9f 0b d9 2c 35 28 13 66 19 be|c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
  742. * .............................................^^ buf points here
  743. */
  744. static void xwrite_encrypted_aesgcm(tls_state_t *tls, unsigned size, unsigned type)
  745. {
  746. #define COUNTER(v) (*(uint32_t*)(v + 12))
  747. uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
  748. uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
  749. uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
  750. uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
  751. uint8_t *buf;
  752. struct record_hdr *xhdr;
  753. unsigned remaining;
  754. unsigned cnt;
  755. uint64_t t64;
  756. buf = tls->outbuf + OUTBUF_PFX; /* see above for the byte it points to */
  757. dump_hex("xwrite_encrypted_aesgcm plaintext:%s\n", buf, size);
  758. xhdr = (void*)(buf - 8 - RECHDR_LEN);
  759. xhdr->type = type; /* do it here so that "type" param no longer used */
  760. aad[8] = type;
  761. aad[9] = TLS_MAJ;
  762. aad[10] = TLS_MIN;
  763. aad[11] = size >> 8;
  764. /* set aad[12], and clear aad[13..15] */
  765. COUNTER(aad) = SWAP_LE32(size & 0xff);
  766. memcpy(nonce, tls->client_write_IV, 4);
  767. t64 = tls->write_seq64_be;
  768. move_to_unaligned64(nonce + 4, t64);
  769. move_to_unaligned64(aad, t64);
  770. move_to_unaligned64(buf - 8, t64);
  771. /* seq64 is not used later in this func, can increment here */
  772. tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(t64));
  773. cnt = 1;
  774. remaining = size;
  775. while (remaining != 0) {
  776. unsigned n;
  777. cnt++;
  778. COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
  779. aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
  780. n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
  781. xorbuf(buf, scratch, n);
  782. buf += n;
  783. remaining -= n;
  784. }
  785. aesgcm_GHASH(tls->H, aad, /*sizeof(aad),*/ tls->outbuf + OUTBUF_PFX, size, authtag /*, sizeof(authtag)*/);
  786. COUNTER(nonce) = htonl(1);
  787. aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
  788. xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
  789. memcpy(buf, authtag, sizeof(authtag));
  790. /* Write out */
  791. xhdr = (void*)(tls->outbuf + OUTBUF_PFX - 8 - RECHDR_LEN);
  792. size += 8 + sizeof(authtag);
  793. /*xhdr->type = type; - already is */
  794. xhdr->proto_maj = TLS_MAJ;
  795. xhdr->proto_min = TLS_MIN;
  796. xhdr->len16_hi = size >> 8;
  797. xhdr->len16_lo = size & 0xff;
  798. size += RECHDR_LEN;
  799. dump_raw_out(">> %s\n", xhdr, size);
  800. xwrite(tls->ofd, xhdr, size);
  801. dbg("wrote %u bytes\n", size);
  802. #undef COUNTER
  803. }
  804. static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
  805. {
  806. if (!(tls->flags & ENCRYPTION_AESGCM)) {
  807. xwrite_encrypted_and_hmac_signed(tls, size, type);
  808. return;
  809. }
  810. xwrite_encrypted_aesgcm(tls, size, type);
  811. }
  812. static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
  813. {
  814. uint8_t *buf = tls->outbuf + OUTBUF_PFX;
  815. struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
  816. xhdr->type = RECORD_TYPE_HANDSHAKE;
  817. xhdr->proto_maj = TLS_MAJ;
  818. xhdr->proto_min = TLS_MIN;
  819. xhdr->len16_hi = size >> 8;
  820. xhdr->len16_lo = size & 0xff;
  821. dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
  822. xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
  823. dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
  824. }
  825. static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
  826. {
  827. if (!(tls->flags & ENCRYPT_ON_WRITE)) {
  828. uint8_t *buf;
  829. xwrite_handshake_record(tls, size);
  830. /* Handshake hash does not include record headers */
  831. buf = tls->outbuf + OUTBUF_PFX;
  832. hash_handshake(tls, ">> hash:%s", buf, size);
  833. return;
  834. }
  835. xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
  836. }
  837. static int tls_has_buffered_record(tls_state_t *tls)
  838. {
  839. int buffered = tls->buffered_size;
  840. struct record_hdr *xhdr;
  841. int rec_size;
  842. if (buffered < RECHDR_LEN)
  843. return 0;
  844. xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
  845. rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  846. if (buffered < rec_size)
  847. return 0;
  848. return rec_size;
  849. }
  850. static const char *alert_text(int code)
  851. {
  852. //10 unexpected_message
  853. //20 bad_record_mac
  854. //21 decryption_failed
  855. //22 record_overflow
  856. //30 decompression_failure
  857. //40 handshake_failure
  858. //41 no_certificate
  859. //42 bad_certificate
  860. //43 unsupported_certificate
  861. //44 certificate_revoked
  862. //45 certificate_expired
  863. //46 certificate_unknown
  864. //47 illegal_parameter
  865. //48 unknown_ca
  866. //49 access_denied
  867. //50 decode_error
  868. //51 decrypt_error
  869. //52 too_many_cids_requested
  870. //60 export_restriction
  871. //70 protocol_version
  872. //71 insufficient_security
  873. //80 internal_error
  874. //86 inappropriate_fallback
  875. //90 user_canceled
  876. //100 no_renegotiation
  877. //109 missing_extension
  878. //110 unsupported_extension
  879. //111 certificate_unobtainable
  880. //112 unrecognized_name
  881. //113 bad_certificate_status_response
  882. //114 bad_certificate_hash_value
  883. //115 unknown_psk_identity
  884. //116 certificate_required
  885. //120 no_application_protocol
  886. switch (code) {
  887. case 20: return "bad MAC";
  888. case 50: return "decode error";
  889. case 40: return "handshake failure";
  890. case 51: return "decrypt error";
  891. case 80: return "internal error";
  892. case 112: return "unrecognized name";
  893. }
  894. return itoa(code);
  895. }
  896. static void tls_aesgcm_decrypt(tls_state_t *tls, uint8_t *buf, int size)
  897. {
  898. #define COUNTER(v) (*(uint32_t*)(v + 12))
  899. //uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
  900. uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
  901. uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
  902. //uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
  903. unsigned remaining;
  904. unsigned cnt;
  905. //memcpy(aad, buf, 8);
  906. //aad[8] = type;
  907. //aad[9] = TLS_MAJ;
  908. //aad[10] = TLS_MIN;
  909. //aad[11] = size >> 8;
  910. ///* set aad[12], and clear aad[13..15] */
  911. //COUNTER(aad) = SWAP_LE32(size & 0xff);
  912. memcpy(nonce, tls->server_write_IV, 4);
  913. memcpy(nonce + 4, buf, 8);
  914. cnt = 1;
  915. remaining = size;
  916. while (remaining != 0) {
  917. unsigned n;
  918. cnt++;
  919. COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
  920. aes_encrypt_one_block(&tls->aes_decrypt, nonce, scratch);
  921. n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
  922. xorbuf3(buf, scratch, buf + 8, n);
  923. buf += n;
  924. remaining -= n;
  925. }
  926. //aesgcm_GHASH(tls->H, aad, tls->inbuf + RECHDR_LEN, size, authtag);
  927. //COUNTER(nonce) = htonl(1);
  928. //aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
  929. //xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
  930. //memcmp(buf, authtag, sizeof(authtag)) || DIE("HASH DOES NOT MATCH!");
  931. #undef COUNTER
  932. }
  933. static int tls_xread_record(tls_state_t *tls, const char *expected)
  934. {
  935. struct record_hdr *xhdr;
  936. int sz;
  937. int total;
  938. int target;
  939. again:
  940. dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
  941. total = tls->buffered_size;
  942. if (total != 0) {
  943. memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
  944. //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
  945. //dump_raw_in("<< %s\n", tls->inbuf, total);
  946. }
  947. errno = 0;
  948. target = MAX_INBUF;
  949. for (;;) {
  950. int rem;
  951. if (total >= RECHDR_LEN && target == MAX_INBUF) {
  952. xhdr = (void*)tls->inbuf;
  953. target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  954. if (target > MAX_INBUF /* malformed input (too long) */
  955. || xhdr->proto_maj != TLS_MAJ
  956. || xhdr->proto_min != TLS_MIN
  957. ) {
  958. sz = total < target ? total : target;
  959. bad_record_die(tls, expected, sz);
  960. }
  961. dbg("xhdr type:%d ver:%d.%d len:%d\n",
  962. xhdr->type, xhdr->proto_maj, xhdr->proto_min,
  963. 0x100 * xhdr->len16_hi + xhdr->len16_lo
  964. );
  965. }
  966. /* if total >= target, we have a full packet (and possibly more)... */
  967. if (total - target >= 0)
  968. break;
  969. /* input buffer is grown only as needed */
  970. rem = tls->inbuf_size - total;
  971. if (rem == 0) {
  972. tls->inbuf_size += MAX_INBUF / 8;
  973. if (tls->inbuf_size > MAX_INBUF)
  974. tls->inbuf_size = MAX_INBUF;
  975. dbg("inbuf_size:%d\n", tls->inbuf_size);
  976. rem = tls->inbuf_size - total;
  977. tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
  978. }
  979. sz = safe_read(tls->ifd, tls->inbuf + total, rem);
  980. if (sz <= 0) {
  981. if (sz == 0 && total == 0) {
  982. /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
  983. dbg("EOF (without TLS shutdown) from peer\n");
  984. tls->buffered_size = 0;
  985. goto end;
  986. }
  987. bb_perror_msg_and_die("short read, have only %d", total);
  988. }
  989. dump_raw_in("<< %s\n", tls->inbuf + total, sz);
  990. total += sz;
  991. }
  992. tls->buffered_size = total - target;
  993. tls->ofs_to_buffered = target;
  994. //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
  995. //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
  996. sz = target - RECHDR_LEN;
  997. /* Needs to be decrypted? */
  998. if (tls->min_encrypted_len_on_read != 0) {
  999. if (sz < (int)tls->min_encrypted_len_on_read)
  1000. bb_error_msg_and_die("bad encrypted len:%u", sz);
  1001. if (tls->flags & ENCRYPTION_AESGCM) {
  1002. /* AESGCM */
  1003. uint8_t *p = tls->inbuf + RECHDR_LEN;
  1004. sz -= 8 + AES_BLOCK_SIZE; /* we will overwrite nonce, drop hash */
  1005. tls_aesgcm_decrypt(tls, p, sz);
  1006. dbg("encrypted size:%u\n", sz);
  1007. } else
  1008. if (tls->min_encrypted_len_on_read > TLS_MAC_SIZE(tls)) {
  1009. /* AES+SHA */
  1010. uint8_t *p = tls->inbuf + RECHDR_LEN;
  1011. int padding_len;
  1012. if (sz & (AES_BLOCK_SIZE-1))
  1013. bb_error_msg_and_die("bad encrypted len:%u", sz);
  1014. /* Decrypt content+MAC+padding, moving it over IV in the process */
  1015. sz -= AES_BLOCK_SIZE; /* we will overwrite IV now */
  1016. aes_cbc_decrypt(
  1017. &tls->aes_decrypt, /* selects 128/256 */
  1018. p, /* IV */
  1019. p + AES_BLOCK_SIZE, sz, /* ciphertext */
  1020. p /* plaintext */
  1021. );
  1022. padding_len = p[sz - 1];
  1023. dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
  1024. padding_len++;
  1025. sz -= TLS_MAC_SIZE(tls) + padding_len; /* drop MAC and padding */
  1026. } else {
  1027. /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
  1028. /* else: no encryption yet on input, subtract zero = NOP */
  1029. sz -= tls->min_encrypted_len_on_read;
  1030. }
  1031. }
  1032. if (sz < 0)
  1033. bb_simple_error_msg_and_die("encrypted data too short");
  1034. //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
  1035. xhdr = (void*)tls->inbuf;
  1036. if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
  1037. uint8_t *p = tls->inbuf + RECHDR_LEN;
  1038. dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
  1039. if (p[0] == 2) { /* fatal */
  1040. bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
  1041. "error",
  1042. p[1], alert_text(p[1])
  1043. );
  1044. }
  1045. if (p[0] == 1) { /* warning */
  1046. if (p[1] == 0) { /* "close_notify" warning: it's EOF */
  1047. dbg("EOF (TLS encoded) from peer\n");
  1048. sz = 0;
  1049. goto end;
  1050. }
  1051. //This possibly needs to be cached and shown only if
  1052. //a fatal alert follows
  1053. // bb_error_msg("TLS %s from peer (alert code %d): %s",
  1054. // "warning",
  1055. // p[1], alert_text(p[1])
  1056. // );
  1057. /* discard it, get next record */
  1058. goto again;
  1059. }
  1060. /* p[0] not 1 or 2: not defined in protocol */
  1061. sz = 0;
  1062. goto end;
  1063. }
  1064. /* RFC 5246 is not saying it explicitly, but sha256 hash
  1065. * in our FINISHED record must include data of incoming packets too!
  1066. */
  1067. if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
  1068. /* HANDSHAKE HASH: */
  1069. // && do_we_know_which_hash_to_use /* server_hello() might not know it in the future! */
  1070. ) {
  1071. hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
  1072. }
  1073. end:
  1074. dbg("got block len:%u\n", sz);
  1075. return sz;
  1076. }
  1077. static void binary_to_pstm(pstm_int *pstm_n, uint8_t *bin_ptr, unsigned len)
  1078. {
  1079. pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
  1080. pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
  1081. //return bin_ptr + len;
  1082. }
  1083. /*
  1084. * DER parsing routines
  1085. */
  1086. static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
  1087. {
  1088. unsigned len, len1;
  1089. if (end - der < 2)
  1090. xfunc_die();
  1091. // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
  1092. // xfunc_die();
  1093. len = der[1]; /* maybe it's short len */
  1094. if (len >= 0x80) {
  1095. /* no, it's long */
  1096. if (len == 0x80 || end - der < (int)(len - 0x7e)) {
  1097. /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
  1098. /* need 3 or 4 bytes for 81, 82 */
  1099. xfunc_die();
  1100. }
  1101. len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
  1102. if (len > 0x82) {
  1103. /* >0x82 is "3+ bytes of len", should not happen realistically */
  1104. xfunc_die();
  1105. }
  1106. if (len == 0x82) { /* it's "ii 82 xx yy" */
  1107. len1 = 0x100*len1 + der[3];
  1108. der += 1; /* skip [yy] */
  1109. }
  1110. der += 1; /* skip [xx] */
  1111. len = len1;
  1112. // if (len < 0x80)
  1113. // xfunc_die(); /* invalid DER: must use short len if can */
  1114. }
  1115. der += 2; /* skip [code]+[1byte] */
  1116. if (end - der < (int)len)
  1117. xfunc_die();
  1118. *bodyp = der;
  1119. return len;
  1120. }
  1121. static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
  1122. {
  1123. uint8_t *new_der;
  1124. unsigned len = get_der_len(&new_der, der, *endp);
  1125. dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
  1126. /* Move "end" position to cover only this item */
  1127. *endp = new_der + len;
  1128. return new_der;
  1129. }
  1130. static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
  1131. {
  1132. uint8_t *new_der;
  1133. unsigned len = get_der_len(&new_der, der, end);
  1134. /* Skip body */
  1135. new_der += len;
  1136. dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
  1137. return new_der;
  1138. }
  1139. static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
  1140. {
  1141. uint8_t *bin_ptr;
  1142. unsigned len = get_der_len(&bin_ptr, der, end);
  1143. dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
  1144. binary_to_pstm(pstm_n, bin_ptr, len);
  1145. }
  1146. static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
  1147. {
  1148. /* Certificate is a DER-encoded data structure. Each DER element has a length,
  1149. * which makes it easy to skip over large compound elements of any complexity
  1150. * without parsing them. Example: partial decode of kernel.org certificate:
  1151. * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
  1152. * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
  1153. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
  1154. * INTEGER (version): 0201 02
  1155. * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
  1156. * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
  1157. * SEQ 0x0d bytes (signatureAlgo): 300d
  1158. * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
  1159. * NULL: 0500
  1160. * SEQ 0x5f bytes (issuer): 305f
  1161. * SET 11 bytes: 310b
  1162. * SEQ 9 bytes: 3009
  1163. * OID 3 bytes: 0603 550406
  1164. * Printable string "FR": 1302 4652
  1165. * SET 14 bytes: 310e
  1166. * SEQ 12 bytes: 300c
  1167. * OID 3 bytes: 0603 550408
  1168. * Printable string "Paris": 1305 5061726973
  1169. * SET 14 bytes: 310e
  1170. * SEQ 12 bytes: 300c
  1171. * OID 3 bytes: 0603 550407
  1172. * Printable string "Paris": 1305 5061726973
  1173. * SET 14 bytes: 310e
  1174. * SEQ 12 bytes: 300c
  1175. * OID 3 bytes: 0603 55040a
  1176. * Printable string "Gandi": 1305 47616e6469
  1177. * SET 32 bytes: 3120
  1178. * SEQ 30 bytes: 301e
  1179. * OID 3 bytes: 0603 550403
  1180. * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
  1181. * SEQ 30 bytes (validity): 301e
  1182. * TIME "161011000000Z": 170d 3136313031313030303030305a
  1183. * TIME "191011235959Z": 170d 3139313031313233353935395a
  1184. * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
  1185. * 3121301f060355040b1318446f6d61696e20436f
  1186. * 6e74726f6c2056616c6964617465643121301f06
  1187. * 0355040b1318506f73697469766553534c204d75
  1188. * 6c74692d446f6d61696e31133011060355040313
  1189. * 0a6b65726e656c2e6f7267
  1190. * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
  1191. * SEQ 13 bytes (algorithm): 300d
  1192. * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
  1193. * NULL: 0500
  1194. * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
  1195. * ????: 00
  1196. * //after the zero byte, it appears key itself uses DER encoding:
  1197. * SEQ 0x018a/394 bytes: 3082018a
  1198. * INTEGER 0x0181/385 bytes (modulus): 02820181
  1199. * 00b1ab2fc727a3bef76780c9349bf3
  1200. * ...24 more blocks of 15 bytes each...
  1201. * 90e895291c6bc8693b65
  1202. * INTEGER 3 bytes (exponent): 0203 010001
  1203. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
  1204. * SEQ 0x01e1 bytes: 308201e1
  1205. * ...
  1206. * Certificate is a sequence of three elements:
  1207. * tbsCertificate (SEQ)
  1208. * signatureAlgorithm (AlgorithmIdentifier)
  1209. * signatureValue (BIT STRING)
  1210. *
  1211. * In turn, tbsCertificate is a sequence of:
  1212. * version
  1213. * serialNumber
  1214. * signatureAlgo (AlgorithmIdentifier)
  1215. * issuer (Name, has complex structure)
  1216. * validity (Validity, SEQ of two Times)
  1217. * subject (Name)
  1218. * subjectPublicKeyInfo (SEQ)
  1219. * ...
  1220. *
  1221. * subjectPublicKeyInfo is a sequence of:
  1222. * algorithm (AlgorithmIdentifier)
  1223. * publicKey (BIT STRING)
  1224. *
  1225. * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
  1226. *
  1227. * Example of an ECDSA key:
  1228. * SEQ 0x59 bytes (subjectPublicKeyInfo): 3059
  1229. * SEQ 0x13 bytes (algorithm): 3013
  1230. * OID 7 bytes: 0607 2a8648ce3d0201 (OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1)
  1231. * OID 8 bytes: 0608 2a8648ce3d030107 (OID_EC_prime256v1 42.134.72.206.61.3.1.7)
  1232. * BITSTRING 0x42 bytes (publicKey): 0342
  1233. * 0004 53af f65e 50cc 7959 7e29 0171 c75c
  1234. * 7335 e07d f45b 9750 b797 3a38 aebb 2ac6
  1235. * 8329 2748 e77e 41cb d482 2ce6 05ec a058
  1236. * f3ab d561 2f4c d845 9ad3 7252 e3de bd3b
  1237. * 9012
  1238. */
  1239. uint8_t *end = der + len;
  1240. /* enter "Certificate" item: [der, end) will be only Cert */
  1241. der = enter_der_item(der, &end);
  1242. /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
  1243. der = enter_der_item(der, &end);
  1244. /*
  1245. * Skip version field only if it is present. For a v1 certificate, the
  1246. * version field won't be present since v1 is the default value for the
  1247. * version field and fields with default values should be omitted (see
  1248. * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
  1249. * it will have a tag class of 2 (context-specific), bit 6 as 1
  1250. * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
  1251. * and 8.14).
  1252. */
  1253. /* bits 7-6: 10 */
  1254. /* bit 5: 1 */
  1255. /* bits 4-0: 00000 */
  1256. if (der[0] == 0xa0)
  1257. der = skip_der_item(der, end); /* version */
  1258. /* skip up to subjectPublicKeyInfo */
  1259. der = skip_der_item(der, end); /* serialNumber */
  1260. der = skip_der_item(der, end); /* signatureAlgo */
  1261. der = skip_der_item(der, end); /* issuer */
  1262. der = skip_der_item(der, end); /* validity */
  1263. der = skip_der_item(der, end); /* subject */
  1264. /* enter subjectPublicKeyInfo */
  1265. der = enter_der_item(der, &end);
  1266. { /* check subjectPublicKeyInfo.algorithm */
  1267. static const uint8_t OID_RSA_KEY_ALG[] ALIGN1 = {
  1268. 0x30,0x0d, // SEQ 13 bytes
  1269. 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, //OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
  1270. //0x05,0x00, // NULL
  1271. };
  1272. static const uint8_t OID_ECDSA_KEY_ALG[] ALIGN1 = {
  1273. 0x30,0x13, // SEQ 0x13 bytes
  1274. 0x06,0x07, 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01, //OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1
  1275. //allow any curve code for now...
  1276. // 0x06,0x08, 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07, //OID_EC_prime256v1 42.134.72.206.61.3.1.7
  1277. //RFC 3279:
  1278. //42.134.72.206.61.3 is ellipticCurve
  1279. //42.134.72.206.61.3.0 is c-TwoCurve
  1280. //42.134.72.206.61.3.1 is primeCurve
  1281. //42.134.72.206.61.3.1.7 is curve_secp256r1
  1282. };
  1283. if (memcmp(der, OID_RSA_KEY_ALG, sizeof(OID_RSA_KEY_ALG)) == 0) {
  1284. dbg("RSA key\n");
  1285. tls->flags |= GOT_CERT_RSA_KEY_ALG;
  1286. } else
  1287. if (memcmp(der, OID_ECDSA_KEY_ALG, sizeof(OID_ECDSA_KEY_ALG)) == 0) {
  1288. dbg("ECDSA key\n");
  1289. //UNUSED: tls->flags |= GOT_CERT_ECDSA_KEY_ALG;
  1290. } else
  1291. bb_simple_error_msg_and_die("not RSA or ECDSA cert");
  1292. }
  1293. if (tls->flags & GOT_CERT_RSA_KEY_ALG) {
  1294. /* parse RSA key: */
  1295. //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
  1296. /* skip subjectPublicKeyInfo.algorithm */
  1297. der = skip_der_item(der, end);
  1298. /* enter subjectPublicKeyInfo.publicKey */
  1299. //die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
  1300. der = enter_der_item(der, &end);
  1301. dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
  1302. if (end - der < 14)
  1303. xfunc_die();
  1304. /* example format:
  1305. * ignore bits: 00
  1306. * SEQ 0x018a/394 bytes: 3082018a
  1307. * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
  1308. * INTEGER 3 bytes (exponent): 0203 010001
  1309. */
  1310. if (*der != 0) /* "ignore bits", should be 0 */
  1311. xfunc_die();
  1312. der++;
  1313. der = enter_der_item(der, &end); /* enter SEQ */
  1314. /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
  1315. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
  1316. der = skip_der_item(der, end);
  1317. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
  1318. tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
  1319. dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
  1320. }
  1321. /* else: ECDSA key. It is not used for generating encryption keys,
  1322. * it is used only to sign the EC public key (which comes in ServerKey message).
  1323. * Since we do not verify cert validity, verifying signature on EC public key
  1324. * wouldn't add any security. Thus, we do nothing here.
  1325. */
  1326. }
  1327. /*
  1328. * TLS Handshake routines
  1329. */
  1330. static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
  1331. {
  1332. struct record_hdr *xhdr;
  1333. int len = tls_xread_record(tls, "handshake record");
  1334. xhdr = (void*)tls->inbuf;
  1335. if (len < min_len
  1336. || xhdr->type != RECORD_TYPE_HANDSHAKE
  1337. ) {
  1338. bad_record_die(tls, "handshake record", len);
  1339. }
  1340. dbg("got HANDSHAKE\n");
  1341. return len;
  1342. }
  1343. static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
  1344. {
  1345. struct handshake_hdr {
  1346. uint8_t type;
  1347. uint8_t len24_hi, len24_mid, len24_lo;
  1348. } *h = buf;
  1349. len -= 4;
  1350. h->type = type;
  1351. h->len24_hi = len >> 16;
  1352. h->len24_mid = len >> 8;
  1353. h->len24_lo = len & 0xff;
  1354. }
  1355. static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
  1356. {
  1357. #define NUM_CIPHERS (0 \
  1358. + 4 * ENABLE_FEATURE_TLS_SHA1 \
  1359. + ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 \
  1360. + ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 \
  1361. + ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \
  1362. + ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 \
  1363. + 2 * ENABLE_FEATURE_TLS_SHA1 \
  1364. + ALLOW_RSA_WITH_AES_128_CBC_SHA256 \
  1365. + ALLOW_RSA_WITH_AES_256_CBC_SHA256 \
  1366. + ALLOW_RSA_WITH_AES_128_GCM_SHA256 \
  1367. + ALLOW_RSA_NULL_SHA256 \
  1368. )
  1369. static const uint8_t ciphers[] = {
  1370. 0x00,2 * (1 + NUM_CIPHERS), //len16_be
  1371. 0x00,0xFF, //not a cipher - TLS_EMPTY_RENEGOTIATION_INFO_SCSV
  1372. /* ^^^^^^ RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
  1373. #if ENABLE_FEATURE_TLS_SHA1
  1374. 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
  1375. 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
  1376. 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
  1377. 0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
  1378. // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  1379. // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
  1380. #endif
  1381. #if ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
  1382. 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
  1383. #endif
  1384. // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1385. #if ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256
  1386. 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
  1387. #endif
  1388. // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1389. #if ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  1390. 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
  1391. #endif
  1392. // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
  1393. //TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
  1394. #if ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  1395. 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
  1396. #endif
  1397. // 0xC0,0x30, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
  1398. //possibly these too:
  1399. #if ENABLE_FEATURE_TLS_SHA1
  1400. // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
  1401. // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
  1402. #endif
  1403. // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  1404. // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1405. #if ENABLE_FEATURE_TLS_SHA1
  1406. 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
  1407. 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
  1408. #endif
  1409. #if ALLOW_RSA_WITH_AES_128_CBC_SHA256
  1410. 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
  1411. #endif
  1412. #if ALLOW_RSA_WITH_AES_256_CBC_SHA256
  1413. 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
  1414. #endif
  1415. #if ALLOW_RSA_WITH_AES_128_GCM_SHA256
  1416. 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
  1417. #endif
  1418. // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
  1419. #if ALLOW_RSA_NULL_SHA256
  1420. 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
  1421. #endif
  1422. 0x01,0x00, //not a cipher - comprtypes_len, comprtype
  1423. };
  1424. struct client_hello {
  1425. uint8_t type;
  1426. uint8_t len24_hi, len24_mid, len24_lo;
  1427. uint8_t proto_maj, proto_min;
  1428. uint8_t rand32[32];
  1429. uint8_t session_id_len;
  1430. /* uint8_t session_id[]; */
  1431. uint8_t cipherid_len16_hi, cipherid_len16_lo;
  1432. uint8_t cipherid[2 * (1 + NUM_CIPHERS)]; /* actually variable */
  1433. uint8_t comprtypes_len;
  1434. uint8_t comprtypes[1]; /* actually variable */
  1435. };
  1436. // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
  1437. static const uint8_t extensions[] = {
  1438. // is.gd responds with "handshake failure" to our hello if there's no supported_groups
  1439. 0x00,0x0a, //extension_type: "supported_groups"
  1440. 0x00,2 * (1 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //ext len
  1441. 0x00,2 * (0 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //list len
  1442. #if ALLOW_CURVE_P256
  1443. 0x00,0x17, //curve_secp256r1 (aka P256, aka prime256v1)
  1444. #endif
  1445. //0x00,0x18, //curve_secp384r1
  1446. //0x00,0x19, //curve_secp521r1
  1447. #if ALLOW_CURVE_X25519
  1448. 0x00,0x1d, //curve_x25519 (RFC 7748)
  1449. #endif
  1450. //0x00,0x1e, //curve_x448 (RFC 7748)
  1451. //0x00,0x0b,0x00,0x04,0x03,0x00,0x01,0x02, //extension_type: "ec_point_formats"
  1452. //0x00,0x16,0x00,0x00, //extension_type: "encrpypt-then-mac"
  1453. //0x00,0x17,0x00,0x00, //extension_type: "extended_master"
  1454. //0x00,0x23,0x00,0x00, //extension_type: "session_ticket"
  1455. // kojipkgs.fedoraproject.org responds with alert code 80 ("internal error")
  1456. // to our hello without signature_algorithms.
  1457. // It is satisfied with just 0x04,0x01.
  1458. 0x00,0x0d, //extension_type: "signature_algorithms" (RFC5246 section 7.4.1.4.1):
  1459. #define SIGALGS (3 + 3 * ENABLE_FEATURE_TLS_SHA1)
  1460. 0x00,2 * (1 + SIGALGS), //ext len
  1461. 0x00,2 * (0 + SIGALGS), //list len
  1462. //Format: two bytes
  1463. // byte 1: 0:none,1:md5,2:sha1,3:sha224,4:sha256,5:sha384,6:sha512
  1464. // byte 2: 1:rsa,2:dsa,3:ecdsa
  1465. // (note that TLS 1.3 changes this, see RFC8446 section 4.2.3)
  1466. #if ENABLE_FEATURE_TLS_SHA1
  1467. 0x02,0x01, //sha1 + rsa
  1468. 0x02,0x02, //sha1 + dsa
  1469. 0x02,0x03, //sha1 + ecdsa
  1470. #endif
  1471. 0x04,0x01, //sha256 + rsa - kojipkgs.fedoraproject.org wants this
  1472. 0x04,0x02, //sha256 + dsa
  1473. 0x04,0x03, //sha256 + ecdsa
  1474. // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
  1475. // 0055
  1476. // 0005 0005 0100000000 - status_request
  1477. // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
  1478. // ff01 0001 00 - renegotiation_info
  1479. // 0023 0000 - session_ticket
  1480. // 000a 0008 0006001700180019 - supported_groups
  1481. // 000b 0002 0100 - ec_point_formats
  1482. // 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
  1483. // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
  1484. // 0017 0000 - extended master secret
  1485. };
  1486. struct client_hello *record;
  1487. uint8_t *ptr;
  1488. int len;
  1489. int ext_len;
  1490. int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
  1491. ext_len = 0;
  1492. ext_len += sizeof(extensions);
  1493. if (sni_len)
  1494. ext_len += 9 + sni_len;
  1495. /* +2 is for "len of all extensions" 2-byte field */
  1496. len = sizeof(*record) + 2 + ext_len;
  1497. record = tls_get_zeroed_outbuf(tls, len);
  1498. fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
  1499. record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
  1500. record->proto_min = TLS_MIN; /* can be higher than one in record headers */
  1501. tls_get_random(record->rand32, sizeof(record->rand32));
  1502. if (TLS_DEBUG_FIXED_SECRETS)
  1503. memset(record->rand32, 0x11, sizeof(record->rand32));
  1504. /* record->session_id_len = 0; - already is */
  1505. BUILD_BUG_ON(sizeof(ciphers) != 2 * (1 + 1 + NUM_CIPHERS + 1));
  1506. memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
  1507. ptr = (void*)(record + 1);
  1508. *ptr++ = ext_len >> 8;
  1509. *ptr++ = ext_len;
  1510. if (sni_len) {
  1511. //ptr[0] = 0; //
  1512. //ptr[1] = 0; //extension_type
  1513. //ptr[2] = 0; //
  1514. ptr[3] = sni_len + 5; //list len
  1515. //ptr[4] = 0; //
  1516. ptr[5] = sni_len + 3; //len of 1st SNI
  1517. //ptr[6] = 0; //name type
  1518. //ptr[7] = 0; //
  1519. ptr[8] = sni_len; //name len
  1520. ptr = mempcpy(&ptr[9], sni, sni_len);
  1521. }
  1522. memcpy(ptr, extensions, sizeof(extensions));
  1523. tls->hsd = xzalloc(sizeof(*tls->hsd));
  1524. /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
  1525. memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
  1526. /* HANDSHAKE HASH:
  1527. tls->hsd->saved_client_hello_size = len;
  1528. memcpy(tls->hsd->saved_client_hello, record, len);
  1529. */
  1530. dbg(">> CLIENT_HELLO\n");
  1531. /* Can hash immediately only if we know which MAC hash to use.
  1532. * So far we do know: it's sha256:
  1533. */
  1534. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1535. xwrite_and_update_handshake_hash(tls, len);
  1536. /* if this would become infeasible: save tls->hsd->saved_client_hello,
  1537. * use "xwrite_handshake_record(tls, len)" here,
  1538. * and hash saved_client_hello later.
  1539. */
  1540. }
  1541. static void get_server_hello(tls_state_t *tls)
  1542. {
  1543. struct server_hello {
  1544. struct record_hdr xhdr;
  1545. uint8_t type;
  1546. uint8_t len24_hi, len24_mid, len24_lo;
  1547. uint8_t proto_maj, proto_min;
  1548. uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
  1549. uint8_t session_id_len;
  1550. uint8_t session_id[32];
  1551. uint8_t cipherid_hi, cipherid_lo;
  1552. uint8_t comprtype;
  1553. /* extensions may follow, but only those which client offered in its Hello */
  1554. };
  1555. struct server_hello *hp;
  1556. uint8_t *cipherid;
  1557. uint8_t cipherid1;
  1558. int len, len24;
  1559. len = tls_xread_handshake_block(tls, 74 - 32);
  1560. hp = (void*)tls->inbuf;
  1561. // 74 bytes:
  1562. // 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|
  1563. //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
  1564. if (hp->type != HANDSHAKE_SERVER_HELLO
  1565. || hp->len24_hi != 0
  1566. || hp->len24_mid != 0
  1567. /* hp->len24_lo checked later */
  1568. || hp->proto_maj != TLS_MAJ
  1569. || hp->proto_min != TLS_MIN
  1570. ) {
  1571. bad_record_die(tls, "'server hello'", len);
  1572. }
  1573. cipherid = &hp->cipherid_hi;
  1574. len24 = hp->len24_lo;
  1575. if (hp->session_id_len != 32) {
  1576. if (hp->session_id_len != 0)
  1577. bad_record_die(tls, "'server hello'", len);
  1578. // session_id_len == 0: no session id
  1579. // "The server
  1580. // may return an empty session_id to indicate that the session will
  1581. // not be cached and therefore cannot be resumed."
  1582. cipherid -= 32;
  1583. len24 += 32; /* what len would be if session id would be present */
  1584. }
  1585. if (len24 < 70)
  1586. bad_record_die(tls, "'server hello'", len);
  1587. dbg("<< SERVER_HELLO\n");
  1588. memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
  1589. /* Set up encryption params based on selected cipher */
  1590. #if 0
  1591. 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
  1592. 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
  1593. 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
  1594. 0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
  1595. // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  1596. // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
  1597. 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
  1598. // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1599. 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
  1600. // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1601. 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
  1602. // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
  1603. 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
  1604. // 0xC0,0x30, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
  1605. //possibly these too:
  1606. // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
  1607. // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
  1608. // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  1609. // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1610. 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
  1611. 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
  1612. 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
  1613. 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
  1614. 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
  1615. // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
  1616. 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
  1617. #endif
  1618. cipherid1 = cipherid[1];
  1619. tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
  1620. tls->key_size = AES256_KEYSIZE;
  1621. tls->MAC_size = SHA256_OUTSIZE;
  1622. /*tls->IV_size = 0; - already is */
  1623. if (cipherid[0] == 0xC0) {
  1624. /* All C0xx are ECDHE */
  1625. tls->flags |= NEED_EC_KEY;
  1626. if (cipherid1 & 1) {
  1627. /* Odd numbered C0xx use AES128 (even ones use AES256) */
  1628. tls->key_size = AES128_KEYSIZE;
  1629. }
  1630. if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x19) {
  1631. tls->MAC_size = SHA1_OUTSIZE;
  1632. } else
  1633. if (cipherid1 >= 0x2B && cipherid1 <= 0x30) {
  1634. /* C02B,2C,2F,30 are AES-GCM */
  1635. tls->flags |= ENCRYPTION_AESGCM;
  1636. tls->MAC_size = 0;
  1637. tls->IV_size = 4;
  1638. }
  1639. } else {
  1640. /* All 00xx are RSA */
  1641. if ((ENABLE_FEATURE_TLS_SHA1 && cipherid1 == 0x2F)
  1642. || cipherid1 == 0x3C
  1643. || cipherid1 == 0x9C
  1644. ) {
  1645. tls->key_size = AES128_KEYSIZE;
  1646. }
  1647. if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x35) {
  1648. tls->MAC_size = SHA1_OUTSIZE;
  1649. } else
  1650. if (cipherid1 == 0x9C /*|| cipherid1 == 0x9D*/) {
  1651. /* 009C,9D are AES-GCM */
  1652. tls->flags |= ENCRYPTION_AESGCM;
  1653. tls->MAC_size = 0;
  1654. tls->IV_size = 4;
  1655. }
  1656. }
  1657. dbg("server chose cipher %04x\n", tls->cipher_id);
  1658. dbg("key_size:%u MAC_size:%u IV_size:%u\n", tls->key_size, tls->MAC_size, tls->IV_size);
  1659. /* Handshake hash eventually destined to FINISHED record
  1660. * is sha256 regardless of cipher
  1661. * (at least for all ciphers defined by RFC5246).
  1662. * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
  1663. */
  1664. /* HANDSHAKE HASH:
  1665. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1666. hash_handshake(tls, ">> client hello hash:%s",
  1667. tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
  1668. );
  1669. hash_handshake(tls, "<< server hello hash:%s",
  1670. tls->inbuf + RECHDR_LEN, len
  1671. );
  1672. */
  1673. }
  1674. static void get_server_cert(tls_state_t *tls)
  1675. {
  1676. struct record_hdr *xhdr;
  1677. uint8_t *certbuf;
  1678. int len, len1;
  1679. len = tls_xread_handshake_block(tls, 10);
  1680. xhdr = (void*)tls->inbuf;
  1681. certbuf = (void*)(xhdr + 1);
  1682. if (certbuf[0] != HANDSHAKE_CERTIFICATE)
  1683. bad_record_die(tls, "certificate", len);
  1684. dbg("<< CERTIFICATE\n");
  1685. // 4392 bytes:
  1686. // 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...
  1687. //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
  1688. len1 = get24be(certbuf + 1);
  1689. if (len1 > len - 4) tls_error_die(tls);
  1690. len = len1;
  1691. len1 = get24be(certbuf + 4);
  1692. if (len1 > len - 3) tls_error_die(tls);
  1693. len = len1;
  1694. len1 = get24be(certbuf + 7);
  1695. if (len1 > len - 3) tls_error_die(tls);
  1696. len = len1;
  1697. if (len)
  1698. find_key_in_der_cert(tls, certbuf + 10, len);
  1699. }
  1700. /* On input, len is known to be >= 4.
  1701. * The record is known to be SERVER_KEY_EXCHANGE.
  1702. */
  1703. static void process_server_key(tls_state_t *tls, int len)
  1704. {
  1705. struct record_hdr *xhdr;
  1706. uint8_t *keybuf;
  1707. int len1;
  1708. uint32_t t32;
  1709. xhdr = (void*)tls->inbuf;
  1710. keybuf = (void*)(xhdr + 1);
  1711. //seen from is.gd: it selects curve_x25519:
  1712. // 0c 00006e //SERVER_KEY_EXCHANGE, len
  1713. // 03 //curve_type: named curve
  1714. // 001d //curve_x25519
  1715. //server-chosen EC point, and then signed_params
  1716. // (RFC 8422: "A hash of the params, with the signature
  1717. // appropriate to that hash applied. The private key corresponding
  1718. // to the certified public key in the server's Certificate message is
  1719. // used for signing.")
  1720. //follow. Format unclear/guessed:
  1721. // 20 //eccPubKeyLen
  1722. // 25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
  1723. // 0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
  1724. // 0046 //len (16bit)
  1725. // 30 44 //SEQ, len
  1726. // 02 20 //INTEGER, len
  1727. // 2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
  1728. //this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
  1729. // 02 20 //INTEGER, len
  1730. // 64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
  1731. //same about this item ^^^^^
  1732. //seen from ftp.openbsd.org
  1733. //(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
  1734. // 0c 000228 //SERVER_KEY_EXCHANGE, len
  1735. // 03 //curve_type: named curve
  1736. // 001d //curve_x25519
  1737. // 20 //eccPubKeyLen
  1738. // eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
  1739. // 0401 //hashSigAlg: 4:SHA256, 1:RSA
  1740. // 0200 //len
  1741. // //0x200 bytes follow
  1742. /* Get and verify length */
  1743. len1 = get24be(keybuf + 1);
  1744. if (len1 > len - 4) tls_error_die(tls);
  1745. len = len1;
  1746. if (len < (1+2+1+32)) tls_error_die(tls);
  1747. keybuf += 4;
  1748. #if BB_BIG_ENDIAN
  1749. # define _0x03001741 0x03001741
  1750. # define _0x03001d20 0x03001d20
  1751. #else
  1752. # define _0x03001741 0x41170003
  1753. # define _0x03001d20 0x201d0003
  1754. #endif
  1755. move_from_unaligned32(t32, keybuf);
  1756. keybuf += 4;
  1757. switch (t32) {
  1758. case _0x03001d20: //curve_x25519
  1759. dbg("got x25519 eccPubKey\n");
  1760. tls->flags |= GOT_EC_CURVE_X25519;
  1761. memcpy(tls->hsd->ecc_pub_key32, keybuf, 32);
  1762. break;
  1763. case _0x03001741: //curve_secp256r1 (aka P256)
  1764. dbg("got P256 eccPubKey\n");
  1765. /* P256 point can be transmitted odd- or even-compressed
  1766. * (first byte is 3 or 2) or uncompressed (4).
  1767. */
  1768. if (*keybuf++ != 4)
  1769. bb_simple_error_msg_and_die("compressed EC points not supported");
  1770. memcpy(tls->hsd->ecc_pub_key32, keybuf, 2 * 32);
  1771. break;
  1772. default:
  1773. bb_error_msg_and_die("elliptic curve is not x25519 or P256: 0x%08x", t32);
  1774. }
  1775. tls->flags |= GOT_EC_KEY;
  1776. }
  1777. static void send_empty_client_cert(tls_state_t *tls)
  1778. {
  1779. struct client_empty_cert {
  1780. uint8_t type;
  1781. uint8_t len24_hi, len24_mid, len24_lo;
  1782. uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
  1783. };
  1784. struct client_empty_cert *record;
  1785. record = tls_get_zeroed_outbuf(tls, sizeof(*record));
  1786. //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
  1787. //record->cert_chain_len24_hi = 0;
  1788. //record->cert_chain_len24_mid = 0;
  1789. //record->cert_chain_len24_lo = 0;
  1790. // same as above:
  1791. record->type = HANDSHAKE_CERTIFICATE;
  1792. record->len24_lo = 3;
  1793. dbg(">> CERTIFICATE\n");
  1794. xwrite_and_update_handshake_hash(tls, sizeof(*record));
  1795. }
  1796. static void send_client_key_exchange(tls_state_t *tls)
  1797. {
  1798. struct client_key_exchange {
  1799. uint8_t type;
  1800. uint8_t len24_hi, len24_mid, len24_lo;
  1801. uint8_t key[2 + 4 * 1024]; // size??
  1802. };
  1803. //FIXME: better size estimate
  1804. struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
  1805. uint8_t premaster[RSA_PREMASTER_SIZE > EC_CURVE_KEYSIZE ? RSA_PREMASTER_SIZE : EC_CURVE_KEYSIZE];
  1806. int premaster_size;
  1807. int len;
  1808. if (!(tls->flags & NEED_EC_KEY)) {
  1809. /* RSA */
  1810. if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
  1811. bb_simple_error_msg_and_die("server cert is not RSA");
  1812. tls_get_random(premaster, RSA_PREMASTER_SIZE);
  1813. if (TLS_DEBUG_FIXED_SECRETS)
  1814. memset(premaster, 0x44, RSA_PREMASTER_SIZE);
  1815. // RFC 5246
  1816. // "Note: The version number in the PreMasterSecret is the version
  1817. // offered by the client in the ClientHello.client_version, not the
  1818. // version negotiated for the connection."
  1819. premaster[0] = TLS_MAJ;
  1820. premaster[1] = TLS_MIN;
  1821. dump_hex("premaster:%s\n", premaster, sizeof(premaster));
  1822. len = psRsaEncryptPub(/*pool:*/ NULL,
  1823. /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
  1824. premaster, /*inlen:*/ RSA_PREMASTER_SIZE,
  1825. record->key + 2, sizeof(record->key) - 2,
  1826. data_param_ignored
  1827. );
  1828. /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
  1829. record->key[0] = len >> 8;
  1830. record->key[1] = len & 0xff;
  1831. len += 2;
  1832. premaster_size = RSA_PREMASTER_SIZE;
  1833. } else {
  1834. /* ECDHE */
  1835. if (!(tls->flags & GOT_EC_KEY))
  1836. bb_simple_error_msg_and_die("server did not provide EC key");
  1837. if (tls->flags & GOT_EC_CURVE_X25519) {
  1838. /* ECDHE, curve x25519 */
  1839. dbg("computing x25519_premaster\n");
  1840. curve_x25519_compute_pubkey_and_premaster(
  1841. record->key + 1, premaster,
  1842. /*point:*/ tls->hsd->ecc_pub_key32
  1843. );
  1844. len = CURVE25519_KEYSIZE;
  1845. //record->key[0] = len;
  1846. //len++;
  1847. //premaster_size = CURVE25519_KEYSIZE;
  1848. } else {
  1849. /* ECDHE, curve P256 */
  1850. dbg("computing P256_premaster\n");
  1851. curve_P256_compute_pubkey_and_premaster(
  1852. record->key + 2, premaster,
  1853. /*point:*/ tls->hsd->ecc_pub_key32
  1854. );
  1855. record->key[1] = 4; /* "uncompressed point" */
  1856. len = 1 + P256_KEYSIZE * 2;
  1857. }
  1858. record->key[0] = len;
  1859. len++;
  1860. premaster_size = P256_KEYSIZE; // = CURVE25519_KEYSIZE = 32
  1861. }
  1862. record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
  1863. /* record->len24_hi = 0; - already is */
  1864. record->len24_mid = len >> 8;
  1865. record->len24_lo = len & 0xff;
  1866. len += 4;
  1867. dbg(">> CLIENT_KEY_EXCHANGE\n");
  1868. xwrite_and_update_handshake_hash(tls, len);
  1869. // RFC 5246
  1870. // For all key exchange methods, the same algorithm is used to convert
  1871. // the pre_master_secret into the master_secret. The pre_master_secret
  1872. // should be deleted from memory once the master_secret has been
  1873. // computed.
  1874. // master_secret = PRF(pre_master_secret, "master secret",
  1875. // ClientHello.random + ServerHello.random)
  1876. // [0..47];
  1877. // The master secret is always exactly 48 bytes in length. The length
  1878. // of the premaster secret will vary depending on key exchange method.
  1879. prf_hmac_sha256(/*tls,*/
  1880. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1881. premaster, premaster_size,
  1882. "master secret",
  1883. tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
  1884. );
  1885. dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1886. // RFC 5246
  1887. // 6.3. Key Calculation
  1888. //
  1889. // The Record Protocol requires an algorithm to generate keys required
  1890. // by the current connection state (see Appendix A.6) from the security
  1891. // parameters provided by the handshake protocol.
  1892. //
  1893. // The master secret is expanded into a sequence of secure bytes, which
  1894. // is then split to a client write MAC key, a server write MAC key, a
  1895. // client write encryption key, and a server write encryption key. Each
  1896. // of these is generated from the byte sequence in that order. Unused
  1897. // values are empty. Some AEAD ciphers may additionally require a
  1898. // client write IV and a server write IV (see Section 6.2.3.3).
  1899. //
  1900. // When keys and MAC keys are generated, the master secret is used as an
  1901. // entropy source.
  1902. //
  1903. // To generate the key material, compute
  1904. //
  1905. // key_block = PRF(SecurityParameters.master_secret,
  1906. // "key expansion",
  1907. // SecurityParameters.server_random +
  1908. // SecurityParameters.client_random);
  1909. //
  1910. // until enough output has been generated. Then, the key_block is
  1911. // partitioned as follows:
  1912. //
  1913. // client_write_MAC_key[SecurityParameters.mac_key_length]
  1914. // server_write_MAC_key[SecurityParameters.mac_key_length]
  1915. // client_write_key[SecurityParameters.enc_key_length]
  1916. // server_write_key[SecurityParameters.enc_key_length]
  1917. // client_write_IV[SecurityParameters.fixed_iv_length]
  1918. // server_write_IV[SecurityParameters.fixed_iv_length]
  1919. {
  1920. uint8_t tmp64[64];
  1921. /* make "server_rand32 + client_rand32" */
  1922. memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
  1923. memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
  1924. prf_hmac_sha256(/*tls,*/
  1925. tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
  1926. // also fills:
  1927. // server_write_MAC_key[]
  1928. // client_write_key[]
  1929. // server_write_key[]
  1930. // client_write_IV[]
  1931. // server_write_IV[]
  1932. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1933. "key expansion",
  1934. tmp64, 64
  1935. );
  1936. tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
  1937. tls->server_write_key = tls->client_write_key + tls->key_size;
  1938. tls->client_write_IV = tls->server_write_key + tls->key_size;
  1939. tls->server_write_IV = tls->client_write_IV + tls->IV_size;
  1940. dump_hex("client_write_MAC_key:%s\n",
  1941. tls->client_write_MAC_key, tls->MAC_size
  1942. );
  1943. dump_hex("client_write_key:%s\n",
  1944. tls->client_write_key, tls->key_size
  1945. );
  1946. dump_hex("client_write_IV:%s\n",
  1947. tls->client_write_IV, tls->IV_size
  1948. );
  1949. aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
  1950. aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
  1951. {
  1952. uint8_t iv[AES_BLOCK_SIZE];
  1953. memset(iv, 0, AES_BLOCK_SIZE);
  1954. aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
  1955. }
  1956. }
  1957. }
  1958. static const uint8_t rec_CHANGE_CIPHER_SPEC[] ALIGN1 = {
  1959. RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
  1960. 01
  1961. };
  1962. static void send_change_cipher_spec(tls_state_t *tls)
  1963. {
  1964. dbg(">> CHANGE_CIPHER_SPEC\n");
  1965. xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
  1966. }
  1967. // 7.4.9. Finished
  1968. // A Finished message is always sent immediately after a change
  1969. // cipher spec message to verify that the key exchange and
  1970. // authentication processes were successful. It is essential that a
  1971. // change cipher spec message be received between the other handshake
  1972. // messages and the Finished message.
  1973. //...
  1974. // The Finished message is the first one protected with the just
  1975. // negotiated algorithms, keys, and secrets. Recipients of Finished
  1976. // messages MUST verify that the contents are correct. Once a side
  1977. // has sent its Finished message and received and validated the
  1978. // Finished message from its peer, it may begin to send and receive
  1979. // application data over the connection.
  1980. //...
  1981. // struct {
  1982. // opaque verify_data[verify_data_length];
  1983. // } Finished;
  1984. //
  1985. // verify_data
  1986. // PRF(master_secret, finished_label, Hash(handshake_messages))
  1987. // [0..verify_data_length-1];
  1988. //
  1989. // finished_label
  1990. // For Finished messages sent by the client, the string
  1991. // "client finished". For Finished messages sent by the server,
  1992. // the string "server finished".
  1993. //
  1994. // Hash denotes a Hash of the handshake messages. For the PRF
  1995. // defined in Section 5, the Hash MUST be the Hash used as the basis
  1996. // for the PRF. Any cipher suite which defines a different PRF MUST
  1997. // also define the Hash to use in the Finished computation.
  1998. //
  1999. // In previous versions of TLS, the verify_data was always 12 octets
  2000. // long. In the current version of TLS, it depends on the cipher
  2001. // suite. Any cipher suite which does not explicitly specify
  2002. // verify_data_length has a verify_data_length equal to 12. This
  2003. // includes all existing cipher suites.
  2004. static void send_client_finished(tls_state_t *tls)
  2005. {
  2006. struct finished {
  2007. uint8_t type;
  2008. uint8_t len24_hi, len24_mid, len24_lo;
  2009. uint8_t prf_result[12];
  2010. };
  2011. struct finished *record = tls_get_outbuf(tls, sizeof(*record));
  2012. uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
  2013. unsigned len;
  2014. fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
  2015. len = sha_end(&tls->hsd->handshake_hash_ctx, handshake_hash);
  2016. prf_hmac_sha256(/*tls,*/
  2017. record->prf_result, sizeof(record->prf_result),
  2018. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  2019. "client finished",
  2020. handshake_hash, len
  2021. );
  2022. dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  2023. dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
  2024. dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
  2025. dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
  2026. dbg(">> FINISHED\n");
  2027. xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
  2028. }
  2029. void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
  2030. {
  2031. // Client RFC 5246 Server
  2032. // (*) - optional messages, not always sent
  2033. //
  2034. // ClientHello ------->
  2035. // ServerHello
  2036. // Certificate*
  2037. // ServerKeyExchange*
  2038. // CertificateRequest*
  2039. // <------- ServerHelloDone
  2040. // Certificate*
  2041. // ClientKeyExchange
  2042. // CertificateVerify*
  2043. // [ChangeCipherSpec]
  2044. // Finished ------->
  2045. // [ChangeCipherSpec]
  2046. // <------- Finished
  2047. // Application Data <------> Application Data
  2048. int len;
  2049. int got_cert_req;
  2050. send_client_hello_and_alloc_hsd(tls, sni);
  2051. get_server_hello(tls);
  2052. // RFC 5246
  2053. // The server MUST send a Certificate message whenever the agreed-
  2054. // upon key exchange method uses certificates for authentication
  2055. // (this includes all key exchange methods defined in this document
  2056. // except DH_anon). This message will always immediately follow the
  2057. // ServerHello message.
  2058. //
  2059. // IOW: in practice, Certificate *always* follows.
  2060. // (for example, kernel.org does not even accept DH_anon cipher id)
  2061. get_server_cert(tls);
  2062. len = tls_xread_handshake_block(tls, 4);
  2063. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
  2064. // 459 bytes:
  2065. // 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...
  2066. //SvKey len=455^
  2067. // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
  2068. // 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...
  2069. //
  2070. // RFC 8422 5.4. Server Key Exchange
  2071. // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
  2072. // ECDH_anon key exchange algorithms.
  2073. // This message is used to convey the server's ephemeral ECDH public key
  2074. // (and the corresponding elliptic curve domain parameters) to the
  2075. // client.
  2076. dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
  2077. dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
  2078. if (tls->flags & NEED_EC_KEY)
  2079. process_server_key(tls, len);
  2080. // read next handshake block
  2081. len = tls_xread_handshake_block(tls, 4);
  2082. }
  2083. got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
  2084. if (got_cert_req) {
  2085. dbg("<< CERTIFICATE_REQUEST\n");
  2086. // RFC 5246: "If no suitable certificate is available,
  2087. // the client MUST send a certificate message containing no
  2088. // certificates. That is, the certificate_list structure has a
  2089. // length of zero. ...
  2090. // Client certificates are sent using the Certificate structure
  2091. // defined in Section 7.4.2."
  2092. // (i.e. the same format as server certs)
  2093. /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
  2094. /* need to hash _all_ server replies first, up to ServerHelloDone */
  2095. len = tls_xread_handshake_block(tls, 4);
  2096. }
  2097. if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
  2098. bad_record_die(tls, "'server hello done'", len);
  2099. }
  2100. // 0e 000000 (len:0)
  2101. dbg("<< SERVER_HELLO_DONE\n");
  2102. if (got_cert_req)
  2103. send_empty_client_cert(tls);
  2104. send_client_key_exchange(tls);
  2105. send_change_cipher_spec(tls);
  2106. /* from now on we should send encrypted */
  2107. /* tls->write_seq64_be = 0; - already is */
  2108. tls->flags |= ENCRYPT_ON_WRITE;
  2109. send_client_finished(tls);
  2110. /* Get CHANGE_CIPHER_SPEC */
  2111. len = tls_xread_record(tls, "switch to encrypted traffic");
  2112. if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
  2113. bad_record_die(tls, "switch to encrypted traffic", len);
  2114. dbg("<< CHANGE_CIPHER_SPEC\n");
  2115. if (ALLOW_RSA_NULL_SHA256
  2116. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  2117. ) {
  2118. tls->min_encrypted_len_on_read = tls->MAC_size;
  2119. } else
  2120. if (!(tls->flags & ENCRYPTION_AESGCM)) {
  2121. unsigned mac_blocks = (unsigned)(TLS_MAC_SIZE(tls) + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
  2122. /* all incoming packets now should be encrypted and have
  2123. * at least IV + (MAC padded to blocksize):
  2124. */
  2125. tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
  2126. } else {
  2127. tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
  2128. }
  2129. dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
  2130. /* Get (encrypted) FINISHED from the server */
  2131. len = tls_xread_record(tls, "'server finished'");
  2132. if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
  2133. bad_record_die(tls, "'server finished'", len);
  2134. dbg("<< FINISHED\n");
  2135. /* application data can be sent/received */
  2136. /* free handshake data */
  2137. psRsaKey_clear(&tls->hsd->server_rsa_pub_key);
  2138. // if (PARANOIA)
  2139. // memset(tls->hsd, 0, tls->hsd->hsd_size);
  2140. free(tls->hsd);
  2141. tls->hsd = NULL;
  2142. }
  2143. static void tls_xwrite(tls_state_t *tls, int len)
  2144. {
  2145. dbg(">> DATA\n");
  2146. xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
  2147. }
  2148. // To run a test server using openssl:
  2149. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  2150. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2
  2151. //
  2152. // Unencryped SHA256 example:
  2153. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  2154. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -cipher NULL
  2155. // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -cipher NULL-SHA256
  2156. void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
  2157. {
  2158. int inbuf_size;
  2159. const int INBUF_STEP = 4 * 1024;
  2160. struct pollfd pfds[2];
  2161. #if 0
  2162. // Debug aid for comparing P256 implementations.
  2163. // Enable this, set SP_DEBUG and FIXED_SECRET to 1,
  2164. // and add
  2165. // tls_run_copy_loop(NULL, 0);
  2166. // e.g. at the very beginning of wget_main()
  2167. //
  2168. {
  2169. uint8_t ecc_pub_key32[2 * 32];
  2170. uint8_t pubkey2x32[2 * 32];
  2171. uint8_t premaster32[32];
  2172. //Fixed input key:
  2173. // memset(ecc_pub_key32, 0xee, sizeof(ecc_pub_key32));
  2174. //Fixed 000000000000000000000000000000000000ab000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
  2175. // memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
  2176. // ecc_pub_key32[18] = 0xab;
  2177. //Random key:
  2178. // tls_get_random(ecc_pub_key32, sizeof(ecc_pub_key32));
  2179. //Biased random (almost all zeros or almost all ones):
  2180. srand(time(NULL) ^ getpid());
  2181. if (rand() & 1)
  2182. memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
  2183. else
  2184. memset(ecc_pub_key32, 0xff, sizeof(ecc_pub_key32));
  2185. ecc_pub_key32[rand() & 0x3f] = rand();
  2186. xmove_fd(xopen("p256.OLD", O_WRONLY | O_CREAT | O_TRUNC), 2);
  2187. curve_P256_compute_pubkey_and_premaster(
  2188. pubkey2x32, premaster32,
  2189. /*point:*/ ecc_pub_key32
  2190. );
  2191. xmove_fd(xopen("p256.NEW", O_WRONLY | O_CREAT | O_TRUNC), 2);
  2192. curve_P256_compute_pubkey_and_premaster_NEW(
  2193. pubkey2x32, premaster32,
  2194. /*point:*/ ecc_pub_key32
  2195. );
  2196. exit(1);
  2197. }
  2198. #endif
  2199. pfds[0].fd = STDIN_FILENO;
  2200. pfds[0].events = POLLIN;
  2201. pfds[1].fd = tls->ifd;
  2202. pfds[1].events = POLLIN;
  2203. inbuf_size = INBUF_STEP;
  2204. for (;;) {
  2205. int nread;
  2206. if (safe_poll(pfds, 2, -1) < 0)
  2207. bb_simple_perror_msg_and_die("poll");
  2208. if (pfds[0].revents) {
  2209. void *buf;
  2210. dbg("STDIN HAS DATA\n");
  2211. buf = tls_get_outbuf(tls, inbuf_size);
  2212. nread = safe_read(STDIN_FILENO, buf, inbuf_size);
  2213. if (nread < 1) {
  2214. /* We'd want to do this: */
  2215. /* Close outgoing half-connection so they get EOF,
  2216. * but leave incoming alone so we can see response
  2217. */
  2218. //shutdown(tls->ofd, SHUT_WR);
  2219. /* But TLS has no way to encode this,
  2220. * doubt it's ok to do it "raw"
  2221. */
  2222. pfds[0].fd = -1;
  2223. tls_free_outbuf(tls); /* mem usage optimization */
  2224. if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
  2225. break;
  2226. } else {
  2227. if (nread == inbuf_size) {
  2228. /* TLS has per record overhead, if input comes fast,
  2229. * read, encrypt and send bigger chunks
  2230. */
  2231. inbuf_size += INBUF_STEP;
  2232. if (inbuf_size > TLS_MAX_OUTBUF)
  2233. inbuf_size = TLS_MAX_OUTBUF;
  2234. }
  2235. tls_xwrite(tls, nread);
  2236. }
  2237. }
  2238. if (pfds[1].revents) {
  2239. dbg("NETWORK HAS DATA\n");
  2240. read_record:
  2241. nread = tls_xread_record(tls, "encrypted data");
  2242. if (nread < 1) {
  2243. /* TLS protocol has no real concept of one-sided shutdowns:
  2244. * if we get "TLS EOF" from the peer, writes will fail too
  2245. */
  2246. //pfds[1].fd = -1;
  2247. //close(STDOUT_FILENO);
  2248. //tls_free_inbuf(tls); /* mem usage optimization */
  2249. //continue;
  2250. break;
  2251. }
  2252. if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
  2253. bad_record_die(tls, "encrypted data", nread);
  2254. xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
  2255. /* We may already have a complete next record buffered,
  2256. * can process it without network reads (and possible blocking)
  2257. */
  2258. if (tls_has_buffered_record(tls))
  2259. goto read_record;
  2260. }
  2261. }
  2262. }