tls.c 86 KB

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