tls.c 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  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. switch (code) {
  853. case 20: return "bad MAC";
  854. case 50: return "decode error";
  855. case 51: return "decrypt error";
  856. case 40: return "handshake failure";
  857. case 112: return "unrecognized name";
  858. }
  859. return itoa(code);
  860. }
  861. static void tls_aesgcm_decrypt(tls_state_t *tls, uint8_t *buf, int size)
  862. {
  863. #define COUNTER(v) (*(uint32_t*)(v + 12))
  864. //uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
  865. uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
  866. uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
  867. //uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
  868. unsigned remaining;
  869. unsigned cnt;
  870. //memcpy(aad, buf, 8);
  871. //aad[8] = type;
  872. //aad[9] = TLS_MAJ;
  873. //aad[10] = TLS_MIN;
  874. //aad[11] = size >> 8;
  875. ///* set aad[12], and clear aad[13..15] */
  876. //COUNTER(aad) = SWAP_LE32(size & 0xff);
  877. memcpy(nonce, tls->server_write_IV, 4);
  878. memcpy(nonce + 4, buf, 8);
  879. cnt = 1;
  880. remaining = size;
  881. while (remaining != 0) {
  882. unsigned n;
  883. cnt++;
  884. COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
  885. aes_encrypt_one_block(&tls->aes_decrypt, nonce, scratch);
  886. n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
  887. xorbuf3(buf, scratch, buf + 8, n);
  888. buf += n;
  889. remaining -= n;
  890. }
  891. //aesgcm_GHASH(tls->H, aad, tls->inbuf + RECHDR_LEN, size, authtag);
  892. //COUNTER(nonce) = htonl(1);
  893. //aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
  894. //xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
  895. //memcmp(buf, authtag, sizeof(authtag)) || DIE("HASH DOES NOT MATCH!");
  896. #undef COUNTER
  897. }
  898. static int tls_xread_record(tls_state_t *tls, const char *expected)
  899. {
  900. struct record_hdr *xhdr;
  901. int sz;
  902. int total;
  903. int target;
  904. again:
  905. dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
  906. total = tls->buffered_size;
  907. if (total != 0) {
  908. memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
  909. //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
  910. //dump_raw_in("<< %s\n", tls->inbuf, total);
  911. }
  912. errno = 0;
  913. target = MAX_INBUF;
  914. for (;;) {
  915. int rem;
  916. if (total >= RECHDR_LEN && target == MAX_INBUF) {
  917. xhdr = (void*)tls->inbuf;
  918. target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
  919. if (target > MAX_INBUF /* malformed input (too long) */
  920. || xhdr->proto_maj != TLS_MAJ
  921. || xhdr->proto_min != TLS_MIN
  922. ) {
  923. sz = total < target ? total : target;
  924. bad_record_die(tls, expected, sz);
  925. }
  926. dbg("xhdr type:%d ver:%d.%d len:%d\n",
  927. xhdr->type, xhdr->proto_maj, xhdr->proto_min,
  928. 0x100 * xhdr->len16_hi + xhdr->len16_lo
  929. );
  930. }
  931. /* if total >= target, we have a full packet (and possibly more)... */
  932. if (total - target >= 0)
  933. break;
  934. /* input buffer is grown only as needed */
  935. rem = tls->inbuf_size - total;
  936. if (rem == 0) {
  937. tls->inbuf_size += MAX_INBUF / 8;
  938. if (tls->inbuf_size > MAX_INBUF)
  939. tls->inbuf_size = MAX_INBUF;
  940. dbg("inbuf_size:%d\n", tls->inbuf_size);
  941. rem = tls->inbuf_size - total;
  942. tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
  943. }
  944. sz = safe_read(tls->ifd, tls->inbuf + total, rem);
  945. if (sz <= 0) {
  946. if (sz == 0 && total == 0) {
  947. /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
  948. dbg("EOF (without TLS shutdown) from peer\n");
  949. tls->buffered_size = 0;
  950. goto end;
  951. }
  952. bb_perror_msg_and_die("short read, have only %d", total);
  953. }
  954. dump_raw_in("<< %s\n", tls->inbuf + total, sz);
  955. total += sz;
  956. }
  957. tls->buffered_size = total - target;
  958. tls->ofs_to_buffered = target;
  959. //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
  960. //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
  961. sz = target - RECHDR_LEN;
  962. /* Needs to be decrypted? */
  963. if (tls->min_encrypted_len_on_read != 0) {
  964. if (sz < (int)tls->min_encrypted_len_on_read)
  965. bb_error_msg_and_die("bad encrypted len:%u", sz);
  966. if (tls->flags & ENCRYPTION_AESGCM) {
  967. /* AESGCM */
  968. uint8_t *p = tls->inbuf + RECHDR_LEN;
  969. sz -= 8 + AES_BLOCK_SIZE; /* we will overwrite nonce, drop hash */
  970. tls_aesgcm_decrypt(tls, p, sz);
  971. dbg("encrypted size:%u\n", sz);
  972. } else
  973. if (tls->min_encrypted_len_on_read > TLS_MAC_SIZE(tls)) {
  974. /* AES+SHA */
  975. uint8_t *p = tls->inbuf + RECHDR_LEN;
  976. int padding_len;
  977. if (sz & (AES_BLOCK_SIZE-1))
  978. bb_error_msg_and_die("bad encrypted len:%u", sz);
  979. /* Decrypt content+MAC+padding, moving it over IV in the process */
  980. sz -= AES_BLOCK_SIZE; /* we will overwrite IV now */
  981. aes_cbc_decrypt(
  982. &tls->aes_decrypt, /* selects 128/256 */
  983. p, /* IV */
  984. p + AES_BLOCK_SIZE, sz, /* ciphertext */
  985. p /* plaintext */
  986. );
  987. padding_len = p[sz - 1];
  988. dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
  989. padding_len++;
  990. sz -= TLS_MAC_SIZE(tls) + padding_len; /* drop MAC and padding */
  991. } else {
  992. /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
  993. /* else: no encryption yet on input, subtract zero = NOP */
  994. sz -= tls->min_encrypted_len_on_read;
  995. }
  996. }
  997. if (sz < 0)
  998. bb_simple_error_msg_and_die("encrypted data too short");
  999. //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
  1000. xhdr = (void*)tls->inbuf;
  1001. if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
  1002. uint8_t *p = tls->inbuf + RECHDR_LEN;
  1003. dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
  1004. if (p[0] == 2) { /* fatal */
  1005. bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
  1006. "error",
  1007. p[1], alert_text(p[1])
  1008. );
  1009. }
  1010. if (p[0] == 1) { /* warning */
  1011. if (p[1] == 0) { /* "close_notify" warning: it's EOF */
  1012. dbg("EOF (TLS encoded) from peer\n");
  1013. sz = 0;
  1014. goto end;
  1015. }
  1016. //This possibly needs to be cached and shown only if
  1017. //a fatal alert follows
  1018. // bb_error_msg("TLS %s from peer (alert code %d): %s",
  1019. // "warning",
  1020. // p[1], alert_text(p[1])
  1021. // );
  1022. /* discard it, get next record */
  1023. goto again;
  1024. }
  1025. /* p[0] not 1 or 2: not defined in protocol */
  1026. sz = 0;
  1027. goto end;
  1028. }
  1029. /* RFC 5246 is not saying it explicitly, but sha256 hash
  1030. * in our FINISHED record must include data of incoming packets too!
  1031. */
  1032. if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
  1033. /* HANDSHAKE HASH: */
  1034. // && do_we_know_which_hash_to_use /* server_hello() might not know it in the future! */
  1035. ) {
  1036. hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
  1037. }
  1038. end:
  1039. dbg("got block len:%u\n", sz);
  1040. return sz;
  1041. }
  1042. static void binary_to_pstm(pstm_int *pstm_n, uint8_t *bin_ptr, unsigned len)
  1043. {
  1044. pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
  1045. pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
  1046. //return bin_ptr + len;
  1047. }
  1048. /*
  1049. * DER parsing routines
  1050. */
  1051. static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
  1052. {
  1053. unsigned len, len1;
  1054. if (end - der < 2)
  1055. xfunc_die();
  1056. // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
  1057. // xfunc_die();
  1058. len = der[1]; /* maybe it's short len */
  1059. if (len >= 0x80) {
  1060. /* no, it's long */
  1061. if (len == 0x80 || end - der < (int)(len - 0x7e)) {
  1062. /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
  1063. /* need 3 or 4 bytes for 81, 82 */
  1064. xfunc_die();
  1065. }
  1066. len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
  1067. if (len > 0x82) {
  1068. /* >0x82 is "3+ bytes of len", should not happen realistically */
  1069. xfunc_die();
  1070. }
  1071. if (len == 0x82) { /* it's "ii 82 xx yy" */
  1072. len1 = 0x100*len1 + der[3];
  1073. der += 1; /* skip [yy] */
  1074. }
  1075. der += 1; /* skip [xx] */
  1076. len = len1;
  1077. // if (len < 0x80)
  1078. // xfunc_die(); /* invalid DER: must use short len if can */
  1079. }
  1080. der += 2; /* skip [code]+[1byte] */
  1081. if (end - der < (int)len)
  1082. xfunc_die();
  1083. *bodyp = der;
  1084. return len;
  1085. }
  1086. static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
  1087. {
  1088. uint8_t *new_der;
  1089. unsigned len = get_der_len(&new_der, der, *endp);
  1090. dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
  1091. /* Move "end" position to cover only this item */
  1092. *endp = new_der + len;
  1093. return new_der;
  1094. }
  1095. static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
  1096. {
  1097. uint8_t *new_der;
  1098. unsigned len = get_der_len(&new_der, der, end);
  1099. /* Skip body */
  1100. new_der += len;
  1101. dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
  1102. return new_der;
  1103. }
  1104. static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
  1105. {
  1106. uint8_t *bin_ptr;
  1107. unsigned len = get_der_len(&bin_ptr, der, end);
  1108. dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
  1109. binary_to_pstm(pstm_n, bin_ptr, len);
  1110. }
  1111. static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
  1112. {
  1113. /* Certificate is a DER-encoded data structure. Each DER element has a length,
  1114. * which makes it easy to skip over large compound elements of any complexity
  1115. * without parsing them. Example: partial decode of kernel.org certificate:
  1116. * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
  1117. * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
  1118. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
  1119. * INTEGER (version): 0201 02
  1120. * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
  1121. * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
  1122. * SEQ 0x0d bytes (signatureAlgo): 300d
  1123. * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
  1124. * NULL: 0500
  1125. * SEQ 0x5f bytes (issuer): 305f
  1126. * SET 11 bytes: 310b
  1127. * SEQ 9 bytes: 3009
  1128. * OID 3 bytes: 0603 550406
  1129. * Printable string "FR": 1302 4652
  1130. * SET 14 bytes: 310e
  1131. * SEQ 12 bytes: 300c
  1132. * OID 3 bytes: 0603 550408
  1133. * Printable string "Paris": 1305 5061726973
  1134. * SET 14 bytes: 310e
  1135. * SEQ 12 bytes: 300c
  1136. * OID 3 bytes: 0603 550407
  1137. * Printable string "Paris": 1305 5061726973
  1138. * SET 14 bytes: 310e
  1139. * SEQ 12 bytes: 300c
  1140. * OID 3 bytes: 0603 55040a
  1141. * Printable string "Gandi": 1305 47616e6469
  1142. * SET 32 bytes: 3120
  1143. * SEQ 30 bytes: 301e
  1144. * OID 3 bytes: 0603 550403
  1145. * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
  1146. * SEQ 30 bytes (validity): 301e
  1147. * TIME "161011000000Z": 170d 3136313031313030303030305a
  1148. * TIME "191011235959Z": 170d 3139313031313233353935395a
  1149. * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
  1150. * 3121301f060355040b1318446f6d61696e20436f
  1151. * 6e74726f6c2056616c6964617465643121301f06
  1152. * 0355040b1318506f73697469766553534c204d75
  1153. * 6c74692d446f6d61696e31133011060355040313
  1154. * 0a6b65726e656c2e6f7267
  1155. * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
  1156. * SEQ 13 bytes (algorithm): 300d
  1157. * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
  1158. * NULL: 0500
  1159. * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
  1160. * ????: 00
  1161. * //after the zero byte, it appears key itself uses DER encoding:
  1162. * SEQ 0x018a/394 bytes: 3082018a
  1163. * INTEGER 0x0181/385 bytes (modulus): 02820181
  1164. * 00b1ab2fc727a3bef76780c9349bf3
  1165. * ...24 more blocks of 15 bytes each...
  1166. * 90e895291c6bc8693b65
  1167. * INTEGER 3 bytes (exponent): 0203 010001
  1168. * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
  1169. * SEQ 0x01e1 bytes: 308201e1
  1170. * ...
  1171. * Certificate is a sequence of three elements:
  1172. * tbsCertificate (SEQ)
  1173. * signatureAlgorithm (AlgorithmIdentifier)
  1174. * signatureValue (BIT STRING)
  1175. *
  1176. * In turn, tbsCertificate is a sequence of:
  1177. * version
  1178. * serialNumber
  1179. * signatureAlgo (AlgorithmIdentifier)
  1180. * issuer (Name, has complex structure)
  1181. * validity (Validity, SEQ of two Times)
  1182. * subject (Name)
  1183. * subjectPublicKeyInfo (SEQ)
  1184. * ...
  1185. *
  1186. * subjectPublicKeyInfo is a sequence of:
  1187. * algorithm (AlgorithmIdentifier)
  1188. * publicKey (BIT STRING)
  1189. *
  1190. * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
  1191. *
  1192. * Example of an ECDSA key:
  1193. * SEQ 0x59 bytes (subjectPublicKeyInfo): 3059
  1194. * SEQ 0x13 bytes (algorithm): 3013
  1195. * OID 7 bytes: 0607 2a8648ce3d0201 (OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1)
  1196. * OID 8 bytes: 0608 2a8648ce3d030107 (OID_EC_prime256v1 42.134.72.206.61.3.1.7)
  1197. * BITSTRING 0x42 bytes (publicKey): 0342
  1198. * 0004 53af f65e 50cc 7959 7e29 0171 c75c
  1199. * 7335 e07d f45b 9750 b797 3a38 aebb 2ac6
  1200. * 8329 2748 e77e 41cb d482 2ce6 05ec a058
  1201. * f3ab d561 2f4c d845 9ad3 7252 e3de bd3b
  1202. * 9012
  1203. */
  1204. uint8_t *end = der + len;
  1205. /* enter "Certificate" item: [der, end) will be only Cert */
  1206. der = enter_der_item(der, &end);
  1207. /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
  1208. der = enter_der_item(der, &end);
  1209. /*
  1210. * Skip version field only if it is present. For a v1 certificate, the
  1211. * version field won't be present since v1 is the default value for the
  1212. * version field and fields with default values should be omitted (see
  1213. * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
  1214. * it will have a tag class of 2 (context-specific), bit 6 as 1
  1215. * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
  1216. * and 8.14).
  1217. */
  1218. /* bits 7-6: 10 */
  1219. /* bit 5: 1 */
  1220. /* bits 4-0: 00000 */
  1221. if (der[0] == 0xa0)
  1222. der = skip_der_item(der, end); /* version */
  1223. /* skip up to subjectPublicKeyInfo */
  1224. der = skip_der_item(der, end); /* serialNumber */
  1225. der = skip_der_item(der, end); /* signatureAlgo */
  1226. der = skip_der_item(der, end); /* issuer */
  1227. der = skip_der_item(der, end); /* validity */
  1228. der = skip_der_item(der, end); /* subject */
  1229. /* enter subjectPublicKeyInfo */
  1230. der = enter_der_item(der, &end);
  1231. { /* check subjectPublicKeyInfo.algorithm */
  1232. static const uint8_t OID_RSA_KEY_ALG[] ALIGN1 = {
  1233. 0x30,0x0d, // SEQ 13 bytes
  1234. 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, //OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
  1235. //0x05,0x00, // NULL
  1236. };
  1237. static const uint8_t OID_ECDSA_KEY_ALG[] ALIGN1 = {
  1238. 0x30,0x13, // SEQ 0x13 bytes
  1239. 0x06,0x07, 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01, //OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1
  1240. //allow any curve code for now...
  1241. // 0x06,0x08, 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07, //OID_EC_prime256v1 42.134.72.206.61.3.1.7
  1242. //RFC 3279:
  1243. //42.134.72.206.61.3 is ellipticCurve
  1244. //42.134.72.206.61.3.0 is c-TwoCurve
  1245. //42.134.72.206.61.3.1 is primeCurve
  1246. //42.134.72.206.61.3.1.7 is curve_secp256r1
  1247. };
  1248. if (memcmp(der, OID_RSA_KEY_ALG, sizeof(OID_RSA_KEY_ALG)) == 0) {
  1249. dbg("RSA key\n");
  1250. tls->flags |= GOT_CERT_RSA_KEY_ALG;
  1251. } else
  1252. if (memcmp(der, OID_ECDSA_KEY_ALG, sizeof(OID_ECDSA_KEY_ALG)) == 0) {
  1253. dbg("ECDSA key\n");
  1254. //UNUSED: tls->flags |= GOT_CERT_ECDSA_KEY_ALG;
  1255. } else
  1256. bb_simple_error_msg_and_die("not RSA or ECDSA cert");
  1257. }
  1258. if (tls->flags & GOT_CERT_RSA_KEY_ALG) {
  1259. /* parse RSA key: */
  1260. //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
  1261. /* skip subjectPublicKeyInfo.algorithm */
  1262. der = skip_der_item(der, end);
  1263. /* enter subjectPublicKeyInfo.publicKey */
  1264. //die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
  1265. der = enter_der_item(der, &end);
  1266. dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
  1267. if (end - der < 14)
  1268. xfunc_die();
  1269. /* example format:
  1270. * ignore bits: 00
  1271. * SEQ 0x018a/394 bytes: 3082018a
  1272. * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
  1273. * INTEGER 3 bytes (exponent): 0203 010001
  1274. */
  1275. if (*der != 0) /* "ignore bits", should be 0 */
  1276. xfunc_die();
  1277. der++;
  1278. der = enter_der_item(der, &end); /* enter SEQ */
  1279. /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
  1280. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
  1281. der = skip_der_item(der, end);
  1282. der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
  1283. tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
  1284. dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
  1285. }
  1286. /* else: ECDSA key. It is not used for generating encryption keys,
  1287. * it is used only to sign the EC public key (which comes in ServerKey message).
  1288. * Since we do not verify cert validity, verifying signature on EC public key
  1289. * wouldn't add any security. Thus, we do nothing here.
  1290. */
  1291. }
  1292. /*
  1293. * TLS Handshake routines
  1294. */
  1295. static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
  1296. {
  1297. struct record_hdr *xhdr;
  1298. int len = tls_xread_record(tls, "handshake record");
  1299. xhdr = (void*)tls->inbuf;
  1300. if (len < min_len
  1301. || xhdr->type != RECORD_TYPE_HANDSHAKE
  1302. ) {
  1303. bad_record_die(tls, "handshake record", len);
  1304. }
  1305. dbg("got HANDSHAKE\n");
  1306. return len;
  1307. }
  1308. static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
  1309. {
  1310. struct handshake_hdr {
  1311. uint8_t type;
  1312. uint8_t len24_hi, len24_mid, len24_lo;
  1313. } *h = buf;
  1314. len -= 4;
  1315. h->type = type;
  1316. h->len24_hi = len >> 16;
  1317. h->len24_mid = len >> 8;
  1318. h->len24_lo = len & 0xff;
  1319. }
  1320. static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
  1321. {
  1322. #define NUM_CIPHERS (0 \
  1323. + 4 * ENABLE_FEATURE_TLS_SHA1 \
  1324. + ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 \
  1325. + ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 \
  1326. + ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \
  1327. + ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 \
  1328. + 2 * ENABLE_FEATURE_TLS_SHA1 \
  1329. + ALLOW_RSA_WITH_AES_128_CBC_SHA256 \
  1330. + ALLOW_RSA_WITH_AES_256_CBC_SHA256 \
  1331. + ALLOW_RSA_WITH_AES_128_GCM_SHA256 \
  1332. + ALLOW_RSA_NULL_SHA256 \
  1333. )
  1334. static const uint8_t ciphers[] = {
  1335. 0x00,2 * (1 + NUM_CIPHERS), //len16_be
  1336. 0x00,0xFF, //not a cipher - TLS_EMPTY_RENEGOTIATION_INFO_SCSV
  1337. /* ^^^^^^ RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
  1338. #if ENABLE_FEATURE_TLS_SHA1
  1339. 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
  1340. 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
  1341. 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
  1342. 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)
  1343. // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  1344. // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
  1345. #endif
  1346. #if ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
  1347. 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
  1348. #endif
  1349. // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1350. #if ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256
  1351. 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
  1352. #endif
  1353. // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1354. #if ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
  1355. 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
  1356. #endif
  1357. // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
  1358. //TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
  1359. #if ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  1360. 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
  1361. #endif
  1362. // 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"
  1363. //possibly these too:
  1364. #if ENABLE_FEATURE_TLS_SHA1
  1365. // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
  1366. // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
  1367. #endif
  1368. // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  1369. // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1370. #if ENABLE_FEATURE_TLS_SHA1
  1371. 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
  1372. 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
  1373. #endif
  1374. #if ALLOW_RSA_WITH_AES_128_CBC_SHA256
  1375. 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
  1376. #endif
  1377. #if ALLOW_RSA_WITH_AES_256_CBC_SHA256
  1378. 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
  1379. #endif
  1380. #if ALLOW_RSA_WITH_AES_128_GCM_SHA256
  1381. 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
  1382. #endif
  1383. // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
  1384. #if ALLOW_RSA_NULL_SHA256
  1385. 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
  1386. #endif
  1387. 0x01,0x00, //not a cipher - comprtypes_len, comprtype
  1388. };
  1389. static const uint8_t supported_groups[] = {
  1390. 0x00,0x0a, //extension_type: "supported_groups"
  1391. 0x00,2 * (1 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //ext len
  1392. 0x00,2 * (0 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //list len
  1393. #if ALLOW_CURVE_P256
  1394. 0x00,0x17, //curve_secp256r1 (aka P256, aka prime256v1)
  1395. #endif
  1396. //0x00,0x18, //curve_secp384r1
  1397. //0x00,0x19, //curve_secp521r1
  1398. #if ALLOW_CURVE_X25519
  1399. 0x00,0x1d, //curve_x25519 (RFC 7748)
  1400. #endif
  1401. //0x00,0x1e, //curve_x448 (RFC 7748)
  1402. };
  1403. //static const uint8_t signature_algorithms[] = {
  1404. // 000d
  1405. // 0020
  1406. // 001e
  1407. // 0601 0602 0603 0501 0502 0503 0401 0402 0403 0301 0302 0303 0201 0202 0203
  1408. //};
  1409. struct client_hello {
  1410. uint8_t type;
  1411. uint8_t len24_hi, len24_mid, len24_lo;
  1412. uint8_t proto_maj, proto_min;
  1413. uint8_t rand32[32];
  1414. uint8_t session_id_len;
  1415. /* uint8_t session_id[]; */
  1416. uint8_t cipherid_len16_hi, cipherid_len16_lo;
  1417. uint8_t cipherid[2 * (1 + NUM_CIPHERS)]; /* actually variable */
  1418. uint8_t comprtypes_len;
  1419. uint8_t comprtypes[1]; /* actually variable */
  1420. /* Extensions (SNI shown):
  1421. * hi,lo // len of all extensions
  1422. * 00,00 // extension_type: "Server Name"
  1423. * 00,0e // list len (there can be more than one SNI)
  1424. * 00,0c // len of 1st Server Name Indication
  1425. * 00 // name type: host_name
  1426. * 00,09 // name len
  1427. * "localhost" // name
  1428. */
  1429. // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
  1430. // 0055
  1431. // 0005 0005 0100000000 - status_request
  1432. // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
  1433. // ff01 0001 00 - renegotiation_info
  1434. // 0023 0000 - session_ticket
  1435. // 000a 0008 0006001700180019 - supported_groups
  1436. // 000b 0002 0100 - ec_point_formats
  1437. // 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
  1438. // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
  1439. // 0017 0000 - extended master secret
  1440. };
  1441. struct client_hello *record;
  1442. uint8_t *ptr;
  1443. int len;
  1444. int ext_len;
  1445. int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
  1446. ext_len = 0;
  1447. /* is.gd responds with "handshake failure" to our hello if there's no supported_groups element */
  1448. ext_len += sizeof(supported_groups);
  1449. if (sni_len)
  1450. ext_len += 9 + sni_len;
  1451. /* +2 is for "len of all extensions" 2-byte field */
  1452. len = sizeof(*record) + 2 + ext_len;
  1453. record = tls_get_zeroed_outbuf(tls, len);
  1454. fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
  1455. record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
  1456. record->proto_min = TLS_MIN; /* can be higher than one in record headers */
  1457. tls_get_random(record->rand32, sizeof(record->rand32));
  1458. if (TLS_DEBUG_FIXED_SECRETS)
  1459. memset(record->rand32, 0x11, sizeof(record->rand32));
  1460. /* record->session_id_len = 0; - already is */
  1461. BUILD_BUG_ON(sizeof(ciphers) != 2 * (1 + 1 + NUM_CIPHERS + 1));
  1462. memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
  1463. ptr = (void*)(record + 1);
  1464. *ptr++ = ext_len >> 8;
  1465. *ptr++ = ext_len;
  1466. if (sni_len) {
  1467. //ptr[0] = 0; //
  1468. //ptr[1] = 0; //extension_type
  1469. //ptr[2] = 0; //
  1470. ptr[3] = sni_len + 5; //list len
  1471. //ptr[4] = 0; //
  1472. ptr[5] = sni_len + 3; //len of 1st SNI
  1473. //ptr[6] = 0; //name type
  1474. //ptr[7] = 0; //
  1475. ptr[8] = sni_len; //name len
  1476. ptr = mempcpy(&ptr[9], sni, sni_len);
  1477. }
  1478. memcpy(ptr, supported_groups, sizeof(supported_groups));
  1479. tls->hsd = xzalloc(sizeof(*tls->hsd));
  1480. /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
  1481. memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
  1482. /* HANDSHAKE HASH:
  1483. tls->hsd->saved_client_hello_size = len;
  1484. memcpy(tls->hsd->saved_client_hello, record, len);
  1485. */
  1486. dbg(">> CLIENT_HELLO\n");
  1487. /* Can hash immediately only if we know which MAC hash to use.
  1488. * So far we do know: it's sha256:
  1489. */
  1490. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1491. xwrite_and_update_handshake_hash(tls, len);
  1492. /* if this would become infeasible: save tls->hsd->saved_client_hello,
  1493. * use "xwrite_handshake_record(tls, len)" here,
  1494. * and hash saved_client_hello later.
  1495. */
  1496. }
  1497. static void get_server_hello(tls_state_t *tls)
  1498. {
  1499. struct server_hello {
  1500. struct record_hdr xhdr;
  1501. uint8_t type;
  1502. uint8_t len24_hi, len24_mid, len24_lo;
  1503. uint8_t proto_maj, proto_min;
  1504. uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
  1505. uint8_t session_id_len;
  1506. uint8_t session_id[32];
  1507. uint8_t cipherid_hi, cipherid_lo;
  1508. uint8_t comprtype;
  1509. /* extensions may follow, but only those which client offered in its Hello */
  1510. };
  1511. struct server_hello *hp;
  1512. uint8_t *cipherid;
  1513. uint8_t cipherid1;
  1514. int len, len24;
  1515. len = tls_xread_handshake_block(tls, 74 - 32);
  1516. hp = (void*)tls->inbuf;
  1517. // 74 bytes:
  1518. // 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|
  1519. //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
  1520. if (hp->type != HANDSHAKE_SERVER_HELLO
  1521. || hp->len24_hi != 0
  1522. || hp->len24_mid != 0
  1523. /* hp->len24_lo checked later */
  1524. || hp->proto_maj != TLS_MAJ
  1525. || hp->proto_min != TLS_MIN
  1526. ) {
  1527. bad_record_die(tls, "'server hello'", len);
  1528. }
  1529. cipherid = &hp->cipherid_hi;
  1530. len24 = hp->len24_lo;
  1531. if (hp->session_id_len != 32) {
  1532. if (hp->session_id_len != 0)
  1533. bad_record_die(tls, "'server hello'", len);
  1534. // session_id_len == 0: no session id
  1535. // "The server
  1536. // may return an empty session_id to indicate that the session will
  1537. // not be cached and therefore cannot be resumed."
  1538. cipherid -= 32;
  1539. len24 += 32; /* what len would be if session id would be present */
  1540. }
  1541. if (len24 < 70)
  1542. bad_record_die(tls, "'server hello'", len);
  1543. dbg("<< SERVER_HELLO\n");
  1544. memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
  1545. /* Set up encryption params based on selected cipher */
  1546. #if 0
  1547. 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
  1548. 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
  1549. 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
  1550. 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)
  1551. // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  1552. // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
  1553. 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
  1554. // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1555. 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
  1556. // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1557. 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
  1558. // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
  1559. 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
  1560. // 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"
  1561. //possibly these too:
  1562. // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
  1563. // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
  1564. // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  1565. // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1566. 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
  1567. 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
  1568. 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
  1569. 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
  1570. 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
  1571. // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
  1572. 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
  1573. #endif
  1574. cipherid1 = cipherid[1];
  1575. tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
  1576. tls->key_size = AES256_KEYSIZE;
  1577. tls->MAC_size = SHA256_OUTSIZE;
  1578. /*tls->IV_size = 0; - already is */
  1579. if (cipherid[0] == 0xC0) {
  1580. /* All C0xx are ECDHE */
  1581. tls->flags |= NEED_EC_KEY;
  1582. if (cipherid1 & 1) {
  1583. /* Odd numbered C0xx use AES128 (even ones use AES256) */
  1584. tls->key_size = AES128_KEYSIZE;
  1585. }
  1586. if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x19) {
  1587. tls->MAC_size = SHA1_OUTSIZE;
  1588. } else
  1589. if (cipherid1 >= 0x2B && cipherid1 <= 0x30) {
  1590. /* C02B,2C,2F,30 are AES-GCM */
  1591. tls->flags |= ENCRYPTION_AESGCM;
  1592. tls->MAC_size = 0;
  1593. tls->IV_size = 4;
  1594. }
  1595. } else {
  1596. /* All 00xx are RSA */
  1597. if ((ENABLE_FEATURE_TLS_SHA1 && cipherid1 == 0x2F)
  1598. || cipherid1 == 0x3C
  1599. || cipherid1 == 0x9C
  1600. ) {
  1601. tls->key_size = AES128_KEYSIZE;
  1602. }
  1603. if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x35) {
  1604. tls->MAC_size = SHA1_OUTSIZE;
  1605. } else
  1606. if (cipherid1 == 0x9C /*|| cipherid1 == 0x9D*/) {
  1607. /* 009C,9D are AES-GCM */
  1608. tls->flags |= ENCRYPTION_AESGCM;
  1609. tls->MAC_size = 0;
  1610. tls->IV_size = 4;
  1611. }
  1612. }
  1613. dbg("server chose cipher %04x\n", tls->cipher_id);
  1614. dbg("key_size:%u MAC_size:%u IV_size:%u\n", tls->key_size, tls->MAC_size, tls->IV_size);
  1615. /* Handshake hash eventually destined to FINISHED record
  1616. * is sha256 regardless of cipher
  1617. * (at least for all ciphers defined by RFC5246).
  1618. * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
  1619. */
  1620. /* HANDSHAKE HASH:
  1621. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1622. hash_handshake(tls, ">> client hello hash:%s",
  1623. tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
  1624. );
  1625. hash_handshake(tls, "<< server hello hash:%s",
  1626. tls->inbuf + RECHDR_LEN, len
  1627. );
  1628. */
  1629. }
  1630. static void get_server_cert(tls_state_t *tls)
  1631. {
  1632. struct record_hdr *xhdr;
  1633. uint8_t *certbuf;
  1634. int len, len1;
  1635. len = tls_xread_handshake_block(tls, 10);
  1636. xhdr = (void*)tls->inbuf;
  1637. certbuf = (void*)(xhdr + 1);
  1638. if (certbuf[0] != HANDSHAKE_CERTIFICATE)
  1639. bad_record_die(tls, "certificate", len);
  1640. dbg("<< CERTIFICATE\n");
  1641. // 4392 bytes:
  1642. // 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...
  1643. //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
  1644. len1 = get24be(certbuf + 1);
  1645. if (len1 > len - 4) tls_error_die(tls);
  1646. len = len1;
  1647. len1 = get24be(certbuf + 4);
  1648. if (len1 > len - 3) tls_error_die(tls);
  1649. len = len1;
  1650. len1 = get24be(certbuf + 7);
  1651. if (len1 > len - 3) tls_error_die(tls);
  1652. len = len1;
  1653. if (len)
  1654. find_key_in_der_cert(tls, certbuf + 10, len);
  1655. }
  1656. /* On input, len is known to be >= 4.
  1657. * The record is known to be SERVER_KEY_EXCHANGE.
  1658. */
  1659. static void process_server_key(tls_state_t *tls, int len)
  1660. {
  1661. struct record_hdr *xhdr;
  1662. uint8_t *keybuf;
  1663. int len1;
  1664. uint32_t t32;
  1665. xhdr = (void*)tls->inbuf;
  1666. keybuf = (void*)(xhdr + 1);
  1667. //seen from is.gd: it selects curve_x25519:
  1668. // 0c 00006e //SERVER_KEY_EXCHANGE, len
  1669. // 03 //curve_type: named curve
  1670. // 001d //curve_x25519
  1671. //server-chosen EC point, and then signed_params
  1672. // (RFC 8422: "A hash of the params, with the signature
  1673. // appropriate to that hash applied. The private key corresponding
  1674. // to the certified public key in the server's Certificate message is
  1675. // used for signing.")
  1676. //follow. Format unclear/guessed:
  1677. // 20 //eccPubKeyLen
  1678. // 25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
  1679. // 0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
  1680. // 0046 //len (16bit)
  1681. // 30 44 //SEQ, len
  1682. // 02 20 //INTEGER, len
  1683. // 2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
  1684. //this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
  1685. // 02 20 //INTEGER, len
  1686. // 64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
  1687. //same about this item ^^^^^
  1688. //seen from ftp.openbsd.org
  1689. //(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
  1690. // 0c 000228 //SERVER_KEY_EXCHANGE, len
  1691. // 03 //curve_type: named curve
  1692. // 001d //curve_x25519
  1693. // 20 //eccPubKeyLen
  1694. // eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
  1695. // 0401 //hashSigAlg: 4:SHA256, 1:RSA
  1696. // 0200 //len
  1697. // //0x200 bytes follow
  1698. /* Get and verify length */
  1699. len1 = get24be(keybuf + 1);
  1700. if (len1 > len - 4) tls_error_die(tls);
  1701. len = len1;
  1702. if (len < (1+2+1+32)) tls_error_die(tls);
  1703. keybuf += 4;
  1704. #if BB_BIG_ENDIAN
  1705. # define _0x03001741 0x03001741
  1706. # define _0x03001d20 0x03001d20
  1707. #else
  1708. # define _0x03001741 0x41170003
  1709. # define _0x03001d20 0x201d0003
  1710. #endif
  1711. move_from_unaligned32(t32, keybuf);
  1712. keybuf += 4;
  1713. switch (t32) {
  1714. case _0x03001d20: //curve_x25519
  1715. dbg("got x25519 eccPubKey\n");
  1716. tls->flags |= GOT_EC_CURVE_X25519;
  1717. memcpy(tls->hsd->ecc_pub_key32, keybuf, 32);
  1718. break;
  1719. case _0x03001741: //curve_secp256r1 (aka P256)
  1720. dbg("got P256 eccPubKey\n");
  1721. /* P256 point can be transmitted odd- or even-compressed
  1722. * (first byte is 3 or 2) or uncompressed (4).
  1723. */
  1724. if (*keybuf++ != 4)
  1725. bb_simple_error_msg_and_die("compressed EC points not supported");
  1726. memcpy(tls->hsd->ecc_pub_key32, keybuf, 2 * 32);
  1727. break;
  1728. default:
  1729. bb_error_msg_and_die("elliptic curve is not x25519 or P256: 0x%08x", t32);
  1730. }
  1731. tls->flags |= GOT_EC_KEY;
  1732. }
  1733. static void send_empty_client_cert(tls_state_t *tls)
  1734. {
  1735. struct client_empty_cert {
  1736. uint8_t type;
  1737. uint8_t len24_hi, len24_mid, len24_lo;
  1738. uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
  1739. };
  1740. struct client_empty_cert *record;
  1741. record = tls_get_zeroed_outbuf(tls, sizeof(*record));
  1742. //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
  1743. //record->cert_chain_len24_hi = 0;
  1744. //record->cert_chain_len24_mid = 0;
  1745. //record->cert_chain_len24_lo = 0;
  1746. // same as above:
  1747. record->type = HANDSHAKE_CERTIFICATE;
  1748. record->len24_lo = 3;
  1749. dbg(">> CERTIFICATE\n");
  1750. xwrite_and_update_handshake_hash(tls, sizeof(*record));
  1751. }
  1752. static void send_client_key_exchange(tls_state_t *tls)
  1753. {
  1754. struct client_key_exchange {
  1755. uint8_t type;
  1756. uint8_t len24_hi, len24_mid, len24_lo;
  1757. uint8_t key[2 + 4 * 1024]; // size??
  1758. };
  1759. //FIXME: better size estimate
  1760. struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
  1761. uint8_t premaster[RSA_PREMASTER_SIZE > EC_CURVE_KEYSIZE ? RSA_PREMASTER_SIZE : EC_CURVE_KEYSIZE];
  1762. int premaster_size;
  1763. int len;
  1764. if (!(tls->flags & NEED_EC_KEY)) {
  1765. /* RSA */
  1766. if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
  1767. bb_simple_error_msg_and_die("server cert is not RSA");
  1768. tls_get_random(premaster, RSA_PREMASTER_SIZE);
  1769. if (TLS_DEBUG_FIXED_SECRETS)
  1770. memset(premaster, 0x44, RSA_PREMASTER_SIZE);
  1771. // RFC 5246
  1772. // "Note: The version number in the PreMasterSecret is the version
  1773. // offered by the client in the ClientHello.client_version, not the
  1774. // version negotiated for the connection."
  1775. premaster[0] = TLS_MAJ;
  1776. premaster[1] = TLS_MIN;
  1777. dump_hex("premaster:%s\n", premaster, sizeof(premaster));
  1778. len = psRsaEncryptPub(/*pool:*/ NULL,
  1779. /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
  1780. premaster, /*inlen:*/ RSA_PREMASTER_SIZE,
  1781. record->key + 2, sizeof(record->key) - 2,
  1782. data_param_ignored
  1783. );
  1784. /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
  1785. record->key[0] = len >> 8;
  1786. record->key[1] = len & 0xff;
  1787. len += 2;
  1788. premaster_size = RSA_PREMASTER_SIZE;
  1789. } else {
  1790. /* ECDHE */
  1791. if (!(tls->flags & GOT_EC_KEY))
  1792. bb_simple_error_msg_and_die("server did not provide EC key");
  1793. if (tls->flags & GOT_EC_CURVE_X25519) {
  1794. /* ECDHE, curve x25519 */
  1795. dbg("computing x25519_premaster\n");
  1796. curve_x25519_compute_pubkey_and_premaster(
  1797. record->key + 1, premaster,
  1798. /*point:*/ tls->hsd->ecc_pub_key32
  1799. );
  1800. len = CURVE25519_KEYSIZE;
  1801. //record->key[0] = len;
  1802. //len++;
  1803. //premaster_size = CURVE25519_KEYSIZE;
  1804. } else {
  1805. /* ECDHE, curve P256 */
  1806. dbg("computing P256_premaster\n");
  1807. curve_P256_compute_pubkey_and_premaster(
  1808. record->key + 2, premaster,
  1809. /*point:*/ tls->hsd->ecc_pub_key32
  1810. );
  1811. record->key[1] = 4; /* "uncompressed point" */
  1812. len = 1 + P256_KEYSIZE * 2;
  1813. }
  1814. record->key[0] = len;
  1815. len++;
  1816. premaster_size = P256_KEYSIZE; // = CURVE25519_KEYSIZE = 32
  1817. }
  1818. record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
  1819. /* record->len24_hi = 0; - already is */
  1820. record->len24_mid = len >> 8;
  1821. record->len24_lo = len & 0xff;
  1822. len += 4;
  1823. dbg(">> CLIENT_KEY_EXCHANGE\n");
  1824. xwrite_and_update_handshake_hash(tls, len);
  1825. // RFC 5246
  1826. // For all key exchange methods, the same algorithm is used to convert
  1827. // the pre_master_secret into the master_secret. The pre_master_secret
  1828. // should be deleted from memory once the master_secret has been
  1829. // computed.
  1830. // master_secret = PRF(pre_master_secret, "master secret",
  1831. // ClientHello.random + ServerHello.random)
  1832. // [0..47];
  1833. // The master secret is always exactly 48 bytes in length. The length
  1834. // of the premaster secret will vary depending on key exchange method.
  1835. prf_hmac_sha256(/*tls,*/
  1836. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1837. premaster, premaster_size,
  1838. "master secret",
  1839. tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
  1840. );
  1841. dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1842. // RFC 5246
  1843. // 6.3. Key Calculation
  1844. //
  1845. // The Record Protocol requires an algorithm to generate keys required
  1846. // by the current connection state (see Appendix A.6) from the security
  1847. // parameters provided by the handshake protocol.
  1848. //
  1849. // The master secret is expanded into a sequence of secure bytes, which
  1850. // is then split to a client write MAC key, a server write MAC key, a
  1851. // client write encryption key, and a server write encryption key. Each
  1852. // of these is generated from the byte sequence in that order. Unused
  1853. // values are empty. Some AEAD ciphers may additionally require a
  1854. // client write IV and a server write IV (see Section 6.2.3.3).
  1855. //
  1856. // When keys and MAC keys are generated, the master secret is used as an
  1857. // entropy source.
  1858. //
  1859. // To generate the key material, compute
  1860. //
  1861. // key_block = PRF(SecurityParameters.master_secret,
  1862. // "key expansion",
  1863. // SecurityParameters.server_random +
  1864. // SecurityParameters.client_random);
  1865. //
  1866. // until enough output has been generated. Then, the key_block is
  1867. // partitioned as follows:
  1868. //
  1869. // client_write_MAC_key[SecurityParameters.mac_key_length]
  1870. // server_write_MAC_key[SecurityParameters.mac_key_length]
  1871. // client_write_key[SecurityParameters.enc_key_length]
  1872. // server_write_key[SecurityParameters.enc_key_length]
  1873. // client_write_IV[SecurityParameters.fixed_iv_length]
  1874. // server_write_IV[SecurityParameters.fixed_iv_length]
  1875. {
  1876. uint8_t tmp64[64];
  1877. /* make "server_rand32 + client_rand32" */
  1878. memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
  1879. memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
  1880. prf_hmac_sha256(/*tls,*/
  1881. tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
  1882. // also fills:
  1883. // server_write_MAC_key[]
  1884. // client_write_key[]
  1885. // server_write_key[]
  1886. // client_write_IV[]
  1887. // server_write_IV[]
  1888. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1889. "key expansion",
  1890. tmp64, 64
  1891. );
  1892. tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
  1893. tls->server_write_key = tls->client_write_key + tls->key_size;
  1894. tls->client_write_IV = tls->server_write_key + tls->key_size;
  1895. tls->server_write_IV = tls->client_write_IV + tls->IV_size;
  1896. dump_hex("client_write_MAC_key:%s\n",
  1897. tls->client_write_MAC_key, tls->MAC_size
  1898. );
  1899. dump_hex("client_write_key:%s\n",
  1900. tls->client_write_key, tls->key_size
  1901. );
  1902. dump_hex("client_write_IV:%s\n",
  1903. tls->client_write_IV, tls->IV_size
  1904. );
  1905. aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
  1906. aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
  1907. {
  1908. uint8_t iv[AES_BLOCK_SIZE];
  1909. memset(iv, 0, AES_BLOCK_SIZE);
  1910. aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
  1911. }
  1912. }
  1913. }
  1914. static const uint8_t rec_CHANGE_CIPHER_SPEC[] ALIGN1 = {
  1915. RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
  1916. 01
  1917. };
  1918. static void send_change_cipher_spec(tls_state_t *tls)
  1919. {
  1920. dbg(">> CHANGE_CIPHER_SPEC\n");
  1921. xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
  1922. }
  1923. // 7.4.9. Finished
  1924. // A Finished message is always sent immediately after a change
  1925. // cipher spec message to verify that the key exchange and
  1926. // authentication processes were successful. It is essential that a
  1927. // change cipher spec message be received between the other handshake
  1928. // messages and the Finished message.
  1929. //...
  1930. // The Finished message is the first one protected with the just
  1931. // negotiated algorithms, keys, and secrets. Recipients of Finished
  1932. // messages MUST verify that the contents are correct. Once a side
  1933. // has sent its Finished message and received and validated the
  1934. // Finished message from its peer, it may begin to send and receive
  1935. // application data over the connection.
  1936. //...
  1937. // struct {
  1938. // opaque verify_data[verify_data_length];
  1939. // } Finished;
  1940. //
  1941. // verify_data
  1942. // PRF(master_secret, finished_label, Hash(handshake_messages))
  1943. // [0..verify_data_length-1];
  1944. //
  1945. // finished_label
  1946. // For Finished messages sent by the client, the string
  1947. // "client finished". For Finished messages sent by the server,
  1948. // the string "server finished".
  1949. //
  1950. // Hash denotes a Hash of the handshake messages. For the PRF
  1951. // defined in Section 5, the Hash MUST be the Hash used as the basis
  1952. // for the PRF. Any cipher suite which defines a different PRF MUST
  1953. // also define the Hash to use in the Finished computation.
  1954. //
  1955. // In previous versions of TLS, the verify_data was always 12 octets
  1956. // long. In the current version of TLS, it depends on the cipher
  1957. // suite. Any cipher suite which does not explicitly specify
  1958. // verify_data_length has a verify_data_length equal to 12. This
  1959. // includes all existing cipher suites.
  1960. static void send_client_finished(tls_state_t *tls)
  1961. {
  1962. struct finished {
  1963. uint8_t type;
  1964. uint8_t len24_hi, len24_mid, len24_lo;
  1965. uint8_t prf_result[12];
  1966. };
  1967. struct finished *record = tls_get_outbuf(tls, sizeof(*record));
  1968. uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
  1969. unsigned len;
  1970. fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
  1971. len = sha_end(&tls->hsd->handshake_hash_ctx, handshake_hash);
  1972. prf_hmac_sha256(/*tls,*/
  1973. record->prf_result, sizeof(record->prf_result),
  1974. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1975. "client finished",
  1976. handshake_hash, len
  1977. );
  1978. dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1979. dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
  1980. dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
  1981. dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
  1982. dbg(">> FINISHED\n");
  1983. xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
  1984. }
  1985. void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
  1986. {
  1987. // Client RFC 5246 Server
  1988. // (*) - optional messages, not always sent
  1989. //
  1990. // ClientHello ------->
  1991. // ServerHello
  1992. // Certificate*
  1993. // ServerKeyExchange*
  1994. // CertificateRequest*
  1995. // <------- ServerHelloDone
  1996. // Certificate*
  1997. // ClientKeyExchange
  1998. // CertificateVerify*
  1999. // [ChangeCipherSpec]
  2000. // Finished ------->
  2001. // [ChangeCipherSpec]
  2002. // <------- Finished
  2003. // Application Data <------> Application Data
  2004. int len;
  2005. int got_cert_req;
  2006. send_client_hello_and_alloc_hsd(tls, sni);
  2007. get_server_hello(tls);
  2008. // RFC 5246
  2009. // The server MUST send a Certificate message whenever the agreed-
  2010. // upon key exchange method uses certificates for authentication
  2011. // (this includes all key exchange methods defined in this document
  2012. // except DH_anon). This message will always immediately follow the
  2013. // ServerHello message.
  2014. //
  2015. // IOW: in practice, Certificate *always* follows.
  2016. // (for example, kernel.org does not even accept DH_anon cipher id)
  2017. get_server_cert(tls);
  2018. len = tls_xread_handshake_block(tls, 4);
  2019. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
  2020. // 459 bytes:
  2021. // 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...
  2022. //SvKey len=455^
  2023. // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
  2024. // 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...
  2025. //
  2026. // RFC 8422 5.4. Server Key Exchange
  2027. // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
  2028. // ECDH_anon key exchange algorithms.
  2029. // This message is used to convey the server's ephemeral ECDH public key
  2030. // (and the corresponding elliptic curve domain parameters) to the
  2031. // client.
  2032. dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
  2033. dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
  2034. if (tls->flags & NEED_EC_KEY)
  2035. process_server_key(tls, len);
  2036. // read next handshake block
  2037. len = tls_xread_handshake_block(tls, 4);
  2038. }
  2039. got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
  2040. if (got_cert_req) {
  2041. dbg("<< CERTIFICATE_REQUEST\n");
  2042. // RFC 5246: "If no suitable certificate is available,
  2043. // the client MUST send a certificate message containing no
  2044. // certificates. That is, the certificate_list structure has a
  2045. // length of zero. ...
  2046. // Client certificates are sent using the Certificate structure
  2047. // defined in Section 7.4.2."
  2048. // (i.e. the same format as server certs)
  2049. /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
  2050. /* need to hash _all_ server replies first, up to ServerHelloDone */
  2051. len = tls_xread_handshake_block(tls, 4);
  2052. }
  2053. if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
  2054. bad_record_die(tls, "'server hello done'", len);
  2055. }
  2056. // 0e 000000 (len:0)
  2057. dbg("<< SERVER_HELLO_DONE\n");
  2058. if (got_cert_req)
  2059. send_empty_client_cert(tls);
  2060. send_client_key_exchange(tls);
  2061. send_change_cipher_spec(tls);
  2062. /* from now on we should send encrypted */
  2063. /* tls->write_seq64_be = 0; - already is */
  2064. tls->flags |= ENCRYPT_ON_WRITE;
  2065. send_client_finished(tls);
  2066. /* Get CHANGE_CIPHER_SPEC */
  2067. len = tls_xread_record(tls, "switch to encrypted traffic");
  2068. if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
  2069. bad_record_die(tls, "switch to encrypted traffic", len);
  2070. dbg("<< CHANGE_CIPHER_SPEC\n");
  2071. if (ALLOW_RSA_NULL_SHA256
  2072. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  2073. ) {
  2074. tls->min_encrypted_len_on_read = tls->MAC_size;
  2075. } else
  2076. if (!(tls->flags & ENCRYPTION_AESGCM)) {
  2077. unsigned mac_blocks = (unsigned)(TLS_MAC_SIZE(tls) + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
  2078. /* all incoming packets now should be encrypted and have
  2079. * at least IV + (MAC padded to blocksize):
  2080. */
  2081. tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
  2082. } else {
  2083. tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
  2084. }
  2085. dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
  2086. /* Get (encrypted) FINISHED from the server */
  2087. len = tls_xread_record(tls, "'server finished'");
  2088. if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
  2089. bad_record_die(tls, "'server finished'", len);
  2090. dbg("<< FINISHED\n");
  2091. /* application data can be sent/received */
  2092. /* free handshake data */
  2093. psRsaKey_clear(&tls->hsd->server_rsa_pub_key);
  2094. // if (PARANOIA)
  2095. // memset(tls->hsd, 0, tls->hsd->hsd_size);
  2096. free(tls->hsd);
  2097. tls->hsd = NULL;
  2098. }
  2099. static void tls_xwrite(tls_state_t *tls, int len)
  2100. {
  2101. dbg(">> DATA\n");
  2102. xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
  2103. }
  2104. // To run a test server using openssl:
  2105. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  2106. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2
  2107. //
  2108. // Unencryped SHA256 example:
  2109. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  2110. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -cipher NULL
  2111. // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -cipher NULL-SHA256
  2112. void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
  2113. {
  2114. int inbuf_size;
  2115. const int INBUF_STEP = 4 * 1024;
  2116. struct pollfd pfds[2];
  2117. #if 0
  2118. // Debug aid for comparing P256 implementations.
  2119. // Enable this, set SP_DEBUG and FIXED_SECRET to 1,
  2120. // and add
  2121. // tls_run_copy_loop(NULL, 0);
  2122. // e.g. at the very beginning of wget_main()
  2123. //
  2124. {
  2125. uint8_t ecc_pub_key32[2 * 32];
  2126. uint8_t pubkey2x32[2 * 32];
  2127. uint8_t premaster32[32];
  2128. //Fixed input key:
  2129. // memset(ecc_pub_key32, 0xee, sizeof(ecc_pub_key32));
  2130. //Fixed 000000000000000000000000000000000000ab000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
  2131. // memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
  2132. // ecc_pub_key32[18] = 0xab;
  2133. //Random key:
  2134. // tls_get_random(ecc_pub_key32, sizeof(ecc_pub_key32));
  2135. //Biased random (almost all zeros or almost all ones):
  2136. srand(time(NULL) ^ getpid());
  2137. if (rand() & 1)
  2138. memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
  2139. else
  2140. memset(ecc_pub_key32, 0xff, sizeof(ecc_pub_key32));
  2141. ecc_pub_key32[rand() & 0x3f] = rand();
  2142. xmove_fd(xopen("p256.OLD", O_WRONLY | O_CREAT | O_TRUNC), 2);
  2143. curve_P256_compute_pubkey_and_premaster(
  2144. pubkey2x32, premaster32,
  2145. /*point:*/ ecc_pub_key32
  2146. );
  2147. xmove_fd(xopen("p256.NEW", O_WRONLY | O_CREAT | O_TRUNC), 2);
  2148. curve_P256_compute_pubkey_and_premaster_NEW(
  2149. pubkey2x32, premaster32,
  2150. /*point:*/ ecc_pub_key32
  2151. );
  2152. exit(1);
  2153. }
  2154. #endif
  2155. pfds[0].fd = STDIN_FILENO;
  2156. pfds[0].events = POLLIN;
  2157. pfds[1].fd = tls->ifd;
  2158. pfds[1].events = POLLIN;
  2159. inbuf_size = INBUF_STEP;
  2160. for (;;) {
  2161. int nread;
  2162. if (safe_poll(pfds, 2, -1) < 0)
  2163. bb_simple_perror_msg_and_die("poll");
  2164. if (pfds[0].revents) {
  2165. void *buf;
  2166. dbg("STDIN HAS DATA\n");
  2167. buf = tls_get_outbuf(tls, inbuf_size);
  2168. nread = safe_read(STDIN_FILENO, buf, inbuf_size);
  2169. if (nread < 1) {
  2170. /* We'd want to do this: */
  2171. /* Close outgoing half-connection so they get EOF,
  2172. * but leave incoming alone so we can see response
  2173. */
  2174. //shutdown(tls->ofd, SHUT_WR);
  2175. /* But TLS has no way to encode this,
  2176. * doubt it's ok to do it "raw"
  2177. */
  2178. pfds[0].fd = -1;
  2179. tls_free_outbuf(tls); /* mem usage optimization */
  2180. if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
  2181. break;
  2182. } else {
  2183. if (nread == inbuf_size) {
  2184. /* TLS has per record overhead, if input comes fast,
  2185. * read, encrypt and send bigger chunks
  2186. */
  2187. inbuf_size += INBUF_STEP;
  2188. if (inbuf_size > TLS_MAX_OUTBUF)
  2189. inbuf_size = TLS_MAX_OUTBUF;
  2190. }
  2191. tls_xwrite(tls, nread);
  2192. }
  2193. }
  2194. if (pfds[1].revents) {
  2195. dbg("NETWORK HAS DATA\n");
  2196. read_record:
  2197. nread = tls_xread_record(tls, "encrypted data");
  2198. if (nread < 1) {
  2199. /* TLS protocol has no real concept of one-sided shutdowns:
  2200. * if we get "TLS EOF" from the peer, writes will fail too
  2201. */
  2202. //pfds[1].fd = -1;
  2203. //close(STDOUT_FILENO);
  2204. //tls_free_inbuf(tls); /* mem usage optimization */
  2205. //continue;
  2206. break;
  2207. }
  2208. if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
  2209. bad_record_die(tls, "encrypted data", nread);
  2210. xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
  2211. /* We may already have a complete next record buffered,
  2212. * can process it without network reads (and possible blocking)
  2213. */
  2214. if (tls_has_buffered_record(tls))
  2215. goto read_record;
  2216. }
  2217. }
  2218. }