forked from awslabs/aws-c-io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths2n_tls_channel_handler.c
1762 lines (1462 loc) · 67.3 KB
/
s2n_tls_channel_handler.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/io/tls_channel_handler.h>
#include <aws/common/clock.h>
#include <aws/common/encoding.h>
#include <aws/common/mutex.h>
#include <aws/common/string.h>
#include <aws/common/task_scheduler.h>
#include <aws/common/thread.h>
#include <aws/io/channel.h>
#include <aws/io/event_loop.h>
#include <aws/io/file_utils.h>
#include <aws/io/logging.h>
#include <aws/io/private/event_loop_impl.h>
#include <aws/io/private/pki_utils.h>
#include <aws/io/private/tls_channel_handler_shared.h>
#include <aws/io/statistics.h>
#include <s2n.h>
#ifdef AWS_S2N_INSOURCE_PATH
# include <api/unstable/cleanup.h>
#else
# include <s2n/unstable/cleanup.h>
#endif
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define EST_TLS_RECORD_OVERHEAD 53 /* 5 byte header + 32 + 16 bytes for padding */
#define KB_1 1024
#define MAX_RECORD_SIZE (KB_1 * 16)
#define EST_HANDSHAKE_SIZE (7 * KB_1)
static const char *s_default_ca_dir = NULL;
static const char *s_default_ca_file = NULL;
struct s2n_handler {
struct aws_channel_handler handler;
struct aws_tls_channel_handler_shared shared_state;
struct s2n_connection *connection;
struct s2n_ctx *s2n_ctx;
struct aws_channel_slot *slot;
struct aws_linked_list input_queue;
struct aws_byte_buf protocol;
struct aws_byte_buf server_name;
aws_channel_on_message_write_completed_fn *latest_message_on_completion;
struct aws_channel_task sequential_tasks;
void *latest_message_completion_user_data;
aws_tls_on_negotiation_result_fn *on_negotiation_result;
aws_tls_on_data_read_fn *on_data_read;
aws_tls_on_error_fn *on_error;
void *user_data;
bool advertise_alpn_message;
enum {
NEGOTIATION_ONGOING,
NEGOTIATION_FAILED,
NEGOTIATION_SUCCEEDED,
} state;
struct aws_channel_task read_task;
bool read_task_pending;
enum aws_tls_handler_read_state read_state;
int shutdown_error_code;
struct aws_channel_task delayed_shutdown_task;
};
struct s2n_ctx {
struct aws_tls_ctx ctx;
struct s2n_config *s2n_config;
/* Only used in special circumstances (ex: have cert but no key, because key is in PKCS#11) */
struct s2n_cert_chain_and_key *custom_cert_chain_and_key;
/**
* Custom key operations to perform when a private key operation is required in the TLS handshake.
* Only will be used if non-NULL, otherwise this is ignored and the standard private key operations
* are performed instead.
* NOTE: PKCS11 also is done via this custom_key_handler.
*
* See aws_custom_key_op_handler in tls_channel_handler.h for more details.
*/
struct aws_custom_key_op_handler *custom_key_handler;
};
struct aws_tls_key_operation {
struct aws_allocator *alloc;
struct s2n_async_pkey_op *s2n_op;
struct s2n_handler *s2n_handler;
enum aws_tls_key_operation_type operation_type;
enum aws_tls_signature_algorithm signature_algorithm;
enum aws_tls_hash_algorithm digest_algorithm;
struct aws_byte_buf input_data;
struct aws_channel_task completion_task;
int completion_error_code;
struct aws_atomic_var complete_count;
};
AWS_STATIC_STRING_FROM_LITERAL(s_debian_path, "/etc/ssl/certs");
AWS_STATIC_STRING_FROM_LITERAL(s_rhel_path, "/etc/pki/tls/certs");
AWS_STATIC_STRING_FROM_LITERAL(s_android_path, "/system/etc/security/cacerts");
AWS_STATIC_STRING_FROM_LITERAL(s_free_bsd_path, "/usr/local/share/certs");
AWS_STATIC_STRING_FROM_LITERAL(s_net_bsd_path, "/etc/openssl/certs");
AWS_IO_API const char *aws_determine_default_pki_dir(void) {
/* debian variants; OpenBSD (although the directory doesn't exist by default) */
if (aws_path_exists(s_debian_path)) {
return aws_string_c_str(s_debian_path);
}
/* RHEL variants */
if (aws_path_exists(s_rhel_path)) {
return aws_string_c_str(s_rhel_path);
}
/* android */
if (aws_path_exists(s_android_path)) {
return aws_string_c_str(s_android_path);
}
/* FreeBSD */
if (aws_path_exists(s_free_bsd_path)) {
return aws_string_c_str(s_free_bsd_path);
}
/* NetBSD */
if (aws_path_exists(s_net_bsd_path)) {
return aws_string_c_str(s_net_bsd_path);
}
return NULL;
}
AWS_STATIC_STRING_FROM_LITERAL(s_debian_ca_file_path, "/etc/ssl/certs/ca-certificates.crt");
AWS_STATIC_STRING_FROM_LITERAL(s_old_rhel_ca_file_path, "/etc/pki/tls/certs/ca-bundle.crt");
AWS_STATIC_STRING_FROM_LITERAL(s_open_suse_ca_file_path, "/etc/ssl/ca-bundle.pem");
AWS_STATIC_STRING_FROM_LITERAL(s_open_elec_ca_file_path, "/etc/pki/tls/cacert.pem");
AWS_STATIC_STRING_FROM_LITERAL(s_modern_rhel_ca_file_path, "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem");
AWS_STATIC_STRING_FROM_LITERAL(s_openbsd_ca_file_path, "/etc/ssl/cert.pem");
AWS_IO_API const char *aws_determine_default_pki_ca_file(void) {
/* debian variants */
if (aws_path_exists(s_debian_ca_file_path)) {
return aws_string_c_str(s_debian_ca_file_path);
}
/* Old RHEL variants */
if (aws_path_exists(s_old_rhel_ca_file_path)) {
return aws_string_c_str(s_old_rhel_ca_file_path);
}
/* Open SUSE */
if (aws_path_exists(s_open_suse_ca_file_path)) {
return aws_string_c_str(s_open_suse_ca_file_path);
}
/* Open ELEC */
if (aws_path_exists(s_open_elec_ca_file_path)) {
return aws_string_c_str(s_open_elec_ca_file_path);
}
/* Modern RHEL variants */
if (aws_path_exists(s_modern_rhel_ca_file_path)) {
return aws_string_c_str(s_modern_rhel_ca_file_path);
}
/* OpenBSD */
if (aws_path_exists(s_openbsd_ca_file_path)) {
return aws_string_c_str(s_openbsd_ca_file_path);
}
return NULL;
}
static struct aws_allocator *s_library_allocator = NULL;
static int s_s2n_mem_init(void) {
return S2N_SUCCESS;
}
static int s_s2n_mem_cleanup(void) {
return S2N_SUCCESS;
}
static int s_s2n_mem_malloc(void **ptr, uint32_t requested, uint32_t *allocated) {
*ptr = aws_mem_acquire(s_library_allocator, requested);
*allocated = requested;
return S2N_SUCCESS;
}
static int s_s2n_mem_free(void *ptr, uint32_t size) {
(void)size;
aws_mem_release(s_library_allocator, ptr);
return S2N_SUCCESS;
}
/* If s2n is already initialized, then we don't call s2n_init() or s2n_cleanup() ourselves */
static bool s_s2n_initialized_externally = false;
void aws_tls_init_static_state(struct aws_allocator *alloc) {
AWS_FATAL_ASSERT(alloc);
AWS_LOGF_INFO(AWS_LS_IO_TLS, "static: Initializing TLS using s2n.");
/* Disable atexit behavior, so that s2n_cleanup() fully cleans things up.
*
* By default, s2n uses an ataexit handler and doesn't fully clean up until the program exits.
* This can cause a crash if s2n is compiled into a shared library and
* that library is unloaded before the appexit handler runs. */
if (s2n_disable_atexit() != S2N_SUCCESS) {
/* If this call fails, then s2n is already initialized
* https://github.com/aws/s2n-tls/blob/2ad65c11a96368591fe809cd27fd1e390b2c8ce3/api/s2n.h#L211-L212 */
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "static: s2n is already initialized");
s_s2n_initialized_externally = true;
} else {
s_s2n_initialized_externally = false;
}
if (!s_s2n_initialized_externally) {
s_library_allocator = alloc;
if (S2N_SUCCESS != s2n_mem_set_callbacks(s_s2n_mem_init, s_s2n_mem_cleanup, s_s2n_mem_malloc, s_s2n_mem_free)) {
fprintf(stderr, "s2n_mem_set_callbacks() failed: %d (%s)\n", s2n_errno, s2n_strerror(s2n_errno, "EN"));
AWS_FATAL_ASSERT(0 && "s2n_mem_set_callbacks() failed");
}
if (s2n_init() != S2N_SUCCESS) {
fprintf(stderr, "s2n_init() failed: %d (%s)\n", s2n_errno, s2n_strerror(s2n_errno, "EN"));
AWS_FATAL_ASSERT(0 && "s2n_init() failed");
}
}
s_default_ca_dir = aws_determine_default_pki_dir();
s_default_ca_file = aws_determine_default_pki_ca_file();
if (s_default_ca_dir || s_default_ca_file) {
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"ctx: Based on OS, we detected the default PKI path as %s, and ca file as %s",
s_default_ca_dir,
s_default_ca_file);
} else {
AWS_LOGF_WARN(
AWS_LS_IO_TLS,
"Default TLS trust store not found on this system."
" TLS connections will fail unless trusted CA certificates are installed,"
" or \"override default trust store\" is used while creating the TLS context.");
}
}
void aws_tls_clean_up_static_state(void) {
/* only clean up s2n if we were the ones that initialized it */
if (!s_s2n_initialized_externally) {
s2n_cleanup_final();
}
}
bool aws_tls_is_alpn_available(void) {
return true;
}
bool aws_tls_is_cipher_pref_supported(enum aws_tls_cipher_pref cipher_pref) {
switch (cipher_pref) {
case AWS_IO_TLS_CIPHER_PREF_SYSTEM_DEFAULT:
return true;
/* PQ Crypto no-ops on android for now */
#ifndef ANDROID
case AWS_IO_TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05:
return true;
case AWS_IO_TLS_CIPHER_PREF_PQ_TLSV1_2_2024_10:
return true;
#endif
default:
return false;
}
}
static int s_generic_read(struct s2n_handler *handler, struct aws_byte_buf *buf) {
size_t written = 0;
while (!aws_linked_list_empty(&handler->input_queue) && written < buf->len) {
struct aws_linked_list_node *node = aws_linked_list_pop_front(&handler->input_queue);
struct aws_io_message *message = AWS_CONTAINER_OF(node, struct aws_io_message, queueing_handle);
size_t remaining_message_len = message->message_data.len - message->copy_mark;
size_t remaining_buf_len = buf->len - written;
size_t to_write = remaining_message_len < remaining_buf_len ? remaining_message_len : remaining_buf_len;
struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);
aws_byte_cursor_advance(&message_cursor, message->copy_mark);
aws_byte_cursor_read(&message_cursor, buf->buffer + written, to_write);
written += to_write;
message->copy_mark += to_write;
if (message->copy_mark == message->message_data.len) {
aws_mem_release(message->allocator, message);
} else {
aws_linked_list_push_front(&handler->input_queue, &message->queueing_handle);
}
}
if (written) {
return (int)written;
}
errno = EAGAIN;
return -1;
}
static int s_s2n_handler_recv(void *io_context, uint8_t *buf, uint32_t len) {
struct s2n_handler *handler = (struct s2n_handler *)io_context;
struct aws_byte_buf read_buffer = aws_byte_buf_from_array(buf, len);
return s_generic_read(handler, &read_buffer);
}
static int s_generic_send(struct s2n_handler *handler, struct aws_byte_buf *buf) {
struct aws_byte_cursor buffer_cursor = aws_byte_cursor_from_buf(buf);
size_t processed = 0;
while (processed < buf->len) {
const size_t overhead = aws_channel_slot_upstream_message_overhead(handler->slot);
const size_t message_size_hint = (buf->len - processed) + overhead;
struct aws_io_message *message = aws_channel_acquire_message_from_pool(
handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, message_size_hint);
if (message->message_data.capacity <= overhead) {
aws_mem_release(message->allocator, message);
errno = ENOMEM;
return -1;
}
const size_t available_msg_write_capacity = message->message_data.capacity - overhead;
const size_t to_write =
available_msg_write_capacity >= buffer_cursor.len ? buffer_cursor.len : available_msg_write_capacity;
struct aws_byte_cursor chunk = aws_byte_cursor_advance(&buffer_cursor, to_write);
if (aws_byte_buf_append(&message->message_data, &chunk)) {
aws_mem_release(message->allocator, message);
return -1;
}
processed += message->message_data.len;
if (processed == buf->len) {
message->on_completion = handler->latest_message_on_completion;
message->user_data = handler->latest_message_completion_user_data;
handler->latest_message_on_completion = NULL;
handler->latest_message_completion_user_data = NULL;
}
if (aws_channel_slot_send_message(handler->slot, message, AWS_CHANNEL_DIR_WRITE)) {
aws_mem_release(message->allocator, message);
errno = EPIPE;
return -1;
}
}
if (processed) {
return (int)processed;
}
errno = EAGAIN;
return -1;
}
static int s_s2n_handler_send(void *io_context, const uint8_t *buf, uint32_t len) {
struct s2n_handler *handler = (struct s2n_handler *)io_context;
struct aws_byte_buf send_buf = aws_byte_buf_from_array(buf, len);
return s_generic_send(handler, &send_buf);
}
static void s_s2n_handler_destroy(struct aws_channel_handler *handler) {
if (handler) {
struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
aws_tls_channel_handler_shared_clean_up(&s2n_handler->shared_state);
if (s2n_handler->connection) {
s2n_connection_free(s2n_handler->connection);
}
if (s2n_handler->s2n_ctx) {
aws_tls_ctx_release(&s2n_handler->s2n_ctx->ctx);
}
aws_mem_release(handler->alloc, (void *)s2n_handler);
}
}
static void s_on_negotiation_result(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
int error_code,
void *user_data) {
struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
aws_on_tls_negotiation_completed(&s2n_handler->shared_state, error_code);
if (s2n_handler->on_negotiation_result) {
s2n_handler->on_negotiation_result(handler, slot, error_code, user_data);
}
}
static int s_drive_negotiation(struct aws_channel_handler *handler) {
struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
AWS_ASSERT(s2n_handler->state == NEGOTIATION_ONGOING);
aws_on_drive_tls_negotiation(&s2n_handler->shared_state);
s2n_blocked_status blocked = S2N_NOT_BLOCKED;
do {
int negotiation_code = s2n_negotiate(s2n_handler->connection, &blocked);
int s2n_error = s2n_errno;
if (negotiation_code == S2N_ERR_T_OK) {
s2n_handler->state = NEGOTIATION_SUCCEEDED;
const char *protocol = s2n_get_application_protocol(s2n_handler->connection);
if (protocol) {
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Alpn protocol negotiated as %s", (void *)handler, protocol);
s2n_handler->protocol = aws_byte_buf_from_c_str(protocol);
}
const char *server_name = s2n_get_server_name(s2n_handler->connection);
if (server_name) {
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Remote server name is %s", (void *)handler, server_name);
s2n_handler->server_name = aws_byte_buf_from_c_str(server_name);
}
if (s2n_handler->slot->adj_right && s2n_handler->advertise_alpn_message && protocol) {
struct aws_io_message *message = aws_channel_acquire_message_from_pool(
s2n_handler->slot->channel,
AWS_IO_MESSAGE_APPLICATION_DATA,
sizeof(struct aws_tls_negotiated_protocol_message));
message->message_tag = AWS_TLS_NEGOTIATED_PROTOCOL_MESSAGE;
struct aws_tls_negotiated_protocol_message *protocol_message =
(struct aws_tls_negotiated_protocol_message *)message->message_data.buffer;
protocol_message->protocol = s2n_handler->protocol;
message->message_data.len = sizeof(struct aws_tls_negotiated_protocol_message);
if (aws_channel_slot_send_message(s2n_handler->slot, message, AWS_CHANNEL_DIR_READ)) {
aws_mem_release(message->allocator, message);
aws_channel_shutdown(s2n_handler->slot->channel, aws_last_error());
return AWS_OP_SUCCESS;
}
}
s_on_negotiation_result(handler, s2n_handler->slot, AWS_OP_SUCCESS, s2n_handler->user_data);
break;
}
if (s2n_error_get_type(s2n_error) != S2N_ERR_T_BLOCKED) {
AWS_LOGF_WARN(
AWS_LS_IO_TLS,
"id=%p: negotiation failed with error %s (%s)",
(void *)handler,
s2n_strerror(s2n_error, "EN"),
s2n_strerror_debug(s2n_error, "EN"));
if (s2n_error_get_type(s2n_error) == S2N_ERR_T_ALERT) {
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"id=%p: Alert code %d",
(void *)handler,
s2n_connection_get_alert(s2n_handler->connection));
}
const char *err_str = s2n_strerror_debug(s2n_error, NULL);
(void)err_str;
s2n_handler->state = NEGOTIATION_FAILED;
aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
s_on_negotiation_result(
handler, s2n_handler->slot, AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE, s2n_handler->user_data);
return AWS_OP_ERR;
}
} while (blocked == S2N_NOT_BLOCKED);
return AWS_OP_SUCCESS;
}
static void s_negotiation_task(struct aws_channel_task *task, void *arg, aws_task_status status) {
task->task_fn = NULL;
task->arg = NULL;
if (status == AWS_TASK_STATUS_RUN_READY) {
struct aws_channel_handler *handler = arg;
struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
if (s2n_handler->state == NEGOTIATION_ONGOING) {
s_drive_negotiation(handler);
}
}
}
int aws_tls_client_handler_start_negotiation(struct aws_channel_handler *handler) {
struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Kicking off TLS negotiation.", (void *)handler);
if (aws_channel_thread_is_callers_thread(s2n_handler->slot->channel)) {
if (s2n_handler->state == NEGOTIATION_ONGOING) {
s_drive_negotiation(handler);
}
return AWS_OP_SUCCESS;
}
aws_channel_task_init(
&s2n_handler->sequential_tasks, s_negotiation_task, handler, "s2n_channel_handler_negotiation");
aws_channel_schedule_task_now(s2n_handler->slot->channel, &s2n_handler->sequential_tasks);
return AWS_OP_SUCCESS;
}
static int s_s2n_handler_process_read_message(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
struct aws_io_message *message) {
struct s2n_handler *s2n_handler = handler->impl;
if (s2n_handler->read_state == AWS_TLS_HANDLER_READ_SHUT_DOWN_COMPLETE) {
if (message) {
aws_mem_release(message->allocator, message);
}
return AWS_OP_SUCCESS;
}
if (AWS_UNLIKELY(s2n_handler->state == NEGOTIATION_FAILED)) {
return aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
}
if (message) {
aws_linked_list_push_back(&s2n_handler->input_queue, &message->queueing_handle);
if (s2n_handler->state == NEGOTIATION_ONGOING) {
size_t message_len = message->message_data.len;
if (s_drive_negotiation(handler) == AWS_OP_SUCCESS) {
aws_channel_slot_increment_read_window(slot, message_len);
} else {
aws_channel_shutdown(s2n_handler->slot->channel, AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
}
return AWS_OP_SUCCESS;
}
}
s2n_blocked_status blocked = S2N_NOT_BLOCKED;
size_t downstream_window = SIZE_MAX;
if (slot->adj_right) {
downstream_window = aws_channel_slot_downstream_read_window(slot);
}
int shutdown_error_code = 0;
size_t processed = 0;
AWS_LOGF_TRACE(
AWS_LS_IO_TLS, "id=%p: Downstream window %llu", (void *)handler, (unsigned long long)downstream_window);
while (processed < downstream_window) {
struct aws_io_message *outgoing_read_message = aws_channel_acquire_message_from_pool(
slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, downstream_window - processed);
ssize_t read = s2n_recv(
s2n_handler->connection,
outgoing_read_message->message_data.buffer,
outgoing_read_message->message_data.capacity,
&blocked);
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Bytes read %lld", (void *)handler, (long long)read);
/* weird race where we received an alert from the peer, but s2n doesn't tell us about it.....
* if this happens, it's a graceful shutdown, so kick it off here.
*
* In other words, s2n, upon graceful shutdown, follows the unix EOF idiom. So just shutdown with
* SUCCESS.
*/
if (read == 0) {
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"id=%p: Alert code %d",
(void *)handler,
s2n_connection_get_alert(s2n_handler->connection));
aws_mem_release(outgoing_read_message->allocator, outgoing_read_message);
goto shutdown_channel;
}
if (read < 0) {
aws_mem_release(outgoing_read_message->allocator, outgoing_read_message);
/* the socket blocked so exit from the loop */
if (s2n_error_get_type(s2n_errno) == S2N_ERR_T_BLOCKED) {
if (s2n_handler->read_state == AWS_TLS_HANDLER_READ_SHUTTING_DOWN) {
/* Propagate the shutdown as we blocked now. */
goto shutdown_channel;
}
break;
}
/* the socket returned a fatal error so shut down */
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: S2N failed to read with error: %s (%s)",
(void *)handler,
s2n_strerror(s2n_errno, "EN"),
s2n_strerror_debug(s2n_errno, "EN"));
shutdown_error_code = AWS_IO_TLS_ERROR_READ_FAILURE;
goto shutdown_channel;
};
/* if read > 0 */
processed += read;
outgoing_read_message->message_data.len = (size_t)read;
if (s2n_handler->on_data_read) {
s2n_handler->on_data_read(handler, slot, &outgoing_read_message->message_data, s2n_handler->user_data);
}
if (slot->adj_right) {
aws_channel_slot_send_message(slot, outgoing_read_message, AWS_CHANNEL_DIR_READ);
} else {
aws_mem_release(outgoing_read_message->allocator, outgoing_read_message);
}
}
AWS_LOGF_TRACE(
AWS_LS_IO_TLS,
"id=%p: Remaining window for this event-loop tick: %llu",
(void *)handler,
(unsigned long long)downstream_window - processed);
return AWS_OP_SUCCESS;
shutdown_channel:
if (s2n_handler->read_state == AWS_TLS_HANDLER_READ_SHUTTING_DOWN) {
if (s2n_handler->shutdown_error_code != 0) {
/* Propagate the original error code if it is set. */
shutdown_error_code = s2n_handler->shutdown_error_code;
}
s2n_handler->read_state = AWS_TLS_HANDLER_READ_SHUT_DOWN_COMPLETE;
aws_channel_slot_on_handler_shutdown_complete(slot, AWS_CHANNEL_DIR_READ, shutdown_error_code, false);
} else {
/* Starts the shutdown process */
aws_channel_shutdown(slot->channel, shutdown_error_code);
}
return AWS_OP_SUCCESS;
}
static int s_s2n_handler_process_write_message(
struct aws_channel_handler *handler,
struct aws_channel_slot *slot,
struct aws_io_message *message) {
(void)slot;
struct s2n_handler *s2n_handler = (struct s2n_handler *)handler->impl;
if (AWS_UNLIKELY(s2n_handler->state != NEGOTIATION_SUCCEEDED)) {
return aws_raise_error(AWS_IO_TLS_ERROR_NOT_NEGOTIATED);
}
s2n_handler->latest_message_on_completion = message->on_completion;
s2n_handler->latest_message_completion_user_data = message->user_data;
s2n_blocked_status blocked;
ssize_t write_code =
s2n_send(s2n_handler->connection, message->message_data.buffer, (ssize_t)message->message_data.len, &blocked);
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Bytes written: %llu", (void *)handler, (unsigned long long)write_code);
ssize_t message_len = (ssize_t)message->message_data.len;
if (write_code < message_len) {
return aws_raise_error(AWS_IO_TLS_ERROR_WRITE_FAILURE);
}
aws_mem_release(message->allocator, message);
return AWS_OP_SUCCESS;
}
static void s_delayed_shutdown_task_fn(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
(void)channel_task;
struct aws_channel_handler *handler = arg;
struct s2n_handler *s2n_handler = handler->impl;
if (status == AWS_TASK_STATUS_RUN_READY) {
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Delayed shut down in write direction", (void *)handler);
s2n_blocked_status blocked;
/* make a best effort, but the channel is going away after this run, so.... you only get one shot anyways */
s2n_shutdown(s2n_handler->connection, &blocked);
}
aws_channel_slot_on_handler_shutdown_complete(
s2n_handler->slot, AWS_CHANNEL_DIR_WRITE, s2n_handler->shutdown_error_code, false);
}
static enum aws_tls_signature_algorithm s_s2n_to_aws_signature_algorithm(s2n_tls_signature_algorithm s2n_alg) {
switch (s2n_alg) {
case S2N_TLS_SIGNATURE_RSA:
return AWS_TLS_SIGNATURE_RSA;
case S2N_TLS_SIGNATURE_ECDSA:
return AWS_TLS_SIGNATURE_ECDSA;
default:
return AWS_TLS_SIGNATURE_UNKNOWN;
}
}
static enum aws_tls_hash_algorithm s_s2n_to_aws_hash_algorithm(s2n_tls_hash_algorithm s2n_alg) {
switch (s2n_alg) {
case (S2N_TLS_HASH_SHA1):
return AWS_TLS_HASH_SHA1;
case (S2N_TLS_HASH_SHA224):
return AWS_TLS_HASH_SHA224;
case (S2N_TLS_HASH_SHA256):
return AWS_TLS_HASH_SHA256;
case (S2N_TLS_HASH_SHA384):
return AWS_TLS_HASH_SHA384;
case (S2N_TLS_HASH_SHA512):
return AWS_TLS_HASH_SHA512;
default:
return AWS_TLS_HASH_UNKNOWN;
}
}
static void s_tls_key_operation_destroy(struct aws_tls_key_operation *operation) {
if (operation->s2n_op) {
s2n_async_pkey_op_free(operation->s2n_op);
}
if (operation->s2n_handler) {
aws_channel_release_hold(operation->s2n_handler->slot->channel);
}
aws_byte_buf_clean_up(&operation->input_data);
aws_mem_release(operation->alloc, operation);
}
/* This task finishes a private key operation on the event-loop thread.
* If the operation was successful, TLS negotiation is resumed.
* If the operation failed, the channel is shut down */
static void s_tls_key_operation_completion_task(
struct aws_channel_task *channel_task,
void *arg,
enum aws_task_status status) {
(void)channel_task;
struct aws_tls_key_operation *operation = arg;
struct s2n_handler *s2n_handler = operation->s2n_handler;
struct aws_channel_handler *handler = &s2n_handler->handler;
/* if things started failing since this task was scheduled, just clean up and bail out */
if (status != AWS_TASK_STATUS_RUN_READY || s2n_handler->state != NEGOTIATION_ONGOING) {
goto clean_up;
}
if (operation->completion_error_code == 0) {
if (s2n_async_pkey_op_apply(operation->s2n_op, s2n_handler->connection)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed applying s2n async pkey op", (void *)handler);
operation->completion_error_code = AWS_ERROR_INVALID_STATE;
}
}
if (operation->completion_error_code == 0) {
s_drive_negotiation(handler);
} else {
aws_channel_shutdown(s2n_handler->slot->channel, operation->completion_error_code);
}
clean_up:
s_tls_key_operation_destroy(operation);
}
/* Common implementation for aws_tls_key_operation_complete() and aws_tls_key_operation_complete_with_error()
* This is called exactly once. Schedules a task to actually finish things up on the event-loop thread. */
static void s_tls_key_operation_complete_common(
struct aws_tls_key_operation *operation,
int error_code,
const struct aws_byte_cursor *output) {
AWS_ASSERT((error_code != 0) ^ (output != NULL)); /* error_code XOR output must be set */
/* Ensure this can only be called once and exactly once. */
size_t complete_count = aws_atomic_fetch_add(&operation->complete_count, 1);
AWS_FATAL_ASSERT(complete_count == 0 && "TLS key operation marked complete multiple times");
struct s2n_handler *s2n_handler = operation->s2n_handler;
struct aws_channel_handler *handler = &s2n_handler->handler;
if (output != NULL) {
/* Immediately pass output through to s2n_op. */
if (s2n_async_pkey_op_set_output(operation->s2n_op, output->ptr, output->len)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed setting output on s2n async pkey op", (void *)handler);
error_code = AWS_ERROR_INVALID_STATE;
goto done;
}
}
done:
operation->completion_error_code = error_code;
/* Schedule a task to finish the operation.
* We schedule a task because the user might
* have completed the operation asynchronously,
* but we need to be on the event-loop thread to
* resume TLS negotiation. */
aws_channel_task_init(
&operation->completion_task,
s_tls_key_operation_completion_task,
operation,
"tls_key_operation_completion_task");
aws_channel_schedule_task_now(s2n_handler->slot->channel, &operation->completion_task);
}
void aws_tls_key_operation_complete(struct aws_tls_key_operation *operation, struct aws_byte_cursor output) {
if (operation == NULL) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "Operation complete: operation is null and therefore cannot be set to complete!");
return;
}
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"id=%p: TLS key operation complete with %zu bytes of output data",
(void *)operation->s2n_handler,
output.len);
s_tls_key_operation_complete_common(operation, 0, &output);
}
void aws_tls_key_operation_complete_with_error(struct aws_tls_key_operation *operation, int error_code) {
if (operation == NULL) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS, "Operation complete with error: operation is null and therefore cannot be set to complete!");
return;
}
if (error_code == 0) {
error_code = AWS_ERROR_UNKNOWN;
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: TLS key operation completed with error, but no error-code set. Using %s",
(void *)operation->s2n_handler,
aws_error_name(error_code));
}
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: TLS key operation complete with error %s",
(void *)operation->s2n_handler,
aws_error_name(error_code));
s_tls_key_operation_complete_common(operation, error_code, NULL);
}
static struct aws_tls_key_operation *s_tls_key_operation_new(
struct aws_channel_handler *handler,
struct s2n_async_pkey_op *s2n_op) {
struct s2n_handler *s2n_handler = handler->impl;
struct aws_tls_key_operation *operation = aws_mem_calloc(handler->alloc, 1, sizeof(struct aws_tls_key_operation));
operation->alloc = handler->alloc;
/* Copy input data */
uint32_t input_size = 0;
if (s2n_async_pkey_op_get_input_size(s2n_op, &input_size)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed querying s2n async pkey op size", (void *)handler);
aws_raise_error(AWS_ERROR_INVALID_STATE);
goto error;
}
aws_byte_buf_init(&operation->input_data, operation->alloc, input_size); /* cannot fail */
if (s2n_async_pkey_op_get_input(s2n_op, operation->input_data.buffer, input_size)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed querying s2n async pkey input", (void *)handler);
aws_raise_error(AWS_ERROR_INVALID_STATE);
goto error;
}
operation->input_data.len = input_size;
/* Get operation type */
s2n_async_pkey_op_type s2n_op_type = 0;
if (s2n_async_pkey_op_get_op_type(s2n_op, &s2n_op_type)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed querying s2n async pkey op type", (void *)handler);
aws_raise_error(AWS_ERROR_INVALID_STATE);
goto error;
}
if (s2n_op_type == S2N_ASYNC_SIGN) {
operation->operation_type = AWS_TLS_KEY_OPERATION_SIGN;
/* Gather additional information if this is a SIGN operation */
s2n_tls_signature_algorithm s2n_sign_alg = 0;
if (s2n_connection_get_selected_client_cert_signature_algorithm(s2n_handler->connection, &s2n_sign_alg)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed getting s2n client cert signature algorithm", (void *)handler);
aws_raise_error(AWS_ERROR_INVALID_STATE);
goto error;
}
operation->signature_algorithm = s_s2n_to_aws_signature_algorithm(s2n_sign_alg);
if (operation->signature_algorithm == AWS_TLS_SIGNATURE_UNKNOWN) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: Cannot sign with s2n_tls_signature_algorithm=%d. Algorithm currently unsupported",
(void *)handler,
s2n_sign_alg);
aws_raise_error(AWS_IO_TLS_SIGNATURE_ALGORITHM_UNSUPPORTED);
goto error;
}
s2n_tls_hash_algorithm s2n_digest_alg = 0;
if (s2n_connection_get_selected_client_cert_digest_algorithm(s2n_handler->connection, &s2n_digest_alg)) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Failed getting s2n client cert digest algorithm", (void *)handler);
aws_raise_error(AWS_ERROR_INVALID_STATE);
goto error;
}
operation->digest_algorithm = s_s2n_to_aws_hash_algorithm(s2n_digest_alg);
if (operation->digest_algorithm == AWS_TLS_HASH_UNKNOWN) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: Cannot sign digest created with s2n_tls_hash_algorithm=%d. Algorithm currently unsupported",
(void *)handler,
s2n_digest_alg);
aws_raise_error(AWS_IO_TLS_DIGEST_ALGORITHM_UNSUPPORTED);
goto error;
}
} else if (s2n_op_type == S2N_ASYNC_DECRYPT) {
operation->operation_type = AWS_TLS_KEY_OPERATION_DECRYPT;
} else {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: Unknown s2n async pkey op type:%d", (void *)handler, (int)s2n_op_type);
aws_raise_error(AWS_ERROR_INVALID_STATE);
goto error;
}
/* Keep channel alive until operation completes */
operation->s2n_handler = s2n_handler;
aws_channel_acquire_hold(s2n_handler->slot->channel);
/* Set this to zero so we can track how many times complete has been called */
aws_atomic_init_int(&operation->complete_count, 0);
/* Set this last. We don't want to take ownership of s2n_op until we know setup was 100% successful */
operation->s2n_op = s2n_op;
return operation;
error:
s_tls_key_operation_destroy(operation);
return NULL;
}
struct aws_byte_cursor aws_tls_key_operation_get_input(const struct aws_tls_key_operation *operation) {
return aws_byte_cursor_from_buf(&operation->input_data);
}
enum aws_tls_key_operation_type aws_tls_key_operation_get_type(const struct aws_tls_key_operation *operation) {
return operation->operation_type;
}
enum aws_tls_signature_algorithm aws_tls_key_operation_get_signature_algorithm(
const struct aws_tls_key_operation *operation) {
return operation->signature_algorithm;
}
enum aws_tls_hash_algorithm aws_tls_key_operation_get_digest_algorithm(const struct aws_tls_key_operation *operation) {
return operation->digest_algorithm;
}
static int s_s2n_async_pkey_callback(struct s2n_connection *conn, struct s2n_async_pkey_op *s2n_op) {
struct s2n_handler *s2n_handler = s2n_connection_get_ctx(conn);
struct aws_channel_handler *handler = &s2n_handler->handler;
AWS_ASSERT(conn == s2n_handler->connection);
(void)conn;
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: s2n async pkey callback received", (void *)handler);
/* Create the AWS wrapper around s2n_async_pkey_op */
struct aws_tls_key_operation *operation = s_tls_key_operation_new(handler, s2n_op);
if (operation == NULL) {
s2n_async_pkey_op_free(s2n_op);
return S2N_FAILURE;
}
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"id=%p: Begin TLS key operation. type=%s input_data.len=%zu signature=%s digest=%s",
(void *)operation,
aws_tls_key_operation_type_str(operation->operation_type),
operation->input_data.len,
aws_tls_signature_algorithm_str(operation->signature_algorithm),
aws_tls_hash_algorithm_str(operation->digest_algorithm));
aws_custom_key_op_handler_perform_operation(s2n_handler->s2n_ctx->custom_key_handler, operation);
return S2N_SUCCESS;