tls.c 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  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_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_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[] = {
  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[] = {
  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_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,0x17, //curve_secp256r1
  1388. //0x00,0x18, //curve_secp384r1
  1389. //0x00,0x19, //curve_secp521r1
  1390. };
  1391. //static const uint8_t signature_algorithms[] = {
  1392. // 000d
  1393. // 0020
  1394. // 001e
  1395. // 0601 0602 0603 0501 0502 0503 0401 0402 0403 0301 0302 0303 0201 0202 0203
  1396. //};
  1397. struct client_hello {
  1398. uint8_t type;
  1399. uint8_t len24_hi, len24_mid, len24_lo;
  1400. uint8_t proto_maj, proto_min;
  1401. uint8_t rand32[32];
  1402. uint8_t session_id_len;
  1403. /* uint8_t session_id[]; */
  1404. uint8_t cipherid_len16_hi, cipherid_len16_lo;
  1405. uint8_t cipherid[2 + NUM_CIPHERS*2]; /* actually variable */
  1406. uint8_t comprtypes_len;
  1407. uint8_t comprtypes[1]; /* actually variable */
  1408. /* Extensions (SNI shown):
  1409. * hi,lo // len of all extensions
  1410. * 00,00 // extension_type: "Server Name"
  1411. * 00,0e // list len (there can be more than one SNI)
  1412. * 00,0c // len of 1st Server Name Indication
  1413. * 00 // name type: host_name
  1414. * 00,09 // name len
  1415. * "localhost" // name
  1416. */
  1417. // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
  1418. // 0055
  1419. // 0005 0005 0100000000 - status_request
  1420. // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
  1421. // ff01 0001 00 - renegotiation_info
  1422. // 0023 0000 - session_ticket
  1423. // 000a 0008 0006001700180019 - supported_groups
  1424. // 000b 0002 0100 - ec_point_formats
  1425. // 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
  1426. // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
  1427. // 0017 0000 - extended master secret
  1428. };
  1429. struct client_hello *record;
  1430. uint8_t *ptr;
  1431. int len;
  1432. int ext_len;
  1433. int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
  1434. ext_len = 0;
  1435. /* is.gd responds with "handshake failure" to our hello if there's no supported_groups element */
  1436. ext_len += sizeof(supported_groups);
  1437. if (sni_len)
  1438. ext_len += 9 + sni_len;
  1439. /* +2 is for "len of all extensions" 2-byte field */
  1440. len = sizeof(*record) + 2 + ext_len;
  1441. record = tls_get_zeroed_outbuf(tls, len);
  1442. fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
  1443. record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
  1444. record->proto_min = TLS_MIN; /* can be higher than one in record headers */
  1445. tls_get_random(record->rand32, sizeof(record->rand32));
  1446. if (TLS_DEBUG_FIXED_SECRETS)
  1447. memset(record->rand32, 0x11, sizeof(record->rand32));
  1448. /* record->session_id_len = 0; - already is */
  1449. BUILD_BUG_ON(sizeof(ciphers) != 2 + 2 + NUM_CIPHERS*2 + 2);
  1450. memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
  1451. ptr = (void*)(record + 1);
  1452. *ptr++ = ext_len >> 8;
  1453. *ptr++ = ext_len;
  1454. if (sni_len) {
  1455. //ptr[0] = 0; //
  1456. //ptr[1] = 0; //extension_type
  1457. //ptr[2] = 0; //
  1458. ptr[3] = sni_len + 5; //list len
  1459. //ptr[4] = 0; //
  1460. ptr[5] = sni_len + 3; //len of 1st SNI
  1461. //ptr[6] = 0; //name type
  1462. //ptr[7] = 0; //
  1463. ptr[8] = sni_len; //name len
  1464. ptr = mempcpy(&ptr[9], sni, sni_len);
  1465. }
  1466. memcpy(ptr, supported_groups, sizeof(supported_groups));
  1467. tls->hsd = xzalloc(sizeof(*tls->hsd));
  1468. /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
  1469. memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
  1470. /* HANDSHAKE HASH:
  1471. tls->hsd->saved_client_hello_size = len;
  1472. memcpy(tls->hsd->saved_client_hello, record, len);
  1473. */
  1474. dbg(">> CLIENT_HELLO\n");
  1475. /* Can hash immediately only if we know which MAC hash to use.
  1476. * So far we do know: it's sha256:
  1477. */
  1478. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1479. xwrite_and_update_handshake_hash(tls, len);
  1480. /* if this would become infeasible: save tls->hsd->saved_client_hello,
  1481. * use "xwrite_handshake_record(tls, len)" here,
  1482. * and hash saved_client_hello later.
  1483. */
  1484. }
  1485. static void get_server_hello(tls_state_t *tls)
  1486. {
  1487. struct server_hello {
  1488. struct record_hdr xhdr;
  1489. uint8_t type;
  1490. uint8_t len24_hi, len24_mid, len24_lo;
  1491. uint8_t proto_maj, proto_min;
  1492. uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
  1493. uint8_t session_id_len;
  1494. uint8_t session_id[32];
  1495. uint8_t cipherid_hi, cipherid_lo;
  1496. uint8_t comprtype;
  1497. /* extensions may follow, but only those which client offered in its Hello */
  1498. };
  1499. struct server_hello *hp;
  1500. uint8_t *cipherid;
  1501. uint8_t cipherid1;
  1502. int len, len24;
  1503. len = tls_xread_handshake_block(tls, 74 - 32);
  1504. hp = (void*)tls->inbuf;
  1505. // 74 bytes:
  1506. // 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|
  1507. //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
  1508. if (hp->type != HANDSHAKE_SERVER_HELLO
  1509. || hp->len24_hi != 0
  1510. || hp->len24_mid != 0
  1511. /* hp->len24_lo checked later */
  1512. || hp->proto_maj != TLS_MAJ
  1513. || hp->proto_min != TLS_MIN
  1514. ) {
  1515. bad_record_die(tls, "'server hello'", len);
  1516. }
  1517. cipherid = &hp->cipherid_hi;
  1518. len24 = hp->len24_lo;
  1519. if (hp->session_id_len != 32) {
  1520. if (hp->session_id_len != 0)
  1521. bad_record_die(tls, "'server hello'", len);
  1522. // session_id_len == 0: no session id
  1523. // "The server
  1524. // may return an empty session_id to indicate that the session will
  1525. // not be cached and therefore cannot be resumed."
  1526. cipherid -= 32;
  1527. len24 += 32; /* what len would be if session id would be present */
  1528. }
  1529. if (len24 < 70)
  1530. bad_record_die(tls, "'server hello'", len);
  1531. dbg("<< SERVER_HELLO\n");
  1532. memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
  1533. /* Set up encryption params based on selected cipher */
  1534. #if 0
  1535. #if ENABLE_FEATURE_TLS_SHA1
  1536. 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
  1537. 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
  1538. 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
  1539. 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)
  1540. // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
  1541. // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
  1542. #endif
  1543. 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
  1544. // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1545. 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
  1546. // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1547. 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
  1548. // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
  1549. //TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
  1550. 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
  1551. // 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"
  1552. //possibly these too:
  1553. #if ENABLE_FEATURE_TLS_SHA1
  1554. // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
  1555. // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
  1556. #endif
  1557. // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
  1558. // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
  1559. #if ENABLE_FEATURE_TLS_SHA1
  1560. 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
  1561. 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
  1562. #endif
  1563. 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
  1564. 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
  1565. 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
  1566. // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
  1567. #if ALLOW_RSA_NULL_SHA256
  1568. 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
  1569. #endif
  1570. #endif
  1571. cipherid1 = cipherid[1];
  1572. tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
  1573. tls->key_size = AES256_KEYSIZE;
  1574. tls->MAC_size = SHA256_OUTSIZE;
  1575. /*tls->IV_size = 0; - already is */
  1576. if (cipherid[0] == 0xC0) {
  1577. /* All C0xx are ECDHE */
  1578. tls->flags |= NEED_EC_KEY;
  1579. if (cipherid1 & 1) {
  1580. /* Odd numbered C0xx use AES128 (even ones use AES256) */
  1581. tls->key_size = AES128_KEYSIZE;
  1582. }
  1583. if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x19) {
  1584. tls->MAC_size = SHA1_OUTSIZE;
  1585. } else
  1586. if (cipherid1 >= 0x2B && cipherid1 <= 0x30) {
  1587. /* C02B,2C,2F,30 are AES-GCM */
  1588. tls->flags |= ENCRYPTION_AESGCM;
  1589. tls->MAC_size = 0;
  1590. tls->IV_size = 4;
  1591. }
  1592. } else {
  1593. /* All 00xx are RSA */
  1594. if ((ENABLE_FEATURE_TLS_SHA1 && cipherid1 == 0x2F)
  1595. || cipherid1 == 0x3C
  1596. || cipherid1 == 0x9C
  1597. ) {
  1598. tls->key_size = AES128_KEYSIZE;
  1599. }
  1600. if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x35) {
  1601. tls->MAC_size = SHA1_OUTSIZE;
  1602. } else
  1603. if (cipherid1 == 0x9C /*|| cipherid1 == 0x9D*/) {
  1604. /* 009C,9D are AES-GCM */
  1605. tls->flags |= ENCRYPTION_AESGCM;
  1606. tls->MAC_size = 0;
  1607. tls->IV_size = 4;
  1608. }
  1609. }
  1610. dbg("server chose cipher %04x\n", tls->cipher_id);
  1611. dbg("key_size:%u MAC_size:%u IV_size:%u\n", tls->key_size, tls->MAC_size, tls->IV_size);
  1612. /* Handshake hash eventually destined to FINISHED record
  1613. * is sha256 regardless of cipher
  1614. * (at least for all ciphers defined by RFC5246).
  1615. * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
  1616. */
  1617. /* HANDSHAKE HASH:
  1618. sha256_begin(&tls->hsd->handshake_hash_ctx);
  1619. hash_handshake(tls, ">> client hello hash:%s",
  1620. tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
  1621. );
  1622. hash_handshake(tls, "<< server hello hash:%s",
  1623. tls->inbuf + RECHDR_LEN, len
  1624. );
  1625. */
  1626. }
  1627. static void get_server_cert(tls_state_t *tls)
  1628. {
  1629. struct record_hdr *xhdr;
  1630. uint8_t *certbuf;
  1631. int len, len1;
  1632. len = tls_xread_handshake_block(tls, 10);
  1633. xhdr = (void*)tls->inbuf;
  1634. certbuf = (void*)(xhdr + 1);
  1635. if (certbuf[0] != HANDSHAKE_CERTIFICATE)
  1636. bad_record_die(tls, "certificate", len);
  1637. dbg("<< CERTIFICATE\n");
  1638. // 4392 bytes:
  1639. // 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...
  1640. //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
  1641. len1 = get24be(certbuf + 1);
  1642. if (len1 > len - 4) tls_error_die(tls);
  1643. len = len1;
  1644. len1 = get24be(certbuf + 4);
  1645. if (len1 > len - 3) tls_error_die(tls);
  1646. len = len1;
  1647. len1 = get24be(certbuf + 7);
  1648. if (len1 > len - 3) tls_error_die(tls);
  1649. len = len1;
  1650. if (len)
  1651. find_key_in_der_cert(tls, certbuf + 10, len);
  1652. }
  1653. /* On input, len is known to be >= 4.
  1654. * The record is known to be SERVER_KEY_EXCHANGE.
  1655. */
  1656. static void process_server_key(tls_state_t *tls, int len)
  1657. {
  1658. struct record_hdr *xhdr;
  1659. uint8_t *keybuf;
  1660. int len1;
  1661. uint32_t t32;
  1662. xhdr = (void*)tls->inbuf;
  1663. keybuf = (void*)(xhdr + 1);
  1664. //seen from is.gd: it selects curve_x25519:
  1665. // 0c 00006e //SERVER_KEY_EXCHANGE, len
  1666. // 03 //curve_type: named curve
  1667. // 001d //curve_x25519
  1668. //server-chosen EC point, and then signed_params
  1669. // (RFC 8422: "A hash of the params, with the signature
  1670. // appropriate to that hash applied. The private key corresponding
  1671. // to the certified public key in the server's Certificate message is
  1672. // used for signing.")
  1673. //follow. Format unclear/guessed:
  1674. // 20 //eccPubKeyLen
  1675. // 25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
  1676. // 0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
  1677. // 0046 //len (16bit)
  1678. // 30 44 //SEQ, len
  1679. // 02 20 //INTEGER, len
  1680. // 2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
  1681. //this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
  1682. // 02 20 //INTEGER, len
  1683. // 64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
  1684. //same about this item ^^^^^
  1685. //seen from ftp.openbsd.org
  1686. //(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
  1687. // 0c 000228 //SERVER_KEY_EXCHANGE, len
  1688. // 03 //curve_type: named curve
  1689. // 001d //curve_x25519
  1690. // 20 //eccPubKeyLen
  1691. // eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
  1692. // 0401 //hashSigAlg: 4:SHA256, 1:RSA
  1693. // 0200 //len
  1694. // //0x200 bytes follow
  1695. /* Get and verify length */
  1696. len1 = get24be(keybuf + 1);
  1697. if (len1 > len - 4) tls_error_die(tls);
  1698. len = len1;
  1699. if (len < (1+2+1+32)) tls_error_die(tls);
  1700. keybuf += 4;
  1701. /* So far we only support curve_x25519 */
  1702. move_from_unaligned32(t32, keybuf);
  1703. if (t32 != htonl(0x03001d20))
  1704. bb_error_msg_and_die("elliptic curve is not x25519");
  1705. memcpy(tls->hsd->ecc_pub_key32, keybuf + 4, 32);
  1706. tls->flags |= GOT_EC_KEY;
  1707. dbg("got eccPubKey\n");
  1708. }
  1709. static void send_empty_client_cert(tls_state_t *tls)
  1710. {
  1711. struct client_empty_cert {
  1712. uint8_t type;
  1713. uint8_t len24_hi, len24_mid, len24_lo;
  1714. uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
  1715. };
  1716. struct client_empty_cert *record;
  1717. record = tls_get_zeroed_outbuf(tls, sizeof(*record));
  1718. //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
  1719. //record->cert_chain_len24_hi = 0;
  1720. //record->cert_chain_len24_mid = 0;
  1721. //record->cert_chain_len24_lo = 0;
  1722. // same as above:
  1723. record->type = HANDSHAKE_CERTIFICATE;
  1724. record->len24_lo = 3;
  1725. dbg(">> CERTIFICATE\n");
  1726. xwrite_and_update_handshake_hash(tls, sizeof(*record));
  1727. }
  1728. static void send_client_key_exchange(tls_state_t *tls)
  1729. {
  1730. struct client_key_exchange {
  1731. uint8_t type;
  1732. uint8_t len24_hi, len24_mid, len24_lo;
  1733. uint8_t key[2 + 4 * 1024]; // size??
  1734. };
  1735. //FIXME: better size estimate
  1736. struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
  1737. uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
  1738. uint8_t x25519_premaster[CURVE25519_KEYSIZE];
  1739. uint8_t *premaster;
  1740. int premaster_size;
  1741. int len;
  1742. if (!(tls->flags & NEED_EC_KEY)) {
  1743. /* RSA */
  1744. if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
  1745. bb_error_msg("server cert is not RSA");
  1746. tls_get_random(rsa_premaster, sizeof(rsa_premaster));
  1747. if (TLS_DEBUG_FIXED_SECRETS)
  1748. memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
  1749. // RFC 5246
  1750. // "Note: The version number in the PreMasterSecret is the version
  1751. // offered by the client in the ClientHello.client_version, not the
  1752. // version negotiated for the connection."
  1753. rsa_premaster[0] = TLS_MAJ;
  1754. rsa_premaster[1] = TLS_MIN;
  1755. dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
  1756. len = psRsaEncryptPub(/*pool:*/ NULL,
  1757. /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
  1758. rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
  1759. record->key + 2, sizeof(record->key) - 2,
  1760. data_param_ignored
  1761. );
  1762. /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
  1763. record->key[0] = len >> 8;
  1764. record->key[1] = len & 0xff;
  1765. len += 2;
  1766. premaster = rsa_premaster;
  1767. premaster_size = sizeof(rsa_premaster);
  1768. } else {
  1769. /* ECDHE */
  1770. static const uint8_t basepoint9[CURVE25519_KEYSIZE] = {9};
  1771. uint8_t privkey[CURVE25519_KEYSIZE]; //[32]
  1772. if (!(tls->flags & GOT_EC_KEY))
  1773. bb_error_msg("server did not provide EC key");
  1774. /* Generate random private key, see RFC 7748 */
  1775. tls_get_random(privkey, sizeof(privkey));
  1776. privkey[0] &= 0xf8;
  1777. privkey[CURVE25519_KEYSIZE-1] = ((privkey[CURVE25519_KEYSIZE-1] & 0x7f) | 0x40);
  1778. /* Compute public key */
  1779. curve25519(record->key + 1, privkey, basepoint9);
  1780. /* Compute premaster using peer's public key */
  1781. dbg("computing x25519_premaster\n");
  1782. curve25519(x25519_premaster, privkey, tls->hsd->ecc_pub_key32);
  1783. len = CURVE25519_KEYSIZE;
  1784. record->key[0] = len;
  1785. len++;
  1786. premaster = x25519_premaster;
  1787. premaster_size = sizeof(x25519_premaster);
  1788. }
  1789. record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
  1790. /* record->len24_hi = 0; - already is */
  1791. record->len24_mid = len >> 8;
  1792. record->len24_lo = len & 0xff;
  1793. len += 4;
  1794. dbg(">> CLIENT_KEY_EXCHANGE\n");
  1795. xwrite_and_update_handshake_hash(tls, len);
  1796. // RFC 5246
  1797. // For all key exchange methods, the same algorithm is used to convert
  1798. // the pre_master_secret into the master_secret. The pre_master_secret
  1799. // should be deleted from memory once the master_secret has been
  1800. // computed.
  1801. // master_secret = PRF(pre_master_secret, "master secret",
  1802. // ClientHello.random + ServerHello.random)
  1803. // [0..47];
  1804. // The master secret is always exactly 48 bytes in length. The length
  1805. // of the premaster secret will vary depending on key exchange method.
  1806. prf_hmac_sha256(/*tls,*/
  1807. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1808. premaster, premaster_size,
  1809. "master secret",
  1810. tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
  1811. );
  1812. dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1813. // RFC 5246
  1814. // 6.3. Key Calculation
  1815. //
  1816. // The Record Protocol requires an algorithm to generate keys required
  1817. // by the current connection state (see Appendix A.6) from the security
  1818. // parameters provided by the handshake protocol.
  1819. //
  1820. // The master secret is expanded into a sequence of secure bytes, which
  1821. // is then split to a client write MAC key, a server write MAC key, a
  1822. // client write encryption key, and a server write encryption key. Each
  1823. // of these is generated from the byte sequence in that order. Unused
  1824. // values are empty. Some AEAD ciphers may additionally require a
  1825. // client write IV and a server write IV (see Section 6.2.3.3).
  1826. //
  1827. // When keys and MAC keys are generated, the master secret is used as an
  1828. // entropy source.
  1829. //
  1830. // To generate the key material, compute
  1831. //
  1832. // key_block = PRF(SecurityParameters.master_secret,
  1833. // "key expansion",
  1834. // SecurityParameters.server_random +
  1835. // SecurityParameters.client_random);
  1836. //
  1837. // until enough output has been generated. Then, the key_block is
  1838. // partitioned as follows:
  1839. //
  1840. // client_write_MAC_key[SecurityParameters.mac_key_length]
  1841. // server_write_MAC_key[SecurityParameters.mac_key_length]
  1842. // client_write_key[SecurityParameters.enc_key_length]
  1843. // server_write_key[SecurityParameters.enc_key_length]
  1844. // client_write_IV[SecurityParameters.fixed_iv_length]
  1845. // server_write_IV[SecurityParameters.fixed_iv_length]
  1846. {
  1847. uint8_t tmp64[64];
  1848. /* make "server_rand32 + client_rand32" */
  1849. memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
  1850. memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
  1851. prf_hmac_sha256(/*tls,*/
  1852. tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
  1853. // also fills:
  1854. // server_write_MAC_key[]
  1855. // client_write_key[]
  1856. // server_write_key[]
  1857. // client_write_IV[]
  1858. // server_write_IV[]
  1859. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1860. "key expansion",
  1861. tmp64, 64
  1862. );
  1863. tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
  1864. tls->server_write_key = tls->client_write_key + tls->key_size;
  1865. tls->client_write_IV = tls->server_write_key + tls->key_size;
  1866. tls->server_write_IV = tls->client_write_IV + tls->IV_size;
  1867. dump_hex("client_write_MAC_key:%s\n",
  1868. tls->client_write_MAC_key, tls->MAC_size
  1869. );
  1870. dump_hex("client_write_key:%s\n",
  1871. tls->client_write_key, tls->key_size
  1872. );
  1873. dump_hex("client_write_IV:%s\n",
  1874. tls->client_write_IV, tls->IV_size
  1875. );
  1876. aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
  1877. aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
  1878. {
  1879. uint8_t iv[AES_BLOCK_SIZE];
  1880. memset(iv, 0, AES_BLOCK_SIZE);
  1881. aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
  1882. }
  1883. }
  1884. }
  1885. static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
  1886. RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
  1887. 01
  1888. };
  1889. static void send_change_cipher_spec(tls_state_t *tls)
  1890. {
  1891. dbg(">> CHANGE_CIPHER_SPEC\n");
  1892. xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
  1893. }
  1894. // 7.4.9. Finished
  1895. // A Finished message is always sent immediately after a change
  1896. // cipher spec message to verify that the key exchange and
  1897. // authentication processes were successful. It is essential that a
  1898. // change cipher spec message be received between the other handshake
  1899. // messages and the Finished message.
  1900. //...
  1901. // The Finished message is the first one protected with the just
  1902. // negotiated algorithms, keys, and secrets. Recipients of Finished
  1903. // messages MUST verify that the contents are correct. Once a side
  1904. // has sent its Finished message and received and validated the
  1905. // Finished message from its peer, it may begin to send and receive
  1906. // application data over the connection.
  1907. //...
  1908. // struct {
  1909. // opaque verify_data[verify_data_length];
  1910. // } Finished;
  1911. //
  1912. // verify_data
  1913. // PRF(master_secret, finished_label, Hash(handshake_messages))
  1914. // [0..verify_data_length-1];
  1915. //
  1916. // finished_label
  1917. // For Finished messages sent by the client, the string
  1918. // "client finished". For Finished messages sent by the server,
  1919. // the string "server finished".
  1920. //
  1921. // Hash denotes a Hash of the handshake messages. For the PRF
  1922. // defined in Section 5, the Hash MUST be the Hash used as the basis
  1923. // for the PRF. Any cipher suite which defines a different PRF MUST
  1924. // also define the Hash to use in the Finished computation.
  1925. //
  1926. // In previous versions of TLS, the verify_data was always 12 octets
  1927. // long. In the current version of TLS, it depends on the cipher
  1928. // suite. Any cipher suite which does not explicitly specify
  1929. // verify_data_length has a verify_data_length equal to 12. This
  1930. // includes all existing cipher suites.
  1931. static void send_client_finished(tls_state_t *tls)
  1932. {
  1933. struct finished {
  1934. uint8_t type;
  1935. uint8_t len24_hi, len24_mid, len24_lo;
  1936. uint8_t prf_result[12];
  1937. };
  1938. struct finished *record = tls_get_outbuf(tls, sizeof(*record));
  1939. uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
  1940. unsigned len;
  1941. fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
  1942. len = sha_end(&tls->hsd->handshake_hash_ctx, handshake_hash);
  1943. prf_hmac_sha256(/*tls,*/
  1944. record->prf_result, sizeof(record->prf_result),
  1945. tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
  1946. "client finished",
  1947. handshake_hash, len
  1948. );
  1949. dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
  1950. dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
  1951. dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
  1952. dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
  1953. dbg(">> FINISHED\n");
  1954. xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
  1955. }
  1956. void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
  1957. {
  1958. // Client RFC 5246 Server
  1959. // (*) - optional messages, not always sent
  1960. //
  1961. // ClientHello ------->
  1962. // ServerHello
  1963. // Certificate*
  1964. // ServerKeyExchange*
  1965. // CertificateRequest*
  1966. // <------- ServerHelloDone
  1967. // Certificate*
  1968. // ClientKeyExchange
  1969. // CertificateVerify*
  1970. // [ChangeCipherSpec]
  1971. // Finished ------->
  1972. // [ChangeCipherSpec]
  1973. // <------- Finished
  1974. // Application Data <------> Application Data
  1975. int len;
  1976. int got_cert_req;
  1977. send_client_hello_and_alloc_hsd(tls, sni);
  1978. get_server_hello(tls);
  1979. // RFC 5246
  1980. // The server MUST send a Certificate message whenever the agreed-
  1981. // upon key exchange method uses certificates for authentication
  1982. // (this includes all key exchange methods defined in this document
  1983. // except DH_anon). This message will always immediately follow the
  1984. // ServerHello message.
  1985. //
  1986. // IOW: in practice, Certificate *always* follows.
  1987. // (for example, kernel.org does not even accept DH_anon cipher id)
  1988. get_server_cert(tls);
  1989. len = tls_xread_handshake_block(tls, 4);
  1990. if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
  1991. // 459 bytes:
  1992. // 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...
  1993. //SvKey len=455^
  1994. // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
  1995. // 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...
  1996. //
  1997. // RFC 8422 5.4. Server Key Exchange
  1998. // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
  1999. // ECDH_anon key exchange algorithms.
  2000. // This message is used to convey the server's ephemeral ECDH public key
  2001. // (and the corresponding elliptic curve domain parameters) to the
  2002. // client.
  2003. dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
  2004. dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
  2005. if (tls->flags & NEED_EC_KEY)
  2006. process_server_key(tls, len);
  2007. // read next handshake block
  2008. len = tls_xread_handshake_block(tls, 4);
  2009. }
  2010. got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
  2011. if (got_cert_req) {
  2012. dbg("<< CERTIFICATE_REQUEST\n");
  2013. // RFC 5246: "If no suitable certificate is available,
  2014. // the client MUST send a certificate message containing no
  2015. // certificates. That is, the certificate_list structure has a
  2016. // length of zero. ...
  2017. // Client certificates are sent using the Certificate structure
  2018. // defined in Section 7.4.2."
  2019. // (i.e. the same format as server certs)
  2020. /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
  2021. /* need to hash _all_ server replies first, up to ServerHelloDone */
  2022. len = tls_xread_handshake_block(tls, 4);
  2023. }
  2024. if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
  2025. bad_record_die(tls, "'server hello done'", len);
  2026. }
  2027. // 0e 000000 (len:0)
  2028. dbg("<< SERVER_HELLO_DONE\n");
  2029. if (got_cert_req)
  2030. send_empty_client_cert(tls);
  2031. send_client_key_exchange(tls);
  2032. send_change_cipher_spec(tls);
  2033. /* from now on we should send encrypted */
  2034. /* tls->write_seq64_be = 0; - already is */
  2035. tls->flags |= ENCRYPT_ON_WRITE;
  2036. send_client_finished(tls);
  2037. /* Get CHANGE_CIPHER_SPEC */
  2038. len = tls_xread_record(tls, "switch to encrypted traffic");
  2039. if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
  2040. bad_record_die(tls, "switch to encrypted traffic", len);
  2041. dbg("<< CHANGE_CIPHER_SPEC\n");
  2042. if (ALLOW_RSA_NULL_SHA256
  2043. && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
  2044. ) {
  2045. tls->min_encrypted_len_on_read = tls->MAC_size;
  2046. } else
  2047. if (!(tls->flags & ENCRYPTION_AESGCM)) {
  2048. unsigned mac_blocks = (unsigned)(TLS_MAC_SIZE(tls) + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
  2049. /* all incoming packets now should be encrypted and have
  2050. * at least IV + (MAC padded to blocksize):
  2051. */
  2052. tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
  2053. } else {
  2054. tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
  2055. }
  2056. dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
  2057. /* Get (encrypted) FINISHED from the server */
  2058. len = tls_xread_record(tls, "'server finished'");
  2059. if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
  2060. bad_record_die(tls, "'server finished'", len);
  2061. dbg("<< FINISHED\n");
  2062. /* application data can be sent/received */
  2063. /* free handshake data */
  2064. psRsaKey_clear(&tls->hsd->server_rsa_pub_key);
  2065. // if (PARANOIA)
  2066. // memset(tls->hsd, 0, tls->hsd->hsd_size);
  2067. free(tls->hsd);
  2068. tls->hsd = NULL;
  2069. }
  2070. static void tls_xwrite(tls_state_t *tls, int len)
  2071. {
  2072. dbg(">> DATA\n");
  2073. xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
  2074. }
  2075. // To run a test server using openssl:
  2076. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  2077. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2
  2078. //
  2079. // Unencryped SHA256 example:
  2080. // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
  2081. // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -cipher NULL
  2082. // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -cipher NULL-SHA256
  2083. void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
  2084. {
  2085. int inbuf_size;
  2086. const int INBUF_STEP = 4 * 1024;
  2087. struct pollfd pfds[2];
  2088. pfds[0].fd = STDIN_FILENO;
  2089. pfds[0].events = POLLIN;
  2090. pfds[1].fd = tls->ifd;
  2091. pfds[1].events = POLLIN;
  2092. inbuf_size = INBUF_STEP;
  2093. for (;;) {
  2094. int nread;
  2095. if (safe_poll(pfds, 2, -1) < 0)
  2096. bb_perror_msg_and_die("poll");
  2097. if (pfds[0].revents) {
  2098. void *buf;
  2099. dbg("STDIN HAS DATA\n");
  2100. buf = tls_get_outbuf(tls, inbuf_size);
  2101. nread = safe_read(STDIN_FILENO, buf, inbuf_size);
  2102. if (nread < 1) {
  2103. /* We'd want to do this: */
  2104. /* Close outgoing half-connection so they get EOF,
  2105. * but leave incoming alone so we can see response
  2106. */
  2107. //shutdown(tls->ofd, SHUT_WR);
  2108. /* But TLS has no way to encode this,
  2109. * doubt it's ok to do it "raw"
  2110. */
  2111. pfds[0].fd = -1;
  2112. tls_free_outbuf(tls); /* mem usage optimization */
  2113. if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
  2114. break;
  2115. } else {
  2116. if (nread == inbuf_size) {
  2117. /* TLS has per record overhead, if input comes fast,
  2118. * read, encrypt and send bigger chunks
  2119. */
  2120. inbuf_size += INBUF_STEP;
  2121. if (inbuf_size > TLS_MAX_OUTBUF)
  2122. inbuf_size = TLS_MAX_OUTBUF;
  2123. }
  2124. tls_xwrite(tls, nread);
  2125. }
  2126. }
  2127. if (pfds[1].revents) {
  2128. dbg("NETWORK HAS DATA\n");
  2129. read_record:
  2130. nread = tls_xread_record(tls, "encrypted data");
  2131. if (nread < 1) {
  2132. /* TLS protocol has no real concept of one-sided shutdowns:
  2133. * if we get "TLS EOF" from the peer, writes will fail too
  2134. */
  2135. //pfds[1].fd = -1;
  2136. //close(STDOUT_FILENO);
  2137. //tls_free_inbuf(tls); /* mem usage optimization */
  2138. //continue;
  2139. break;
  2140. }
  2141. if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
  2142. bad_record_die(tls, "encrypted data", nread);
  2143. xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
  2144. /* We may already have a complete next record buffered,
  2145. * can process it without network reads (and possible blocking)
  2146. */
  2147. if (tls_has_buffered_record(tls))
  2148. goto read_record;
  2149. }
  2150. }
  2151. }