picotls.h 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  1. /*
  2. * Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to
  6. * deal in the Software without restriction, including without limitation the
  7. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. * sell copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. * IN THE SOFTWARE.
  21. */
  22. #ifndef picotls_h
  23. #define picotls_h
  24. #ifdef __cplusplus
  25. extern "C" {
  26. #endif
  27. #ifdef _WINDOWS
  28. #include "wincompat.h"
  29. #endif
  30. #include <assert.h>
  31. #include <inttypes.h>
  32. #include <string.h>
  33. #include <sys/types.h>
  34. #ifndef _WINDOWS
  35. #include <netinet/in.h>
  36. #include <arpa/inet.h>
  37. #endif
  38. #if __GNUC__ >= 3
  39. #define PTLS_LIKELY(x) __builtin_expect(!!(x), 1)
  40. #define PTLS_UNLIKELY(x) __builtin_expect(!!(x), 0)
  41. #define PTLS_BUILD_ASSERT_EXPR(cond) (sizeof(char[2 * !!(!__builtin_constant_p(cond) || (cond)) - 1]) != 0)
  42. #define PTLS_BUILD_ASSERT(cond) ((void)PTLS_BUILD_ASSERT_EXPR(cond))
  43. #else
  44. #define PTLS_LIKELY(x) (x)
  45. #define PTLS_UNLIKELY(x) (x)
  46. #define PTLS_BUILD_ASSERT(cond) 1
  47. #endif
  48. /* __builtin_types_compatible_p yields incorrect results when older versions of GCC is used; see #303.
  49. * Clang with Xcode 9.4 or prior is known to not work correctly when a pointer is const-qualified; see
  50. * https://github.com/h2o/quicly/pull/306#issuecomment-626037269. Older versions of clang upstream works fine, but we do not need
  51. * best coverage. This macro is for preventing misuse going into the master branch, having it work one of the compilers supported in
  52. * our CI is enough.
  53. */
  54. #if ((defined(__clang__) && __clang_major__ >= 10) || __GNUC__ >= 6) && !defined(__cplusplus)
  55. #define PTLS_ASSERT_IS_ARRAY_EXPR(a) PTLS_BUILD_ASSERT_EXPR(__builtin_types_compatible_p(__typeof__(a[0])[], __typeof__(a)))
  56. #else
  57. #define PTLS_ASSERT_IS_ARRAY_EXPR(a) 1
  58. #endif
  59. #define PTLS_ELEMENTSOF(x) (PTLS_ASSERT_IS_ARRAY_EXPR(x) * sizeof(x) / sizeof((x)[0]))
  60. #ifdef _WINDOWS
  61. #define PTLS_THREADLOCAL __declspec(thread)
  62. #else
  63. #define PTLS_THREADLOCAL __thread
  64. #endif
  65. #ifndef PTLS_HAVE_LOG
  66. #ifdef _WINDOWS
  67. #define PTLS_HAVE_LOG 0
  68. #else
  69. #define PTLS_HAVE_LOG 1
  70. #endif
  71. #endif
  72. #ifndef PTLS_FUZZ_HANDSHAKE
  73. #define PTLS_FUZZ_HANDSHAKE 0
  74. #endif
  75. #define PTLS_HELLO_RANDOM_SIZE 32
  76. #define PTLS_AES128_KEY_SIZE 16
  77. #define PTLS_AES256_KEY_SIZE 32
  78. #define PTLS_AES_BLOCK_SIZE 16
  79. #define PTLS_AES_IV_SIZE 16
  80. #define PTLS_AESGCM_IV_SIZE 12
  81. #define PTLS_AESGCM_TAG_SIZE 16
  82. #define PTLS_AESGCM_CONFIDENTIALITY_LIMIT 0x2000000 /* 2^25 */
  83. #define PTLS_AESGCM_INTEGRITY_LIMIT UINT64_C(0x40000000000000) /* 2^54 */
  84. #define PTLS_AESCCM_CONFIDENTIALITY_LIMIT 0xB504F3 /* 2^23.5 */
  85. #define PTLS_AESCCM_INTEGRITY_LIMIT 0xB504F3 /* 2^23.5 */
  86. #define PTLS_CHACHA20_KEY_SIZE 32
  87. #define PTLS_CHACHA20_IV_SIZE 16 /* contrary to RFC 7539, follow OpenSSL way of using first 32 bits as ctr and latter 96 as IV */
  88. #define PTLS_CHACHA20POLY1305_IV_SIZE 12
  89. #define PTLS_CHACHA20POLY1305_TAG_SIZE 16
  90. #define PTLS_CHACHA20POLY1305_CONFIDENTIALITY_LIMIT UINT64_MAX /* at least 2^64 */
  91. #define PTLS_CHACHA20POLY1305_INTEGRITY_LIMIT UINT64_C(0x1000000000) /* 2^36 */
  92. #define PTLS_AEGIS128L_KEY_SIZE 16
  93. #define PTLS_AEGIS128L_IV_SIZE 16
  94. #define PTLS_AEGIS128L_TAG_SIZE 16
  95. #define PTLS_AEGIS128L_CONFIDENTIALITY_LIMIT UINT64_MAX /* at least 2^64 */
  96. #define PTLS_AEGIS128L_INTEGRITY_LIMIT UINT64_C(0x1000000000000) /* 2^48 */
  97. #define PTLS_AEGIS256_KEY_SIZE 32
  98. #define PTLS_AEGIS256_IV_SIZE 32
  99. #define PTLS_AEGIS256_TAG_SIZE 16
  100. #define PTLS_AEGIS256_CONFIDENTIALITY_LIMIT UINT64_MAX /* at least 2^64 */
  101. #define PTLS_AEGIS256_INTEGRITY_LIMIT UINT64_C(0x1000000000000) /* 2^48 */
  102. #define PTLS_BLOWFISH_KEY_SIZE 16
  103. #define PTLS_BLOWFISH_BLOCK_SIZE 8
  104. #define PTLS_SHA256_BLOCK_SIZE 64
  105. #define PTLS_SHA256_DIGEST_SIZE 32
  106. #define PTLS_SHA384_BLOCK_SIZE 128
  107. #define PTLS_SHA384_DIGEST_SIZE 48
  108. #define PTLS_SHA512_BLOCK_SIZE 128
  109. #define PTLS_SHA512_DIGEST_SIZE 64
  110. #define PTLS_MAX_SECRET_SIZE 32
  111. #define PTLS_MAX_IV_SIZE 32
  112. #define PTLS_MAX_DIGEST_SIZE 64
  113. /* versions */
  114. #define PTLS_PROTOCOL_VERSION_TLS12 0x0303
  115. #define PTLS_PROTOCOL_VERSION_TLS13 0x0304
  116. /* cipher-suites */
  117. #define PTLS_CIPHER_SUITE_AES_128_GCM_SHA256 0x1301
  118. #define PTLS_CIPHER_SUITE_NAME_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256"
  119. #define PTLS_CIPHER_SUITE_AES_256_GCM_SHA384 0x1302
  120. #define PTLS_CIPHER_SUITE_NAME_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384"
  121. #define PTLS_CIPHER_SUITE_CHACHA20_POLY1305_SHA256 0x1303
  122. #define PTLS_CIPHER_SUITE_NAME_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256"
  123. #define PTLS_CIPHER_SUITE_AEGIS256_SHA512 0x1306
  124. #define PTLS_CIPHER_SUITE_NAME_AEGIS256_SHA512 "TLS_AEGIS_256_SHA512"
  125. #define PTLS_CIPHER_SUITE_AEGIS128L_SHA256 0x1307
  126. #define PTLS_CIPHER_SUITE_NAME_AEGIS128L_SHA256 "TLS_AEGIS_128L_SHA256"
  127. /* TLS/1.2 cipher-suites that we support (for compatibility, OpenSSL names are used) */
  128. #define PTLS_CIPHER_SUITE_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xc02b
  129. #define PTLS_CIPHER_SUITE_NAME_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256"
  130. #define PTLS_CIPHER_SUITE_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xc02c
  131. #define PTLS_CIPHER_SUITE_NAME_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384"
  132. #define PTLS_CIPHER_SUITE_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xc02f
  133. #define PTLS_CIPHER_SUITE_NAME_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256"
  134. #define PTLS_CIPHER_SUITE_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xc030
  135. #define PTLS_CIPHER_SUITE_NAME_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384"
  136. #define PTLS_CIPHER_SUITE_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xcca8
  137. #define PTLS_CIPHER_SUITE_NAME_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 "ECDHE-RSA-CHACHA20-POLY1305"
  138. #define PTLS_CIPHER_SUITE_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xcca9
  139. #define PTLS_CIPHER_SUITE_NAME_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 "ECDHE-ECDSA-CHACHA20-POLY1305"
  140. /* negotiated_groups */
  141. #define PTLS_GROUP_SECP256R1 23
  142. #define PTLS_GROUP_NAME_SECP256R1 "secp256r1"
  143. #define PTLS_GROUP_SECP384R1 24
  144. #define PTLS_GROUP_NAME_SECP384R1 "secp384r1"
  145. #define PTLS_GROUP_SECP521R1 25
  146. #define PTLS_GROUP_NAME_SECP521R1 "secp521r1"
  147. #define PTLS_GROUP_X25519 29
  148. #define PTLS_GROUP_NAME_X25519 "x25519"
  149. #define PTLS_GROUP_X448 30
  150. #define PTLS_GROUP_NAME_X448 "x448"
  151. #define PTLS_GROUP_X25519MLKEM768 4588
  152. #define PTLS_GROUP_NAME_X25519MLKEM768 "X25519MLKEM768"
  153. /* signature algorithms */
  154. #define PTLS_SIGNATURE_RSA_PKCS1_SHA1 0x0201
  155. #define PTLS_SIGNATURE_RSA_PKCS1_SHA256 0x0401
  156. #define PTLS_SIGNATURE_ECDSA_SECP256R1_SHA256 0x0403
  157. #define PTLS_SIGNATURE_ECDSA_SECP384R1_SHA384 0x0503
  158. #define PTLS_SIGNATURE_ECDSA_SECP521R1_SHA512 0x0603
  159. #define PTLS_SIGNATURE_RSA_PSS_RSAE_SHA256 0x0804
  160. #define PTLS_SIGNATURE_RSA_PSS_RSAE_SHA384 0x0805
  161. #define PTLS_SIGNATURE_RSA_PSS_RSAE_SHA512 0x0806
  162. #define PTLS_SIGNATURE_ED25519 0x0807
  163. /* HPKE */
  164. #define PTLS_HPKE_MODE_BASE 0
  165. #define PTLS_HPKE_MODE_PSK 1
  166. #define PTLS_HPKE_MODE_AUTH 2
  167. #define PTLS_HPKE_MODE_AUTH_PSK 3
  168. #define PTLS_HPKE_KEM_P256_SHA256 16
  169. #define PTLS_HPKE_KEM_P384_SHA384 17
  170. #define PTLS_HPKE_KEM_X25519_SHA256 32
  171. #define PTLS_HPKE_HKDF_SHA256 1
  172. #define PTLS_HPKE_HKDF_SHA384 2
  173. #define PTLS_HPKE_HKDF_SHA512 3
  174. #define PTLS_HPKE_AEAD_AES_128_GCM 1
  175. #define PTLS_HPKE_AEAD_AES_256_GCM 2
  176. #define PTLS_HPKE_AEAD_CHACHA20POLY1305 3
  177. /* error classes and macros */
  178. #define PTLS_ERROR_CLASS_SELF_ALERT 0
  179. #define PTLS_ERROR_CLASS_PEER_ALERT 0x100
  180. #define PTLS_ERROR_CLASS_INTERNAL 0x200
  181. #define PTLS_ERROR_GET_CLASS(e) ((e) & ~0xff)
  182. #define PTLS_ALERT_TO_SELF_ERROR(e) ((e) + PTLS_ERROR_CLASS_SELF_ALERT)
  183. #define PTLS_ALERT_TO_PEER_ERROR(e) ((e) + PTLS_ERROR_CLASS_PEER_ALERT)
  184. #define PTLS_ERROR_TO_ALERT(e) ((e) & 0xff)
  185. /* the HKDF prefix */
  186. #define PTLS_HKDF_EXPAND_LABEL_PREFIX "tls13 "
  187. /* alerts */
  188. #define PTLS_ALERT_LEVEL_WARNING 1
  189. #define PTLS_ALERT_LEVEL_FATAL 2
  190. #define PTLS_ALERT_CLOSE_NOTIFY 0
  191. #define PTLS_ALERT_UNEXPECTED_MESSAGE 10
  192. #define PTLS_ALERT_BAD_RECORD_MAC 20
  193. #define PTLS_ALERT_HANDSHAKE_FAILURE 40
  194. #define PTLS_ALERT_BAD_CERTIFICATE 42
  195. #define PTLS_ALERT_UNSUPPORTED_CERTIFICATE 43
  196. #define PTLS_ALERT_CERTIFICATE_REVOKED 44
  197. #define PTLS_ALERT_CERTIFICATE_EXPIRED 45
  198. #define PTLS_ALERT_CERTIFICATE_UNKNOWN 46
  199. #define PTLS_ALERT_ILLEGAL_PARAMETER 47
  200. #define PTLS_ALERT_UNKNOWN_CA 48
  201. #define PTLS_ALERT_ACCESS_DENIED 49
  202. #define PTLS_ALERT_DECODE_ERROR 50
  203. #define PTLS_ALERT_DECRYPT_ERROR 51
  204. #define PTLS_ALERT_PROTOCOL_VERSION 70
  205. #define PTLS_ALERT_INTERNAL_ERROR 80
  206. #define PTLS_ALERT_USER_CANCELED 90
  207. #define PTLS_ALERT_MISSING_EXTENSION 109
  208. #define PTLS_ALERT_UNSUPPORTED_EXTENSION 110
  209. #define PTLS_ALERT_UNRECOGNIZED_NAME 112
  210. #define PTLS_ALERT_UNKNOWN_PSK_IDENTITY 115
  211. #define PTLS_ALERT_CERTIFICATE_REQUIRED 116
  212. #define PTLS_ALERT_NO_APPLICATION_PROTOCOL 120
  213. #define PTLS_ALERT_ECH_REQUIRED 121
  214. /* TLS 1.2 */
  215. #define PTLS_TLS12_MASTER_SECRET_SIZE 48
  216. #define PTLS_TLS12_AAD_SIZE 13
  217. #define PTLS_TLS12_AESGCM_FIXED_IV_SIZE 4
  218. #define PTLS_TLS12_AESGCM_RECORD_IV_SIZE 8
  219. #define PTLS_TLS12_CHACHAPOLY_FIXED_IV_SIZE 12
  220. #define PTLS_TLS12_CHACHAPOLY_RECORD_IV_SIZE 0
  221. /* internal errors */
  222. #define PTLS_ERROR_NO_MEMORY (PTLS_ERROR_CLASS_INTERNAL + 1)
  223. #define PTLS_ERROR_IN_PROGRESS (PTLS_ERROR_CLASS_INTERNAL + 2)
  224. #define PTLS_ERROR_LIBRARY (PTLS_ERROR_CLASS_INTERNAL + 3)
  225. #define PTLS_ERROR_INCOMPATIBLE_KEY (PTLS_ERROR_CLASS_INTERNAL + 4)
  226. #define PTLS_ERROR_SESSION_NOT_FOUND (PTLS_ERROR_CLASS_INTERNAL + 5)
  227. #define PTLS_ERROR_STATELESS_RETRY (PTLS_ERROR_CLASS_INTERNAL + 6)
  228. #define PTLS_ERROR_NOT_AVAILABLE (PTLS_ERROR_CLASS_INTERNAL + 7)
  229. #define PTLS_ERROR_COMPRESSION_FAILURE (PTLS_ERROR_CLASS_INTERNAL + 8)
  230. #define PTLS_ERROR_REJECT_EARLY_DATA (PTLS_ERROR_CLASS_INTERNAL + 9)
  231. #define PTLS_ERROR_DELEGATE (PTLS_ERROR_CLASS_INTERNAL + 10)
  232. #define PTLS_ERROR_ASYNC_OPERATION (PTLS_ERROR_CLASS_INTERNAL + 11)
  233. #define PTLS_ERROR_BLOCK_OVERFLOW (PTLS_ERROR_CLASS_INTERNAL + 12)
  234. #define PTLS_ERROR_INCORRECT_BASE64 (PTLS_ERROR_CLASS_INTERNAL + 50)
  235. #define PTLS_ERROR_PEM_LABEL_NOT_FOUND (PTLS_ERROR_CLASS_INTERNAL + 51)
  236. #define PTLS_ERROR_BER_INCORRECT_ENCODING (PTLS_ERROR_CLASS_INTERNAL + 52)
  237. #define PTLS_ERROR_BER_MALFORMED_TYPE (PTLS_ERROR_CLASS_INTERNAL + 53)
  238. #define PTLS_ERROR_BER_MALFORMED_LENGTH (PTLS_ERROR_CLASS_INTERNAL + 54)
  239. #define PTLS_ERROR_BER_EXCESSIVE_LENGTH (PTLS_ERROR_CLASS_INTERNAL + 55)
  240. #define PTLS_ERROR_BER_ELEMENT_TOO_SHORT (PTLS_ERROR_CLASS_INTERNAL + 56)
  241. #define PTLS_ERROR_BER_UNEXPECTED_EOC (PTLS_ERROR_CLASS_INTERNAL + 57)
  242. #define PTLS_ERROR_DER_INDEFINITE_LENGTH (PTLS_ERROR_CLASS_INTERNAL + 58)
  243. #define PTLS_ERROR_INCORRECT_ASN1_SYNTAX (PTLS_ERROR_CLASS_INTERNAL + 59)
  244. #define PTLS_ERROR_INCORRECT_PEM_KEY_VERSION (PTLS_ERROR_CLASS_INTERNAL + 60)
  245. #define PTLS_ERROR_INCORRECT_PEM_ECDSA_KEY_VERSION (PTLS_ERROR_CLASS_INTERNAL + 61)
  246. #define PTLS_ERROR_INCORRECT_PEM_ECDSA_CURVE (PTLS_ERROR_CLASS_INTERNAL + 62)
  247. #define PTLS_ERROR_INCORRECT_PEM_ECDSA_KEYSIZE (PTLS_ERROR_CLASS_INTERNAL + 63)
  248. #define PTLS_ERROR_INCORRECT_ASN1_ECDSA_KEY_SYNTAX (PTLS_ERROR_CLASS_INTERNAL + 64)
  249. #define PTLS_HANDSHAKE_TYPE_CLIENT_HELLO 1
  250. #define PTLS_HANDSHAKE_TYPE_SERVER_HELLO 2
  251. #define PTLS_HANDSHAKE_TYPE_NEW_SESSION_TICKET 4
  252. #define PTLS_HANDSHAKE_TYPE_END_OF_EARLY_DATA 5
  253. #define PTLS_HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS 8
  254. #define PTLS_HANDSHAKE_TYPE_CERTIFICATE 11
  255. #define PTLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST 13
  256. #define PTLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY 15
  257. #define PTLS_HANDSHAKE_TYPE_FINISHED 20
  258. #define PTLS_HANDSHAKE_TYPE_KEY_UPDATE 24
  259. #define PTLS_HANDSHAKE_TYPE_COMPRESSED_CERTIFICATE 25
  260. #define PTLS_HANDSHAKE_TYPE_MESSAGE_HASH 254
  261. #define PTLS_HANDSHAKE_TYPE_PSEUDO_HRR -1
  262. #define PTLS_CERTIFICATE_TYPE_X509 0
  263. #define PTLS_CERTIFICATE_TYPE_RAW_PUBLIC_KEY 2
  264. #define PTLS_ZERO_DIGEST_SHA256 \
  265. {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, \
  266. 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}
  267. #define PTLS_ZERO_DIGEST_SHA384 \
  268. {0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, \
  269. 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, \
  270. 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b}
  271. #define PTLS_ZERO_DIGEST_SHA512 \
  272. {0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, \
  273. 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, \
  274. 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, \
  275. 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e}
  276. #define PTLS_TO__STR(n) #n
  277. #define PTLS_TO_STR(n) PTLS_TO__STR(n)
  278. /**
  279. * default maximum of tickets to send (see ptls_context_t::ticket_requests.server.max_count)
  280. */
  281. #define PTLS_DEFAULT_MAX_TICKETS_TO_SERVE 4
  282. typedef struct st_ptls_t ptls_t;
  283. typedef struct st_ptls_context_t ptls_context_t;
  284. typedef struct st_ptls_key_schedule_t ptls_key_schedule_t;
  285. /**
  286. * represents a sequence of octets
  287. */
  288. typedef struct st_ptls_iovec_t {
  289. uint8_t *base;
  290. size_t len;
  291. } ptls_iovec_t;
  292. /**
  293. * used for storing output
  294. */
  295. typedef struct st_ptls_buffer_t {
  296. uint8_t *base;
  297. size_t capacity;
  298. size_t off;
  299. uint8_t is_allocated; /* boolean */
  300. uint8_t align_bits; /* if particular alignment is required, set to log2(alignment); otherwize zero */
  301. } ptls_buffer_t;
  302. /**
  303. * key exchange context built by ptls_key_exchange_algorithm::create.
  304. */
  305. typedef struct st_ptls_key_exchange_context_t {
  306. /**
  307. * the underlying algorithm
  308. */
  309. const struct st_ptls_key_exchange_algorithm_t *algo;
  310. /**
  311. * public key of this context
  312. */
  313. ptls_iovec_t pubkey;
  314. /**
  315. * This function can be used for deriving a shared secret or for destroying the context.
  316. * When `secret` is non-NULL, this callback derives the shared secret using the private key of the context and the peer key
  317. * being given, and sets the value in `secret`. The memory pointed to by `secret->base` must be freed by the caller by calling
  318. * `free`. When `release` is set, the callee frees resources allocated to the context and set *keyex to NULL. Upon failure
  319. * (i.e., when an PTLS error code is returned), `*pubkey` and `*secret` either remain unchanged or are zero-cleared.
  320. */
  321. int (*on_exchange)(struct st_ptls_key_exchange_context_t **keyex, int release, ptls_iovec_t *secret, ptls_iovec_t peerkey);
  322. } ptls_key_exchange_context_t;
  323. /**
  324. * A key exchange algorithm.
  325. */
  326. typedef const struct st_ptls_key_exchange_algorithm_t {
  327. /**
  328. * ID defined by the TLS specification
  329. */
  330. uint16_t id;
  331. /**
  332. * Creates a context for asynchronous key exchange. The function is called when ClientHello is generated. The on_exchange
  333. * callback of the created context is called when the client receives ServerHello.
  334. */
  335. int (*create)(const struct st_ptls_key_exchange_algorithm_t *algo, ptls_key_exchange_context_t **ctx);
  336. /**
  337. * Implements synchronous key exchange. Called when ServerHello is generated.
  338. * Given a public key provided by the peer (`peerkey`), this callback generates an ephemeral private and public key, and returns
  339. * the public key (`pubkey`) and a secret (`secret`) derived from the peerkey and private key.
  340. * Upon failure (i.e., when an PTLS error code is returned), `*pubkey` and `*secret` either remain unchanged or are
  341. * zero-cleared.
  342. */
  343. int (*exchange)(const struct st_ptls_key_exchange_algorithm_t *algo, ptls_iovec_t *pubkey, ptls_iovec_t *secret,
  344. ptls_iovec_t peerkey);
  345. /**
  346. * crypto-specific data
  347. */
  348. intptr_t data;
  349. /**
  350. * Description as defined in the IANA TLS registry
  351. */
  352. const char *name;
  353. } ptls_key_exchange_algorithm_t;
  354. /**
  355. * context of a symmetric cipher
  356. */
  357. typedef struct st_ptls_cipher_context_t {
  358. const struct st_ptls_cipher_algorithm_t *algo;
  359. /* field above this line must not be altered by the crypto binding */
  360. void (*do_dispose)(struct st_ptls_cipher_context_t *ctx);
  361. void (*do_init)(struct st_ptls_cipher_context_t *ctx, const void *iv);
  362. void (*do_transform)(struct st_ptls_cipher_context_t *ctx, void *output, const void *input, size_t len);
  363. } ptls_cipher_context_t;
  364. /**
  365. * a symmetric cipher
  366. */
  367. typedef const struct st_ptls_cipher_algorithm_t {
  368. const char *name;
  369. size_t key_size;
  370. size_t block_size;
  371. size_t iv_size;
  372. size_t context_size;
  373. int (*setup_crypto)(ptls_cipher_context_t *ctx, int is_enc, const void *key);
  374. } ptls_cipher_algorithm_t;
  375. /**
  376. * This object specifies symmetric cipher to be calculated alongside the AEAD encryption.
  377. * QUIC stacks can use this object to apply QUIC header protection and AEAD encryption in one shot.
  378. */
  379. typedef struct st_ptls_aead_supplementary_encryption_t {
  380. /**
  381. * Cipher context to be used.
  382. */
  383. ptls_cipher_context_t *ctx;
  384. /**
  385. * Input to the cipher.
  386. * This field may point to the output of AEAD encryption, in which case the input will be read after AEAD encryption is
  387. * complete.
  388. */
  389. const void *input;
  390. /**
  391. * Output.
  392. */
  393. uint8_t output[16];
  394. } ptls_aead_supplementary_encryption_t;
  395. /**
  396. * AEAD context.
  397. * AEAD implementations are allowed to stuff data at the end of the struct; see `ptls_aead_algorithm_t::setup_crypto`.
  398. * Ciphers for TLS over TCP MUST implement `do_encrypt`, `do_encrypt_v`, `do_decrypt`.
  399. * `do_encrypt_init`, `~update`, `~final` are obsolete, and therefore may not be available.
  400. */
  401. typedef struct st_ptls_aead_context_t {
  402. /**
  403. * Points to the algorithm. This field is governed by picotls core; backends must not alter.
  404. */
  405. const struct st_ptls_aead_algorithm_t *algo;
  406. /**
  407. * Mandatory callback that disposes of all the backend-specific data.
  408. */
  409. void (*dispose_crypto)(struct st_ptls_aead_context_t *ctx);
  410. /**
  411. * Mandatory callback that returns the static IV. The size of IV is available as `ptls_aead_algorithm_t::iv_size`.
  412. */
  413. void (*do_get_iv)(struct st_ptls_aead_context_t *ctx, void *iv);
  414. /**
  415. * Mandatory callback that sets the static IV. The size of IV is available as `ptls_aead_algorithm_t::iv_size`.
  416. */
  417. void (*do_set_iv)(struct st_ptls_aead_context_t *ctx, const void *iv);
  418. /**
  419. * Deprecated.
  420. */
  421. void (*do_encrypt_init)(struct st_ptls_aead_context_t *ctx, uint64_t seq, const void *aad, size_t aadlen);
  422. /**
  423. * Deprecated.
  424. */
  425. size_t (*do_encrypt_update)(struct st_ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen);
  426. /**
  427. * Deprecated.
  428. */
  429. size_t (*do_encrypt_final)(struct st_ptls_aead_context_t *ctx, void *output);
  430. /**
  431. * Mandatory callback that does "one-shot" encryption of an AEAD block.
  432. * When `supp` is set to non-NULL, the callback must also encrypt the supplementary block.
  433. * Backends may set this field to `ptls_aead__do_encrypt` that calls `do_encrypt_v` and `ptls_cipher_*` functions for handling
  434. * the supplimentary block.
  435. */
  436. void (*do_encrypt)(struct st_ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  437. const void *aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp);
  438. /**
  439. * Variant of `do_encrypt` that gathers input from multiple blocks. Support for this callback is also mandatory.
  440. * Legacy backends may set this field to `ptls_aead__do_encrypt_v` that calls `do_encrypt_init`, `do_encrypt_update`,
  441. * `do_encrypt_final`.
  442. */
  443. void (*do_encrypt_v)(struct st_ptls_aead_context_t *ctx, void *output, ptls_iovec_t *input, size_t incnt, uint64_t seq,
  444. const void *aad, size_t aadlen);
  445. /**
  446. * Mandatory callback for decrypting an AEAD block.
  447. * If successful, returns the amount of cleartext bytes being written to output. Otherwise, returns SIZE_MAX.
  448. */
  449. size_t (*do_decrypt)(struct st_ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  450. const void *aad, size_t aadlen);
  451. } ptls_aead_context_t;
  452. /**
  453. * An AEAD cipher.
  454. */
  455. typedef const struct st_ptls_aead_algorithm_t {
  456. /**
  457. * name (following the convention of `openssl ciphers -v ALL`)
  458. */
  459. const char *name;
  460. /**
  461. * confidentiality_limit (max records / packets sent before re-key)
  462. */
  463. const uint64_t confidentiality_limit;
  464. /**
  465. * integrity_limit (max decryption failure records / packets before re-key)
  466. */
  467. const uint64_t integrity_limit;
  468. /**
  469. * the underlying key stream
  470. */
  471. ptls_cipher_algorithm_t *ctr_cipher;
  472. /**
  473. * the underlying ecb cipher (might not be available)
  474. */
  475. ptls_cipher_algorithm_t *ecb_cipher;
  476. /**
  477. * key size
  478. */
  479. size_t key_size;
  480. /**
  481. * size of the IV
  482. */
  483. size_t iv_size;
  484. /**
  485. * size of the tag
  486. */
  487. size_t tag_size;
  488. /**
  489. * TLS/1.2 Security Parameters (AEAD without support for TLS 1.2 must set both values to 0)
  490. */
  491. struct {
  492. size_t fixed_iv_size;
  493. size_t record_iv_size;
  494. } tls12;
  495. /**
  496. * if encrypted bytes are going to be written using non-temporal store instructions (i.e., skip cache)
  497. */
  498. unsigned non_temporal : 1;
  499. /**
  500. * log2(alignment) being required
  501. */
  502. uint8_t align_bits;
  503. /**
  504. * size of memory allocated for `ptls_aead_context_t`
  505. */
  506. size_t context_size;
  507. /**
  508. * Backend callback called to setup `ptls_aead_context_t`.
  509. * Backends are allowed to stuff arbitrary data at the end of `ptls_aead_context_t`; actual size of the memory chunk being
  510. * allocated is that specified by `ptls_aead_algorithm_t::context_size`. When the `setup_crypto` callback is called, all the
  511. * fields outside of `ptls_aead_context_t` will be in undefined state; it is the responsibility of the callback to initialize
  512. * them, as well as the callbacks of `ptls_aead_context_t` that the backend supports.
  513. * A non-zero return value indicates failure, in which case the error will propagate as `ptls_aead_new` returning NULL.
  514. */
  515. int (*setup_crypto)(ptls_aead_context_t *ctx, int is_enc, const void *key, const void *iv);
  516. } ptls_aead_algorithm_t;
  517. /**
  518. *
  519. */
  520. typedef enum en_ptls_hash_final_mode_t {
  521. /**
  522. * obtains the digest and frees the context
  523. */
  524. PTLS_HASH_FINAL_MODE_FREE = 0,
  525. /**
  526. * obtains the digest and reset the context to initial state
  527. */
  528. PTLS_HASH_FINAL_MODE_RESET = 1,
  529. /**
  530. * obtains the digest while leaving the context as-is
  531. */
  532. PTLS_HASH_FINAL_MODE_SNAPSHOT = 2
  533. } ptls_hash_final_mode_t;
  534. /**
  535. * A hash context.
  536. */
  537. typedef struct st_ptls_hash_context_t {
  538. /**
  539. * feeds additional data into the hash context
  540. */
  541. void (*update)(struct st_ptls_hash_context_t *ctx, const void *src, size_t len);
  542. /**
  543. * returns the digest and performs necessary operation specified by mode
  544. */
  545. void (*final)(struct st_ptls_hash_context_t *ctx, void *md, ptls_hash_final_mode_t mode);
  546. /**
  547. * creates a copy of the hash context
  548. */
  549. struct st_ptls_hash_context_t *(*clone_)(struct st_ptls_hash_context_t *src);
  550. } ptls_hash_context_t;
  551. /**
  552. * A hash algorithm and its properties.
  553. */
  554. typedef const struct st_ptls_hash_algorithm_t {
  555. /**
  556. * name of the hash algorithm
  557. */
  558. const char *name;
  559. /**
  560. * block size
  561. */
  562. size_t block_size;
  563. /**
  564. * digest size
  565. */
  566. size_t digest_size;
  567. /**
  568. * constructor that creates the hash context
  569. */
  570. ptls_hash_context_t *(*create)(void);
  571. /**
  572. * digest of zero-length octets
  573. */
  574. uint8_t empty_digest[PTLS_MAX_DIGEST_SIZE];
  575. } ptls_hash_algorithm_t;
  576. typedef const struct st_ptls_cipher_suite_t {
  577. /**
  578. * ID as defined by the TLS Cipher Suites registry
  579. */
  580. uint16_t id;
  581. /**
  582. * underlying AEAD algorithm
  583. */
  584. ptls_aead_algorithm_t *aead;
  585. /**
  586. * underlying hash algorithm
  587. */
  588. ptls_hash_algorithm_t *hash;
  589. /**
  590. * value of the "Description" field of the TLS Cipher Suites registry
  591. */
  592. const char *name;
  593. } ptls_cipher_suite_t;
  594. struct st_ptls_traffic_protection_t;
  595. typedef struct st_ptls_message_emitter_t {
  596. ptls_buffer_t *buf;
  597. struct st_ptls_traffic_protection_t *enc;
  598. size_t record_header_length;
  599. int (*begin_message)(struct st_ptls_message_emitter_t *self);
  600. int (*commit_message)(struct st_ptls_message_emitter_t *self);
  601. } ptls_message_emitter_t;
  602. /**
  603. * HPKE KEM
  604. */
  605. typedef const struct st_ptls_hpke_kem_t {
  606. uint16_t id;
  607. ptls_key_exchange_algorithm_t *keyex;
  608. ptls_hash_algorithm_t *hash;
  609. } ptls_hpke_kem_t;
  610. typedef struct st_ptls_hpke_cipher_suite_id_t {
  611. uint16_t kdf;
  612. uint16_t aead;
  613. } ptls_hpke_cipher_suite_id_t;
  614. typedef const struct st_ptls_hpke_cipher_suite_t {
  615. ptls_hpke_cipher_suite_id_t id;
  616. const char *name; /* in form of "<kdf>/<aead>" using the sames specified in IANA HPKE registry */
  617. ptls_hash_algorithm_t *hash;
  618. ptls_aead_algorithm_t *aead;
  619. } ptls_hpke_cipher_suite_t;
  620. #define PTLS_CALLBACK_TYPE0(ret, name) \
  621. typedef struct st_ptls_##name##_t { \
  622. ret (*cb)(struct st_ptls_##name##_t * self); \
  623. } ptls_##name##_t
  624. #define PTLS_CALLBACK_TYPE(ret, name, ...) \
  625. typedef struct st_ptls_##name##_t { \
  626. ret (*cb)(struct st_ptls_##name##_t * self, __VA_ARGS__); \
  627. } ptls_##name##_t
  628. typedef struct st_ptls_client_hello_psk_identity_t {
  629. ptls_iovec_t identity;
  630. uint32_t obfuscated_ticket_age;
  631. ptls_iovec_t binder;
  632. } ptls_client_hello_psk_identity_t;
  633. /**
  634. * arguments passsed to the on_client_hello callback
  635. */
  636. typedef struct st_ptls_on_client_hello_parameters_t {
  637. /**
  638. * SNI value received from the client. The value is {NULL, 0} if the extension was absent.
  639. */
  640. ptls_iovec_t server_name;
  641. /**
  642. * Raw value of the client_hello message.
  643. */
  644. ptls_iovec_t raw_message;
  645. /**
  646. * points to the cipher-suites section of the raw_message (see above)
  647. */
  648. ptls_iovec_t cipher_suites;
  649. /**
  650. *
  651. */
  652. struct {
  653. ptls_iovec_t *list;
  654. size_t count;
  655. } negotiated_protocols;
  656. struct {
  657. const uint16_t *list;
  658. size_t count;
  659. } signature_algorithms;
  660. struct {
  661. const uint16_t *list;
  662. size_t count;
  663. } certificate_compression_algorithms;
  664. struct {
  665. const uint8_t *list;
  666. size_t count;
  667. } server_certificate_types;
  668. struct {
  669. const ptls_client_hello_psk_identity_t *list;
  670. size_t count;
  671. } psk_identities;
  672. /**
  673. * set to 1 if ClientHello is too old (or too new) to be handled by picotls
  674. */
  675. unsigned incompatible_version : 1;
  676. } ptls_on_client_hello_parameters_t;
  677. /**
  678. * returns current time in milliseconds (ptls_get_time can be used to return the physical time)
  679. */
  680. PTLS_CALLBACK_TYPE0(uint64_t, get_time);
  681. /**
  682. * after receiving ClientHello, the core calls the optional callback to give a chance to the swap the context depending on the input
  683. * values. The callback is required to call `ptls_set_server_name` if an SNI extension needs to be sent to the client.
  684. */
  685. PTLS_CALLBACK_TYPE(int, on_client_hello, ptls_t *tls, ptls_on_client_hello_parameters_t *params);
  686. /**
  687. * callback to generate the certificate message. `ptls_context::certificates` are set when the callback is set to NULL.
  688. */
  689. PTLS_CALLBACK_TYPE(int, emit_certificate, ptls_t *tls, ptls_message_emitter_t *emitter, ptls_key_schedule_t *key_sched,
  690. ptls_iovec_t context, int push_status_request, const uint16_t *compress_algos, size_t num_compress_algos);
  691. /**
  692. * An object that represents an asynchronous task (e.g., RSA signature generation).
  693. * When `ptls_handshake` returns `PTLS_ERROR_ASYNC_OPERATION`, it has an associated task in flight. The user should obtain the
  694. * reference to the associated task by calling `ptls_get_async_job`, then either wait for the file descriptor obtained from
  695. * the `get_fd` callback to become readable, or set a completion callback via `set_completion_callback` and wait for its
  696. * invocation. Once notified, the user should invoke `ptls_handshake` again.
  697. * Async jobs typically provide support for only one of the two methods.
  698. */
  699. typedef struct st_ptls_async_job_t {
  700. void (*destroy_)(struct st_ptls_async_job_t *self);
  701. /**
  702. * optional callback returning a file descriptor that becomes readable when the job is complete
  703. */
  704. int (*get_fd)(struct st_ptls_async_job_t *self);
  705. /**
  706. * optional callback for setting a completion callback
  707. */
  708. void (*set_completion_callback)(struct st_ptls_async_job_t *self, void (*cb)(void *), void *cbdata);
  709. } ptls_async_job_t;
  710. /**
  711. * When gerenating CertificateVerify, the core calls the callback to sign the handshake context using the certificate. This callback
  712. * supports asynchronous mode; see `ptls_openssl_sign_certificate_t` for more information.
  713. */
  714. PTLS_CALLBACK_TYPE(int, sign_certificate, ptls_t *tls, ptls_async_job_t **async, uint16_t *selected_algorithm,
  715. ptls_buffer_t *output, ptls_iovec_t input, const uint16_t *algorithms, size_t num_algorithms);
  716. /**
  717. * after receiving Certificate, the core calls the callback to verify the certificate chain and to obtain a pointer to a
  718. * callback that should be used for verifying CertificateVerify. If an error occurs between a successful return from this
  719. * callback to the invocation of the verify_sign callback, verify_sign is called with both data and sign set to an empty buffer.
  720. * The implementor of the callback should use that as the opportunity to free any temporary data allocated for the verify_sign
  721. * callback.
  722. * The name of the server to be verified, if any, is provided explicitly as `server_name`. When ECH is offered by the client but
  723. * the was rejected by the server, this value can be different from that being sent via `ptls_get_server_name`.
  724. */
  725. typedef struct st_ptls_verify_certificate_t {
  726. int (*cb)(struct st_ptls_verify_certificate_t *self, ptls_t *tls, const char *server_name,
  727. int (**verify_sign)(void *verify_ctx, uint16_t algo, ptls_iovec_t data, ptls_iovec_t sign), void **verify_data,
  728. ptls_iovec_t *certs, size_t num_certs);
  729. /**
  730. * list of signature algorithms being supported, terminated by UINT16_MAX
  731. */
  732. const uint16_t *algos;
  733. } ptls_verify_certificate_t;
  734. /**
  735. * Encrypt-and-signs (or verify-and-decrypts) a ticket (server-only).
  736. * When used for encryption (i.e., is_encrypt being set), the function should return 0 if successful, or else a non-zero value.
  737. * When used for decryption, the function should return 0 (successful), PTLS_ERROR_REJECT_EARLY_DATA (successful, but 0-RTT is
  738. * forbidden), or any other value to indicate failure.
  739. */
  740. PTLS_CALLBACK_TYPE(int, encrypt_ticket, ptls_t *tls, int is_encrypt, ptls_buffer_t *dst, ptls_iovec_t src);
  741. /**
  742. * saves a ticket (client-only)
  743. */
  744. PTLS_CALLBACK_TYPE(int, save_ticket, ptls_t *tls, ptls_iovec_t input);
  745. /**
  746. * event logging (incl. secret logging)
  747. */
  748. typedef struct st_ptls_log_event_t {
  749. void (*cb)(struct st_ptls_log_event_t *self, ptls_t *tls, const char *type, const char *fmt, ...)
  750. __attribute__((format(printf, 4, 5)));
  751. } ptls_log_event_t;
  752. /**
  753. * reference counting
  754. */
  755. PTLS_CALLBACK_TYPE(void, update_open_count, ssize_t delta);
  756. /**
  757. * applications that have their own record layer can set this function to derive their own traffic keys from the traffic secret.
  758. * The cipher-suite that is being associated to the connection can be obtained by calling the ptls_get_cipher function.
  759. */
  760. PTLS_CALLBACK_TYPE(int, update_traffic_key, ptls_t *tls, int is_enc, size_t epoch, const void *secret);
  761. /**
  762. * callback for every extension detected during decoding
  763. */
  764. PTLS_CALLBACK_TYPE(int, on_extension, ptls_t *tls, uint8_t hstype, uint16_t exttype, ptls_iovec_t extdata);
  765. /**
  766. *
  767. */
  768. typedef struct st_ptls_decompress_certificate_t {
  769. /**
  770. * list of supported algorithms terminated by UINT16_MAX
  771. */
  772. const uint16_t *supported_algorithms;
  773. /**
  774. * callback that decompresses the message
  775. */
  776. int (*cb)(struct st_ptls_decompress_certificate_t *self, ptls_t *tls, uint16_t algorithm, ptls_iovec_t output,
  777. ptls_iovec_t input);
  778. } ptls_decompress_certificate_t;
  779. /**
  780. * ECH: creates the AEAD context to be used for "Open"-ing inner CH. Given `config_id`, the callback looks up the ECH config and the
  781. * corresponding private key, invokes `ptls_hpke_setup_base_r` with provided `cipher`, `enc`, and `info_prefix` (which will be
  782. * "tls ech" || 00).
  783. */
  784. PTLS_CALLBACK_TYPE(ptls_aead_context_t *, ech_create_opener, ptls_hpke_kem_t **kem, ptls_hpke_cipher_suite_t **cipher, ptls_t *tls,
  785. uint8_t config_id, ptls_hpke_cipher_suite_id_t cipher_id, ptls_iovec_t enc, ptls_iovec_t info_prefix);
  786. /**
  787. * the configuration
  788. */
  789. struct st_ptls_context_t {
  790. /**
  791. * PRNG to be used
  792. */
  793. void (*random_bytes)(void *buf, size_t len);
  794. /**
  795. *
  796. */
  797. ptls_get_time_t *get_time;
  798. /**
  799. * list of supported key-exchange algorithms terminated by NULL
  800. */
  801. ptls_key_exchange_algorithm_t **key_exchanges;
  802. /**
  803. * list of supported cipher-suites terminated by NULL
  804. */
  805. ptls_cipher_suite_t **cipher_suites;
  806. /**
  807. * list of certificates
  808. */
  809. struct {
  810. ptls_iovec_t *list;
  811. size_t count;
  812. } certificates;
  813. /**
  814. * External pre-shared key used for mutual authentication. Unless when using PSK, all the fields must be set to NULL / 0.
  815. */
  816. struct {
  817. ptls_iovec_t identity;
  818. ptls_iovec_t secret;
  819. /**
  820. * (mandatory) hash algorithm associated to the PSK; cipher-suites not sharing the same `ptls_hash_algorithm_t` will be
  821. * ignored
  822. */
  823. ptls_hash_algorithm_t *hash;
  824. } pre_shared_key;
  825. /**
  826. * ECH
  827. */
  828. struct {
  829. struct {
  830. /**
  831. * list of HPKE symmetric cipher-suites (set to NULL to disable ECH altogether)
  832. */
  833. ptls_hpke_cipher_suite_t **ciphers;
  834. /**
  835. * KEMs being supported
  836. */
  837. ptls_hpke_kem_t **kems;
  838. } client;
  839. struct {
  840. /**
  841. * callback that does ECDH key exchange and returns the AEAD context
  842. */
  843. ptls_ech_create_opener_t *create_opener;
  844. /**
  845. * ECHConfigList to be sent to the client when there is mismatch (or when the client sends a grease)
  846. */
  847. ptls_iovec_t retry_configs;
  848. } server;
  849. } ech;
  850. /**
  851. *
  852. */
  853. ptls_on_client_hello_t *on_client_hello;
  854. /**
  855. *
  856. */
  857. ptls_emit_certificate_t *emit_certificate;
  858. /**
  859. *
  860. */
  861. ptls_sign_certificate_t *sign_certificate;
  862. /**
  863. *
  864. */
  865. ptls_verify_certificate_t *verify_certificate;
  866. /**
  867. * lifetime of a session ticket (server-only)
  868. */
  869. uint32_t ticket_lifetime;
  870. /**
  871. * maximum permitted size of early data (server-only)
  872. */
  873. uint32_t max_early_data_size;
  874. /**
  875. * maximum size of the message buffer (default: 0 = unlimited = 3 + 2^24 bytes)
  876. */
  877. size_t max_buffer_size;
  878. /**
  879. * this field is obsolete and ignored
  880. */
  881. const char *hkdf_label_prefix__obsolete;
  882. /**
  883. * if set, psk handshakes use (ec)dhe
  884. */
  885. unsigned require_dhe_on_psk : 1;
  886. /**
  887. * if exporter master secrets should be recorded
  888. */
  889. unsigned use_exporter : 1;
  890. /**
  891. * if ChangeCipherSpec record should be sent during handshake. If the client sends CCS, the server sends one in response
  892. * regardless of the value of this flag. See RFC 8446 Appendix D.3.
  893. */
  894. unsigned send_change_cipher_spec : 1;
  895. /**
  896. * if set, the server requests client certificates to authenticate the client
  897. */
  898. unsigned require_client_authentication : 1;
  899. /**
  900. * if set, EOED will not be emitted or accepted
  901. */
  902. unsigned omit_end_of_early_data : 1;
  903. /**
  904. * This option turns on support for Raw Public Keys (RFC 7250).
  905. *
  906. * When running as a client, this option instructs the client to request the server to send raw public keys in place of X.509
  907. * certificate chain. The client should set its `certificate_verify` callback to one that is capable of validating the raw
  908. * public key that will be sent by the server.
  909. *
  910. * When running as a server, this option instructs the server to only handle clients requesting the use of raw public keys. If
  911. * the client does not, the handshake is rejected. Note however that the rejection happens only after the `on_client_hello`
  912. * callback is being called. Therefore, applications can support both X.509 and raw public keys by swapping `ptls_context_t` to
  913. * the correct one when that callback is being called (like handling swapping the contexts based on the value of SNI).
  914. */
  915. unsigned use_raw_public_keys : 1;
  916. /**
  917. * boolean indicating if the cipher-suite should be chosen based on server's preference
  918. */
  919. unsigned server_cipher_preference : 1;
  920. /**
  921. * boolean indicating if ChaCha20-Poly1305 should be reprioritized to the top of the server cipher list if a ChaCha20-Poly1305
  922. * cipher is at the top of the client cipher list
  923. */
  924. unsigned server_cipher_chacha_priority : 1;
  925. /**
  926. *
  927. */
  928. ptls_encrypt_ticket_t *encrypt_ticket;
  929. /**
  930. *
  931. */
  932. ptls_save_ticket_t *save_ticket;
  933. /**
  934. *
  935. */
  936. ptls_log_event_t *log_event;
  937. /**
  938. *
  939. */
  940. ptls_update_open_count_t *update_open_count;
  941. /**
  942. *
  943. */
  944. ptls_update_traffic_key_t *update_traffic_key;
  945. /**
  946. *
  947. */
  948. ptls_decompress_certificate_t *decompress_certificate;
  949. /**
  950. *
  951. */
  952. ptls_on_extension_t *on_extension;
  953. /**
  954. * (optional) list of supported tls12 cipher-suites terminated by NULL
  955. */
  956. ptls_cipher_suite_t **tls12_cipher_suites;
  957. /**
  958. * (optional) session ID Context to segment resumption
  959. */
  960. struct {
  961. uint8_t bytes[PTLS_SHA256_DIGEST_SIZE];
  962. unsigned is_set : 1;
  963. } ticket_context;
  964. /**
  965. * (optional) list of CAs advertised to clients as supported in the CertificateRequest message; each item must be DNs in DER
  966. * format. The values are sent to the client only when `ptls_context_t::require_client_authentication` is set to true.
  967. */
  968. struct {
  969. const ptls_iovec_t *list;
  970. size_t count;
  971. } client_ca_names;
  972. /**
  973. * (optional)
  974. */
  975. struct {
  976. /**
  977. * if set to non-zero and if the save_ticket callback is provided, a ticket_request extension containing the specified
  978. * values is sent
  979. */
  980. struct {
  981. uint8_t new_session_count;
  982. uint8_t resumption_count;
  983. } client;
  984. /**
  985. * if set to non-zero, the maximum number of tickets being sent is capped to the specifed value; if set to zero, the maximum
  986. * adopted is PTLS_DEFAULT_MAX_TICKETS_TO_SERVE.
  987. */
  988. struct {
  989. uint8_t max_count;
  990. } server;
  991. } ticket_requests;
  992. };
  993. typedef struct st_ptls_raw_extension_t {
  994. uint16_t type;
  995. ptls_iovec_t data;
  996. } ptls_raw_extension_t;
  997. typedef enum en_ptls_early_data_acceptance_t {
  998. PTLS_EARLY_DATA_ACCEPTANCE_UNKNOWN = 0,
  999. PTLS_EARLY_DATA_REJECTED,
  1000. PTLS_EARLY_DATA_ACCEPTED
  1001. } ptls_early_data_acceptance_t;
  1002. /**
  1003. * optional arguments to client-driven handshake
  1004. */
  1005. #ifdef _WINDOWS
  1006. /* suppress warning C4201: nonstandard extension used: nameless struct/union */
  1007. #pragma warning(push)
  1008. #pragma warning(disable : 4201)
  1009. #endif
  1010. typedef struct st_ptls_handshake_properties_t {
  1011. union {
  1012. struct {
  1013. /**
  1014. * list of protocols offered through ALPN
  1015. */
  1016. struct {
  1017. const ptls_iovec_t *list;
  1018. size_t count;
  1019. } negotiated_protocols;
  1020. /**
  1021. * session ticket sent to the application via save_ticket callback
  1022. */
  1023. ptls_iovec_t session_ticket;
  1024. /**
  1025. * pointer to store the maximum size of early-data that can be sent immediately. If set to non-NULL, the first call to
  1026. * ptls_handshake (or ptls_handle_message) will set `*max_early_data` to the value obtained from the session ticket, or
  1027. * to zero if early-data cannot be sent. If NULL, early data will not be used.
  1028. */
  1029. size_t *max_early_data_size;
  1030. /**
  1031. * If early-data has been accepted by peer, or if the state is still unknown. The state changes anytime after handshake
  1032. * keys become available. Applications can peek the tri-state variable every time it calls `ptls_hanshake` or
  1033. * `ptls_handle_message` to determine the result at the earliest moment. This is an output parameter.
  1034. */
  1035. ptls_early_data_acceptance_t early_data_acceptance;
  1036. /**
  1037. * negotiate the key exchange method before sending key_share
  1038. */
  1039. unsigned negotiate_before_key_exchange : 1;
  1040. /**
  1041. * ECH
  1042. */
  1043. struct {
  1044. /**
  1045. * Config offered by server e.g., by HTTPS RR. If config.base is non-NULL but config.len is zero, a grease ECH will
  1046. * be sent, assuming that X25519-SHA256 KEM and SHA256-AES-128-GCM HPKE cipher is available.
  1047. */
  1048. ptls_iovec_t configs;
  1049. /**
  1050. * slot to save the config obtained from server on mismatch; user must free the returned blob by calling `free`
  1051. */
  1052. ptls_iovec_t *retry_configs;
  1053. } ech;
  1054. } client;
  1055. struct {
  1056. /**
  1057. * psk binder being selected (len is set to zero if none)
  1058. */
  1059. struct {
  1060. uint8_t base[PTLS_MAX_DIGEST_SIZE];
  1061. size_t len;
  1062. } selected_psk_binder;
  1063. /**
  1064. * parameters related to use of the Cookie extension
  1065. */
  1066. struct {
  1067. /**
  1068. * HMAC key to protect the integrity of the cookie. The key should be as long as the digest size of the first
  1069. * ciphersuite specified in ptls_context_t (i.e. the hash algorithm of the best ciphersuite that can be chosen).
  1070. */
  1071. const void *key;
  1072. /**
  1073. * additional data to be used for verifying the cookie
  1074. */
  1075. ptls_iovec_t additional_data;
  1076. } cookie;
  1077. /**
  1078. * if HRR should always be sent
  1079. */
  1080. unsigned enforce_retry : 1;
  1081. /**
  1082. * if retry should be stateless (cookie.key MUST be set when this option is used)
  1083. */
  1084. unsigned retry_uses_cookie : 1;
  1085. } server;
  1086. };
  1087. /**
  1088. * an optional list of additional extensions to send either in CH or EE, terminated by type == UINT16_MAX
  1089. */
  1090. ptls_raw_extension_t *additional_extensions;
  1091. /**
  1092. * an optional callback that returns a boolean value indicating if a particular extension should be collected
  1093. */
  1094. int (*collect_extension)(ptls_t *tls, struct st_ptls_handshake_properties_t *properties, uint16_t type);
  1095. /**
  1096. * an optional callback that reports the extensions being collected
  1097. */
  1098. int (*collected_extensions)(ptls_t *tls, struct st_ptls_handshake_properties_t *properties, ptls_raw_extension_t *extensions);
  1099. } ptls_handshake_properties_t;
  1100. #ifdef _WINDOWS
  1101. #pragma warning(pop)
  1102. #endif
  1103. #ifdef _WINDOWS
  1104. /* suppress warning C4293: >> shift count negative or too big */
  1105. #pragma warning(disable : 4293)
  1106. #endif
  1107. /**
  1108. * builds a new ptls_iovec_t instance using the supplied parameters
  1109. */
  1110. static ptls_iovec_t ptls_iovec_init(const void *p, size_t len);
  1111. /**
  1112. * initializes a buffer, setting the default destination to the small buffer provided as the argument.
  1113. */
  1114. static void ptls_buffer_init(ptls_buffer_t *buf, void *smallbuf, size_t smallbuf_size);
  1115. /**
  1116. * disposes a buffer, freeing resources allocated by the buffer itself (if any)
  1117. */
  1118. static void ptls_buffer_dispose(ptls_buffer_t *buf);
  1119. /**
  1120. * internal
  1121. */
  1122. void ptls_buffer__release_memory(ptls_buffer_t *buf);
  1123. /**
  1124. * reserves space for additional amount of memory
  1125. */
  1126. int ptls_buffer_reserve(ptls_buffer_t *buf, size_t delta);
  1127. /**
  1128. * reserves space for additional amount of memory, requiring `buf->base` to follow specified alignment
  1129. */
  1130. int ptls_buffer_reserve_aligned(ptls_buffer_t *buf, size_t delta, uint8_t align_bits);
  1131. /**
  1132. * internal
  1133. */
  1134. int ptls_buffer__do_pushv(ptls_buffer_t *buf, const void *src, size_t len);
  1135. /**
  1136. * internal
  1137. */
  1138. int ptls_buffer__adjust_quic_blocksize(ptls_buffer_t *buf, size_t body_size);
  1139. /**
  1140. * internal
  1141. */
  1142. int ptls_buffer__adjust_asn1_blocksize(ptls_buffer_t *buf, size_t body_size);
  1143. /**
  1144. * pushes an unsigned bigint
  1145. */
  1146. int ptls_buffer_push_asn1_ubigint(ptls_buffer_t *buf, const void *bignum, size_t size);
  1147. /**
  1148. * encodes a quic varint (maximum length is PTLS_ENCODE_QUICINT_CAPACITY)
  1149. */
  1150. static uint8_t *ptls_encode_quicint(uint8_t *p, uint64_t v);
  1151. #define PTLS_ENCODE_QUICINT_CAPACITY 8
  1152. #define PTLS_QUICINT_MAX 4611686018427387903 // (1 << 62) - 1
  1153. #define PTLS_QUICINT_LONGEST_STR "4611686018427387903"
  1154. #define ptls_buffer_pushv(buf, src, len) \
  1155. do { \
  1156. if ((ret = ptls_buffer__do_pushv((buf), (src), (len))) != 0) \
  1157. goto Exit; \
  1158. } while (0)
  1159. #define ptls_buffer_push(buf, ...) \
  1160. do { \
  1161. if ((ret = ptls_buffer__do_pushv((buf), (uint8_t[]){__VA_ARGS__}, sizeof((uint8_t[]){__VA_ARGS__}))) != 0) \
  1162. goto Exit; \
  1163. } while (0)
  1164. #define ptls_buffer_push16(buf, v) \
  1165. do { \
  1166. uint16_t _v = (v); \
  1167. ptls_buffer_push(buf, (uint8_t)(_v >> 8), (uint8_t)_v); \
  1168. } while (0)
  1169. #define ptls_buffer_push24(buf, v) \
  1170. do { \
  1171. uint32_t _v = (v); \
  1172. ptls_buffer_push(buf, (uint8_t)(_v >> 16), (uint8_t)(_v >> 8), (uint8_t)_v); \
  1173. } while (0)
  1174. #define ptls_buffer_push32(buf, v) \
  1175. do { \
  1176. uint32_t _v = (v); \
  1177. ptls_buffer_push(buf, (uint8_t)(_v >> 24), (uint8_t)(_v >> 16), (uint8_t)(_v >> 8), (uint8_t)_v); \
  1178. } while (0)
  1179. #define ptls_buffer_push64(buf, v) \
  1180. do { \
  1181. uint64_t _v = (v); \
  1182. ptls_buffer_push(buf, (uint8_t)(_v >> 56), (uint8_t)(_v >> 48), (uint8_t)(_v >> 40), (uint8_t)(_v >> 32), \
  1183. (uint8_t)(_v >> 24), (uint8_t)(_v >> 16), (uint8_t)(_v >> 8), (uint8_t)_v); \
  1184. } while (0)
  1185. #define ptls_buffer_push_quicint(buf, v) \
  1186. do { \
  1187. if ((ret = ptls_buffer_reserve((buf), PTLS_ENCODE_QUICINT_CAPACITY)) != 0) \
  1188. goto Exit; \
  1189. uint8_t *d = ptls_encode_quicint((buf)->base + (buf)->off, (v)); \
  1190. (buf)->off = d - (buf)->base; \
  1191. } while (0)
  1192. #define ptls_buffer_push_block(buf, _capacity, block) \
  1193. do { \
  1194. size_t capacity = (_capacity); \
  1195. ptls_buffer_pushv((buf), (uint8_t *)"\0\0\0\0\0\0\0", capacity != -1 ? capacity : 1); \
  1196. size_t body_start = (buf)->off; \
  1197. do { \
  1198. block \
  1199. } while (0); \
  1200. size_t body_size = (buf)->off - body_start; \
  1201. if (capacity != -1) { \
  1202. if (capacity < sizeof(size_t) && body_size >= (size_t)1 << (capacity * 8)) { \
  1203. ret = PTLS_ERROR_BLOCK_OVERFLOW; \
  1204. goto Exit; \
  1205. } \
  1206. for (; capacity != 0; --capacity) \
  1207. (buf)->base[body_start - capacity] = (uint8_t)(body_size >> (8 * (capacity - 1))); \
  1208. } else { \
  1209. if ((ret = ptls_buffer__adjust_quic_blocksize((buf), body_size)) != 0) \
  1210. goto Exit; \
  1211. } \
  1212. } while (0)
  1213. #define ptls_buffer_push_asn1_block(buf, block) \
  1214. do { \
  1215. ptls_buffer_push((buf), 0xff); /* dummy */ \
  1216. size_t body_start = (buf)->off; \
  1217. do { \
  1218. block \
  1219. } while (0); \
  1220. size_t body_size = (buf)->off - body_start; \
  1221. if (body_size < 128) { \
  1222. (buf)->base[body_start - 1] = (uint8_t)body_size; \
  1223. } else { \
  1224. if ((ret = ptls_buffer__adjust_asn1_blocksize((buf), body_size)) != 0) \
  1225. goto Exit; \
  1226. } \
  1227. } while (0)
  1228. #define ptls_buffer_push_asn1_sequence(buf, block) \
  1229. do { \
  1230. ptls_buffer_push((buf), 0x30); \
  1231. ptls_buffer_push_asn1_block((buf), block); \
  1232. } while (0)
  1233. #define ptls_buffer_push_message_body(buf, key_sched, type, block) \
  1234. do { \
  1235. ptls_buffer_t *_buf = (buf); \
  1236. ptls_key_schedule_t *_key_sched = (key_sched); \
  1237. size_t mess_start = _buf->off; \
  1238. ptls_buffer_push(_buf, (type)); \
  1239. ptls_buffer_push_block(_buf, 3, block); \
  1240. if (_key_sched != NULL) \
  1241. ptls__key_schedule_update_hash(_key_sched, _buf->base + mess_start, _buf->off - mess_start, 0); \
  1242. } while (0)
  1243. #define ptls_push_message(emitter, key_sched, type, block) \
  1244. do { \
  1245. ptls_message_emitter_t *_emitter = (emitter); \
  1246. if ((ret = _emitter->begin_message(_emitter)) != 0) \
  1247. goto Exit; \
  1248. ptls_buffer_push_message_body(_emitter->buf, (key_sched), (type), block); \
  1249. if ((ret = _emitter->commit_message(_emitter)) != 0) \
  1250. goto Exit; \
  1251. } while (0)
  1252. int ptls_decode8(uint8_t *value, const uint8_t **src, const uint8_t *end);
  1253. int ptls_decode16(uint16_t *value, const uint8_t **src, const uint8_t *end);
  1254. int ptls_decode24(uint32_t *value, const uint8_t **src, const uint8_t *end);
  1255. int ptls_decode32(uint32_t *value, const uint8_t **src, const uint8_t *end);
  1256. int ptls_decode64(uint64_t *value, const uint8_t **src, const uint8_t *end);
  1257. uint64_t ptls_decode_quicint(const uint8_t **src, const uint8_t *end);
  1258. #define ptls_decode_open_block(src, end, capacity, block) \
  1259. do { \
  1260. size_t _capacity = (capacity); \
  1261. size_t _block_size; \
  1262. if (_capacity == -1) { \
  1263. uint64_t _block_size64; \
  1264. const uint8_t *_src = (src); \
  1265. if ((_block_size64 = ptls_decode_quicint(&_src, end)) == UINT64_MAX || \
  1266. (sizeof(size_t) < 8 && (_block_size64 >> (8 * sizeof(size_t))) != 0)) { \
  1267. ret = PTLS_ALERT_DECODE_ERROR; \
  1268. goto Exit; \
  1269. } \
  1270. (src) = _src; \
  1271. _block_size = (size_t)_block_size64; \
  1272. } else { \
  1273. if (_capacity > (size_t)(end - (src))) { \
  1274. ret = PTLS_ALERT_DECODE_ERROR; \
  1275. goto Exit; \
  1276. } \
  1277. _block_size = 0; \
  1278. do { \
  1279. _block_size = _block_size << 8 | *(src)++; \
  1280. } while (--_capacity != 0); \
  1281. } \
  1282. if (_block_size > (size_t)(end - (src))) { \
  1283. ret = PTLS_ALERT_DECODE_ERROR; \
  1284. goto Exit; \
  1285. } \
  1286. do { \
  1287. const uint8_t *const end = (src) + _block_size; \
  1288. do { \
  1289. block \
  1290. } while (0); \
  1291. if ((src) != end) { \
  1292. ret = PTLS_ALERT_DECODE_ERROR; \
  1293. goto Exit; \
  1294. } \
  1295. } while (0); \
  1296. } while (0)
  1297. #define ptls_decode_assert_block_close(src, end) \
  1298. do { \
  1299. if ((src) != end) { \
  1300. ret = PTLS_ALERT_DECODE_ERROR; \
  1301. goto Exit; \
  1302. } \
  1303. } while (0);
  1304. #define ptls_decode_block(src, end, capacity, block) \
  1305. do { \
  1306. ptls_decode_open_block((src), end, capacity, block); \
  1307. ptls_decode_assert_block_close((src), end); \
  1308. } while (0)
  1309. #if PTLS_HAVE_LOG
  1310. #define PTLS_LOG__DO_LOG(module, name, conn_state, get_sni, get_sni_arg, add_time, block) \
  1311. do { \
  1312. int ptlslog_include_appdata = 0; \
  1313. do { \
  1314. ptls_log__do_write_start(&logpoint, (add_time)); \
  1315. do { \
  1316. block \
  1317. } while (0); \
  1318. ptlslog_include_appdata = \
  1319. ptls_log__do_write_end(&logpoint, (conn_state), (get_sni), (get_sni_arg), ptlslog_include_appdata); \
  1320. } while (PTLS_UNLIKELY(ptlslog_include_appdata)); \
  1321. } while (0)
  1322. #else
  1323. #define PTLS_LOG__DO_LOG(module, name, conn_state, get_sni, get_sni_arg, add_time, block) /* don't generate code */
  1324. #endif
  1325. #define PTLS_LOG_DEFINE_POINT(_module, _name, _var) \
  1326. static struct st_ptls_log_point_t _var = {.name = PTLS_TO_STR(_module) ":" PTLS_TO_STR(_name)}
  1327. #define PTLS_LOG(module, name, block) \
  1328. do { \
  1329. PTLS_LOG_DEFINE_POINT(module, name, logpoint); \
  1330. if (PTLS_LIKELY(ptls_log_point_maybe_active(&logpoint) == 0)) \
  1331. break; \
  1332. PTLS_LOG__DO_LOG(module, name, NULL, NULL, NULL, 1, {block}); \
  1333. } while (0)
  1334. #define PTLS_LOG_CONN(name, tls, block) \
  1335. do { \
  1336. PTLS_LOG_DEFINE_POINT(picotls, name, logpoint); \
  1337. uint32_t active = ptls_log_point_maybe_active(&logpoint); \
  1338. if (PTLS_LIKELY(active == 0)) \
  1339. break; \
  1340. ptls_t *_tls = (tls); \
  1341. ptls_log_conn_state_t *conn_state = ptls_get_log_state(_tls); \
  1342. active &= ptls_log_conn_maybe_active(conn_state, (const char *(*)(void *))ptls_get_server_name, _tls); \
  1343. if (PTLS_LIKELY(active == 0)) \
  1344. break; \
  1345. PTLS_LOG__DO_LOG(picotls, name, conn_state, (const char *(*)(void *))ptls_get_server_name, _tls, 1, { \
  1346. PTLS_LOG_ELEMENT_PTR(tls, _tls); \
  1347. do { \
  1348. block \
  1349. } while (0); \
  1350. }); \
  1351. } while (0)
  1352. #define PTLS_LOG__ELEMENT_PREFIX_CORE(lit) ",\"" lit "\":"
  1353. #define PTLS_LOG__ELEMENT_PREFIX(lit) PTLS_LOG__ELEMENT_PREFIX_CORE(lit), sizeof(PTLS_LOG__ELEMENT_PREFIX_CORE(lit)) - 1
  1354. #define PTLS_LOG_ELEMENT_SAFESTR(name, value) \
  1355. do { \
  1356. const char *value_ = (value); \
  1357. ptls_log__do_push_element_safestr(PTLS_LOG__ELEMENT_PREFIX(PTLS_TO_STR(name)), (value_), strlen(value_)); \
  1358. } while (0)
  1359. #define PTLS_LOG_ELEMENT_UNSAFESTR(name, value, value_len) \
  1360. ptls_log__do_push_element_unsafestr(PTLS_LOG__ELEMENT_PREFIX(PTLS_TO_STR(name)), (value), (value_len))
  1361. #define PTLS_LOG_ELEMENT_HEXDUMP(name, value, value_len) \
  1362. ptls_log__do_push_element_hexdump(PTLS_LOG__ELEMENT_PREFIX(PTLS_TO_STR(name)), (value), (value_len))
  1363. #define PTLS_LOG_ELEMENT_PTR(name, value) PTLS_LOG_ELEMENT_UNSIGNED(name, (uint64_t)(value))
  1364. #define PTLS_LOG_ELEMENT_SIGNED(name, value) \
  1365. do { \
  1366. if (sizeof(value) <= sizeof(int32_t)) { \
  1367. ptls_log__do_push_element_signed32(PTLS_LOG__ELEMENT_PREFIX(PTLS_TO_STR(name)), (value)); \
  1368. } else { \
  1369. ptls_log__do_push_element_signed64(PTLS_LOG__ELEMENT_PREFIX(PTLS_TO_STR(name)), (value)); \
  1370. } \
  1371. } while (0)
  1372. #define PTLS_LOG__DO_ELEMENT_UNSIGNED(lit, value) \
  1373. do { \
  1374. if (sizeof(value) <= sizeof(uint32_t)) { \
  1375. ptls_log__do_push_element_unsigned32(PTLS_LOG__ELEMENT_PREFIX(lit), (value)); \
  1376. } else { \
  1377. ptls_log__do_push_element_unsigned64(PTLS_LOG__ELEMENT_PREFIX(lit), (value)); \
  1378. } \
  1379. } while (0)
  1380. #define PTLS_LOG_ELEMENT_UNSIGNED(name, value) PTLS_LOG__DO_ELEMENT_UNSIGNED(PTLS_TO_STR(name), (value))
  1381. #define PTLS_LOG_ELEMENT_BOOL(name, value) ptls_log__do_push_element_bool(PTLS_LOG__ELEMENT_PREFIX(PTLS_TO_STR(name)), (value))
  1382. #define PTLS_LOG_APPDATA_ELEMENT_UNSAFESTR(name, value, value_len) \
  1383. do { \
  1384. if (ptlslog_include_appdata) { \
  1385. PTLS_LOG_ELEMENT_UNSAFESTR(name, value, value_len); \
  1386. } else { \
  1387. PTLS_LOG__DO_ELEMENT_UNSIGNED(PTLS_TO_STR(name) "_len", value_len); \
  1388. } \
  1389. } while (0)
  1390. #define PTLS_LOG_APPDATA_ELEMENT_HEXDUMP(name, value, value_len) \
  1391. do { \
  1392. if (ptlslog_include_appdata) { \
  1393. PTLS_LOG_ELEMENT_HEXDUMP(name, value, value_len); \
  1394. } else { \
  1395. PTLS_LOG__DO_ELEMENT_UNSIGNED(PTLS_TO_STR(name) "_len", value_len); \
  1396. } \
  1397. } while (0)
  1398. /**
  1399. * retains a list of connections that are bound to the object
  1400. */
  1401. struct st_ptls_log_state_t {
  1402. /**
  1403. * bit array of connections (1 is active)
  1404. */
  1405. uint32_t active_conns;
  1406. /**
  1407. * generation counter used for staleness check; see `ptls_log._generation`
  1408. */
  1409. uint64_t generation;
  1410. };
  1411. /**
  1412. * represents a log point identified by name (`module:type`)
  1413. */
  1414. struct st_ptls_log_point_t {
  1415. const char *name;
  1416. struct st_ptls_log_state_t state;
  1417. };
  1418. /**
  1419. * represents a logging state of each connection
  1420. */
  1421. typedef struct st_ptls_log_conn_state_t {
  1422. /**
  1423. * random value between 0 (inclusive) and 1 (non-inclusive) used to determine the ratio of sampling-based logging; see
  1424. * `ptls_add_fd'`. To disable logging entirely, use `ptls_log.dummy_conn_state`, or set the value exactly to 1.
  1425. */
  1426. float random_;
  1427. /**
  1428. * represents peer address; ipv4 addresses are stored using the mapped form (::ffff:192.0.2.1)
  1429. */
  1430. struct in6_addr address;
  1431. struct st_ptls_log_state_t state;
  1432. } ptls_log_conn_state_t;
  1433. /**
  1434. * see `ptls_get_log_state`
  1435. */
  1436. extern PTLS_THREADLOCAL ptls_log_conn_state_t *ptls_log_conn_state_override;
  1437. /**
  1438. * global variables exposed
  1439. */
  1440. extern struct st_ptls_log_t {
  1441. /**
  1442. * if application-data (e.g., payload) should be emitted as well
  1443. */
  1444. volatile unsigned may_include_appdata : 1;
  1445. /**
  1446. * endpoints that want to disable logging entirely can provide this value to the loggers
  1447. */
  1448. ptls_log_conn_state_t dummy_conn_state;
  1449. /**
  1450. * generation counter that is incremented whenever the state of loggers change; see `st_ptls_log_state_t::generation`
  1451. */
  1452. volatile uint64_t _generation;
  1453. } ptls_log;
  1454. /**
  1455. * initializes a ptls_log_conn_state_t
  1456. */
  1457. void ptls_log_init_conn_state(ptls_log_conn_state_t *state, void (*random_bytes)(void *, size_t));
  1458. /**
  1459. * forces recalculation of the log state (should be called when SNI is determined)
  1460. */
  1461. static void ptls_log_recalc_conn_state(ptls_log_conn_state_t *state);
  1462. /**
  1463. * returns a bitmap indicating the loggers active for given log point
  1464. */
  1465. static uint32_t ptls_log_point_maybe_active(struct st_ptls_log_point_t *point);
  1466. /**
  1467. * returns a bitmap indicating the loggers active for given connection
  1468. */
  1469. static uint32_t ptls_log_conn_maybe_active(ptls_log_conn_state_t *conn, const char *(*get_sni)(void *), void *get_sni_arg);
  1470. /**
  1471. * Returns the number of log events that were unable to be emitted.
  1472. */
  1473. size_t ptls_log_num_lost(void);
  1474. /**
  1475. * Registers an fd to the logger. A registered fd is automatically closed and removed when it is closed by the peer.
  1476. * @param sample_ratio sampling ratio between 0 and 1
  1477. * @param points list of points to log, in the form of p1\0p2\0\0 (i.e., concatenated list of C strings with an empty string
  1478. * marking the end). An empty list means attach to all.
  1479. * @param snis list of SNIs to log, using the same form as points
  1480. * @param addresses list of IPv4/v6 addresses to log, using the same form as points
  1481. */
  1482. int ptls_log_add_fd(int fd, float sample_ratio, const char *points, const char *snis, const char *addresses, int appdata);
  1483. void ptls_log__recalc_point(int caller_locked, struct st_ptls_log_point_t *point);
  1484. void ptls_log__recalc_conn(int caller_locked, struct st_ptls_log_conn_state_t *conn, const char *(*get_sni)(void *),
  1485. void *get_sni_arg);
  1486. void ptls_log__do_push_element_safestr(const char *prefix, size_t prefix_len, const char *s, size_t l);
  1487. void ptls_log__do_push_element_unsafestr(const char *prefix, size_t prefix_len, const char *s, size_t l);
  1488. void ptls_log__do_push_element_hexdump(const char *prefix, size_t prefix_len, const void *s, size_t l);
  1489. void ptls_log__do_push_element_signed32(const char *prefix, size_t prefix_len, int32_t v);
  1490. void ptls_log__do_push_element_signed64(const char *prefix, size_t prefix_len, int64_t v);
  1491. void ptls_log__do_push_element_unsigned32(const char *prefix, size_t prefix_len, uint32_t v);
  1492. void ptls_log__do_push_element_unsigned64(const char *prefix, size_t prefix_len, uint64_t v);
  1493. void ptls_log__do_push_element_bool(const char *prefix, size_t prefix_len, int v);
  1494. void ptls_log__do_push_appdata_element_unsafestr(int includes_appdata, const char *prefix, size_t prefix_len, const char *s,
  1495. size_t l);
  1496. void ptls_log__do_push_appdata_element_hexdump(int includes_appdata, const char *prefix, size_t prefix_len, const void *s,
  1497. size_t l);
  1498. void ptls_log__do_write_start(struct st_ptls_log_point_t *point, int add_time);
  1499. int ptls_log__do_write_end(struct st_ptls_log_point_t *point, struct st_ptls_log_conn_state_t *conn, const char *(*get_sni)(void *),
  1500. void *get_sni_arg, int includes_appdata);
  1501. /**
  1502. * create a client object to handle new TLS connection
  1503. */
  1504. ptls_t *ptls_client_new(ptls_context_t *ctx);
  1505. /**
  1506. * create a server object to handle new TLS connection
  1507. */
  1508. ptls_t *ptls_server_new(ptls_context_t *ctx);
  1509. /**
  1510. * creates an object handle new TLS connection
  1511. */
  1512. static ptls_t *ptls_new(ptls_context_t *ctx, int is_server);
  1513. /**
  1514. * creates TLS 1.2 record layer for post-handshake communication
  1515. */
  1516. int ptls_build_tls12_export_params(ptls_context_t *ctx, ptls_buffer_t *output, int is_server, int session_reused,
  1517. ptls_cipher_suite_t *cipher, const void *master_secret, const void *hello_randoms,
  1518. uint64_t next_send_record_iv, const char *server_name, ptls_iovec_t negotiated_protocol);
  1519. /**
  1520. * store the parameters of a post-handshake TLS connection so that it can be reconstructed later
  1521. */
  1522. int ptls_export(ptls_t *tls, ptls_buffer_t *output);
  1523. /**
  1524. * create a post-handshake TLS connection object using given parameters
  1525. */
  1526. int ptls_import(ptls_context_t *ctx, ptls_t **tls, ptls_iovec_t params);
  1527. /**
  1528. * releases all resources associated to the object
  1529. */
  1530. void ptls_free(ptls_t *tls);
  1531. /**
  1532. * returns address of the crypto callbacks that the connection is using
  1533. */
  1534. ptls_context_t *ptls_get_context(ptls_t *tls);
  1535. /**
  1536. * updates the context of a connection. Can be called from `on_client_hello` callback.
  1537. */
  1538. void ptls_set_context(ptls_t *tls, ptls_context_t *ctx);
  1539. /**
  1540. * get the signature context
  1541. */
  1542. ptls_async_job_t *ptls_get_async_job(ptls_t *tls);
  1543. /**
  1544. * returns the client-random
  1545. */
  1546. ptls_iovec_t ptls_get_client_random(ptls_t *tls);
  1547. /**
  1548. * returns the cipher-suite being used
  1549. */
  1550. ptls_cipher_suite_t *ptls_get_cipher(ptls_t *tls);
  1551. /**
  1552. * returns a supported cipher-suite given an id
  1553. */
  1554. ptls_cipher_suite_t *ptls_find_cipher_suite(ptls_cipher_suite_t **cipher_suites, uint16_t id);
  1555. /**
  1556. * Returns protocol version (e.g., 0x0303 for TLS 1.2, 0x0304 for TLS 1.3). The result may be unstable prior to handshake
  1557. * completion.
  1558. */
  1559. uint16_t ptls_get_protocol_version(ptls_t *tls);
  1560. /**
  1561. * Returns current state of traffic keys. The cipher-suite being used, as well as the length of the traffic keys, can be obtained
  1562. * via `ptls_get_cipher`.
  1563. * TODO: Even in case of offloading just the TX side, there should be API for handling key updates, sending Close aleart.
  1564. */
  1565. int ptls_get_traffic_keys(ptls_t *tls, int is_enc, uint8_t *key, uint8_t *iv, uint64_t *seq);
  1566. /**
  1567. * returns the server-name (NULL if SNI is not used or failed to negotiate)
  1568. */
  1569. const char *ptls_get_server_name(ptls_t *tls);
  1570. /**
  1571. * sets the server-name associated to the TLS connection. If server_name_len is zero, then strlen(server_name) is called to
  1572. * determine the length of the name.
  1573. * On the client-side, the value is used for certificate validation. The value will be also sent as an SNI extension, if it looks
  1574. * like a DNS name.
  1575. * On the server-side, it can be called from on_client_hello to indicate the acceptance of the SNI extension to the client.
  1576. */
  1577. int ptls_set_server_name(ptls_t *tls, const char *server_name, size_t server_name_len);
  1578. /**
  1579. * returns the negotiated protocol (or NULL)
  1580. */
  1581. const char *ptls_get_negotiated_protocol(ptls_t *tls);
  1582. /**
  1583. * sets the negotiated protocol. If protocol_len is zero, strlen(protocol) is called to determine the length of the protocol name.
  1584. */
  1585. int ptls_set_negotiated_protocol(ptls_t *tls, const char *protocol, size_t protocol_len);
  1586. /**
  1587. * returns if the handshake has been completed
  1588. */
  1589. int ptls_handshake_is_complete(ptls_t *tls);
  1590. /**
  1591. * returns if a PSK (or PSK-DHE) handshake was performed
  1592. */
  1593. int ptls_is_psk_handshake(ptls_t *tls);
  1594. /**
  1595. * return if a ECH handshake was performed, as well as optionally the kem and cipher-suite being used
  1596. * FIXME: this function always return false when the TLS session is exported and imported
  1597. */
  1598. int ptls_is_ech_handshake(ptls_t *tls, uint8_t *config_id, ptls_hpke_kem_t **kem, ptls_hpke_cipher_suite_t **cipher);
  1599. /**
  1600. * returns a pointer to user data pointer (client is reponsible for freeing the associated data prior to calling ptls_free)
  1601. */
  1602. void **ptls_get_data_ptr(ptls_t *tls);
  1603. /**
  1604. * Returns `ptls_log_conn_state_t` of `ptls_t`. By default, the state is initialized by calling `ptls_log_init_conn_state`, but the
  1605. * behavior can be overidden by setting `ptls_log_conn_state_override`.
  1606. * This value can be changed by setting `ptls_log_random_override` or by calling `ptls_set_log_random`.
  1607. */
  1608. ptls_log_conn_state_t *ptls_get_log_state(ptls_t *tls);
  1609. /**
  1610. * proceeds with the handshake, optionally taking some input from peer. The function returns zero in case the handshake completed
  1611. * successfully. PTLS_ERROR_IN_PROGRESS is returned in case the handshake is incomplete. Otherwise, an error value is returned. The
  1612. * contents of sendbuf should be sent to the client, regardless of whether if an error is returned. inlen is an argument used for
  1613. * both input and output. As an input, the arguments takes the size of the data available as input. Upon return the value is updated
  1614. * to the number of bytes consumed by the handshake. In case the returned value is PTLS_ERROR_IN_PROGRESS there is a guarantee that
  1615. * all the input are consumed (i.e. the value of inlen does not change).
  1616. */
  1617. int ptls_handshake(ptls_t *tls, ptls_buffer_t *sendbuf, const void *input, size_t *inlen, ptls_handshake_properties_t *args);
  1618. /**
  1619. * decrypts the first record within given buffer
  1620. */
  1621. int ptls_receive(ptls_t *tls, ptls_buffer_t *plaintextbuf, const void *input, size_t *len);
  1622. /**
  1623. * encrypts given buffer into multiple TLS records
  1624. */
  1625. int ptls_send(ptls_t *tls, ptls_buffer_t *sendbuf, const void *input, size_t inlen);
  1626. /**
  1627. * updates the send traffic key (as well as asks the peer to update)
  1628. */
  1629. int ptls_update_key(ptls_t *tls, int request_update);
  1630. /**
  1631. * Returns if the context is a server context.
  1632. */
  1633. int ptls_is_server(ptls_t *tls);
  1634. /**
  1635. * returns per-record overhead
  1636. */
  1637. size_t ptls_get_record_overhead(ptls_t *tls);
  1638. /**
  1639. * sends an alert
  1640. */
  1641. int ptls_send_alert(ptls_t *tls, ptls_buffer_t *sendbuf, uint8_t level, uint8_t description);
  1642. /**
  1643. *
  1644. */
  1645. int ptls_export_secret(ptls_t *tls, void *output, size_t outlen, const char *label, ptls_iovec_t context_value, int is_early);
  1646. /**
  1647. * build the body of a Certificate message. Can be called with tls set to NULL in order to create a precompressed message.
  1648. */
  1649. int ptls_build_certificate_message(ptls_buffer_t *buf, ptls_iovec_t request_context, ptls_iovec_t *certificates,
  1650. size_t num_certificates, ptls_iovec_t ocsp_status);
  1651. /**
  1652. *
  1653. */
  1654. int ptls_calc_hash(ptls_hash_algorithm_t *algo, void *output, const void *src, size_t len);
  1655. /**
  1656. *
  1657. */
  1658. ptls_hash_context_t *ptls_hmac_create(ptls_hash_algorithm_t *algo, const void *key, size_t key_size);
  1659. /**
  1660. *
  1661. */
  1662. int ptls_hkdf_extract(ptls_hash_algorithm_t *hash, void *output, ptls_iovec_t salt, ptls_iovec_t ikm);
  1663. /**
  1664. *
  1665. */
  1666. int ptls_hkdf_expand(ptls_hash_algorithm_t *hash, void *output, size_t outlen, ptls_iovec_t prk, ptls_iovec_t info);
  1667. /**
  1668. *
  1669. */
  1670. int ptls_hkdf_expand_label(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
  1671. ptls_iovec_t hash_value, const char *label_prefix);
  1672. /**
  1673. * The expansion function of TLS 1.2 defined in RFC 5426 section 5. When `label` is NULL, acts as P_<hash>, or if non-NULL, as PRF.
  1674. */
  1675. int ptls_tls12_phash(ptls_hash_algorithm_t *algo, void *output, size_t outlen, ptls_iovec_t secret, const char *label,
  1676. ptls_iovec_t seed);
  1677. /**
  1678. * instantiates a symmetric cipher
  1679. */
  1680. ptls_cipher_context_t *ptls_cipher_new(ptls_cipher_algorithm_t *algo, int is_enc, const void *key);
  1681. /**
  1682. * destroys a symmetric cipher
  1683. */
  1684. void ptls_cipher_free(ptls_cipher_context_t *ctx);
  1685. /**
  1686. * initializes the IV; this function must be called prior to calling ptls_cipher_encrypt
  1687. */
  1688. static void ptls_cipher_init(ptls_cipher_context_t *ctx, const void *iv);
  1689. /**
  1690. * Encrypts given text. The function must be used in a way that the output length would be equal to the input length. For example,
  1691. * when using a block cipher in ECB mode, `len` must be a multiple of the block size when using a block cipher. The length can be
  1692. * of any value when using a stream cipher or a block cipher in CTR mode.
  1693. */
  1694. static void ptls_cipher_encrypt(ptls_cipher_context_t *ctx, void *output, const void *input, size_t len);
  1695. /**
  1696. * instantiates an AEAD cipher given a secret, which is expanded using hkdf to a set of key and iv
  1697. * @param aead
  1698. * @param hash
  1699. * @param is_enc 1 if creating a context for encryption, 0 if creating a context for decryption
  1700. * @param secret the secret. The size must be the digest length of the hash algorithm
  1701. * @return pointer to an AEAD context if successful, otherwise NULL
  1702. */
  1703. ptls_aead_context_t *ptls_aead_new(ptls_aead_algorithm_t *aead, ptls_hash_algorithm_t *hash, int is_enc, const void *secret,
  1704. const char *label_prefix);
  1705. /**
  1706. * instantiates an AEAD cipher given key and iv
  1707. * @param aead
  1708. * @param is_enc 1 if creating a context for encryption, 0 if creating a context for decryption
  1709. * @return pointer to an AEAD context if successful, otherwise NULL
  1710. */
  1711. ptls_aead_context_t *ptls_aead_new_direct(ptls_aead_algorithm_t *aead, int is_enc, const void *key, const void *iv);
  1712. /**
  1713. * destroys an AEAD cipher context
  1714. */
  1715. void ptls_aead_free(ptls_aead_context_t *ctx);
  1716. /**
  1717. * Permutes the static IV by applying given bytes using bit-wise XOR. This API can be used for supplying nonces longer than 64-
  1718. * bits.
  1719. */
  1720. void ptls_aead_xor_iv(ptls_aead_context_t *ctx, const void *bytes, size_t len);
  1721. static void ptls_aead_get_iv(ptls_aead_context_t *ctx, void *iv);
  1722. static void ptls_aead_set_iv(ptls_aead_context_t *ctx, const void *iv);
  1723. /**
  1724. * Encrypts one AEAD block, given input and output vectors.
  1725. */
  1726. static size_t ptls_aead_encrypt(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1727. const void *aad, size_t aadlen);
  1728. /**
  1729. * Encrypts one AEAD block, as well as one block of ECB (for QUIC / DTLS packet number encryption). Depending on the AEAD engine
  1730. * being used, the two operations might run simultaneously.
  1731. */
  1732. static void ptls_aead_encrypt_s(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1733. const void *aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp);
  1734. /**
  1735. * Encrypts one AEAD block, given a vector of vectors.
  1736. */
  1737. static void ptls_aead_encrypt_v(ptls_aead_context_t *ctx, void *output, ptls_iovec_t *input, size_t incnt, uint64_t seq,
  1738. const void *aad, size_t aadlen);
  1739. /**
  1740. * Obsolete; new applications should use one of: `ptls_aead_encrypt`, `ptls_aead_encrypt_s`, `ptls_aead_encrypt_v`.
  1741. */
  1742. static void ptls_aead_encrypt_init(ptls_aead_context_t *ctx, uint64_t seq, const void *aad, size_t aadlen);
  1743. /**
  1744. * Obsolete; see `ptls_aead_encrypt_init`.
  1745. */
  1746. static size_t ptls_aead_encrypt_update(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen);
  1747. /**
  1748. * Obsolete; see `ptls_aead_encrypt_init`.
  1749. */
  1750. static size_t ptls_aead_encrypt_final(ptls_aead_context_t *ctx, void *output);
  1751. /**
  1752. * decrypts an AEAD record
  1753. * @return number of bytes emitted to output if successful, or SIZE_MAX if the input is invalid (e.g. broken MAC)
  1754. */
  1755. static size_t ptls_aead_decrypt(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1756. const void *aad, size_t aadlen);
  1757. /**
  1758. * Return the current read epoch (i.e., that of the message being received or to be)
  1759. */
  1760. size_t ptls_get_read_epoch(ptls_t *tls);
  1761. /**
  1762. * Runs the handshake by dealing directly with handshake messages. Callers MUST delay supplying input to this function until the
  1763. * epoch of the input becomes equal to the value returned by `ptls_get_read_epoch()`.
  1764. * @param tls the TLS context
  1765. * @param sendbuf buffer to which the output will be written
  1766. * @param epoch_offsets start and end offset of the messages in each epoch. For example, when the server emits ServerHello between
  1767. * offset 0 and 38, the following handshake messages between offset 39 and 348, and a post-handshake message
  1768. * between 349 and 451, epoch_offsets will be {0,39,39,349,452} and the length of the sendbuf will be 452.
  1769. * This argument is an I/O argument. Applications can either reset sendbuf to empty and epoch_offsets and to
  1770. * all zero every time they invoke the function, or retain the values until the handshake completes so that
  1771. * data will be appended to sendbuf and epoch_offsets will be adjusted.
  1772. * @param in_epoch epoch of the input
  1773. * @param input input bytes (must be NULL when starting the handshake on the client side)
  1774. * @param inlen length of the input
  1775. * @param properties properties specific to the running handshake
  1776. * @return same as `ptls_handshake`
  1777. */
  1778. int ptls_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
  1779. size_t inlen, ptls_handshake_properties_t *properties);
  1780. int ptls_client_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
  1781. size_t inlen, ptls_handshake_properties_t *properties);
  1782. int ptls_server_handle_message(ptls_t *tls, ptls_buffer_t *sendbuf, size_t epoch_offsets[5], size_t in_epoch, const void *input,
  1783. size_t inlen, ptls_handshake_properties_t *properties);
  1784. /**
  1785. * internal
  1786. */
  1787. void ptls_aead__build_iv(ptls_aead_algorithm_t *algo, uint8_t *iv, const uint8_t *static_iv, uint64_t seq);
  1788. /**
  1789. *
  1790. */
  1791. static void ptls_aead__do_encrypt(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1792. const void *aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp);
  1793. /**
  1794. *
  1795. */
  1796. static void ptls_aead__do_encrypt_v(ptls_aead_context_t *ctx, void *_output, ptls_iovec_t *input, size_t incnt, uint64_t seq,
  1797. const void *aad, size_t aadlen);
  1798. /**
  1799. * internal
  1800. */
  1801. void ptls__key_schedule_update_hash(ptls_key_schedule_t *sched, const uint8_t *msg, size_t msglen, int use_outer);
  1802. /**
  1803. * clears memory
  1804. */
  1805. extern void (*volatile ptls_clear_memory)(void *p, size_t len);
  1806. /**
  1807. * constant-time memcmp
  1808. */
  1809. extern int (*volatile ptls_mem_equal)(const void *x, const void *y, size_t len);
  1810. /**
  1811. * checks if a server name is an IP address.
  1812. */
  1813. int ptls_server_name_is_ipaddr(const char *name);
  1814. /**
  1815. * encodes one ECH Config
  1816. */
  1817. int ptls_ech_encode_config(ptls_buffer_t *buf, uint8_t config_id, ptls_hpke_kem_t *kem, ptls_iovec_t public_key,
  1818. ptls_hpke_cipher_suite_t **ciphers, uint8_t max_name_length, const char *public_name);
  1819. /**
  1820. * loads a certificate chain to ptls_context_t::certificates. `certificate.list` and each element of the list is allocated by
  1821. * malloc. It is the responsibility of the user to free them when discarding the TLS context.
  1822. */
  1823. int ptls_load_certificates(ptls_context_t *ctx, char const *cert_pem_file);
  1824. /**
  1825. * SetupBaseS function of RFC 9180. Given `kem`, `algo`, `info`, and receiver's public key, returns an ephemeral public key and an
  1826. * AEAD context used for encrypting data.
  1827. */
  1828. int ptls_hpke_setup_base_s(ptls_hpke_kem_t *kem, ptls_hpke_cipher_suite_t *cipher, ptls_iovec_t *pk_s, ptls_aead_context_t **ctx,
  1829. ptls_iovec_t pk_r, ptls_iovec_t info);
  1830. /**
  1831. * SetupBaseR function of RFC 9180. Given `kem`, `algo`, `info`, receiver's private key (`keyex`), and the esnder's public key,
  1832. * returns the AEAD context to be used for decrypting data.
  1833. */
  1834. int ptls_hpke_setup_base_r(ptls_hpke_kem_t *kem, ptls_hpke_cipher_suite_t *cipher, ptls_key_exchange_context_t *keyex,
  1835. ptls_aead_context_t **ctx, ptls_iovec_t pk_s, ptls_iovec_t info);
  1836. /**
  1837. *
  1838. */
  1839. char *ptls_hexdump(char *dst, const void *src, size_t len);
  1840. /**
  1841. * Builds a JSON-safe string without double quotes. Supplied buffer MUST be at least 6x + 1 bytes larger than the input.
  1842. */
  1843. char *ptls_jsonescape(char *buf, const char *s, size_t len);
  1844. /**
  1845. * builds a v4-mapped address (i.e., ::ffff:192.0.2.1)
  1846. */
  1847. void ptls_build_v4_mapped_v6_address(struct in6_addr *v6, const struct in_addr *v4);
  1848. /**
  1849. * the default get_time callback
  1850. */
  1851. extern ptls_get_time_t ptls_get_time;
  1852. /**
  1853. * default hash clone function that calls memcpy
  1854. */
  1855. static void ptls_hash_clone_memcpy(void *dst, const void *src, size_t size);
  1856. /* inline functions */
  1857. inline uint32_t ptls_log_point_maybe_active(struct st_ptls_log_point_t *point)
  1858. {
  1859. #if PTLS_HAVE_LOG
  1860. if (PTLS_UNLIKELY(point->state.generation != ptls_log._generation))
  1861. ptls_log__recalc_point(0, point);
  1862. return point->state.active_conns;
  1863. #else
  1864. return 0;
  1865. #endif
  1866. }
  1867. inline void ptls_log_recalc_conn_state(ptls_log_conn_state_t *state)
  1868. {
  1869. state->state.generation = 0;
  1870. }
  1871. inline uint32_t ptls_log_conn_maybe_active(ptls_log_conn_state_t *conn, const char *(*get_sni)(void *), void *get_sni_arg)
  1872. {
  1873. #if PTLS_HAVE_LOG
  1874. if (PTLS_UNLIKELY(conn->state.generation != ptls_log._generation))
  1875. ptls_log__recalc_conn(0, conn, get_sni, get_sni_arg);
  1876. return conn->state.active_conns;
  1877. #else
  1878. return 0;
  1879. #endif
  1880. }
  1881. inline ptls_t *ptls_new(ptls_context_t *ctx, int is_server)
  1882. {
  1883. return is_server ? ptls_server_new(ctx) : ptls_client_new(ctx);
  1884. }
  1885. inline ptls_iovec_t ptls_iovec_init(const void *p, size_t len)
  1886. {
  1887. /* avoid the "return (ptls_iovec_t){(uint8_t *)p, len};" construct because it requires C99
  1888. * and triggers a warning "C4204: nonstandard extension used: non-constant aggregate initializer"
  1889. * in Visual Studio */
  1890. ptls_iovec_t r;
  1891. r.base = (uint8_t *)p;
  1892. r.len = len;
  1893. return r;
  1894. }
  1895. inline void ptls_buffer_init(ptls_buffer_t *buf, void *smallbuf, size_t smallbuf_size)
  1896. {
  1897. assert(smallbuf != NULL);
  1898. buf->base = (uint8_t *)smallbuf;
  1899. buf->off = 0;
  1900. buf->capacity = smallbuf_size;
  1901. buf->is_allocated = 0;
  1902. buf->align_bits = 0;
  1903. }
  1904. inline void ptls_buffer_dispose(ptls_buffer_t *buf)
  1905. {
  1906. ptls_buffer__release_memory(buf);
  1907. *buf = (ptls_buffer_t){NULL, 0, 0, 0, 0};
  1908. }
  1909. inline uint8_t *ptls_encode_quicint(uint8_t *p, uint64_t v)
  1910. {
  1911. if (PTLS_UNLIKELY(v > 63)) {
  1912. if (PTLS_UNLIKELY(v > 16383)) {
  1913. unsigned sb;
  1914. if (PTLS_UNLIKELY(v > 1073741823)) {
  1915. assert(v <= 4611686018427387903);
  1916. *p++ = 0xc0 | (uint8_t)(v >> 56);
  1917. sb = 6 * 8;
  1918. } else {
  1919. *p++ = 0x80 | (uint8_t)(v >> 24);
  1920. sb = 2 * 8;
  1921. }
  1922. do {
  1923. *p++ = (uint8_t)(v >> sb);
  1924. } while ((sb -= 8) != 0);
  1925. } else {
  1926. *p++ = 0x40 | (uint8_t)((uint16_t)v >> 8);
  1927. }
  1928. }
  1929. *p++ = (uint8_t)v;
  1930. return p;
  1931. }
  1932. inline void ptls_cipher_init(ptls_cipher_context_t *ctx, const void *iv)
  1933. {
  1934. ctx->do_init(ctx, iv);
  1935. }
  1936. inline void ptls_cipher_encrypt(ptls_cipher_context_t *ctx, void *output, const void *input, size_t len)
  1937. {
  1938. ctx->do_transform(ctx, output, input, len);
  1939. }
  1940. inline void ptls_aead_get_iv(ptls_aead_context_t *ctx, void *iv)
  1941. {
  1942. ctx->do_get_iv(ctx, iv);
  1943. }
  1944. inline void ptls_aead_set_iv(ptls_aead_context_t *ctx, const void *iv)
  1945. {
  1946. ctx->do_set_iv(ctx, iv);
  1947. }
  1948. inline size_t ptls_aead_encrypt(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1949. const void *aad, size_t aadlen)
  1950. {
  1951. ctx->do_encrypt(ctx, output, input, inlen, seq, aad, aadlen, NULL);
  1952. return inlen + ctx->algo->tag_size;
  1953. }
  1954. inline void ptls_aead_encrypt_s(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1955. const void *aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp)
  1956. {
  1957. ctx->do_encrypt(ctx, output, input, inlen, seq, aad, aadlen, supp);
  1958. }
  1959. inline void ptls_aead_encrypt_v(ptls_aead_context_t *ctx, void *output, ptls_iovec_t *input, size_t incnt, uint64_t seq,
  1960. const void *aad, size_t aadlen)
  1961. {
  1962. ctx->do_encrypt_v(ctx, output, input, incnt, seq, aad, aadlen);
  1963. }
  1964. inline void ptls_aead_encrypt_init(ptls_aead_context_t *ctx, uint64_t seq, const void *aad, size_t aadlen)
  1965. {
  1966. ctx->do_encrypt_init(ctx, seq, aad, aadlen);
  1967. }
  1968. inline size_t ptls_aead_encrypt_update(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen)
  1969. {
  1970. return ctx->do_encrypt_update(ctx, output, input, inlen);
  1971. }
  1972. inline size_t ptls_aead_encrypt_final(ptls_aead_context_t *ctx, void *output)
  1973. {
  1974. return ctx->do_encrypt_final(ctx, output);
  1975. }
  1976. inline void ptls_aead__do_encrypt(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1977. const void *aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp)
  1978. {
  1979. ptls_iovec_t invec = ptls_iovec_init(input, inlen);
  1980. ctx->do_encrypt_v(ctx, output, &invec, 1, seq, aad, aadlen);
  1981. if (supp != NULL) {
  1982. ptls_cipher_init(supp->ctx, supp->input);
  1983. memset(supp->output, 0, sizeof(supp->output));
  1984. ptls_cipher_encrypt(supp->ctx, supp->output, supp->output, sizeof(supp->output));
  1985. }
  1986. }
  1987. inline void ptls_aead__do_encrypt_v(ptls_aead_context_t *ctx, void *_output, ptls_iovec_t *input, size_t incnt, uint64_t seq,
  1988. const void *aad, size_t aadlen)
  1989. {
  1990. uint8_t *output = (uint8_t *)_output;
  1991. ctx->do_encrypt_init(ctx, seq, aad, aadlen);
  1992. for (size_t i = 0; i < incnt; ++i)
  1993. output += ctx->do_encrypt_update(ctx, output, input[i].base, input[i].len);
  1994. ctx->do_encrypt_final(ctx, output);
  1995. }
  1996. inline size_t ptls_aead_decrypt(ptls_aead_context_t *ctx, void *output, const void *input, size_t inlen, uint64_t seq,
  1997. const void *aad, size_t aadlen)
  1998. {
  1999. return ctx->do_decrypt(ctx, output, input, inlen, seq, aad, aadlen);
  2000. }
  2001. inline void ptls_hash_clone_memcpy(void *dst, const void *src, size_t size)
  2002. {
  2003. memcpy(dst, src, size);
  2004. }
  2005. #define ptls_define_hash(name, ctx_type, init_func, update_func, final_func) \
  2006. ptls_define_hash6(name, ctx_type, init_func, update_func, final_func, ptls_hash_clone_memcpy)
  2007. #define ptls_define_hash6(name, ctx_type, init_func, update_func, final_func, clone_func) \
  2008. \
  2009. struct name##_context_t { \
  2010. ptls_hash_context_t super; \
  2011. ctx_type ctx; \
  2012. }; \
  2013. \
  2014. static void name##_update(ptls_hash_context_t *_ctx, const void *src, size_t len) \
  2015. { \
  2016. struct name##_context_t *ctx = (struct name##_context_t *)_ctx; \
  2017. update_func(&ctx->ctx, src, len); \
  2018. } \
  2019. \
  2020. static void name##_final(ptls_hash_context_t *_ctx, void *md, ptls_hash_final_mode_t mode) \
  2021. { \
  2022. struct name##_context_t *ctx = (struct name##_context_t *)_ctx; \
  2023. if (mode == PTLS_HASH_FINAL_MODE_SNAPSHOT) { \
  2024. ctx_type copy = ctx->ctx; \
  2025. final_func(&copy, md); \
  2026. ptls_clear_memory(&copy, sizeof(copy)); \
  2027. return; \
  2028. } \
  2029. if (md != NULL) \
  2030. final_func(&ctx->ctx, md); \
  2031. switch (mode) { \
  2032. case PTLS_HASH_FINAL_MODE_FREE: \
  2033. ptls_clear_memory(&ctx->ctx, sizeof(ctx->ctx)); \
  2034. free(ctx); \
  2035. break; \
  2036. case PTLS_HASH_FINAL_MODE_RESET: \
  2037. init_func(&ctx->ctx); \
  2038. break; \
  2039. default: \
  2040. assert(!"FIXME"); \
  2041. break; \
  2042. } \
  2043. } \
  2044. \
  2045. static ptls_hash_context_t *name##_clone(ptls_hash_context_t *_src) \
  2046. { \
  2047. struct name##_context_t *dst, *src = (struct name##_context_t *)_src; \
  2048. if ((dst = malloc(sizeof(*dst))) == NULL) \
  2049. return NULL; \
  2050. dst->super = src->super; \
  2051. clone_func(&dst->ctx, &src->ctx, sizeof(dst->ctx)); \
  2052. return &dst->super; \
  2053. } \
  2054. \
  2055. static ptls_hash_context_t *name##_create(void) \
  2056. { \
  2057. struct name##_context_t *ctx; \
  2058. if ((ctx = malloc(sizeof(*ctx))) == NULL) \
  2059. return NULL; \
  2060. ctx->super = (ptls_hash_context_t){name##_update, name##_final, name##_clone}; \
  2061. init_func(&ctx->ctx); \
  2062. return &ctx->super; \
  2063. }
  2064. #ifdef __cplusplus
  2065. }
  2066. #endif
  2067. #endif