tls.c 86 KB

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