s2n_tls_channel_handler.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/io/tls_channel_handler.h>
  6. #include <aws/common/clock.h>
  7. #include <aws/common/mutex.h>
  8. #include <aws/io/channel.h>
  9. #include <aws/io/event_loop.h>
  10. #include <aws/io/file_utils.h>
  11. #include <aws/io/logging.h>
  12. #include <aws/io/private/pki_utils.h>
  13. #include <aws/io/private/tls_channel_handler_shared.h>
  14. #include <aws/io/statistics.h>
  15. #include <aws/common/encoding.h>
  16. #include <aws/common/string.h>
  17. #include <aws/common/task_scheduler.h>
  18. #include <aws/common/thread.h>
  19. #include <errno.h>
  20. #include <inttypes.h>
  21. #include <math.h>
  22. #include <s2n.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #define EST_TLS_RECORD_OVERHEAD 53 /* 5 byte header + 32 + 16 bytes for padding */
  26. #define KB_1 1024
  27. #define MAX_RECORD_SIZE (KB_1 * 16)
  28. #define EST_HANDSHAKE_SIZE (7 * KB_1)
  29. static const char *s_default_ca_dir = NULL;
  30. static const char *s_default_ca_file = NULL;
  31. struct s2n_delayed_shutdown_task {
  32. struct aws_channel_task task;
  33. struct aws_channel_slot *slot;
  34. int error;
  35. };
  36. struct s2n_handler {
  37. struct aws_channel_handler handler;
  38. struct aws_tls_channel_handler_shared shared_state;
  39. struct s2n_connection *connection;
  40. struct s2n_ctx *s2n_ctx;
  41. struct aws_channel_slot *slot;
  42. struct aws_linked_list input_queue;
  43. struct aws_byte_buf protocol;
  44. struct aws_byte_buf server_name;
  45. aws_channel_on_message_write_completed_fn *latest_message_on_completion;
  46. struct aws_channel_task sequential_tasks;
  47. void *latest_message_completion_user_data;
  48. aws_tls_on_negotiation_result_fn *on_negotiation_result;
  49. aws_tls_on_data_read_fn *on_data_read;
  50. aws_tls_on_error_fn *on_error;
  51. void *user_data;
  52. bool advertise_alpn_message;
  53. enum {
  54. NEGOTIATION_ONGOING,
  55. NEGOTIATION_FAILED,
  56. NEGOTIATION_SUCCEEDED,
  57. } state;
  58. struct s2n_delayed_shutdown_task delayed_shutdown_task;
  59. };
  60. struct s2n_ctx {
  61. struct aws_tls_ctx ctx;
  62. struct s2n_config *s2n_config;
  63. /* Only used in special circumstances (ex: have cert but no key, because key is in PKCS#11) */
  64. struct s2n_cert_chain_and_key *custom_cert_chain_and_key;
  65. /**
  66. * Custom key operations to perform when a private key operation is required in the TLS handshake.
  67. * Only will be used if non-NULL, otherwise this is ignored and the standard private key operations
  68. * are performed instead.
  69. * NOTE: PKCS11 also is done via this custom_key_handler.
  70. *
  71. * See aws_custom_key_op_handler in tls_channel_handler.h for more details.
  72. */
  73. struct aws_custom_key_op_handler *custom_key_handler;
  74. };
  75. struct aws_tls_key_operation {
  76. struct aws_allocator *alloc;
  77. struct s2n_async_pkey_op *s2n_op;
  78. struct s2n_handler *s2n_handler;
  79. enum aws_tls_key_operation_type operation_type;
  80. enum aws_tls_signature_algorithm signature_algorithm;
  81. enum aws_tls_hash_algorithm digest_algorithm;
  82. struct aws_byte_buf input_data;
  83. struct aws_channel_task completion_task;
  84. int completion_error_code;
  85. struct aws_atomic_var complete_count;
  86. };
  87. AWS_STATIC_STRING_FROM_LITERAL(s_debian_path, "/etc/ssl/certs");
  88. AWS_STATIC_STRING_FROM_LITERAL(s_rhel_path, "/etc/pki/tls/certs");
  89. AWS_STATIC_STRING_FROM_LITERAL(s_android_path, "/system/etc/security/cacerts");
  90. AWS_STATIC_STRING_FROM_LITERAL(s_free_bsd_path, "/usr/local/share/certs");
  91. AWS_STATIC_STRING_FROM_LITERAL(s_net_bsd_path, "/etc/openssl/certs");
  92. AWS_IO_API const char *aws_determine_default_pki_dir(void) {
  93. /* debian variants; OpenBSD (although the directory doesn't exist by default) */
  94. if (aws_path_exists(s_debian_path)) {
  95. return aws_string_c_str(s_debian_path);
  96. }
  97. /* RHEL variants */
  98. if (aws_path_exists(s_rhel_path)) {
  99. return aws_string_c_str(s_rhel_path);
  100. }
  101. /* android */
  102. if (aws_path_exists(s_android_path)) {
  103. return aws_string_c_str(s_android_path);
  104. }
  105. /* FreeBSD */
  106. if (aws_path_exists(s_free_bsd_path)) {
  107. return aws_string_c_str(s_free_bsd_path);
  108. }
  109. /* NetBSD */
  110. if (aws_path_exists(s_net_bsd_path)) {
  111. return aws_string_c_str(s_net_bsd_path);
  112. }
  113. return NULL;
  114. }
  115. AWS_STATIC_STRING_FROM_LITERAL(s_debian_ca_file_path, "/etc/ssl/certs/ca-certificates.crt");
  116. AWS_STATIC_STRING_FROM_LITERAL(s_old_rhel_ca_file_path, "/etc/pki/tls/certs/ca-bundle.crt");
  117. AWS_STATIC_STRING_FROM_LITERAL(s_open_suse_ca_file_path, "/etc/ssl/ca-bundle.pem");
  118. AWS_STATIC_STRING_FROM_LITERAL(s_open_elec_ca_file_path, "/etc/pki/tls/cacert.pem");
  119. AWS_STATIC_STRING_FROM_LITERAL(s_modern_rhel_ca_file_path, "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem");
  120. AWS_STATIC_STRING_FROM_LITERAL(s_openbsd_ca_file_path, "/etc/ssl/cert.pem");
  121. AWS_IO_API const char *aws_determine_default_pki_ca_file(void) {
  122. /* debian variants */
  123. if (aws_path_exists(s_debian_ca_file_path)) {
  124. return aws_string_c_str(s_debian_ca_file_path);
  125. }
  126. /* Old RHEL variants */
  127. if (aws_path_exists(s_old_rhel_ca_file_path)) {
  128. return aws_string_c_str(s_old_rhel_ca_file_path);
  129. }
  130. /* Open SUSE */
  131. if (aws_path_exists(s_open_suse_ca_file_path)) {
  132. return aws_string_c_str(s_open_suse_ca_file_path);
  133. }
  134. /* Open ELEC */
  135. if (aws_path_exists(s_open_elec_ca_file_path)) {
  136. return aws_string_c_str(s_open_elec_ca_file_path);
  137. }
  138. /* Modern RHEL variants */
  139. if (aws_path_exists(s_modern_rhel_ca_file_path)) {
  140. return aws_string_c_str(s_modern_rhel_ca_file_path);
  141. }
  142. /* OpenBSD */
  143. if (aws_path_exists(s_openbsd_ca_file_path)) {
  144. return aws_string_c_str(s_openbsd_ca_file_path);
  145. }
  146. return NULL;
  147. }
  148. /* If s2n is already initialized, then we don't call s2n_init() or s2n_cleanup() ourselves */
  149. static bool s_s2n_initialized_externally = false;
  150. void aws_tls_init_static_state(struct aws_allocator *alloc) {
  151. (void)alloc;
  152. AWS_LOGF_INFO(AWS_LS_IO_TLS, "static: Initializing TLS using s2n.");
  153. /* Disable atexit behavior, so that s2n_cleanup() fully cleans things up.
  154. *
  155. * By default, s2n uses an ataexit handler and doesn't fully clean up until the program exits.
  156. * This can cause a crash if s2n is compiled into a shared library and
  157. * that library is unloaded before the appexit handler runs. */
  158. if (s2n_disable_atexit() != S2N_SUCCESS) {
  159. /* If this call fails, then s2n is already initialized
  160. * https://github.com/aws/s2n-tls/blob/2ad65c11a96368591fe809cd27fd1e390b2c8ce3/api/s2n.h#L211-L212 */
  161. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "static: s2n is already initialized");
  162. s_s2n_initialized_externally = true;
  163. } else {
  164. s_s2n_initialized_externally = false;
  165. }
  166. if (!s_s2n_initialized_externally) {
  167. setenv("S2N_DONT_MLOCK", "1", 1);
  168. if (s2n_init() != S2N_SUCCESS) {
  169. fprintf(stderr, "s2n_init() failed: %d (%s)\n", s2n_errno, s2n_strerror(s2n_errno, "EN"));
  170. AWS_FATAL_ASSERT(0 && "s2n_init() failed");
  171. }
  172. }
  173. s_default_ca_dir = aws_determine_default_pki_dir();
  174. s_default_ca_file = aws_determine_default_pki_ca_file();
  175. if (s_default_ca_dir || s_default_ca_file) {
  176. AWS_LOGF_DEBUG(
  177. AWS_LS_IO_TLS,
  178. "ctx: Based on OS, we detected the default PKI path as %s, and ca file as %s",
  179. s_default_ca_dir,
  180. s_default_ca_file);
  181. } else {
  182. AWS_LOGF_WARN(
  183. AWS_LS_IO_TLS,
  184. "Default TLS trust store not found on this system."
  185. " TLS connections will fail unless trusted CA certificates are installed,"
  186. " or \"override default trust store\" is used while creating the TLS context.");
  187. }
  188. }
  189. void aws_tls_clean_up_static_state(void) {
  190. /* only clean up s2n if we were the ones that initialized it */
  191. if (!s_s2n_initialized_externally) {
  192. s2n_cleanup();
  193. }
  194. }
  195. bool aws_tls_is_alpn_available(void) {
  196. return true;
  197. }
  198. bool aws_tls_is_cipher_pref_supported(enum aws_tls_cipher_pref cipher_pref) {
  199. switch (cipher_pref) {
  200. case AWS_IO_TLS_CIPHER_PREF_SYSTEM_DEFAULT:
  201. return true;
  202. /* PQ Crypto no-ops on android for now */
  203. #ifndef ANDROID
  204. case AWS_IO_TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05:
  205. return true;
  206. #endif
  207. default:
  208. return false;
  209. }
  210. }
  211. static int s_generic_read(struct s2n_handler *handler, struct aws_byte_buf *buf) {
  212. size_t written = 0;
  213. while (!aws_linked_list_empty(&handler->input_queue) && written < buf->len) {
  214. struct aws_linked_list_node *node = aws_linked_list_pop_front(&handler->input_queue);
  215. struct aws_io_message *message = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);
  216. size_t remaining_message_len = message->message_data.len - message->copy_mark;
  217. size_t remaining_buf_len = buf->len - written;
  218. size_t to_write = remaining_message_len < remaining_buf_len ? remaining_message_len : remaining_buf_len;
  219. struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);
  220. aws_byte_cursor_advance(&message_cursor, message->copy_mark);
  221. aws_byte_cursor_read(&message_cursor, buf->buffer + written, to_write);
  222. written += to_write;
  223. message->copy_mark += to_write;
  224. if (message->copy_mark == message->message_data.len) {
  225. aws_mem_release(message->allocator, message);
  226. } else {
  227. aws_linked_list_push_front(&handler->input_queue, &message->queueing_handle);
  228. }
  229. }
  230. if (written) {
  231. return (int)written;
  232. }
  233. errno = EAGAIN;
  234. return -1;
  235. }
  236. static int s_s2n_handler_recv(void *io_context, uint8_t *buf, uint32_t len) {
  237. struct s2n_handler *handler = (struct s2n_handler *)io_context;
  238. struct aws_byte_buf read_buffer = aws_byte_buf_from_array(buf, len);
  239. return s_generic_read(handler, &read_buffer);
  240. }
  241. static int s_generic_send(struct s2n_handler *handler, struct aws_byte_buf *buf) {
  242. struct aws_byte_cursor buffer_cursor = aws_byte_cursor_from_buf(buf);
  243. size_t processed = 0;
  244. while (processed < buf->len) {
  245. const size_t overhead = aws_channel_slot_upstream_message_overhead(handler->slot);
  246. const size_t message_size_hint = (buf->len - processed) + overhead;
  247. struct aws_io_message *message = aws_channel_acquire_message_from_pool(
  248. handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, message_size_hint);
  249. if (!message || message->message_data.capacity <= overhead) {
  250. errno = ENOMEM;
  251. return -1;
  252. }
  253. const size_t available_msg_write_capacity = message->message_data.capacity - overhead;
  254. const size_t to_write =
  255. available_msg_write_capacity >= buffer_cursor.len ? buffer_cursor.len : available_msg_write_capacity;
  256. struct aws_byte_cursor chunk = aws_byte_cursor_advance(&buffer_cursor, to_write);
  257. if (aws_byte_buf_append(&message->message_data, &chunk)) {
  258. aws_mem_release(message->allocator, message);
  259. return -1;
  260. }
  261. processed += message->message_data.len;
  262. if (processed == buf->len) {
  263. message->on_completion = handler->latest_message_on_completion;
  264. message->user_data = handler->latest_message_completion_user_data;
  265. handler->latest_message_on_completion = NULL;
  266. handler->latest_message_completion_user_data = NULL;
  267. }
  268. if (aws_channel_slot_send_message(handler->slot, message, AWS_CHANNEL_DIR_WRITE)) {
  269. aws_mem_release(message->allocator, message);
  270. errno = EPIPE;
  271. return -1;
  272. }
  273. }
  274. if (processed) {
  275. return (int)processed;
  276. }
  277. errno = EAGAIN;
  278. return -1;
  279. }
  280. static int s_s2n_handler_send(void *io_context, const uint8_t *buf, uint32_t len) {
  281. struct s2n_handler *handler = (struct s2n_handler *)io_context;
  282. struct aws_byte_buf send_buf = aws_byte_buf_from_array(buf, len);
  283. return s_generic_send(handler, &send_buf);
  284. }
  285. static void s_s2n_handler_destroy(struct aws_channel_handler *handler) {
  286. if (handler) {
  287. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  288. aws_tls_channel_handler_shared_clean_up(&s2n_handler->shared_state);
  289. if (s2n_handler->connection) {
  290. s2n_connection_free(s2n_handler->connection);
  291. }
  292. if (s2n_handler->s2n_ctx) {
  293. aws_tls_ctx_release(&s2n_handler->s2n_ctx->ctx);
  294. }
  295. aws_mem_release(handler->alloc, (void *)s2n_handler);
  296. }
  297. }
  298. static void s_on_negotiation_result(
  299. struct aws_channel_handler *handler,
  300. struct aws_channel_slot *slot,
  301. int error_code,
  302. void *user_data) {
  303. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  304. aws_on_tls_negotiation_completed(&s2n_handler->shared_state, error_code);
  305. if (s2n_handler->on_negotiation_result) {
  306. s2n_handler->on_negotiation_result(handler, slot, error_code, user_data);
  307. }
  308. }
  309. static int s_drive_negotiation(struct aws_channel_handler *handler) {
  310. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  311. AWS_ASSERT(s2n_handler->state == NEGOTIATION_ONGOING);
  312. aws_on_drive_tls_negotiation(&s2n_handler->shared_state);
  313. s2n_blocked_status blocked = S2N_NOT_BLOCKED;
  314. do {
  315. int negotiation_code = s2n_negotiate(s2n_handler->connection, &blocked);
  316. int s2n_error = s2n_errno;
  317. if (negotiation_code == S2N_ERR_T_OK) {
  318. s2n_handler->state = NEGOTIATION_SUCCEEDED;
  319. const char *protocol = s2n_get_application_protocol(s2n_handler->connection);
  320. if (protocol) {
  321. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Alpn protocol negotiated as %s", (void *)handler, protocol);
  322. s2n_handler->protocol = aws_byte_buf_from_c_str(protocol);
  323. }
  324. const char *server_name = s2n_get_server_name(s2n_handler->connection);
  325. if (server_name) {
  326. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Remote server name is %s", (void *)handler, server_name);
  327. s2n_handler->server_name = aws_byte_buf_from_c_str(server_name);
  328. }
  329. if (s2n_handler->slot->adj_right && s2n_handler->advertise_alpn_message && protocol) {
  330. struct aws_io_message *message = aws_channel_acquire_message_from_pool(
  331. s2n_handler->slot->channel,
  332. AWS_IO_MESSAGE_APPLICATION_DATA,
  333. sizeof(struct aws_tls_negotiated_protocol_message));
  334. message->message_tag = AWS_TLS_NEGOTIATED_PROTOCOL_MESSAGE;
  335. struct aws_tls_negotiated_protocol_message *protocol_message =
  336. (struct aws_tls_negotiated_protocol_message *)message->message_data.buffer;
  337. protocol_message->protocol = s2n_handler->protocol;
  338. message->message_data.len = sizeof(struct aws_tls_negotiated_protocol_message);
  339. if (aws_channel_slot_send_message(s2n_handler->slot, message, AWS_CHANNEL_DIR_READ)) {
  340. aws_mem_release(message->allocator, message);
  341. aws_channel_shutdown(s2n_handler->slot->channel, aws_last_error());
  342. return AWS_OP_SUCCESS;
  343. }
  344. }
  345. s_on_negotiation_result(handler, s2n_handler->slot, AWS_OP_SUCCESS, s2n_handler->user_data);
  346. break;
  347. }
  348. if (s2n_error_get_type(s2n_error) != S2N_ERR_T_BLOCKED) {
  349. AWS_LOGF_WARN(
  350. AWS_LS_IO_TLS,
  351. "id=%p: negotiation failed with error %s (%s)",
  352. (void *)handler,
  353. s2n_strerror(s2n_error, "EN"),
  354. s2n_strerror_debug(s2n_error, "EN"));
  355. if (s2n_error_get_type(s2n_error) == S2N_ERR_T_ALERT) {
  356. AWS_LOGF_DEBUG(
  357. AWS_LS_IO_TLS,
  358. "id=%p: Alert code %d",
  359. (void *)handler,
  360. s2n_connection_get_alert(s2n_handler->connection));
  361. }
  362. const char *err_str = s2n_strerror_debug(s2n_error, NULL);
  363. (void)err_str;
  364. s2n_handler->state = NEGOTIATION_FAILED;
  365. aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
  366. s_on_negotiation_result(
  367. handler, s2n_handler->slot, AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE, s2n_handler->user_data);
  368. return AWS_OP_ERR;
  369. }
  370. } while (blocked == S2N_NOT_BLOCKED);
  371. return AWS_OP_SUCCESS;
  372. }
  373. static void s_negotiation_task(struct aws_channel_task *task, void *arg, aws_task_status status) {
  374. task->task_fn = NULL;
  375. task->arg = NULL;
  376. if (status == AWS_TASK_STATUS_RUN_READY) {
  377. struct aws_channel_handler *handler = arg;
  378. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  379. if (s2n_handler->state == NEGOTIATION_ONGOING) {
  380. s_drive_negotiation(handler);
  381. }
  382. }
  383. }
  384. int aws_tls_client_handler_start_negotiation(struct aws_channel_handler *handler) {
  385. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  386. AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Kicking off TLS negotiation.", (void *)handler);
  387. if (aws_channel_thread_is_callers_thread(s2n_handler->slot->channel)) {
  388. if (s2n_handler->state == NEGOTIATION_ONGOING) {
  389. s_drive_negotiation(handler);
  390. }
  391. return AWS_OP_SUCCESS;
  392. }
  393. aws_channel_task_init(
  394. &s2n_handler->sequential_tasks, s_negotiation_task, handler, "s2n_channel_handler_negotiation");
  395. aws_channel_schedule_task_now(s2n_handler->slot->channel, &s2n_handler->sequential_tasks);
  396. return AWS_OP_SUCCESS;
  397. }
  398. static int s_s2n_handler_process_read_message(
  399. struct aws_channel_handler *handler,
  400. struct aws_channel_slot *slot,
  401. struct aws_io_message *message) {
  402. struct s2n_handler *s2n_handler = handler->impl;
  403. if (AWS_UNLIKELY(s2n_handler->state == NEGOTIATION_FAILED)) {
  404. return aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
  405. }
  406. if (message) {
  407. aws_linked_list_push_back(&s2n_handler->input_queue, &message->queueing_handle);
  408. if (s2n_handler->state == NEGOTIATION_ONGOING) {
  409. size_t message_len = message->message_data.len;
  410. if (!s_drive_negotiation(handler)) {
  411. aws_channel_slot_increment_read_window(slot, message_len);
  412. } else {
  413. aws_channel_shutdown(s2n_handler->slot->channel, AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
  414. }
  415. return AWS_OP_SUCCESS;
  416. }
  417. }
  418. s2n_blocked_status blocked = S2N_NOT_BLOCKED;
  419. size_t downstream_window = SIZE_MAX;
  420. if (slot->adj_right) {
  421. downstream_window = aws_channel_slot_downstream_read_window(slot);
  422. }
  423. size_t processed = 0;
  424. AWS_LOGF_TRACE(
  425. AWS_LS_IO_TLS, "id=%p: Downstream window %llu", (void *)handler, (unsigned long long)downstream_window);
  426. while (processed < downstream_window && blocked == S2N_NOT_BLOCKED) {
  427. struct aws_io_message *outgoing_read_message = aws_channel_acquire_message_from_pool(
  428. slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, downstream_window - processed);
  429. if (!outgoing_read_message) {
  430. return AWS_OP_ERR;
  431. }
  432. ssize_t read = s2n_recv(
  433. s2n_handler->connection,
  434. outgoing_read_message->message_data.buffer,
  435. outgoing_read_message->message_data.capacity,
  436. &blocked);
  437. AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Bytes read %lld", (void *)handler, (long long)read);
  438. /* weird race where we received an alert from the peer, but s2n doesn't tell us about it.....
  439. * if this happens, it's a graceful shutdown, so kick it off here.
  440. *
  441. * In other words, s2n, upon graceful shutdown, follows the unix EOF idiom. So just shutdown with
  442. * SUCCESS.
  443. */
  444. if (read == 0) {
  445. AWS_LOGF_DEBUG(
  446. AWS_LS_IO_TLS,
  447. "id=%p: Alert code %d",
  448. (void *)handler,
  449. s2n_connection_get_alert(s2n_handler->connection));
  450. aws_mem_release(outgoing_read_message->allocator, outgoing_read_message);
  451. aws_channel_shutdown(slot->channel, AWS_OP_SUCCESS);
  452. return AWS_OP_SUCCESS;
  453. }
  454. if (read < 0) {
  455. aws_mem_release(outgoing_read_message->allocator, outgoing_read_message);
  456. continue;
  457. };
  458. processed += read;
  459. outgoing_read_message->message_data.len = (size_t)read;
  460. if (s2n_handler->on_data_read) {
  461. s2n_handler->on_data_read(handler, slot, &outgoing_read_message->message_data, s2n_handler->user_data);
  462. }
  463. if (slot->adj_right) {
  464. aws_channel_slot_send_message(slot, outgoing_read_message, AWS_CHANNEL_DIR_READ);
  465. } else {
  466. aws_mem_release(outgoing_read_message->allocator, outgoing_read_message);
  467. }
  468. }
  469. AWS_LOGF_TRACE(
  470. AWS_LS_IO_TLS,
  471. "id=%p: Remaining window for this event-loop tick: %llu",
  472. (void *)handler,
  473. (unsigned long long)downstream_window - processed);
  474. return AWS_OP_SUCCESS;
  475. }
  476. static int s_s2n_handler_process_write_message(
  477. struct aws_channel_handler *handler,
  478. struct aws_channel_slot *slot,
  479. struct aws_io_message *message) {
  480. (void)slot;
  481. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  482. if (AWS_UNLIKELY(s2n_handler->state != NEGOTIATION_SUCCEEDED)) {
  483. return aws_raise_error(AWS_IO_TLS_ERROR_NOT_NEGOTIATED);
  484. }
  485. s2n_handler->latest_message_on_completion = message->on_completion;
  486. s2n_handler->latest_message_completion_user_data = message->user_data;
  487. s2n_blocked_status blocked;
  488. ssize_t write_code =
  489. s2n_send(s2n_handler->connection, message->message_data.buffer, (ssize_t)message->message_data.len, &blocked);
  490. AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Bytes written: %llu", (void *)handler, (unsigned long long)write_code);
  491. ssize_t message_len = (ssize_t)message->message_data.len;
  492. if (write_code < message_len) {
  493. return aws_raise_error(AWS_IO_TLS_ERROR_WRITE_FAILURE);
  494. }
  495. aws_mem_release(message->allocator, message);
  496. return AWS_OP_SUCCESS;
  497. }
  498. static void s_delayed_shutdown_task_fn(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
  499. (void)channel_task;
  500. struct aws_channel_handler *handler = arg;
  501. struct s2n_handler *s2n_handler = handler->impl;
  502. if (status == AWS_TASK_STATUS_RUN_READY) {
  503. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Delayed shut down in write direction", (void *)handler);
  504. s2n_blocked_status blocked;
  505. /* make a best effort, but the channel is going away after this run, so.... you only get one shot anyways */
  506. s2n_shutdown(s2n_handler->connection, &blocked);
  507. }
  508. aws_channel_slot_on_handler_shutdown_complete(
  509. s2n_handler->delayed_shutdown_task.slot,
  510. AWS_CHANNEL_DIR_WRITE,
  511. s2n_handler->delayed_shutdown_task.error,
  512. false);
  513. }
  514. static enum aws_tls_signature_algorithm s_s2n_to_aws_signature_algorithm(s2n_tls_signature_algorithm s2n_alg) {
  515. switch (s2n_alg) {
  516. case S2N_TLS_SIGNATURE_RSA:
  517. return AWS_TLS_SIGNATURE_RSA;
  518. case S2N_TLS_SIGNATURE_ECDSA:
  519. return AWS_TLS_SIGNATURE_ECDSA;
  520. default:
  521. return AWS_TLS_SIGNATURE_UNKNOWN;
  522. }
  523. }
  524. static enum aws_tls_hash_algorithm s_s2n_to_aws_hash_algorithm(s2n_tls_hash_algorithm s2n_alg) {
  525. switch (s2n_alg) {
  526. case (S2N_TLS_HASH_SHA1):
  527. return AWS_TLS_HASH_SHA1;
  528. case (S2N_TLS_HASH_SHA224):
  529. return AWS_TLS_HASH_SHA224;
  530. case (S2N_TLS_HASH_SHA256):
  531. return AWS_TLS_HASH_SHA256;
  532. case (S2N_TLS_HASH_SHA384):
  533. return AWS_TLS_HASH_SHA384;
  534. case (S2N_TLS_HASH_SHA512):
  535. return AWS_TLS_HASH_SHA512;
  536. default:
  537. return AWS_TLS_HASH_UNKNOWN;
  538. }
  539. }
  540. static void s_tls_key_operation_destroy(struct aws_tls_key_operation *operation) {
  541. if (operation->s2n_op) {
  542. s2n_async_pkey_op_free(operation->s2n_op);
  543. }
  544. if (operation->s2n_handler) {
  545. aws_channel_release_hold(operation->s2n_handler->slot->channel);
  546. }
  547. aws_byte_buf_clean_up(&operation->input_data);
  548. aws_mem_release(operation->alloc, operation);
  549. }
  550. /* This task finishes a private key operation on the event-loop thread.
  551. * If the operation was successful, TLS negotiation is resumed.
  552. * If the operation failed, the channel is shut down */
  553. static void s_tls_key_operation_completion_task(
  554. struct aws_channel_task *channel_task,
  555. void *arg,
  556. enum aws_task_status status) {
  557. (void)channel_task;
  558. struct aws_tls_key_operation *operation = arg;
  559. struct s2n_handler *s2n_handler = operation->s2n_handler;
  560. struct aws_channel_handler *handler = &s2n_handler->handler;
  561. /* if things started failing since this task was scheduled, just clean up and bail out */
  562. if (status != AWS_TASK_STATUS_RUN_READY || s2n_handler->state != NEGOTIATION_ONGOING) {
  563. goto clean_up;
  564. }
  565. if (operation->completion_error_code == 0) {
  566. if (s2n_async_pkey_op_apply(operation->s2n_op, s2n_handler->connection)) {
  567. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed applying s2n async pkey op", (void *)handler);
  568. operation->completion_error_code = AWS_ERROR_INVALID_STATE;
  569. }
  570. }
  571. if (operation->completion_error_code == 0) {
  572. s_drive_negotiation(handler);
  573. } else {
  574. aws_channel_shutdown(s2n_handler->slot->channel, operation->completion_error_code);
  575. }
  576. clean_up:
  577. s_tls_key_operation_destroy(operation);
  578. }
  579. /* Common implementation for aws_tls_key_operation_complete() and aws_tls_key_operation_complete_with_error()
  580. * This is called exactly once. Schedules a task to actually finish things up on the event-loop thread. */
  581. static void s_tls_key_operation_complete_common(
  582. struct aws_tls_key_operation *operation,
  583. int error_code,
  584. const struct aws_byte_cursor *output) {
  585. AWS_ASSERT((error_code != 0) ^ (output != NULL)); /* error_code XOR output must be set */
  586. /* Ensure this can only be called once and exactly once. */
  587. size_t complete_count = aws_atomic_fetch_add(&operation->complete_count, 1);
  588. AWS_FATAL_ASSERT(complete_count == 0 && "TLS key operation marked complete multiple times");
  589. struct s2n_handler *s2n_handler = operation->s2n_handler;
  590. struct aws_channel_handler *handler = &s2n_handler->handler;
  591. if (output != NULL) {
  592. /* Immediately pass output through to s2n_op. */
  593. if (s2n_async_pkey_op_set_output(operation->s2n_op, output->ptr, output->len)) {
  594. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed setting output on s2n async pkey op", (void *)handler);
  595. error_code = AWS_ERROR_INVALID_STATE;
  596. goto done;
  597. }
  598. }
  599. done:
  600. operation->completion_error_code = error_code;
  601. /* Schedule a task to finish the operation.
  602. * We schedule a task because the user might
  603. * have completed the operation asynchronously,
  604. * but we need to be on the event-loop thread to
  605. * resume TLS negotiation. */
  606. aws_channel_task_init(
  607. &operation->completion_task,
  608. s_tls_key_operation_completion_task,
  609. operation,
  610. "tls_key_operation_completion_task");
  611. aws_channel_schedule_task_now(s2n_handler->slot->channel, &operation->completion_task);
  612. }
  613. void aws_tls_key_operation_complete(struct aws_tls_key_operation *operation, struct aws_byte_cursor output) {
  614. if (operation == NULL) {
  615. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "Operation complete: operation is null and therefore cannot be set to complete!");
  616. return;
  617. }
  618. AWS_LOGF_DEBUG(
  619. AWS_LS_IO_TLS,
  620. "id=%p: TLS key operation complete with %zu bytes of output data",
  621. (void *)operation->s2n_handler,
  622. output.len);
  623. s_tls_key_operation_complete_common(operation, 0, &output);
  624. }
  625. void aws_tls_key_operation_complete_with_error(struct aws_tls_key_operation *operation, int error_code) {
  626. if (operation == NULL) {
  627. AWS_LOGF_ERROR(
  628. AWS_LS_IO_TLS, "Operation complete with error: operation is null and therefore cannot be set to complete!");
  629. return;
  630. }
  631. if (error_code == 0) {
  632. error_code = AWS_ERROR_UNKNOWN;
  633. AWS_LOGF_ERROR(
  634. AWS_LS_IO_TLS,
  635. "id=%p: TLS key operation completed with error, but no error-code set. Using %s",
  636. (void *)operation->s2n_handler,
  637. aws_error_name(error_code));
  638. }
  639. AWS_LOGF_ERROR(
  640. AWS_LS_IO_TLS,
  641. "id=%p: TLS key operation complete with error %s",
  642. (void *)operation->s2n_handler,
  643. aws_error_name(error_code));
  644. s_tls_key_operation_complete_common(operation, error_code, NULL);
  645. }
  646. static struct aws_tls_key_operation *s_tls_key_operation_new(
  647. struct aws_channel_handler *handler,
  648. struct s2n_async_pkey_op *s2n_op) {
  649. struct s2n_handler *s2n_handler = handler->impl;
  650. struct aws_tls_key_operation *operation = aws_mem_calloc(handler->alloc, 1, sizeof(struct aws_tls_key_operation));
  651. operation->alloc = handler->alloc;
  652. /* Copy input data */
  653. uint32_t input_size = 0;
  654. if (s2n_async_pkey_op_get_input_size(s2n_op, &input_size)) {
  655. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed querying s2n async pkey op size", (void *)handler);
  656. aws_raise_error(AWS_ERROR_INVALID_STATE);
  657. goto error;
  658. }
  659. aws_byte_buf_init(&operation->input_data, operation->alloc, input_size); /* cannot fail */
  660. if (s2n_async_pkey_op_get_input(s2n_op, operation->input_data.buffer, input_size)) {
  661. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed querying s2n async pkey input", (void *)handler);
  662. aws_raise_error(AWS_ERROR_INVALID_STATE);
  663. goto error;
  664. }
  665. operation->input_data.len = input_size;
  666. /* Get operation type */
  667. s2n_async_pkey_op_type s2n_op_type = 0;
  668. if (s2n_async_pkey_op_get_op_type(s2n_op, &s2n_op_type)) {
  669. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed querying s2n async pkey op type", (void *)handler);
  670. aws_raise_error(AWS_ERROR_INVALID_STATE);
  671. goto error;
  672. }
  673. if (s2n_op_type == S2N_ASYNC_SIGN) {
  674. operation->operation_type = AWS_TLS_KEY_OPERATION_SIGN;
  675. /* Gather additional information if this is a SIGN operation */
  676. s2n_tls_signature_algorithm s2n_sign_alg = 0;
  677. if (s2n_connection_get_selected_client_cert_signature_algorithm(s2n_handler->connection, &s2n_sign_alg)) {
  678. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed getting s2n client cert signature algorithm", (void *)handler);
  679. aws_raise_error(AWS_ERROR_INVALID_STATE);
  680. goto error;
  681. }
  682. operation->signature_algorithm = s_s2n_to_aws_signature_algorithm(s2n_sign_alg);
  683. if (operation->signature_algorithm == AWS_TLS_SIGNATURE_UNKNOWN) {
  684. AWS_LOGF_ERROR(
  685. AWS_LS_IO_TLS,
  686. "id=%p: Cannot sign with s2n_tls_signature_algorithm=%d. Algorithm currently unsupported",
  687. (void *)handler,
  688. s2n_sign_alg);
  689. aws_raise_error(AWS_IO_TLS_SIGNATURE_ALGORITHM_UNSUPPORTED);
  690. goto error;
  691. }
  692. s2n_tls_hash_algorithm s2n_digest_alg = 0;
  693. if (s2n_connection_get_selected_client_cert_digest_algorithm(s2n_handler->connection, &s2n_digest_alg)) {
  694. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed getting s2n client cert digest algorithm", (void *)handler);
  695. aws_raise_error(AWS_ERROR_INVALID_STATE);
  696. goto error;
  697. }
  698. operation->digest_algorithm = s_s2n_to_aws_hash_algorithm(s2n_digest_alg);
  699. if (operation->digest_algorithm == AWS_TLS_HASH_UNKNOWN) {
  700. AWS_LOGF_ERROR(
  701. AWS_LS_IO_TLS,
  702. "id=%p: Cannot sign digest created with s2n_tls_hash_algorithm=%d. Algorithm currently unsupported",
  703. (void *)handler,
  704. s2n_digest_alg);
  705. aws_raise_error(AWS_IO_TLS_DIGEST_ALGORITHM_UNSUPPORTED);
  706. goto error;
  707. }
  708. } else if (s2n_op_type == S2N_ASYNC_DECRYPT) {
  709. operation->operation_type = AWS_TLS_KEY_OPERATION_DECRYPT;
  710. } else {
  711. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Unknown s2n async pkey op type:%d", (void *)handler, (int)s2n_op_type);
  712. aws_raise_error(AWS_ERROR_INVALID_STATE);
  713. goto error;
  714. }
  715. /* Keep channel alive until operation completes */
  716. operation->s2n_handler = s2n_handler;
  717. aws_channel_acquire_hold(s2n_handler->slot->channel);
  718. /* Set this to zero so we can track how many times complete has been called */
  719. aws_atomic_init_int(&operation->complete_count, 0);
  720. /* Set this last. We don't want to take ownership of s2n_op until we know setup was 100% successful */
  721. operation->s2n_op = s2n_op;
  722. return operation;
  723. error:
  724. s_tls_key_operation_destroy(operation);
  725. return NULL;
  726. }
  727. struct aws_byte_cursor aws_tls_key_operation_get_input(const struct aws_tls_key_operation *operation) {
  728. return aws_byte_cursor_from_buf(&operation->input_data);
  729. }
  730. enum aws_tls_key_operation_type aws_tls_key_operation_get_type(const struct aws_tls_key_operation *operation) {
  731. return operation->operation_type;
  732. }
  733. enum aws_tls_signature_algorithm aws_tls_key_operation_get_signature_algorithm(
  734. const struct aws_tls_key_operation *operation) {
  735. return operation->signature_algorithm;
  736. }
  737. enum aws_tls_hash_algorithm aws_tls_key_operation_get_digest_algorithm(const struct aws_tls_key_operation *operation) {
  738. return operation->digest_algorithm;
  739. }
  740. static int s_s2n_async_pkey_callback(struct s2n_connection *conn, struct s2n_async_pkey_op *s2n_op) {
  741. struct s2n_handler *s2n_handler = s2n_connection_get_ctx(conn);
  742. struct aws_channel_handler *handler = &s2n_handler->handler;
  743. AWS_ASSERT(conn == s2n_handler->connection);
  744. (void)conn;
  745. AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: s2n async pkey callback received", (void *)handler);
  746. /* Create the AWS wrapper around s2n_async_pkey_op */
  747. struct aws_tls_key_operation *operation = s_tls_key_operation_new(handler, s2n_op);
  748. if (operation == NULL) {
  749. s2n_async_pkey_op_free(s2n_op);
  750. return S2N_FAILURE;
  751. }
  752. AWS_LOGF_DEBUG(
  753. AWS_LS_IO_TLS,
  754. "id=%p: Begin TLS key operation. type=%s input_data.len=%zu signature=%s digest=%s",
  755. (void *)operation,
  756. aws_tls_key_operation_type_str(operation->operation_type),
  757. operation->input_data.len,
  758. aws_tls_signature_algorithm_str(operation->signature_algorithm),
  759. aws_tls_hash_algorithm_str(operation->digest_algorithm));
  760. aws_custom_key_op_handler_perform_operation(s2n_handler->s2n_ctx->custom_key_handler, operation);
  761. return S2N_SUCCESS;
  762. }
  763. static int s_s2n_do_delayed_shutdown(
  764. struct aws_channel_handler *handler,
  765. struct aws_channel_slot *slot,
  766. int error_code) {
  767. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  768. s2n_handler->delayed_shutdown_task.slot = slot;
  769. s2n_handler->delayed_shutdown_task.error = error_code;
  770. uint64_t shutdown_delay = s2n_connection_get_delay(s2n_handler->connection);
  771. uint64_t now = 0;
  772. if (aws_channel_current_clock_time(slot->channel, &now)) {
  773. return AWS_OP_ERR;
  774. }
  775. uint64_t shutdown_time = aws_add_u64_saturating(shutdown_delay, now);
  776. aws_channel_schedule_task_future(slot->channel, &s2n_handler->delayed_shutdown_task.task, shutdown_time);
  777. return AWS_OP_SUCCESS;
  778. }
  779. static int s_s2n_handler_shutdown(
  780. struct aws_channel_handler *handler,
  781. struct aws_channel_slot *slot,
  782. enum aws_channel_direction dir,
  783. int error_code,
  784. bool abort_immediately) {
  785. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  786. if (dir == AWS_CHANNEL_DIR_WRITE) {
  787. if (!abort_immediately && error_code != AWS_IO_SOCKET_CLOSED) {
  788. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Scheduling delayed write direction shutdown", (void *)handler);
  789. if (s_s2n_do_delayed_shutdown(handler, slot, error_code) == AWS_OP_SUCCESS) {
  790. return AWS_OP_SUCCESS;
  791. }
  792. }
  793. } else {
  794. AWS_LOGF_DEBUG(
  795. AWS_LS_IO_TLS, "id=%p: Shutting down read direction with error code %d", (void *)handler, error_code);
  796. /* If negotiation hasn't succeeded yet, it's certainly not going to succeed now */
  797. if (s2n_handler->state == NEGOTIATION_ONGOING) {
  798. s2n_handler->state = NEGOTIATION_FAILED;
  799. }
  800. while (!aws_linked_list_empty(&s2n_handler->input_queue)) {
  801. struct aws_linked_list_node *node = aws_linked_list_pop_front(&s2n_handler->input_queue);
  802. struct aws_io_message *message = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);
  803. aws_mem_release(message->allocator, message);
  804. }
  805. }
  806. return aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, abort_immediately);
  807. }
  808. static void s_run_read(struct aws_channel_task *task, void *arg, aws_task_status status) {
  809. task->task_fn = NULL;
  810. task->arg = NULL;
  811. if (status == AWS_TASK_STATUS_RUN_READY) {
  812. struct aws_channel_handler *handler = (struct aws_channel_handler *)arg;
  813. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  814. s_s2n_handler_process_read_message(handler, s2n_handler->slot, NULL);
  815. }
  816. }
  817. static int s_s2n_handler_increment_read_window(
  818. struct aws_channel_handler *handler,
  819. struct aws_channel_slot *slot,
  820. size_t size) {
  821. (void)size;
  822. struct s2n_handler *s2n_handler = handler->impl;
  823. size_t downstream_size = aws_channel_slot_downstream_read_window(slot);
  824. size_t current_window_size = slot->window_size;
  825. AWS_LOGF_TRACE(
  826. AWS_LS_IO_TLS, "id=%p: Increment read window message received %llu", (void *)handler, (unsigned long long)size);
  827. size_t likely_records_count = (size_t)ceil((double)(downstream_size) / (double)(MAX_RECORD_SIZE));
  828. size_t offset_size = aws_mul_size_saturating(likely_records_count, EST_TLS_RECORD_OVERHEAD);
  829. size_t total_desired_size = aws_add_size_saturating(offset_size, downstream_size);
  830. if (total_desired_size > current_window_size) {
  831. size_t window_update_size = total_desired_size - current_window_size;
  832. AWS_LOGF_TRACE(
  833. AWS_LS_IO_TLS,
  834. "id=%p: Propagating read window increment of size %llu",
  835. (void *)handler,
  836. (unsigned long long)window_update_size);
  837. aws_channel_slot_increment_read_window(slot, window_update_size);
  838. }
  839. if (s2n_handler->state == NEGOTIATION_SUCCEEDED && !s2n_handler->sequential_tasks.node.next) {
  840. /* TLS requires full records before it can decrypt anything. As a result we need to check everything we've
  841. * buffered instead of just waiting on a read from the socket, or we'll hit a deadlock.
  842. *
  843. * We have messages in a queue and they need to be run after the socket has popped (even if it didn't have data
  844. * to read). Alternatively, s2n reads entire records at a time, so we'll need to grab whatever we can and we
  845. * have no idea what's going on inside there. So we need to attempt another read.*/
  846. aws_channel_task_init(
  847. &s2n_handler->sequential_tasks, s_run_read, handler, "s2n_channel_handler_read_on_window_increment");
  848. aws_channel_schedule_task_now(slot->channel, &s2n_handler->sequential_tasks);
  849. }
  850. return AWS_OP_SUCCESS;
  851. }
  852. static size_t s_s2n_handler_message_overhead(struct aws_channel_handler *handler) {
  853. (void)handler;
  854. return EST_TLS_RECORD_OVERHEAD;
  855. }
  856. static size_t s_s2n_handler_initial_window_size(struct aws_channel_handler *handler) {
  857. (void)handler;
  858. return EST_HANDSHAKE_SIZE;
  859. }
  860. static void s_s2n_handler_reset_statistics(struct aws_channel_handler *handler) {
  861. struct s2n_handler *s2n_handler = handler->impl;
  862. aws_crt_statistics_tls_reset(&s2n_handler->shared_state.stats);
  863. }
  864. static void s_s2n_handler_gather_statistics(struct aws_channel_handler *handler, struct aws_array_list *stats) {
  865. struct s2n_handler *s2n_handler = handler->impl;
  866. void *stats_base = &s2n_handler->shared_state.stats;
  867. aws_array_list_push_back(stats, &stats_base);
  868. }
  869. struct aws_byte_buf aws_tls_handler_protocol(struct aws_channel_handler *handler) {
  870. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  871. return s2n_handler->protocol;
  872. }
  873. struct aws_byte_buf aws_tls_handler_server_name(struct aws_channel_handler *handler) {
  874. struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
  875. return s2n_handler->server_name;
  876. }
  877. static struct aws_channel_handler_vtable s_handler_vtable = {
  878. .destroy = s_s2n_handler_destroy,
  879. .process_read_message = s_s2n_handler_process_read_message,
  880. .process_write_message = s_s2n_handler_process_write_message,
  881. .shutdown = s_s2n_handler_shutdown,
  882. .increment_read_window = s_s2n_handler_increment_read_window,
  883. .initial_window_size = s_s2n_handler_initial_window_size,
  884. .message_overhead = s_s2n_handler_message_overhead,
  885. .reset_statistics = s_s2n_handler_reset_statistics,
  886. .gather_statistics = s_s2n_handler_gather_statistics,
  887. };
  888. static int s_parse_protocol_preferences(
  889. struct aws_string *alpn_list_str,
  890. const char protocol_output[4][128],
  891. size_t *protocol_count) {
  892. size_t max_count = *protocol_count;
  893. *protocol_count = 0;
  894. struct aws_byte_cursor alpn_list_buffer[4];
  895. AWS_ZERO_ARRAY(alpn_list_buffer);
  896. struct aws_array_list alpn_list;
  897. struct aws_byte_cursor user_alpn_str = aws_byte_cursor_from_string(alpn_list_str);
  898. aws_array_list_init_static(&alpn_list, alpn_list_buffer, 4, sizeof(struct aws_byte_cursor));
  899. if (aws_byte_cursor_split_on_char(&user_alpn_str, ';', &alpn_list)) {
  900. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  901. return AWS_OP_ERR;
  902. }
  903. size_t protocols_list_len = aws_array_list_length(&alpn_list);
  904. if (protocols_list_len < 1) {
  905. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  906. return AWS_OP_ERR;
  907. }
  908. for (size_t i = 0; i < protocols_list_len && i < max_count; ++i) {
  909. struct aws_byte_cursor cursor;
  910. AWS_ZERO_STRUCT(cursor);
  911. if (aws_array_list_get_at(&alpn_list, (void *)&cursor, (size_t)i)) {
  912. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  913. return AWS_OP_ERR;
  914. }
  915. AWS_FATAL_ASSERT(cursor.ptr && cursor.len > 0);
  916. memcpy((void *)protocol_output[i], cursor.ptr, cursor.len);
  917. *protocol_count += 1;
  918. }
  919. return AWS_OP_SUCCESS;
  920. }
  921. static size_t s_tl_cleanup_key = 0; /* Address of variable serves as key in hash table */
  922. /*
  923. * This local object is added to the table of every event loop that has a (s2n) tls connection
  924. * added to it at some point in time
  925. */
  926. static struct aws_event_loop_local_object s_tl_cleanup_object = {
  927. .key = &s_tl_cleanup_key,
  928. .object = NULL,
  929. .on_object_removed = NULL,
  930. };
  931. static void s_aws_cleanup_s2n_thread_local_state(void *user_data) {
  932. (void)user_data;
  933. s2n_cleanup();
  934. }
  935. /* s2n allocates thread-local data structures. We need to clean these up when the event loop's thread exits. */
  936. static int s_s2n_tls_channel_handler_schedule_thread_local_cleanup(struct aws_channel_slot *slot) {
  937. struct aws_channel *channel = slot->channel;
  938. struct aws_event_loop_local_object existing_marker;
  939. AWS_ZERO_STRUCT(existing_marker);
  940. /*
  941. * Check whether another s2n_tls_channel_handler has already scheduled the cleanup task.
  942. */
  943. if (aws_channel_fetch_local_object(channel, &s_tl_cleanup_key, &existing_marker)) {
  944. /* Doesn't exist in event loop table: add it and add the at-exit cleanup callback */
  945. if (aws_channel_put_local_object(channel, &s_tl_cleanup_key, &s_tl_cleanup_object)) {
  946. return AWS_OP_ERR;
  947. }
  948. aws_thread_current_at_exit(s_aws_cleanup_s2n_thread_local_state, NULL);
  949. }
  950. return AWS_OP_SUCCESS;
  951. }
  952. static struct aws_channel_handler *s_new_tls_handler(
  953. struct aws_allocator *allocator,
  954. struct aws_tls_connection_options *options,
  955. struct aws_channel_slot *slot,
  956. s2n_mode mode) {
  957. AWS_ASSERT(options->ctx);
  958. struct s2n_handler *s2n_handler = aws_mem_calloc(allocator, 1, sizeof(struct s2n_handler));
  959. s2n_handler->handler.impl = s2n_handler;
  960. s2n_handler->handler.alloc = allocator;
  961. s2n_handler->handler.vtable = &s_handler_vtable;
  962. s2n_handler->handler.slot = slot;
  963. aws_tls_ctx_acquire(options->ctx);
  964. s2n_handler->s2n_ctx = options->ctx->impl;
  965. s2n_handler->connection = s2n_connection_new(mode);
  966. if (!s2n_handler->connection) {
  967. goto cleanup_conn;
  968. }
  969. aws_tls_channel_handler_shared_init(&s2n_handler->shared_state, &s2n_handler->handler, options);
  970. s2n_handler->user_data = options->user_data;
  971. s2n_handler->on_data_read = options->on_data_read;
  972. s2n_handler->on_error = options->on_error;
  973. s2n_handler->on_negotiation_result = options->on_negotiation_result;
  974. s2n_handler->advertise_alpn_message = options->advertise_alpn_message;
  975. s2n_handler->latest_message_completion_user_data = NULL;
  976. s2n_handler->latest_message_on_completion = NULL;
  977. s2n_handler->slot = slot;
  978. aws_linked_list_init(&s2n_handler->input_queue);
  979. s2n_handler->protocol = aws_byte_buf_from_array(NULL, 0);
  980. if (options->server_name) {
  981. if (s2n_set_server_name(s2n_handler->connection, aws_string_c_str(options->server_name))) {
  982. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  983. goto cleanup_conn;
  984. }
  985. }
  986. s2n_handler->state = NEGOTIATION_ONGOING;
  987. s2n_connection_set_recv_cb(s2n_handler->connection, s_s2n_handler_recv);
  988. s2n_connection_set_recv_ctx(s2n_handler->connection, s2n_handler);
  989. s2n_connection_set_send_cb(s2n_handler->connection, s_s2n_handler_send);
  990. s2n_connection_set_send_ctx(s2n_handler->connection, s2n_handler);
  991. s2n_connection_set_ctx(s2n_handler->connection, s2n_handler);
  992. s2n_connection_set_blinding(s2n_handler->connection, S2N_SELF_SERVICE_BLINDING);
  993. if (options->alpn_list) {
  994. AWS_LOGF_DEBUG(
  995. AWS_LS_IO_TLS,
  996. "id=%p: Setting ALPN list %s",
  997. (void *)&s2n_handler->handler,
  998. aws_string_c_str(options->alpn_list));
  999. const char protocols_cpy[4][128];
  1000. AWS_ZERO_ARRAY(protocols_cpy);
  1001. size_t protocols_size = 4;
  1002. if (s_parse_protocol_preferences(options->alpn_list, protocols_cpy, &protocols_size)) {
  1003. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  1004. goto cleanup_conn;
  1005. }
  1006. const char *protocols[4];
  1007. AWS_ZERO_ARRAY(protocols);
  1008. for (size_t i = 0; i < protocols_size; ++i) {
  1009. protocols[i] = protocols_cpy[i];
  1010. }
  1011. if (s2n_connection_set_protocol_preferences(
  1012. s2n_handler->connection, (const char *const *)protocols, (int)protocols_size)) {
  1013. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  1014. goto cleanup_conn;
  1015. }
  1016. }
  1017. if (s2n_connection_set_config(s2n_handler->connection, s2n_handler->s2n_ctx->s2n_config)) {
  1018. AWS_LOGF_WARN(
  1019. AWS_LS_IO_TLS,
  1020. "id=%p: configuration error %s (%s)",
  1021. (void *)&s2n_handler->handler,
  1022. s2n_strerror(s2n_errno, "EN"),
  1023. s2n_strerror_debug(s2n_errno, "EN"));
  1024. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  1025. goto cleanup_conn;
  1026. }
  1027. aws_channel_task_init(
  1028. &s2n_handler->delayed_shutdown_task.task,
  1029. s_delayed_shutdown_task_fn,
  1030. &s2n_handler->handler,
  1031. "s2n_delayed_shutdown");
  1032. if (s_s2n_tls_channel_handler_schedule_thread_local_cleanup(slot)) {
  1033. goto cleanup_conn;
  1034. }
  1035. return &s2n_handler->handler;
  1036. cleanup_conn:
  1037. s_s2n_handler_destroy(&s2n_handler->handler);
  1038. return NULL;
  1039. }
  1040. struct aws_channel_handler *aws_tls_client_handler_new(
  1041. struct aws_allocator *allocator,
  1042. struct aws_tls_connection_options *options,
  1043. struct aws_channel_slot *slot) {
  1044. return s_new_tls_handler(allocator, options, slot, S2N_CLIENT);
  1045. }
  1046. struct aws_channel_handler *aws_tls_server_handler_new(
  1047. struct aws_allocator *allocator,
  1048. struct aws_tls_connection_options *options,
  1049. struct aws_channel_slot *slot) {
  1050. return s_new_tls_handler(allocator, options, slot, S2N_SERVER);
  1051. }
  1052. static void s_s2n_ctx_destroy(struct s2n_ctx *s2n_ctx) {
  1053. if (s2n_ctx != NULL) {
  1054. s2n_config_free(s2n_ctx->s2n_config);
  1055. if (s2n_ctx->custom_cert_chain_and_key) {
  1056. s2n_cert_chain_and_key_free(s2n_ctx->custom_cert_chain_and_key);
  1057. }
  1058. s2n_ctx->custom_key_handler = aws_custom_key_op_handler_release(s2n_ctx->custom_key_handler);
  1059. aws_mem_release(s2n_ctx->ctx.alloc, s2n_ctx);
  1060. }
  1061. }
  1062. static int s2n_wall_clock_time_nanoseconds(void *context, uint64_t *time_in_ns) {
  1063. (void)context;
  1064. if (aws_sys_clock_get_ticks(time_in_ns)) {
  1065. *time_in_ns = 0;
  1066. return -1;
  1067. }
  1068. return 0;
  1069. }
  1070. static int s2n_monotonic_clock_time_nanoseconds(void *context, uint64_t *time_in_ns) {
  1071. (void)context;
  1072. if (aws_high_res_clock_get_ticks(time_in_ns)) {
  1073. *time_in_ns = 0;
  1074. return -1;
  1075. }
  1076. return 0;
  1077. }
  1078. static void s_log_and_raise_s2n_errno(const char *msg) {
  1079. AWS_LOGF_ERROR(
  1080. AWS_LS_IO_TLS, "%s: %s (%s)", msg, s2n_strerror(s2n_errno, "EN"), s2n_strerror_debug(s2n_errno, "EN"));
  1081. aws_raise_error(AWS_IO_TLS_CTX_ERROR);
  1082. }
  1083. static struct aws_tls_ctx *s_tls_ctx_new(
  1084. struct aws_allocator *alloc,
  1085. const struct aws_tls_ctx_options *options,
  1086. s2n_mode mode) {
  1087. struct s2n_ctx *s2n_ctx = aws_mem_calloc(alloc, 1, sizeof(struct s2n_ctx));
  1088. if (!s2n_ctx) {
  1089. return NULL;
  1090. }
  1091. if (!aws_tls_is_cipher_pref_supported(options->cipher_pref)) {
  1092. aws_raise_error(AWS_IO_TLS_CIPHER_PREF_UNSUPPORTED);
  1093. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "static: TLS Cipher Preference is not supported: %d.", options->cipher_pref);
  1094. return NULL;
  1095. }
  1096. s2n_ctx->ctx.alloc = alloc;
  1097. s2n_ctx->ctx.impl = s2n_ctx;
  1098. aws_ref_count_init(&s2n_ctx->ctx.ref_count, s2n_ctx, (aws_simple_completion_callback *)s_s2n_ctx_destroy);
  1099. s2n_ctx->s2n_config = s2n_config_new();
  1100. if (!s2n_ctx->s2n_config) {
  1101. s_log_and_raise_s2n_errno("ctx: creation failed");
  1102. goto cleanup_s2n_config;
  1103. }
  1104. int set_clock_result = s2n_config_set_wall_clock(s2n_ctx->s2n_config, s2n_wall_clock_time_nanoseconds, NULL);
  1105. if (set_clock_result != S2N_ERR_T_OK) {
  1106. s_log_and_raise_s2n_errno("ctx: failed to set wall clock");
  1107. goto cleanup_s2n_config;
  1108. }
  1109. set_clock_result = s2n_config_set_monotonic_clock(s2n_ctx->s2n_config, s2n_monotonic_clock_time_nanoseconds, NULL);
  1110. if (set_clock_result != S2N_ERR_T_OK) {
  1111. s_log_and_raise_s2n_errno("ctx: failed to set monotonic clock");
  1112. goto cleanup_s2n_config;
  1113. }
  1114. if (options->custom_key_op_handler != NULL) {
  1115. /* PKCS#11 integration hasn't been tested with TLS 1.3, so don't use cipher preferences that allow 1.3 */
  1116. switch (options->minimum_tls_version) {
  1117. case AWS_IO_SSLv3:
  1118. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "CloudFront-SSL-v-3");
  1119. break;
  1120. case AWS_IO_TLSv1:
  1121. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "CloudFront-TLS-1-0-2014");
  1122. break;
  1123. case AWS_IO_TLSv1_1:
  1124. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "ELBSecurityPolicy-TLS-1-1-2017-01");
  1125. break;
  1126. case AWS_IO_TLSv1_2:
  1127. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "ELBSecurityPolicy-TLS-1-2-Ext-2018-06");
  1128. break;
  1129. case AWS_IO_TLSv1_3:
  1130. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "TLS 1.3 with PKCS#11 is not supported yet.");
  1131. aws_raise_error(AWS_IO_TLS_VERSION_UNSUPPORTED);
  1132. goto cleanup_s2n_config;
  1133. case AWS_IO_TLS_VER_SYS_DEFAULTS:
  1134. default:
  1135. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "ELBSecurityPolicy-TLS-1-1-2017-01");
  1136. }
  1137. } else {
  1138. switch (options->minimum_tls_version) {
  1139. case AWS_IO_SSLv3:
  1140. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "AWS-CRT-SDK-SSLv3.0");
  1141. break;
  1142. case AWS_IO_TLSv1:
  1143. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "AWS-CRT-SDK-TLSv1.0");
  1144. break;
  1145. case AWS_IO_TLSv1_1:
  1146. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "AWS-CRT-SDK-TLSv1.1");
  1147. break;
  1148. case AWS_IO_TLSv1_2:
  1149. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "AWS-CRT-SDK-TLSv1.2");
  1150. break;
  1151. case AWS_IO_TLSv1_3:
  1152. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "AWS-CRT-SDK-TLSv1.3");
  1153. break;
  1154. case AWS_IO_TLS_VER_SYS_DEFAULTS:
  1155. default:
  1156. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "AWS-CRT-SDK-TLSv1.0");
  1157. }
  1158. }
  1159. switch (options->cipher_pref) {
  1160. case AWS_IO_TLS_CIPHER_PREF_SYSTEM_DEFAULT:
  1161. /* No-Op, if the user configured a minimum_tls_version then a version-specific Cipher Preference was set */
  1162. break;
  1163. case AWS_IO_TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05:
  1164. s2n_config_set_cipher_preferences(s2n_ctx->s2n_config, "PQ-TLS-1-0-2021-05-26");
  1165. break;
  1166. default:
  1167. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "Unrecognized TLS Cipher Preference: %d", options->cipher_pref);
  1168. aws_raise_error(AWS_IO_TLS_CIPHER_PREF_UNSUPPORTED);
  1169. goto cleanup_s2n_config;
  1170. }
  1171. if (aws_tls_options_buf_is_set(&options->certificate) && aws_tls_options_buf_is_set(&options->private_key)) {
  1172. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "ctx: Certificate and key have been set, setting them up now.");
  1173. if (!aws_text_is_utf8(options->certificate.buffer, options->certificate.len)) {
  1174. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "static: failed to import certificate, must be ASCII/UTF-8 encoded");
  1175. aws_raise_error(AWS_IO_FILE_VALIDATION_FAILURE);
  1176. goto cleanup_s2n_config;
  1177. }
  1178. if (!aws_text_is_utf8(options->private_key.buffer, options->private_key.len)) {
  1179. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "static: failed to import private key, must be ASCII/UTF-8 encoded");
  1180. aws_raise_error(AWS_IO_FILE_VALIDATION_FAILURE);
  1181. goto cleanup_s2n_config;
  1182. }
  1183. /* Ensure that what we pass to s2n is zero-terminated */
  1184. struct aws_string *certificate_string = aws_string_new_from_buf(alloc, &options->certificate);
  1185. struct aws_string *private_key_string = aws_string_new_from_buf(alloc, &options->private_key);
  1186. int err_code = s2n_config_add_cert_chain_and_key(
  1187. s2n_ctx->s2n_config, (const char *)certificate_string->bytes, (const char *)private_key_string->bytes);
  1188. aws_string_destroy(certificate_string);
  1189. aws_string_destroy_secure(private_key_string);
  1190. if (mode == S2N_CLIENT) {
  1191. s2n_config_set_client_auth_type(s2n_ctx->s2n_config, S2N_CERT_AUTH_REQUIRED);
  1192. }
  1193. if (err_code != S2N_ERR_T_OK) {
  1194. s_log_and_raise_s2n_errno("ctx: Failed to add certificate and private key");
  1195. goto cleanup_s2n_config;
  1196. }
  1197. } else if (options->custom_key_op_handler != NULL) {
  1198. s2n_ctx->custom_key_handler = aws_custom_key_op_handler_acquire(options->custom_key_op_handler);
  1199. /* set callback so that we can do custom private key operations */
  1200. if (s2n_config_set_async_pkey_callback(s2n_ctx->s2n_config, s_s2n_async_pkey_callback)) {
  1201. s_log_and_raise_s2n_errno("ctx: failed to set private key callback");
  1202. goto cleanup_s2n_config;
  1203. }
  1204. /* set certificate.
  1205. * we need to create a custom s2n_cert_chain_and_key that knows the cert but not the key */
  1206. s2n_ctx->custom_cert_chain_and_key = s2n_cert_chain_and_key_new();
  1207. if (!s2n_ctx->custom_cert_chain_and_key) {
  1208. s_log_and_raise_s2n_errno("ctx: creation failed");
  1209. goto cleanup_s2n_config;
  1210. }
  1211. if (s2n_cert_chain_and_key_load_public_pem_bytes(
  1212. s2n_ctx->custom_cert_chain_and_key, options->certificate.buffer, options->certificate.len)) {
  1213. s_log_and_raise_s2n_errno("ctx: failed to load certificate");
  1214. goto cleanup_s2n_config;
  1215. }
  1216. if (s2n_config_add_cert_chain_and_key_to_store(s2n_ctx->s2n_config, s2n_ctx->custom_cert_chain_and_key)) {
  1217. s_log_and_raise_s2n_errno("ctx: failed to add certificate to store");
  1218. goto cleanup_s2n_config;
  1219. }
  1220. if (mode == S2N_CLIENT) {
  1221. s2n_config_set_client_auth_type(s2n_ctx->s2n_config, S2N_CERT_AUTH_REQUIRED);
  1222. }
  1223. }
  1224. if (options->verify_peer) {
  1225. if (s2n_config_set_check_stapled_ocsp_response(s2n_ctx->s2n_config, 1) == S2N_SUCCESS) {
  1226. if (s2n_config_set_status_request_type(s2n_ctx->s2n_config, S2N_STATUS_REQUEST_OCSP) != S2N_SUCCESS) {
  1227. s_log_and_raise_s2n_errno("ctx: ocsp status request cannot be set");
  1228. goto cleanup_s2n_config;
  1229. }
  1230. } else {
  1231. if (s2n_error_get_type(s2n_errno) == S2N_ERR_T_USAGE) {
  1232. AWS_LOGF_INFO(AWS_LS_IO_TLS, "ctx: cannot enable ocsp stapling: %s", s2n_strerror(s2n_errno, "EN"));
  1233. } else {
  1234. s_log_and_raise_s2n_errno("ctx: cannot enable ocsp stapling");
  1235. goto cleanup_s2n_config;
  1236. }
  1237. }
  1238. if (options->ca_path || aws_tls_options_buf_is_set(&options->ca_file)) {
  1239. /* The user called an override_default_trust_store() function.
  1240. * Begin by wiping anything that s2n loaded by default */
  1241. if (s2n_config_wipe_trust_store(s2n_ctx->s2n_config)) {
  1242. s_log_and_raise_s2n_errno("ctx: failed to wipe default trust store");
  1243. goto cleanup_s2n_config;
  1244. }
  1245. if (options->ca_path) {
  1246. if (s2n_config_set_verification_ca_location(
  1247. s2n_ctx->s2n_config, NULL, aws_string_c_str(options->ca_path))) {
  1248. s_log_and_raise_s2n_errno("ctx: configuration error");
  1249. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "Failed to set ca_path %s\n", aws_string_c_str(options->ca_path));
  1250. goto cleanup_s2n_config;
  1251. }
  1252. }
  1253. if (aws_tls_options_buf_is_set(&options->ca_file)) {
  1254. /* Ensure that what we pass to s2n is zero-terminated */
  1255. struct aws_string *ca_file_string = aws_string_new_from_buf(alloc, &options->ca_file);
  1256. int set_ca_result =
  1257. s2n_config_add_pem_to_trust_store(s2n_ctx->s2n_config, (const char *)ca_file_string->bytes);
  1258. aws_string_destroy(ca_file_string);
  1259. if (set_ca_result) {
  1260. s_log_and_raise_s2n_errno("ctx: configuration error");
  1261. AWS_LOGF_ERROR(AWS_LS_IO_TLS, "Failed to set ca_file %s\n", (const char *)options->ca_file.buffer);
  1262. goto cleanup_s2n_config;
  1263. }
  1264. }
  1265. } else if (s_default_ca_file || s_default_ca_dir) {
  1266. /* User wants to use the system's default trust store.
  1267. *
  1268. * Note that s2n's trust store always starts with libcrypto's default locations.
  1269. * These paths are configured when libcrypto is built (--openssldir),
  1270. * but might not be right for the current machine (e.g. if libcrypto
  1271. * is statically linked into an application that is distributed
  1272. * to multiple flavors of Linux). Therefore, load the locations that
  1273. * were found at library startup. */
  1274. if (s2n_config_set_verification_ca_location(s2n_ctx->s2n_config, s_default_ca_file, s_default_ca_dir)) {
  1275. s_log_and_raise_s2n_errno("ctx: configuration error");
  1276. AWS_LOGF_ERROR(
  1277. AWS_LS_IO_TLS, "Failed to set ca_path: %s and ca_file %s\n", s_default_ca_dir, s_default_ca_file);
  1278. goto cleanup_s2n_config;
  1279. }
  1280. } else {
  1281. /* Cannot find system's trust store */
  1282. aws_raise_error(AWS_IO_TLS_ERROR_DEFAULT_TRUST_STORE_NOT_FOUND);
  1283. AWS_LOGF_ERROR(
  1284. AWS_LS_IO_TLS,
  1285. "Default TLS trust store not found on this system."
  1286. " Install CA certificates, or \"override default trust store\".");
  1287. goto cleanup_s2n_config;
  1288. }
  1289. if (mode == S2N_SERVER && s2n_config_set_client_auth_type(s2n_ctx->s2n_config, S2N_CERT_AUTH_REQUIRED)) {
  1290. s_log_and_raise_s2n_errno("ctx: failed to set client auth type");
  1291. goto cleanup_s2n_config;
  1292. }
  1293. } else if (mode != S2N_SERVER) {
  1294. AWS_LOGF_WARN(
  1295. AWS_LS_IO_TLS,
  1296. "ctx: X.509 validation has been disabled. "
  1297. "If this is not running in a test environment, this is likely a security vulnerability.");
  1298. if (s2n_config_disable_x509_verification(s2n_ctx->s2n_config)) {
  1299. s_log_and_raise_s2n_errno("ctx: failed to disable x509 verification");
  1300. goto cleanup_s2n_config;
  1301. }
  1302. }
  1303. if (options->alpn_list) {
  1304. AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "ctx: Setting ALPN list %s", aws_string_c_str(options->alpn_list));
  1305. const char protocols_cpy[4][128];
  1306. AWS_ZERO_ARRAY(protocols_cpy);
  1307. size_t protocols_size = 4;
  1308. if (s_parse_protocol_preferences(options->alpn_list, protocols_cpy, &protocols_size)) {
  1309. s_log_and_raise_s2n_errno("ctx: Failed to parse ALPN list");
  1310. goto cleanup_s2n_config;
  1311. }
  1312. const char *protocols[4];
  1313. AWS_ZERO_ARRAY(protocols);
  1314. for (size_t i = 0; i < protocols_size; ++i) {
  1315. protocols[i] = protocols_cpy[i];
  1316. }
  1317. if (s2n_config_set_protocol_preferences(s2n_ctx->s2n_config, protocols, (int)protocols_size)) {
  1318. s_log_and_raise_s2n_errno("ctx: Failed to set protocol preferences");
  1319. goto cleanup_s2n_config;
  1320. }
  1321. }
  1322. if (options->max_fragment_size == 512) {
  1323. s2n_config_send_max_fragment_length(s2n_ctx->s2n_config, S2N_TLS_MAX_FRAG_LEN_512);
  1324. } else if (options->max_fragment_size == 1024) {
  1325. s2n_config_send_max_fragment_length(s2n_ctx->s2n_config, S2N_TLS_MAX_FRAG_LEN_1024);
  1326. } else if (options->max_fragment_size == 2048) {
  1327. s2n_config_send_max_fragment_length(s2n_ctx->s2n_config, S2N_TLS_MAX_FRAG_LEN_2048);
  1328. } else if (options->max_fragment_size == 4096) {
  1329. s2n_config_send_max_fragment_length(s2n_ctx->s2n_config, S2N_TLS_MAX_FRAG_LEN_4096);
  1330. }
  1331. return &s2n_ctx->ctx;
  1332. cleanup_s2n_config:
  1333. s_s2n_ctx_destroy(s2n_ctx);
  1334. return NULL;
  1335. }
  1336. struct aws_tls_ctx *aws_tls_server_ctx_new(struct aws_allocator *alloc, const struct aws_tls_ctx_options *options) {
  1337. aws_io_fatal_assert_library_initialized();
  1338. return s_tls_ctx_new(alloc, options, S2N_SERVER);
  1339. }
  1340. struct aws_tls_ctx *aws_tls_client_ctx_new(struct aws_allocator *alloc, const struct aws_tls_ctx_options *options) {
  1341. aws_io_fatal_assert_library_initialized();
  1342. return s_tls_ctx_new(alloc, options, S2N_CLIENT);
  1343. }