-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathsecure_channel_tls_handler.c
2044 lines (1732 loc) · 83 KB
/
secure_channel_tls_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.
*/
#define SECURITY_WIN32
#include <aws/io/tls_channel_handler.h>
#include <aws/common/encoding.h>
#include <aws/common/math.h>
#include <aws/common/string.h>
#include <aws/common/task_scheduler.h>
#include <aws/io/channel.h>
#include <aws/io/file_utils.h>
#include <aws/io/logging.h>
#include <aws/io/private/pki_utils.h>
#include <aws/io/private/tls_channel_handler_shared.h>
#include <aws/io/statistics.h>
#include <Windows.h>
#include <schannel.h>
#include <security.h>
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef _MSC_VER
# pragma warning(disable : 4221) /* aggregate initializer using local variable addresses */
# pragma warning(disable : 4204) /* non-constant aggregate initializer */
# pragma warning(disable : 4306) /* Identifier is type cast to a larger pointer. */
#endif
#define KB_1 1024
#define READ_OUT_SIZE (16 * KB_1)
#define READ_IN_SIZE READ_OUT_SIZE
#define EST_HANDSHAKE_SIZE (7 * KB_1)
#define EST_TLS_RECORD_OVERHEAD 53 /* 5 byte header + 32 + 16 bytes for padding */
void aws_tls_init_static_state(struct aws_allocator *alloc) {
AWS_LOGF_INFO(AWS_LS_IO_TLS, "static: Initializing TLS using SecureChannel (SSPI).");
(void)alloc;
}
void aws_tls_clean_up_static_state(void) {}
struct secure_channel_ctx {
struct aws_tls_ctx ctx;
struct aws_string *alpn_list;
SCHANNEL_CRED credentials;
PCERT_CONTEXT pcerts;
HCERTSTORE cert_store;
HCERTSTORE custom_trust_store;
HCRYPTPROV crypto_provider;
HCRYPTKEY private_key;
bool verify_peer;
bool should_free_pcerts;
};
struct secure_channel_handler {
struct aws_channel_handler handler;
struct aws_tls_channel_handler_shared shared_state;
CtxtHandle sec_handle;
CredHandle creds;
/*
* The SSPI API expects an array of len 1 of these where it's the leaf certificate associated with its private
* key.
*/
PCCERT_CONTEXT cert_context[1];
HCERTSTORE cert_store;
HCERTSTORE custom_ca_store;
SecPkgContext_StreamSizes stream_sizes;
unsigned long ctx_req;
unsigned long ctx_ret_flags;
struct aws_channel_slot *slot;
struct aws_byte_buf protocol;
struct aws_byte_buf server_name;
TimeStamp sspi_timestamp;
int (*s_connection_state_fn)(struct aws_channel_handler *handler);
/*
* Give a little bit of extra head room, for split records.
*/
uint8_t buffered_read_in_data[READ_IN_SIZE + KB_1];
struct aws_byte_buf buffered_read_in_data_buf;
size_t estimated_incomplete_size;
size_t read_extra;
/* This is to accommodate the extra head room we added above.
because we're allowing for splits, we may have more data decrypted
than we can fit in this buffer if we don't make them match. */
uint8_t buffered_read_out_data[READ_OUT_SIZE + KB_1];
struct aws_byte_buf buffered_read_out_data_buf;
struct aws_channel_task sequential_task_storage;
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;
struct aws_string *alpn_list;
void *user_data;
bool advertise_alpn_message;
bool negotiation_finished;
bool verify_peer;
};
static size_t s_message_overhead(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
if (AWS_UNLIKELY(!sc_handler->stream_sizes.cbMaximumMessage)) {
SECURITY_STATUS status =
QueryContextAttributes(&sc_handler->sec_handle, SECPKG_ATTR_STREAM_SIZES, &sc_handler->stream_sizes);
if (status != SEC_E_OK) {
return EST_TLS_RECORD_OVERHEAD;
}
}
return sc_handler->stream_sizes.cbTrailer + sc_handler->stream_sizes.cbHeader;
}
bool aws_tls_is_alpn_available(void) {
/* if you built on an old version of windows, still no support, but if you did, we still
want to check the OS version at runtime before agreeing to attempt alpn. */
#ifdef SECBUFFER_APPLICATION_PROTOCOLS
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"static: This library was built with Windows 8.1 or later, "
"probing OS to see what we're actually running on.");
/* make sure we're on windows 8.1 or later. */
OSVERSIONINFOEX os_version;
DWORDLONG condition_mask = 0;
VER_SET_CONDITION(condition_mask, VER_MAJORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(condition_mask, VER_MINORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(condition_mask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
VER_SET_CONDITION(condition_mask, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL);
AWS_ZERO_STRUCT(os_version);
os_version.dwMajorVersion = HIBYTE(_WIN32_WINNT_WIN8);
os_version.dwMinorVersion = LOBYTE(_WIN32_WINNT_WIN8);
os_version.wServicePackMajor = 0;
os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (VerifyVersionInfo(
&os_version,
VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
condition_mask)) {
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "static: We're running on Windows 8.1 or later. ALPN is available.");
return true;
}
AWS_LOGF_WARN(
AWS_LS_IO_TLS,
"static: Running on older version of windows, ALPN is not supported. "
"Please update your OS to take advantage of modern features.");
#else
AWS_LOGF_WARN(
AWS_LS_IO_TLS,
"static: This library was built using a Windows SDK prior to 8.1. "
"Please build with a version of windows >= 8.1 to take advantage modern features. ALPN is not supported.");
#endif /*SECBUFFER_APPLICATION_PROTOCOLS */
return false;
}
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;
case AWS_IO_TLS_CIPHER_PREF_KMS_PQ_TLSv1_0_2019_06:
default:
return false;
}
}
/* technically we could lower this, but lets be forgiving */
#define MAX_HOST_LENGTH 255
/* this only gets called if the user specified a custom ca. */
static int s_manually_verify_peer_cert(struct aws_channel_handler *handler) {
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"id=%p: manually verifying certifcate chain because a custom CA is configured.",
(void *)handler);
struct secure_channel_handler *sc_handler = handler->impl;
int result = AWS_OP_ERR;
CERT_CONTEXT *peer_certificate = NULL;
HCERTCHAINENGINE engine = NULL;
CERT_CHAIN_CONTEXT *cert_chain_ctx = NULL;
/* get the peer's certificate so we can validate it.*/
SECURITY_STATUS status =
QueryContextAttributes(&sc_handler->sec_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &peer_certificate);
if (status != SEC_E_OK || !peer_certificate) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: failed to load peer's certificate with SECURITY_STATUS %d",
(void *)handler,
(int)status);
return AWS_OP_ERR;
}
/* this next bit scours the custom trust store to try and load a chain to verify
the leaf certificate against. */
CERT_CHAIN_ENGINE_CONFIG engine_config;
AWS_ZERO_STRUCT(engine_config);
engine_config.cbSize = sizeof(engine_config);
engine_config.hExclusiveRoot = sc_handler->custom_ca_store;
if (!CertCreateCertificateChainEngine(&engine_config, &engine)) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: failed to load a certificate chain engine with SECURITY_STATUS %d. "
"Most likely, the configured CA is corrupted.",
(void *)handler,
(int)status);
goto done;
}
/*
* TODO: Investigate CRL options further on a per-platform basis. Add control APIs if appropriate.
*/
DWORD get_chain_flags = 0;
/* mimic chromium here since we intend for this to be used generally */
const LPCSTR usage_identifiers[] = {
szOID_PKIX_KP_SERVER_AUTH,
szOID_SERVER_GATED_CRYPTO,
szOID_SGC_NETSCAPE,
};
CERT_CHAIN_PARA chain_params;
AWS_ZERO_STRUCT(chain_params);
chain_params.cbSize = sizeof(chain_params);
chain_params.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
chain_params.RequestedUsage.Usage.cUsageIdentifier = AWS_ARRAY_SIZE(usage_identifiers);
chain_params.RequestedUsage.Usage.rgpszUsageIdentifier = (LPSTR *)usage_identifiers;
if (!CertGetCertificateChain(
engine,
peer_certificate,
NULL,
peer_certificate->hCertStore,
&chain_params,
get_chain_flags,
NULL,
&cert_chain_ctx)) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: unable to find certificate in chain with SECURITY_STATUS %d.",
(void *)handler,
(int)status);
goto done;
}
struct aws_byte_buf host = aws_tls_handler_server_name(handler);
if (host.len > MAX_HOST_LENGTH) {
AWS_LOGF_ERROR(AWS_LS_IO_TLS, "id=%p: host name too long (%d).", (void *)handler, (int)host.len);
goto done;
}
wchar_t whost[MAX_HOST_LENGTH + 1];
AWS_ZERO_ARRAY(whost);
int converted = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, (const char *)host.buffer, (int)host.len, whost, AWS_ARRAY_SIZE(whost));
if ((size_t)converted != host.len) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: unable to convert host to wstr, %d -> %d, with last error 0x%x.",
(void *)handler,
(int)host.len,
(int)converted,
(int)GetLastError());
goto done;
}
/* check if the chain was trusted */
LPCSTR policyiod = CERT_CHAIN_POLICY_SSL;
SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslpolicy;
AWS_ZERO_STRUCT(sslpolicy);
sslpolicy.cbSize = sizeof(sslpolicy);
sslpolicy.dwAuthType = AUTHTYPE_SERVER;
sslpolicy.fdwChecks = 0;
sslpolicy.pwszServerName = whost;
CERT_CHAIN_POLICY_PARA policypara;
AWS_ZERO_STRUCT(policypara);
policypara.cbSize = sizeof(policypara);
policypara.dwFlags = 0;
policypara.pvExtraPolicyPara = &sslpolicy;
CERT_CHAIN_POLICY_STATUS policystatus;
AWS_ZERO_STRUCT(policystatus);
policystatus.cbSize = sizeof(policystatus);
if (!CertVerifyCertificateChainPolicy(policyiod, cert_chain_ctx, &policypara, &policystatus)) {
int error = GetLastError();
AWS_LOGF_ERROR(
AWS_LS_IO_TLS, "id=%p: CertVerifyCertificateChainPolicy() failed, error 0x%x", (void *)handler, (int)error);
goto done;
}
if (policystatus.dwError) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: certificate verification failed, error 0x%x",
(void *)handler,
(int)policystatus.dwError);
goto done;
}
/* if the chain was trusted, then we're good to go, if it was not
we bail out. */
CERT_SIMPLE_CHAIN *simple_chain = cert_chain_ctx->rgpChain[0];
DWORD trust_mask = ~(DWORD)CERT_TRUST_IS_NOT_TIME_NESTED;
trust_mask &= simple_chain->TrustStatus.dwErrorStatus;
if (trust_mask != 0) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: peer certificate is un-trusted with SECURITY_STATUS %d.",
(void *)handler,
(int)trust_mask);
goto done;
}
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: peer certificate is trusted.", (void *)handler);
result = AWS_OP_SUCCESS;
done:
if (cert_chain_ctx != NULL) {
CertFreeCertificateChain(cert_chain_ctx);
}
if (engine != NULL) {
CertFreeCertificateChainEngine(engine);
}
if (peer_certificate != NULL) {
CertFreeCertificateContext(peer_certificate);
}
return result;
}
static void s_invoke_negotiation_error(struct aws_channel_handler *handler, int err) {
struct secure_channel_handler *sc_handler = handler->impl;
aws_on_tls_negotiation_completed(&sc_handler->shared_state, err);
if (sc_handler->on_negotiation_result) {
sc_handler->on_negotiation_result(handler, sc_handler->slot, err, sc_handler->user_data);
}
}
static void s_on_negotiation_success(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
/* if the user provided an ALPN handler to the channel, we need to let them know what their protocol is. */
if (sc_handler->slot->adj_right && sc_handler->advertise_alpn_message && sc_handler->protocol.len) {
struct aws_io_message *message = aws_channel_acquire_message_from_pool(
sc_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 = sc_handler->protocol;
message->message_data.len = sizeof(struct aws_tls_negotiated_protocol_message);
if (aws_channel_slot_send_message(sc_handler->slot, message, AWS_CHANNEL_DIR_READ)) {
aws_mem_release(message->allocator, message);
aws_channel_shutdown(sc_handler->slot->channel, aws_last_error());
}
}
aws_on_tls_negotiation_completed(&sc_handler->shared_state, AWS_ERROR_SUCCESS);
if (sc_handler->on_negotiation_result) {
sc_handler->on_negotiation_result(handler, sc_handler->slot, AWS_OP_SUCCESS, sc_handler->user_data);
}
}
static int s_determine_sspi_error(int sspi_status) {
switch (sspi_status) {
case SEC_E_INSUFFICIENT_MEMORY:
return AWS_ERROR_OOM;
case SEC_I_CONTEXT_EXPIRED:
return AWS_IO_TLS_ALERT_NOT_GRACEFUL;
case SEC_E_WRONG_PRINCIPAL:
return AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE;
/*
case SEC_E_INVALID_HANDLE:
case SEC_E_INVALID_TOKEN:
case SEC_E_LOGON_DENIED:
case SEC_E_TARGET_UNKNOWN:
case SEC_E_NO_AUTHENTICATING_AUTHORITY:
case SEC_E_INTERNAL_ERROR:
case SEC_E_NO_CREDENTIALS:
case SEC_E_UNSUPPORTED_FUNCTION:
case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
*/
default:
return AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE;
}
}
#define CHECK_ALPN_BUFFER_SIZE(s, i, b) \
if (s <= i) { \
aws_array_list_clean_up(&b); \
return aws_raise_error(AWS_ERROR_SHORT_BUFFER); \
}
/* construct ALPN extension data... apparently this works on big-endian machines? but I don't believe the docs
if you're running ARM and you find ALPN isn't working, it's probably because I trusted the documentation
and your bug is in here. Note, dotnet's corefx also acts like endianness isn't at play so if this is broken
so is everyone's dotnet code. */
static int s_fillin_alpn_data(
struct aws_channel_handler *handler,
unsigned char *alpn_buffer_data,
size_t buffer_size,
size_t *written) {
*written = 0;
struct secure_channel_handler *sc_handler = handler->impl;
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "");
struct aws_array_list alpn_buffers;
struct aws_byte_cursor alpn_buffer_array[4];
aws_array_list_init_static(&alpn_buffers, alpn_buffer_array, 4, sizeof(struct aws_byte_cursor));
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "Setting ALPN extension with string %s.", aws_string_c_str(sc_handler->alpn_list));
struct aws_byte_cursor alpn_str_cur = aws_byte_cursor_from_string(sc_handler->alpn_list);
if (aws_byte_cursor_split_on_char(&alpn_str_cur, ';', &alpn_buffers)) {
return AWS_OP_ERR;
}
size_t protocols_count = aws_array_list_length(&alpn_buffers);
size_t index = 0;
CHECK_ALPN_BUFFER_SIZE(buffer_size, index + sizeof(uint32_t), alpn_buffers)
uint32_t *extension_length = (uint32_t *)&alpn_buffer_data[index];
index += sizeof(uint32_t);
CHECK_ALPN_BUFFER_SIZE(buffer_size, index + sizeof(uint32_t), alpn_buffers)
uint32_t *extension_name = (uint32_t *)&alpn_buffer_data[index];
index += sizeof(uint32_t);
CHECK_ALPN_BUFFER_SIZE(buffer_size, index + sizeof(uint32_t), alpn_buffers)
uint16_t *protocols_byte_length = (uint16_t *)&alpn_buffer_data[index];
index += sizeof(uint16_t);
CHECK_ALPN_BUFFER_SIZE(buffer_size, index + sizeof(uint16_t), alpn_buffers)
*extension_length += sizeof(uint32_t) + sizeof(uint16_t);
*extension_name = SecApplicationProtocolNegotiationExt_ALPN;
/*now add the protocols*/
for (size_t i = 0; i < protocols_count; ++i) {
struct aws_byte_cursor *protocol_ptr = NULL;
aws_array_list_get_at_ptr(&alpn_buffers, (void **)&protocol_ptr, i);
AWS_ASSERT(protocol_ptr);
*extension_length += (uint32_t)protocol_ptr->len + 1;
*protocols_byte_length += (uint16_t)protocol_ptr->len + 1;
CHECK_ALPN_BUFFER_SIZE(buffer_size, index + 1, alpn_buffers)
alpn_buffer_data[index++] = (unsigned char)protocol_ptr->len;
CHECK_ALPN_BUFFER_SIZE(buffer_size, index + protocol_ptr->len, alpn_buffers)
memcpy(alpn_buffer_data + index, protocol_ptr->ptr, protocol_ptr->len);
index += protocol_ptr->len;
}
aws_array_list_clean_up(&alpn_buffers);
*written = *extension_length + sizeof(uint32_t);
return AWS_OP_SUCCESS;
}
static int s_process_connection_state(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
return sc_handler->s_connection_state_fn(handler);
}
static int s_do_application_data_decrypt(struct aws_channel_handler *handler);
static int s_do_server_side_negotiation_step_2(struct aws_channel_handler *handler);
/** invoked during the first step of the server's negotiation. It receives the client hello,
adds its alpn data if available, and if everything is good, sends out the server hello. */
static int s_do_server_side_negotiation_step_1(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: server starting negotiation", (void *)handler);
aws_on_drive_tls_negotiation(&sc_handler->shared_state);
unsigned char alpn_buffer_data[128] = {0};
SecBuffer input_bufs[] = {
{
.pvBuffer = sc_handler->buffered_read_in_data_buf.buffer,
.cbBuffer = (unsigned long)sc_handler->buffered_read_in_data_buf.len,
.BufferType = SECBUFFER_TOKEN,
},
{
.pvBuffer = NULL,
.cbBuffer = 0,
.BufferType = SECBUFFER_EMPTY,
},
};
SecBufferDesc input_bufs_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 2,
.pBuffers = input_bufs,
};
#ifdef SECBUFFER_APPLICATION_PROTOCOLS
if (sc_handler->alpn_list && aws_tls_is_alpn_available()) {
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: Setting ALPN to %s", handler, aws_string_c_str(sc_handler->alpn_list));
size_t extension_length = 0;
if (s_fillin_alpn_data(handler, alpn_buffer_data, sizeof(alpn_buffer_data), &extension_length)) {
return AWS_OP_ERR;
}
input_bufs[1].pvBuffer = alpn_buffer_data, input_bufs[1].cbBuffer = (unsigned long)extension_length,
input_bufs[1].BufferType = SECBUFFER_APPLICATION_PROTOCOLS;
}
#endif /* SECBUFFER_APPLICATION_PROTOCOLS*/
sc_handler->ctx_req = ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | ASC_REQ_CONFIDENTIALITY |
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_STREAM;
if (sc_handler->verify_peer) {
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS,
"id=%p: server configured to use mutual tls, expecting a certficate from client.",
(void *)handler);
sc_handler->ctx_req |= ASC_REQ_MUTUAL_AUTH;
}
SecBuffer output_buffer = {
.pvBuffer = NULL,
.cbBuffer = 0,
.BufferType = SECBUFFER_TOKEN,
};
SecBufferDesc output_buffer_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 1,
.pBuffers = &output_buffer,
};
/* process the client hello. */
SECURITY_STATUS status = AcceptSecurityContext(
&sc_handler->creds,
NULL,
&input_bufs_desc,
sc_handler->ctx_req,
0,
&sc_handler->sec_handle,
&output_buffer_desc,
&sc_handler->ctx_ret_flags,
NULL);
if (!(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_OK)) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: error during processing of the ClientHello. SECURITY_STATUS is %d",
(void *)handler,
(int)status);
int error = s_determine_sspi_error(status);
aws_raise_error(error);
s_invoke_negotiation_error(handler, error);
return AWS_OP_ERR;
}
size_t data_to_write_len = output_buffer.cbBuffer;
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: Sending ServerHello. Data size %zu", (void *)handler, data_to_write_len);
/* send the server hello. */
struct aws_io_message *outgoing_message = aws_channel_acquire_message_from_pool(
sc_handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, data_to_write_len);
if (!outgoing_message) {
FreeContextBuffer(output_buffer.pvBuffer);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
AWS_ASSERT(outgoing_message->message_data.capacity >= data_to_write_len);
memcpy(outgoing_message->message_data.buffer, output_buffer.pvBuffer, output_buffer.cbBuffer);
outgoing_message->message_data.len = output_buffer.cbBuffer;
FreeContextBuffer(output_buffer.pvBuffer);
if (aws_channel_slot_send_message(sc_handler->slot, outgoing_message, AWS_CHANNEL_DIR_WRITE)) {
aws_mem_release(outgoing_message->allocator, outgoing_message);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
sc_handler->s_connection_state_fn = s_do_server_side_negotiation_step_2;
return AWS_OP_SUCCESS;
}
/* cipher change, key exchange, mutual TLS stuff. */
static int s_do_server_side_negotiation_step_2(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
AWS_LOGF_TRACE(
AWS_LS_IO_TLS, "id=%p: running step 2 of negotiation (cipher change, key exchange etc...)", (void *)handler);
SecBuffer input_buffers[] = {
[0] =
{
.pvBuffer = sc_handler->buffered_read_in_data_buf.buffer,
.cbBuffer = (unsigned long)sc_handler->buffered_read_in_data_buf.len,
.BufferType = SECBUFFER_TOKEN,
},
[1] =
{
.pvBuffer = NULL,
.cbBuffer = 0,
.BufferType = SECBUFFER_EMPTY,
},
};
SecBufferDesc input_buffers_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 2,
.pBuffers = input_buffers,
};
SecBuffer output_buffers[3];
AWS_ZERO_ARRAY(output_buffers);
output_buffers[0].BufferType = SECBUFFER_TOKEN;
output_buffers[1].BufferType = SECBUFFER_ALERT;
SecBufferDesc output_buffers_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 3,
.pBuffers = output_buffers,
};
sc_handler->read_extra = 0;
sc_handler->estimated_incomplete_size = 0;
SECURITY_STATUS status = AcceptSecurityContext(
&sc_handler->creds,
&sc_handler->sec_handle,
&input_buffers_desc,
sc_handler->ctx_req,
0,
NULL,
&output_buffers_desc,
&sc_handler->ctx_ret_flags,
&sc_handler->sspi_timestamp);
if (status != SEC_E_INCOMPLETE_MESSAGE && status != SEC_I_CONTINUE_NEEDED && status != SEC_E_OK) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS, "id=%p: Error during negotiation. SECURITY_STATUS is %d", (void *)handler, (int)status);
int aws_error = s_determine_sspi_error(status);
aws_raise_error(aws_error);
s_invoke_negotiation_error(handler, aws_error);
return AWS_OP_ERR;
}
if (status == SEC_E_INCOMPLETE_MESSAGE) {
AWS_LOGF_TRACE(
AWS_LS_IO_TLS, "id=%p: Last processed buffer was incomplete, waiting on more data.", (void *)handler);
sc_handler->estimated_incomplete_size = input_buffers[1].cbBuffer;
return aws_raise_error(AWS_IO_READ_WOULD_BLOCK);
};
/* any output buffers that were filled in with SECBUFFER_TOKEN need to be sent,
SECBUFFER_EXTRA means we need to account for extra data and shift everything for the next run. */
if (status == SEC_I_CONTINUE_NEEDED || status == SEC_E_OK) {
for (size_t i = 0; i < output_buffers_desc.cBuffers; ++i) {
SecBuffer *buf_ptr = &output_buffers[i];
if (buf_ptr->BufferType == SECBUFFER_TOKEN && buf_ptr->cbBuffer) {
struct aws_io_message *outgoing_message = aws_channel_acquire_message_from_pool(
sc_handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, buf_ptr->cbBuffer);
if (!outgoing_message) {
FreeContextBuffer(buf_ptr->pvBuffer);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
memcpy(outgoing_message->message_data.buffer, buf_ptr->pvBuffer, buf_ptr->cbBuffer);
outgoing_message->message_data.len = buf_ptr->cbBuffer;
FreeContextBuffer(buf_ptr->pvBuffer);
if (aws_channel_slot_send_message(sc_handler->slot, outgoing_message, AWS_CHANNEL_DIR_WRITE)) {
aws_mem_release(outgoing_message->allocator, outgoing_message);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
}
}
if (input_buffers[1].BufferType == SECBUFFER_EXTRA && input_buffers[1].cbBuffer > 0) {
AWS_LOGF_TRACE(
AWS_LS_IO_TLS,
"id=%p: Extra data recieved. Extra size is %lu",
(void *)handler,
input_buffers[1].cbBuffer);
sc_handler->read_extra = input_buffers[1].cbBuffer;
}
}
if (status == SEC_E_OK) {
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: handshake completed", (void *)handler);
/* if a custom CA store was configured, we have to do the verification ourselves. */
if (sc_handler->custom_ca_store) {
AWS_LOGF_TRACE(
AWS_LS_IO_TLS,
"id=%p: Custom CA was configured, evaluating trust before completing connection",
(void *)handler);
if (s_manually_verify_peer_cert(handler)) {
aws_raise_error(AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
s_invoke_negotiation_error(handler, AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE);
return AWS_OP_ERR;
}
}
sc_handler->negotiation_finished = true;
/* force query of the sizes so future calls to encrypt will be loaded. */
s_message_overhead(handler);
/*
grab the negotiated protocol out of the session.
*/
#ifdef SECBUFFER_APPLICATION_PROTOCOLS
if (sc_handler->alpn_list && aws_tls_is_alpn_available()) {
SecPkgContext_ApplicationProtocol alpn_result;
status = QueryContextAttributes(&sc_handler->sec_handle, SECPKG_ATTR_APPLICATION_PROTOCOL, &alpn_result);
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: ALPN is configured. Checking for negotiated protocol", handler);
if (status == SEC_E_OK && alpn_result.ProtoNegoStatus == SecApplicationProtocolNegotiationStatus_Success) {
aws_byte_buf_init(&sc_handler->protocol, handler->alloc, alpn_result.ProtocolIdSize + 1);
memset(sc_handler->protocol.buffer, 0, alpn_result.ProtocolIdSize + 1);
memcpy(sc_handler->protocol.buffer, alpn_result.ProtocolId, alpn_result.ProtocolIdSize);
sc_handler->protocol.len = alpn_result.ProtocolIdSize;
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS, "id=%p: negotiated protocol %s", handler, (char *)sc_handler->protocol.buffer);
} else {
AWS_LOGF_WARN(
AWS_LS_IO_TLS,
"id=%p: Error retrieving negotiated protocol. SECURITY_STATUS is %d",
handler,
(int)status);
int aws_error = s_determine_sspi_error(status);
aws_raise_error(aws_error);
}
}
#endif
sc_handler->s_connection_state_fn = s_do_application_data_decrypt;
AWS_LOGF_DEBUG(AWS_LS_IO_TLS, "id=%p: TLS handshake completed successfully.", (void *)handler);
s_on_negotiation_success(handler);
}
return AWS_OP_SUCCESS;
}
static int s_do_client_side_negotiation_step_2(struct aws_channel_handler *handler);
/* send the client hello */
static int s_do_client_side_negotiation_step_1(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: client starting negotiation", (void *)handler);
aws_on_drive_tls_negotiation(&sc_handler->shared_state);
unsigned char alpn_buffer_data[128] = {0};
SecBuffer input_buf = {
.pvBuffer = NULL,
.cbBuffer = 0,
.BufferType = SECBUFFER_EMPTY,
};
SecBufferDesc input_buf_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 1,
.pBuffers = &input_buf,
};
SecBufferDesc *alpn_sspi_data = NULL;
/* add alpn data to the client hello if it's supported. */
#ifdef SECBUFFER_APPLICATION_PROTOCOLS
if (sc_handler->alpn_list && aws_tls_is_alpn_available()) {
AWS_LOGF_DEBUG(
AWS_LS_IO_TLS, "id=%p: Setting ALPN data as %s", handler, aws_string_c_str(sc_handler->alpn_list));
size_t extension_length = 0;
if (s_fillin_alpn_data(handler, alpn_buffer_data, sizeof(alpn_buffer_data), &extension_length)) {
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
input_buf.pvBuffer = alpn_buffer_data, input_buf.cbBuffer = (unsigned long)extension_length,
input_buf.BufferType = SECBUFFER_APPLICATION_PROTOCOLS;
alpn_sspi_data = &input_buf_desc;
}
#endif /* SECBUFFER_APPLICATION_PROTOCOLS*/
sc_handler->ctx_req = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY |
ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM;
SecBuffer output_buffer = {
.pvBuffer = NULL,
.cbBuffer = 0,
.BufferType = SECBUFFER_EMPTY,
};
SecBufferDesc output_buffer_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 1,
.pBuffers = &output_buffer,
};
char server_name_cstr[256];
AWS_ZERO_ARRAY(server_name_cstr);
AWS_ASSERT(sc_handler->server_name.len < 256);
memcpy(server_name_cstr, sc_handler->server_name.buffer, sc_handler->server_name.len);
SECURITY_STATUS status = InitializeSecurityContextA(
&sc_handler->creds,
NULL,
(SEC_CHAR *)server_name_cstr,
sc_handler->ctx_req,
0,
0,
alpn_sspi_data,
0,
&sc_handler->sec_handle,
&output_buffer_desc,
&sc_handler->ctx_ret_flags,
&sc_handler->sspi_timestamp);
if (status != SEC_I_CONTINUE_NEEDED) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS,
"id=%p: Error sending client/receiving server handshake data. SECURITY_STATUS is %d",
(void *)handler,
(int)status);
int aws_error = s_determine_sspi_error(status);
aws_raise_error(aws_error);
s_invoke_negotiation_error(handler, aws_error);
return AWS_OP_ERR;
}
size_t data_to_write_len = output_buffer.cbBuffer;
AWS_LOGF_TRACE(
AWS_LS_IO_TLS, "id=%p: Sending client handshake data of size %zu", (void *)handler, data_to_write_len);
struct aws_io_message *outgoing_message = aws_channel_acquire_message_from_pool(
sc_handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, data_to_write_len);
if (!outgoing_message) {
FreeContextBuffer(output_buffer.pvBuffer);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
AWS_ASSERT(outgoing_message->message_data.capacity >= data_to_write_len);
memcpy(outgoing_message->message_data.buffer, output_buffer.pvBuffer, output_buffer.cbBuffer);
outgoing_message->message_data.len = output_buffer.cbBuffer;
FreeContextBuffer(output_buffer.pvBuffer);
if (aws_channel_slot_send_message(sc_handler->slot, outgoing_message, AWS_CHANNEL_DIR_WRITE)) {
aws_mem_release(outgoing_message->allocator, outgoing_message);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
sc_handler->s_connection_state_fn = s_do_client_side_negotiation_step_2;
return AWS_OP_SUCCESS;
}
/* cipher exchange, key exchange etc.... */
static int s_do_client_side_negotiation_step_2(struct aws_channel_handler *handler) {
struct secure_channel_handler *sc_handler = handler->impl;
AWS_LOGF_TRACE(
AWS_LS_IO_TLS,
"id=%p: running step 2 of client-side negotiation (cipher change, key exchange etc...)",
(void *)handler);
SecBuffer input_buffers[] = {
[0] =
{
.pvBuffer = sc_handler->buffered_read_in_data_buf.buffer,
.cbBuffer = (unsigned long)sc_handler->buffered_read_in_data_buf.len,
.BufferType = SECBUFFER_TOKEN,
},
[1] =
{
.pvBuffer = NULL,
.cbBuffer = 0,
.BufferType = SECBUFFER_EMPTY,
},
};
SecBufferDesc input_buffers_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 2,
.pBuffers = input_buffers,
};
SecBuffer output_buffers[3];
AWS_ZERO_ARRAY(output_buffers);
output_buffers[0].BufferType = SECBUFFER_TOKEN;
output_buffers[1].BufferType = SECBUFFER_ALERT;
SecBufferDesc output_buffers_desc = {
.ulVersion = SECBUFFER_VERSION,
.cBuffers = 3,
.pBuffers = output_buffers,
};
SECURITY_STATUS status = SEC_E_OK;
sc_handler->read_extra = 0;
sc_handler->estimated_incomplete_size = 0;
char server_name_cstr[256];
AWS_ZERO_ARRAY(server_name_cstr);
AWS_FATAL_ASSERT(sc_handler->server_name.len < sizeof(server_name_cstr));
memcpy(server_name_cstr, sc_handler->server_name.buffer, sc_handler->server_name.len);
status = InitializeSecurityContextA(
&sc_handler->creds,
&sc_handler->sec_handle,
(SEC_CHAR *)server_name_cstr,
sc_handler->ctx_req,
0,
0,
&input_buffers_desc,
0,
NULL,
&output_buffers_desc,
&sc_handler->ctx_ret_flags,
&sc_handler->sspi_timestamp);
if (status != SEC_E_INCOMPLETE_MESSAGE && status != SEC_I_CONTINUE_NEEDED && status != SEC_E_OK) {
AWS_LOGF_ERROR(
AWS_LS_IO_TLS, "id=%p: Error during negotiation. SECURITY_STATUS is %d", (void *)handler, (int)status);
int aws_error = s_determine_sspi_error(status);
aws_raise_error(aws_error);
s_invoke_negotiation_error(handler, aws_error);
return AWS_OP_ERR;
}
if (status == SEC_E_INCOMPLETE_MESSAGE) {
sc_handler->estimated_incomplete_size = input_buffers[1].cbBuffer;
AWS_LOGF_TRACE(
AWS_LS_IO_TLS,
"id=%p: Incomplete buffer recieved. Incomplete size is %zu. Waiting for more data.",
(void *)handler,
sc_handler->estimated_incomplete_size);
return aws_raise_error(AWS_IO_READ_WOULD_BLOCK);
}
if (status == SEC_I_CONTINUE_NEEDED || status == SEC_E_OK) {
for (size_t i = 0; i < output_buffers_desc.cBuffers; ++i) {
SecBuffer *buf_ptr = &output_buffers[i];
if (buf_ptr->BufferType == SECBUFFER_TOKEN && buf_ptr->cbBuffer) {
struct aws_io_message *outgoing_message = aws_channel_acquire_message_from_pool(
sc_handler->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, buf_ptr->cbBuffer);
if (!outgoing_message) {
FreeContextBuffer(buf_ptr->pvBuffer);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
memcpy(outgoing_message->message_data.buffer, buf_ptr->pvBuffer, buf_ptr->cbBuffer);
outgoing_message->message_data.len = buf_ptr->cbBuffer;
FreeContextBuffer(buf_ptr->pvBuffer);
if (aws_channel_slot_send_message(sc_handler->slot, outgoing_message, AWS_CHANNEL_DIR_WRITE)) {
aws_mem_release(outgoing_message->allocator, outgoing_message);
s_invoke_negotiation_error(handler, aws_last_error());
return AWS_OP_ERR;
}
}
}
if (input_buffers[1].BufferType == SECBUFFER_EXTRA && input_buffers[1].cbBuffer > 0) {
AWS_LOGF_TRACE(
AWS_LS_IO_TLS,
"id=%p: Extra data recieved. Extra data size is %lu.",
(void *)handler,
input_buffers[1].cbBuffer);
sc_handler->read_extra = input_buffers[1].cbBuffer;
}
}
if (status == SEC_E_OK) {
AWS_LOGF_TRACE(AWS_LS_IO_TLS, "id=%p: handshake completed", handler);