aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/restricted/aws/s2n/tls/s2n_connection.c
blob: ae23da243970466489f6174e045bf95040923d07 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>

#include <s2n.h>
#include <stdbool.h>

#include "crypto/s2n_fips.h"

#include "error/s2n_errno.h"

#include "tls/extensions/s2n_client_server_name.h"
#include "tls/s2n_alerts.h"
#include "tls/s2n_cipher_suites.h"
#include "tls/s2n_connection.h"
#include "tls/s2n_connection_evp_digests.h"
#include "tls/s2n_handshake.h"
#include "tls/s2n_kem.h"
#include "tls/s2n_prf.h"
#include "tls/s2n_record.h"
#include "tls/s2n_resume.h"
#include "tls/s2n_security_policies.h"
#include "tls/s2n_tls.h"
#include "tls/s2n_tls_parameters.h"

#include "crypto/s2n_certificate.h"
#include "crypto/s2n_cipher.h"

#include "utils/s2n_blob.h"
#include "utils/s2n_compiler.h"
#include "utils/s2n_mem.h"
#include "utils/s2n_random.h"
#include "utils/s2n_safety.h"
#include "utils/s2n_socket.h"
#include "utils/s2n_timer.h"

#define S2N_SET_KEY_SHARE_LIST_EMPTY(keyshares) (keyshares |= 1)
#define S2N_SET_KEY_SHARE_REQUEST(keyshares, i) (keyshares |= ( 1 << ( i + 1 )))

static int s2n_connection_new_hashes(struct s2n_connection *conn)
{
    /* Allocate long-term memory for the Connection's hash states */
    GUARD(s2n_hash_new(&conn->handshake.md5));
    GUARD(s2n_hash_new(&conn->handshake.sha1));
    GUARD(s2n_hash_new(&conn->handshake.sha224));
    GUARD(s2n_hash_new(&conn->handshake.sha256));
    GUARD(s2n_hash_new(&conn->handshake.sha384));
    GUARD(s2n_hash_new(&conn->handshake.sha512));
    GUARD(s2n_hash_new(&conn->handshake.md5_sha1));
    GUARD(s2n_hash_new(&conn->handshake.ccv_hash_copy));
    GUARD(s2n_hash_new(&conn->handshake.prf_md5_hash_copy));
    GUARD(s2n_hash_new(&conn->handshake.prf_sha1_hash_copy));
    GUARD(s2n_hash_new(&conn->handshake.prf_tls12_hash_copy));
    GUARD(s2n_hash_new(&conn->handshake.server_finished_copy));
    GUARD(s2n_hash_new(&conn->prf_space.ssl3.md5));
    GUARD(s2n_hash_new(&conn->prf_space.ssl3.sha1));
    GUARD(s2n_hash_new(&conn->initial.signature_hash));
    GUARD(s2n_hash_new(&conn->secure.signature_hash));

    return 0;
}

static int s2n_connection_init_hashes(struct s2n_connection *conn)
{
    /* Initialize all of the Connection's hash states */

    if (s2n_hash_is_available(S2N_HASH_MD5)) {
        /* Only initialize hashes that use MD5 if available. */
        GUARD(s2n_hash_init(&conn->prf_space.ssl3.md5, S2N_HASH_MD5));
    }


    /* Allow MD5 for hash states that are used by the PRF. This is required
     * to comply with the TLS 1.0 and 1.1 RFCs and is approved as per
     * NIST Special Publication 800-52 Revision 1.
     */
    if (s2n_is_in_fips_mode()) {
        GUARD(s2n_hash_allow_md5_for_fips(&conn->handshake.md5));
        GUARD(s2n_hash_allow_md5_for_fips(&conn->handshake.prf_md5_hash_copy));

        /* Do not check s2n_hash_is_available before initialization. Allow MD5 and
         * SHA-1 for both fips and non-fips mode. This is required to perform the
         * signature checks in the CertificateVerify message in TLS 1.0 and TLS 1.1.
         * This is approved per Nist SP 800-52r1.*/
        GUARD(s2n_hash_allow_md5_for_fips(&conn->handshake.md5_sha1));
    }

    GUARD(s2n_hash_init(&conn->handshake.md5, S2N_HASH_MD5));
    GUARD(s2n_hash_init(&conn->handshake.prf_md5_hash_copy, S2N_HASH_MD5));
    GUARD(s2n_hash_init(&conn->handshake.md5_sha1, S2N_HASH_MD5_SHA1));

    GUARD(s2n_hash_init(&conn->handshake.sha1, S2N_HASH_SHA1));
    GUARD(s2n_hash_init(&conn->handshake.sha224, S2N_HASH_SHA224));
    GUARD(s2n_hash_init(&conn->handshake.sha256, S2N_HASH_SHA256));
    GUARD(s2n_hash_init(&conn->handshake.sha384, S2N_HASH_SHA384));
    GUARD(s2n_hash_init(&conn->handshake.sha512, S2N_HASH_SHA512));
    GUARD(s2n_hash_init(&conn->handshake.ccv_hash_copy, S2N_HASH_NONE));
    GUARD(s2n_hash_init(&conn->handshake.prf_tls12_hash_copy, S2N_HASH_NONE));
    GUARD(s2n_hash_init(&conn->handshake.server_finished_copy, S2N_HASH_NONE));
    GUARD(s2n_hash_init(&conn->handshake.prf_sha1_hash_copy, S2N_HASH_SHA1));
    GUARD(s2n_hash_init(&conn->prf_space.ssl3.sha1, S2N_HASH_SHA1));
    GUARD(s2n_hash_init(&conn->initial.signature_hash, S2N_HASH_NONE));
    GUARD(s2n_hash_init(&conn->secure.signature_hash, S2N_HASH_NONE));

    return 0;
}

static int s2n_connection_new_hmacs(struct s2n_connection *conn)
{
    /* Allocate long-term memory for the Connection's HMAC states */
    GUARD(s2n_hmac_new(&conn->initial.client_record_mac));
    GUARD(s2n_hmac_new(&conn->initial.server_record_mac));
    GUARD(s2n_hmac_new(&conn->initial.record_mac_copy_workspace));
    GUARD(s2n_hmac_new(&conn->secure.client_record_mac));
    GUARD(s2n_hmac_new(&conn->secure.server_record_mac));
    GUARD(s2n_hmac_new(&conn->secure.record_mac_copy_workspace));

    return 0;
}

static int s2n_connection_init_hmacs(struct s2n_connection *conn)
{
    /* Initialize all of the Connection's HMAC states */
    GUARD(s2n_hmac_init(&conn->initial.client_record_mac, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->initial.server_record_mac, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->initial.record_mac_copy_workspace, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->secure.client_record_mac, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->secure.server_record_mac, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->secure.record_mac_copy_workspace, S2N_HMAC_NONE, NULL, 0));

    return 0;
}

struct s2n_connection *s2n_connection_new(s2n_mode mode)
{
    struct s2n_blob blob = {0};
    GUARD_PTR(s2n_alloc(&blob, sizeof(struct s2n_connection)));
    GUARD_PTR(s2n_blob_zero(&blob));

    /* Cast 'through' void to acknowledge that we are changing alignment,
     * which is ok, as blob.data is always aligned.
     */
    struct s2n_connection* conn = (struct s2n_connection *)(void *)blob.data;

    GUARD_PTR(s2n_connection_set_config(conn, s2n_fetch_default_config()));

    conn->mode = mode;
    conn->blinding = S2N_BUILT_IN_BLINDING;
    conn->close_notify_queued = 0;
    conn->client_session_resumed = 0;
    conn->session_id_len = 0;
    conn->verify_host_fn = NULL;
    conn->data_for_verify_host = NULL;
    conn->verify_host_fn_overridden = 0;
    conn->data_for_verify_host = NULL;
    conn->send = NULL;
    conn->recv = NULL;
    conn->send_io_context = NULL;
    conn->recv_io_context = NULL;
    conn->managed_io = 0;
    conn->corked_io = 0;
    conn->context = NULL;
    conn->security_policy_override = NULL;
    conn->ticket_lifetime_hint = 0;
    conn->session_ticket_status = S2N_NO_TICKET;

    /* Allocate the fixed-size stuffers */
    blob = (struct s2n_blob) {0};
    GUARD_PTR(s2n_blob_init(&blob, conn->alert_in_data, S2N_ALERT_LENGTH));
    GUARD_PTR(s2n_stuffer_init(&conn->alert_in, &blob));

    blob = (struct s2n_blob) {0};
    GUARD_PTR(s2n_blob_init(&blob, conn->reader_alert_out_data, S2N_ALERT_LENGTH));
    GUARD_PTR(s2n_stuffer_init(&conn->reader_alert_out, &blob));

    blob = (struct s2n_blob) {0};
    GUARD_PTR(s2n_blob_init(&blob, conn->writer_alert_out_data, S2N_ALERT_LENGTH));
    GUARD_PTR(s2n_stuffer_init(&conn->writer_alert_out, &blob));

    blob = (struct s2n_blob) {0};
    GUARD_PTR(s2n_blob_init(&blob, conn->ticket_ext_data, S2N_TICKET_SIZE_IN_BYTES));
    GUARD_PTR(s2n_stuffer_init(&conn->client_ticket_to_decrypt, &blob));

    /* Allocate long term key memory */
    GUARD_PTR(s2n_session_key_alloc(&conn->secure.client_key));
    GUARD_PTR(s2n_session_key_alloc(&conn->secure.server_key));
    GUARD_PTR(s2n_session_key_alloc(&conn->initial.client_key));
    GUARD_PTR(s2n_session_key_alloc(&conn->initial.server_key));

    /* Allocate long term hash and HMAC memory */
    GUARD_PTR(s2n_prf_new(conn));

    GUARD_PTR(s2n_connection_new_hashes(conn));
    GUARD_PTR(s2n_connection_init_hashes(conn));

    GUARD_PTR(s2n_connection_new_hmacs(conn));
    GUARD_PTR(s2n_connection_init_hmacs(conn));

    /* Initialize the growable stuffers. Zero length at first, but the resize
     * in _wipe will fix that
     */
    blob = (struct s2n_blob) {0};
    GUARD_PTR(s2n_blob_init(&blob, conn->header_in_data, S2N_TLS_RECORD_HEADER_LENGTH));
    GUARD_PTR(s2n_stuffer_init(&conn->header_in, &blob));
    GUARD_PTR(s2n_stuffer_growable_alloc(&conn->out, 0));
    GUARD_PTR(s2n_stuffer_growable_alloc(&conn->in, 0));
    GUARD_PTR(s2n_stuffer_growable_alloc(&conn->handshake.io, 0));
    GUARD_PTR(s2n_stuffer_growable_alloc(&conn->client_hello.raw_message, 0));
    GUARD_PTR(s2n_connection_wipe(conn));
    GUARD_RESULT_PTR(s2n_timer_start(conn->config, &conn->write_timer));

    /* Initialize the cookie stuffer with zero length. If a cookie extension
     * is received, the stuffer will be resized according to the cookie length */
    GUARD_PTR(s2n_stuffer_growable_alloc(&conn->cookie_stuffer, 0));

    return conn;
}

static int s2n_connection_free_keys(struct s2n_connection *conn)
{
    GUARD(s2n_session_key_free(&conn->secure.client_key));
    GUARD(s2n_session_key_free(&conn->secure.server_key));
    GUARD(s2n_session_key_free(&conn->initial.client_key));
    GUARD(s2n_session_key_free(&conn->initial.server_key));

    return 0;
}

static int s2n_connection_zero(struct s2n_connection *conn, int mode, struct s2n_config *config)
{
    /* Zero the whole connection structure */
    memset_check(conn, 0, sizeof(struct s2n_connection));

    conn->send = NULL;
    conn->recv = NULL;
    conn->send_io_context = NULL;
    conn->recv_io_context = NULL;
    conn->mode = mode;
    conn->close_notify_queued = 0;
    conn->client_session_resumed = 0;
    conn->current_user_data_consumed = 0;
    conn->initial.cipher_suite = &s2n_null_cipher_suite;
    conn->secure.cipher_suite = &s2n_null_cipher_suite;
    conn->initial.kem_params.kem = NULL;
    conn->secure.kem_params.kem = NULL;
    conn->server = &conn->initial;
    conn->client = &conn->initial;
    conn->max_outgoing_fragment_length = S2N_DEFAULT_FRAGMENT_LENGTH;
    conn->mfl_code = S2N_TLS_MAX_FRAG_LEN_EXT_NONE;
    conn->handshake.handshake_type = INITIAL;
    conn->handshake.message_number = 0;
    conn->handshake.paused = 0;
    conn->verify_host_fn = NULL;
    conn->verify_host_fn_overridden = 0;
    conn->data_for_verify_host = NULL;
    s2n_connection_set_config(conn, config);

    return 0;
}

static int s2n_connection_wipe_keys(struct s2n_connection *conn)
{
    /* Destroy any keys - we call destroy on the object as that is where
     * keys are allocated. */
    if (conn->secure.cipher_suite
            && conn->secure.cipher_suite->record_alg
            && conn->secure.cipher_suite->record_alg->cipher
            && conn->secure.cipher_suite->record_alg->cipher->destroy_key) {
        GUARD(conn->secure.cipher_suite->record_alg->cipher->destroy_key(&conn->secure.client_key));
        GUARD(conn->secure.cipher_suite->record_alg->cipher->destroy_key(&conn->secure.server_key));
    }

    /* Free any server key received (we may not have completed a
     * handshake, so this may not have been free'd yet) */
    GUARD(s2n_pkey_free(&conn->secure.server_public_key));
    GUARD(s2n_pkey_zero_init(&conn->secure.server_public_key));
    GUARD(s2n_pkey_free(&conn->secure.client_public_key));
    GUARD(s2n_pkey_zero_init(&conn->secure.client_public_key));
    s2n_x509_validator_wipe(&conn->x509_validator);
    GUARD(s2n_dh_params_free(&conn->secure.server_dh_params));
    GUARD(s2n_ecc_evp_params_free(&conn->secure.server_ecc_evp_params));
    for (int i=0; i < S2N_ECC_EVP_SUPPORTED_CURVES_COUNT; i++) {
        GUARD(s2n_ecc_evp_params_free(&conn->secure.client_ecc_evp_params[i]));
    }
    GUARD(s2n_kem_group_free(&conn->secure.server_kem_group_params));
    for (int i = 0; i < S2N_SUPPORTED_KEM_GROUPS_COUNT; i++) {
        GUARD(s2n_kem_group_free(&conn->secure.client_kem_group_params[i]));
    }
    GUARD(s2n_kem_free(&conn->secure.kem_params));
    GUARD(s2n_free(&conn->secure.client_cert_chain));
    GUARD(s2n_free(&conn->ct_response));

    return 0;
}

static int s2n_connection_reset_hashes(struct s2n_connection *conn)
{
    /* Reset all of the Connection's hash states */
    GUARD(s2n_hash_reset(&conn->handshake.md5));
    GUARD(s2n_hash_reset(&conn->handshake.sha1));
    GUARD(s2n_hash_reset(&conn->handshake.sha224));
    GUARD(s2n_hash_reset(&conn->handshake.sha256));
    GUARD(s2n_hash_reset(&conn->handshake.sha384));
    GUARD(s2n_hash_reset(&conn->handshake.sha512));
    GUARD(s2n_hash_reset(&conn->handshake.md5_sha1));
    GUARD(s2n_hash_reset(&conn->handshake.ccv_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.prf_md5_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.prf_sha1_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.prf_tls12_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.server_finished_copy));
    GUARD(s2n_hash_reset(&conn->prf_space.ssl3.md5));
    GUARD(s2n_hash_reset(&conn->prf_space.ssl3.sha1));
    GUARD(s2n_hash_reset(&conn->initial.signature_hash));
    GUARD(s2n_hash_reset(&conn->secure.signature_hash));

    return 0;
}

static int s2n_connection_reset_hmacs(struct s2n_connection *conn)
{
    /* Reset all of the Connection's HMAC states */
    GUARD(s2n_hmac_reset(&conn->initial.client_record_mac));
    GUARD(s2n_hmac_reset(&conn->initial.server_record_mac));
    GUARD(s2n_hmac_reset(&conn->initial.record_mac_copy_workspace));
    GUARD(s2n_hmac_reset(&conn->secure.client_record_mac));
    GUARD(s2n_hmac_reset(&conn->secure.server_record_mac));
    GUARD(s2n_hmac_reset(&conn->secure.record_mac_copy_workspace));

    return 0;
}

static int s2n_connection_free_io_contexts(struct s2n_connection *conn)
{
    /* Free the I/O context if it was allocated by s2n. Don't touch user-controlled contexts. */
    if (!conn->managed_io) {
        return 0;
    }

    GUARD(s2n_free_object((uint8_t **)&conn->send_io_context, sizeof(struct s2n_socket_write_io_context)));
    GUARD(s2n_free_object((uint8_t **)&conn->recv_io_context, sizeof(struct s2n_socket_read_io_context)));

    return 0;
}

static int s2n_connection_wipe_io(struct s2n_connection *conn)
{
    if (s2n_connection_is_managed_corked(conn) && conn->recv){
        GUARD(s2n_socket_read_restore(conn));
    }
    if (s2n_connection_is_managed_corked(conn) && conn->send){
        GUARD(s2n_socket_write_restore(conn));
    }

    /* Remove all I/O-related members */
    GUARD(s2n_connection_free_io_contexts(conn));
    conn->managed_io = 0;
    conn->send = NULL;
    conn->recv = NULL;

    return 0;
}

static int s2n_connection_free_hashes(struct s2n_connection *conn)
{
    /* Free all of the Connection's hash states */
    GUARD(s2n_hash_free(&conn->handshake.md5));
    GUARD(s2n_hash_free(&conn->handshake.sha1));
    GUARD(s2n_hash_free(&conn->handshake.sha224));
    GUARD(s2n_hash_free(&conn->handshake.sha256));
    GUARD(s2n_hash_free(&conn->handshake.sha384));
    GUARD(s2n_hash_free(&conn->handshake.sha512));
    GUARD(s2n_hash_free(&conn->handshake.md5_sha1));
    GUARD(s2n_hash_free(&conn->handshake.ccv_hash_copy));
    GUARD(s2n_hash_free(&conn->handshake.prf_md5_hash_copy));
    GUARD(s2n_hash_free(&conn->handshake.prf_sha1_hash_copy));
    GUARD(s2n_hash_free(&conn->handshake.prf_tls12_hash_copy));
    GUARD(s2n_hash_free(&conn->handshake.server_finished_copy));
    GUARD(s2n_hash_free(&conn->prf_space.ssl3.md5));
    GUARD(s2n_hash_free(&conn->prf_space.ssl3.sha1));
    GUARD(s2n_hash_free(&conn->initial.signature_hash));
    GUARD(s2n_hash_free(&conn->secure.signature_hash));

    return 0;
}

static int s2n_connection_free_hmacs(struct s2n_connection *conn)
{
    /* Free all of the Connection's HMAC states */
    GUARD(s2n_hmac_free(&conn->initial.client_record_mac));
    GUARD(s2n_hmac_free(&conn->initial.server_record_mac));
    GUARD(s2n_hmac_free(&conn->initial.record_mac_copy_workspace));
    GUARD(s2n_hmac_free(&conn->secure.client_record_mac));
    GUARD(s2n_hmac_free(&conn->secure.server_record_mac));
    GUARD(s2n_hmac_free(&conn->secure.record_mac_copy_workspace));

    return 0;
}

static uint8_t s2n_default_verify_host(const char *host_name, size_t len, void *data)
{
    /* if present, match server_name of the connection using rules
     * outlined in RFC6125 6.4. */

    struct s2n_connection *conn = data;

    if (conn->server_name[0] == '\0') {
        return 0;
    }

    /* complete match */
    if (strlen(conn->server_name) == len &&
            strncasecmp(conn->server_name, host_name, len) == 0) {
        return 1;
    }

    /* match 1 level of wildcard */
    if (len > 2 && host_name[0] == '*' && host_name[1] == '.') {
        const char *suffix = strchr(conn->server_name, '.');

        if (suffix == NULL) {
            return 0;
        }

        if (strlen(suffix) == len - 1 &&
                strncasecmp(suffix, host_name + 1, len - 1) == 0) {
            return 1;
        }
    }

    return 0;
}

int s2n_connection_free(struct s2n_connection *conn)
{
    GUARD(s2n_connection_wipe_keys(conn));
    GUARD(s2n_connection_free_keys(conn));
    GUARD(s2n_psk_parameters_free(&conn->psk_params));

    GUARD(s2n_prf_free(conn));

    GUARD(s2n_connection_reset_hashes(conn));
    GUARD(s2n_connection_free_hashes(conn));

    GUARD(s2n_connection_reset_hmacs(conn));
    GUARD(s2n_connection_free_hmacs(conn));

    GUARD(s2n_connection_free_io_contexts(conn));

    GUARD(s2n_free(&conn->client_ticket));
    GUARD(s2n_free(&conn->status_response));
    GUARD(s2n_free(&conn->our_quic_transport_parameters));
    GUARD(s2n_free(&conn->peer_quic_transport_parameters));
    GUARD(s2n_stuffer_free(&conn->in));
    GUARD(s2n_stuffer_free(&conn->out));
    GUARD(s2n_stuffer_free(&conn->handshake.io));
    s2n_x509_validator_wipe(&conn->x509_validator);
    GUARD(s2n_client_hello_free(&conn->client_hello));
    GUARD(s2n_free(&conn->application_protocols_overridden));
    GUARD(s2n_stuffer_free(&conn->cookie_stuffer));
    GUARD(s2n_free_object((uint8_t **)&conn, sizeof(struct s2n_connection)));

    return 0;
}

int s2n_connection_set_config(struct s2n_connection *conn, struct s2n_config *config)
{
    notnull_check(conn);
    notnull_check(config);

    if (conn->config == config) {
        return 0;
    }

    /* We only support one client certificate */
    if (s2n_config_get_num_default_certs(config) > 1 && conn->mode == S2N_CLIENT) {
        S2N_ERROR(S2N_ERR_TOO_MANY_CERTIFICATES);
    }

    s2n_x509_validator_wipe(&conn->x509_validator);

    s2n_cert_auth_type auth_type = config->client_cert_auth_type;

    if (conn->client_cert_auth_type_overridden) {
        auth_type = conn->client_cert_auth_type;
    }

    int8_t dont_need_x509_validation = (conn->mode == S2N_SERVER) && (auth_type == S2N_CERT_AUTH_NONE);

    if (config->disable_x509_validation || dont_need_x509_validation) {
        GUARD(s2n_x509_validator_init_no_x509_validation(&conn->x509_validator));
    }
    else {
        GUARD(s2n_x509_validator_init(&conn->x509_validator, &config->trust_store, config->check_ocsp));
        if (!conn->verify_host_fn_overridden) {
            if (config->verify_host != NULL) {
                conn->verify_host_fn = config->verify_host;
                conn->data_for_verify_host = config->data_for_verify_host;
            } else {
                conn->verify_host_fn = s2n_default_verify_host;
                conn->data_for_verify_host = conn;
            }
        }

        if (config->max_verify_cert_chain_depth_set) {
            GUARD(s2n_x509_validator_set_max_chain_depth(&conn->x509_validator, config->max_verify_cert_chain_depth));
        }
    }

    conn->config = config;
    return 0;
}

int s2n_connection_set_ctx(struct s2n_connection *conn, void *ctx)
{
    conn->context = ctx;
    return 0;
}

void *s2n_connection_get_ctx(struct s2n_connection *conn)
{
    return conn->context;
}

int s2n_connection_release_buffers(struct s2n_connection *conn)
{
    notnull_check(conn);
    PRECONDITION_POSIX(s2n_stuffer_validate(&conn->out));
    PRECONDITION_POSIX(s2n_stuffer_validate(&conn->in));

    ENSURE_POSIX(s2n_stuffer_is_consumed(&conn->out), S2N_ERR_STUFFER_HAS_UNPROCESSED_DATA);
    GUARD(s2n_stuffer_resize(&conn->out, 0));

    ENSURE_POSIX(s2n_stuffer_is_consumed(&conn->in), S2N_ERR_STUFFER_HAS_UNPROCESSED_DATA);
    GUARD(s2n_stuffer_resize(&conn->in, 0));

    POSTCONDITION_POSIX(s2n_stuffer_validate(&conn->out));
    POSTCONDITION_POSIX(s2n_stuffer_validate(&conn->in));
    return S2N_SUCCESS;
}

int s2n_connection_free_handshake(struct s2n_connection *conn)
{
    /* We are done with the handshake */
    GUARD(s2n_hash_reset(&conn->handshake.md5));
    GUARD(s2n_hash_reset(&conn->handshake.sha1));
    GUARD(s2n_hash_reset(&conn->handshake.sha224));
    GUARD(s2n_hash_reset(&conn->handshake.sha256));
    GUARD(s2n_hash_reset(&conn->handshake.sha384));
    GUARD(s2n_hash_reset(&conn->handshake.sha512));
    GUARD(s2n_hash_reset(&conn->handshake.md5_sha1));
    GUARD(s2n_hash_reset(&conn->handshake.ccv_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.prf_md5_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.prf_sha1_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.prf_tls12_hash_copy));
    GUARD(s2n_hash_reset(&conn->handshake.server_finished_copy));

    /* Wipe the buffers we are going to free */
    GUARD(s2n_stuffer_wipe(&conn->handshake.io));
    GUARD(s2n_stuffer_wipe(&conn->client_hello.raw_message));

    /* Truncate buffers to save memory, we are done with the handshake */
    GUARD(s2n_stuffer_resize(&conn->handshake.io, 0));
    GUARD(s2n_stuffer_resize(&conn->client_hello.raw_message, 0));

    /* We can free extension data we no longer need */
    GUARD(s2n_free(&conn->client_ticket));
    GUARD(s2n_free(&conn->status_response));
    GUARD(s2n_free(&conn->our_quic_transport_parameters));
    GUARD(s2n_free(&conn->application_protocols_overridden));
    GUARD(s2n_stuffer_free(&conn->cookie_stuffer));

    return 0;
}

int s2n_connection_wipe(struct s2n_connection *conn)
{
    /* First make a copy of everything we'd like to save, which isn't very much. */
    int mode = conn->mode;
    struct s2n_config *config = conn->config;
    struct s2n_stuffer alert_in = {0};
    struct s2n_stuffer reader_alert_out = {0};
    struct s2n_stuffer writer_alert_out = {0};
    struct s2n_stuffer client_ticket_to_decrypt = {0};
    struct s2n_stuffer handshake_io = {0};
    struct s2n_stuffer client_hello_raw_message = {0};
    struct s2n_stuffer header_in = {0};
    struct s2n_stuffer in = {0};
    struct s2n_stuffer out = {0};
    /* Session keys will be wiped. Preserve structs to avoid reallocation */
    struct s2n_session_key initial_client_key = {0};
    struct s2n_session_key initial_server_key = {0};
    struct s2n_session_key secure_client_key = {0};
    struct s2n_session_key secure_server_key = {0};
    /* Parts of the PRF working space, hash states, and hmac states  will be wiped. Preserve structs to avoid reallocation */
    struct s2n_connection_prf_handles prf_handles = {0};
    struct s2n_connection_hash_handles hash_handles = {0};
    struct s2n_connection_hmac_handles hmac_handles = {0};

    /* Wipe all of the sensitive stuff */
    GUARD(s2n_connection_wipe_keys(conn));
    GUARD(s2n_connection_reset_hashes(conn));
    GUARD(s2n_connection_reset_hmacs(conn));
    GUARD(s2n_stuffer_wipe(&conn->alert_in));
    GUARD(s2n_stuffer_wipe(&conn->reader_alert_out));
    GUARD(s2n_stuffer_wipe(&conn->writer_alert_out));
    GUARD(s2n_stuffer_wipe(&conn->client_ticket_to_decrypt));
    GUARD(s2n_stuffer_wipe(&conn->handshake.io));
    GUARD(s2n_stuffer_wipe(&conn->client_hello.raw_message));
    GUARD(s2n_stuffer_wipe(&conn->header_in));
    GUARD(s2n_stuffer_wipe(&conn->in));
    GUARD(s2n_stuffer_wipe(&conn->out));

    GUARD_AS_POSIX(s2n_psk_parameters_wipe(&conn->psk_params));

    /* Wipe the I/O-related info and restore the original socket if necessary */
    GUARD(s2n_connection_wipe_io(conn));

    GUARD(s2n_free(&conn->client_ticket));
    GUARD(s2n_free(&conn->status_response));
    GUARD(s2n_free(&conn->application_protocols_overridden));
    GUARD(s2n_free(&conn->our_quic_transport_parameters));
    GUARD(s2n_free(&conn->peer_quic_transport_parameters));

    /* Allocate memory for handling handshakes */
    GUARD(s2n_stuffer_resize(&conn->handshake.io, S2N_LARGE_RECORD_LENGTH));

    /* Truncate the message buffers to save memory, we will dynamically resize it as needed */
    GUARD(s2n_stuffer_resize(&conn->client_hello.raw_message, 0));
    GUARD(s2n_stuffer_resize(&conn->in, 0));
    GUARD(s2n_stuffer_resize(&conn->out, 0));

    /* Remove context associated with connection */
    conn->context = NULL;
    conn->verify_host_fn_overridden = 0;
    conn->verify_host_fn = NULL;
    conn->data_for_verify_host = NULL;

    /* Clone the stuffers */
    /* ignore gcc 4.7 address warnings because dest is allocated on the stack */
    /* pragma gcc diagnostic was added in gcc 4.6 */
#if S2N_GCC_VERSION_AT_LEAST(4,6,0)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress"
#endif
    memcpy_check(&alert_in, &conn->alert_in, sizeof(struct s2n_stuffer));
    memcpy_check(&reader_alert_out, &conn->reader_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&writer_alert_out, &conn->writer_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&client_ticket_to_decrypt, &conn->client_ticket_to_decrypt, sizeof(struct s2n_stuffer));
    memcpy_check(&handshake_io, &conn->handshake.io, sizeof(struct s2n_stuffer));
    memcpy_check(&client_hello_raw_message, &conn->client_hello.raw_message, sizeof(struct s2n_stuffer));
    memcpy_check(&header_in, &conn->header_in, sizeof(struct s2n_stuffer));
    memcpy_check(&in, &conn->in, sizeof(struct s2n_stuffer));
    memcpy_check(&out, &conn->out, sizeof(struct s2n_stuffer));
    memcpy_check(&initial_client_key, &conn->initial.client_key, sizeof(struct s2n_session_key));
    memcpy_check(&initial_server_key, &conn->initial.server_key, sizeof(struct s2n_session_key));
    memcpy_check(&secure_client_key, &conn->secure.client_key, sizeof(struct s2n_session_key));
    memcpy_check(&secure_server_key, &conn->secure.server_key, sizeof(struct s2n_session_key));
    GUARD(s2n_connection_save_prf_state(&prf_handles, conn));
    GUARD(s2n_connection_save_hash_state(&hash_handles, conn));
    GUARD(s2n_connection_save_hmac_state(&hmac_handles, conn));
#if S2N_GCC_VERSION_AT_LEAST(4,6,0)
#pragma GCC diagnostic pop
#endif

    GUARD(s2n_connection_zero(conn, mode, config));

    memcpy_check(&conn->alert_in, &alert_in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->reader_alert_out, &reader_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->writer_alert_out, &writer_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->client_ticket_to_decrypt, &client_ticket_to_decrypt, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->handshake.io, &handshake_io, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->client_hello.raw_message, &client_hello_raw_message, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->header_in, &header_in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->in, &in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->out, &out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->initial.client_key, &initial_client_key, sizeof(struct s2n_session_key));
    memcpy_check(&conn->initial.server_key, &initial_server_key, sizeof(struct s2n_session_key));
    memcpy_check(&conn->secure.client_key, &secure_client_key, sizeof(struct s2n_session_key));
    memcpy_check(&conn->secure.server_key, &secure_server_key, sizeof(struct s2n_session_key));
    GUARD(s2n_connection_restore_prf_state(conn, &prf_handles));
    GUARD(s2n_connection_restore_hash_state(conn, &hash_handles));
    GUARD(s2n_connection_restore_hmac_state(conn, &hmac_handles));

    /* Re-initialize hash and hmac states */
    GUARD(s2n_connection_init_hashes(conn));
    GUARD(s2n_connection_init_hmacs(conn));

    GUARD_AS_POSIX(s2n_psk_parameters_init(&conn->psk_params));

    /* Require all handshakes hashes. This set can be reduced as the handshake progresses. */
    GUARD(s2n_handshake_require_all_hashes(&conn->handshake));

    if (conn->mode == S2N_SERVER) {
        /* Start with the highest protocol version so that the highest common protocol version can be selected */
        /* during handshake. */
        conn->server_protocol_version = s2n_highest_protocol_version;
        conn->client_protocol_version = s2n_unknown_protocol_version;
        conn->actual_protocol_version = s2n_unknown_protocol_version;
    }
    else {
        /* For clients, also set actual_protocol_version.  Record generation uses that value for the initial */
        /* ClientHello record version. Not all servers ignore the record version in ClientHello. */
        conn->server_protocol_version = s2n_unknown_protocol_version;
        conn->client_protocol_version = s2n_highest_protocol_version;
        conn->actual_protocol_version = s2n_highest_protocol_version;
    }

    return 0;
}

int s2n_connection_set_recv_ctx(struct s2n_connection *conn, void *ctx)
{
    conn->recv_io_context = ctx;
    return 0;
}

int s2n_connection_set_send_ctx(struct s2n_connection *conn, void *ctx)
{
    conn->send_io_context = ctx;
    return 0;
}

int s2n_connection_set_recv_cb(struct s2n_connection *conn, s2n_recv_fn recv)
{
    conn->recv = recv;
    return 0;
}

int s2n_connection_set_send_cb(struct s2n_connection *conn, s2n_send_fn send)
{
    conn->send = send;
    return 0;
}

int s2n_connection_get_client_cert_chain(struct s2n_connection *conn, uint8_t **der_cert_chain_out, uint32_t *cert_chain_len)
{
    notnull_check(conn);
    notnull_check(der_cert_chain_out);
    notnull_check(cert_chain_len);
    notnull_check(conn->secure.client_cert_chain.data);

    *der_cert_chain_out = conn->secure.client_cert_chain.data;
    *cert_chain_len = conn->secure.client_cert_chain.size;

    return 0;
}

int s2n_connection_get_cipher_preferences(struct s2n_connection *conn, const struct s2n_cipher_preferences **cipher_preferences)
{
    notnull_check(conn);
    notnull_check(conn->config);
    notnull_check(cipher_preferences);

    if (conn->security_policy_override != NULL) {
        *cipher_preferences = conn->security_policy_override->cipher_preferences;
    } else if (conn->config->security_policy != NULL) {
        *cipher_preferences = conn->config->security_policy->cipher_preferences;
    } else {
        S2N_ERROR(S2N_ERR_INVALID_CIPHER_PREFERENCES);
    }

    notnull_check(*cipher_preferences);
    return 0;
}

int s2n_connection_get_security_policy(struct s2n_connection *conn, const struct s2n_security_policy **security_policy)
{
    notnull_check(conn);
    notnull_check(conn->config);
    notnull_check(security_policy);

    if (conn->security_policy_override != NULL) {
        *security_policy = conn->security_policy_override;
    } else if (conn->config->security_policy != NULL) {
        *security_policy = conn->config->security_policy;
    } else {
        S2N_ERROR(S2N_ERR_INVALID_SECURITY_POLICY);
    }

    notnull_check(*security_policy);
    return 0;
}

int s2n_connection_get_kem_preferences(struct s2n_connection *conn, const struct s2n_kem_preferences **kem_preferences)
{
    notnull_check(conn);
    notnull_check(conn->config);
    notnull_check(kem_preferences);

    if (conn->security_policy_override != NULL) {
        *kem_preferences = conn->security_policy_override->kem_preferences;
    } else if (conn->config->security_policy != NULL) {
        *kem_preferences = conn->config->security_policy->kem_preferences;
    } else {
        S2N_ERROR(S2N_ERR_INVALID_KEM_PREFERENCES);
    }

    notnull_check(*kem_preferences);
    return 0;
}

int s2n_connection_get_signature_preferences(struct s2n_connection *conn, const struct s2n_signature_preferences **signature_preferences)
{
    notnull_check(conn);
    notnull_check(conn->config);
    notnull_check(signature_preferences);

    if (conn->security_policy_override != NULL) {
        *signature_preferences = conn->security_policy_override->signature_preferences;
    } else if (conn->config->security_policy != NULL) {
        *signature_preferences = conn->config->security_policy->signature_preferences;
    } else {
        S2N_ERROR(S2N_ERR_INVALID_SIGNATURE_ALGORITHMS_PREFERENCES);
    }

    notnull_check(*signature_preferences);
    return 0;

}

int s2n_connection_get_ecc_preferences(struct s2n_connection *conn, const struct s2n_ecc_preferences **ecc_preferences)
{
    notnull_check(conn);
    notnull_check(conn->config);
    notnull_check(ecc_preferences);

    if (conn->security_policy_override != NULL) {
        *ecc_preferences = conn->security_policy_override->ecc_preferences;
    } else if (conn->config->security_policy != NULL) {
        *ecc_preferences = conn->config->security_policy->ecc_preferences;
    } else {
        S2N_ERROR(S2N_ERR_INVALID_ECC_PREFERENCES);
    }

    notnull_check(*ecc_preferences);
    return 0;

}

int s2n_connection_get_protocol_preferences(struct s2n_connection *conn, struct s2n_blob **protocol_preferences)
{
    notnull_check(conn);
    notnull_check(protocol_preferences);

    *protocol_preferences = NULL;
    if (conn->application_protocols_overridden.size > 0) {
        *protocol_preferences = &conn->application_protocols_overridden;
    } else {
        *protocol_preferences = &conn->config->application_protocols;
    }

    notnull_check(*protocol_preferences);
    return 0;
}

int s2n_connection_get_client_auth_type(struct s2n_connection *conn, s2n_cert_auth_type *client_cert_auth_type)
{
    notnull_check(conn);
    notnull_check(client_cert_auth_type);

    if (conn->client_cert_auth_type_overridden) {
        *client_cert_auth_type = conn->client_cert_auth_type;
    } else {
        *client_cert_auth_type = conn->config->client_cert_auth_type;
    }

    return 0;
}

int s2n_connection_set_client_auth_type(struct s2n_connection *conn, s2n_cert_auth_type client_cert_auth_type)
{
    conn->client_cert_auth_type_overridden = 1;
    conn->client_cert_auth_type = client_cert_auth_type;
    return 0;
}

int s2n_connection_set_read_fd(struct s2n_connection *conn, int rfd)
{
    struct s2n_blob ctx_mem = {0};
    struct s2n_socket_read_io_context *peer_socket_ctx;

    GUARD(s2n_alloc(&ctx_mem, sizeof(struct s2n_socket_read_io_context)));
    GUARD(s2n_blob_zero(&ctx_mem));

    peer_socket_ctx = (struct s2n_socket_read_io_context *)(void *)ctx_mem.data;
    peer_socket_ctx->fd = rfd;

    s2n_connection_set_recv_cb(conn, s2n_socket_read);
    s2n_connection_set_recv_ctx(conn, peer_socket_ctx);
    conn->managed_io = 1;

    /* This is only needed if the user is using corked io.
     * Take the snapshot in case optimized io is enabled after setting the fd.
     */
    GUARD(s2n_socket_read_snapshot(conn));

    return 0;
}

int s2n_connection_set_write_fd(struct s2n_connection *conn, int wfd)
{
    struct s2n_blob ctx_mem = {0};
    struct s2n_socket_write_io_context *peer_socket_ctx;

    GUARD(s2n_alloc(&ctx_mem, sizeof(struct s2n_socket_write_io_context)));

    peer_socket_ctx = (struct s2n_socket_write_io_context *)(void *)ctx_mem.data;
    peer_socket_ctx->fd = wfd;

    s2n_connection_set_send_cb(conn, s2n_socket_write);
    s2n_connection_set_send_ctx(conn, peer_socket_ctx);
    conn->managed_io = 1;

    /* This is only needed if the user is using corked io.
     * Take the snapshot in case optimized io is enabled after setting the fd.
     */
    GUARD(s2n_socket_write_snapshot(conn));

    uint8_t ipv6;
    if (0 == s2n_socket_is_ipv6(wfd, &ipv6)) {
        conn->ipv6 = (ipv6 ? 1 : 0);
    }

    conn->write_fd_broken = 0;

    return 0;
}

int s2n_connection_set_fd(struct s2n_connection *conn, int fd)
{
    GUARD(s2n_connection_set_read_fd(conn, fd));
    GUARD(s2n_connection_set_write_fd(conn, fd));
    return 0;
}

int s2n_connection_use_corked_io(struct s2n_connection *conn)
{
    if (!conn->managed_io) {
        /* Caller shouldn't be trying to set s2n IO corked on non-s2n-managed IO */
        S2N_ERROR(S2N_ERR_CORK_SET_ON_UNMANAGED);
    }
    conn->corked_io = 1;

    return 0;
}

uint64_t s2n_connection_get_wire_bytes_in(struct s2n_connection *conn)
{
    return conn->wire_bytes_in;
}

uint64_t s2n_connection_get_wire_bytes_out(struct s2n_connection *conn)
{
    return conn->wire_bytes_out;
}

const char *s2n_connection_get_cipher(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);
    notnull_check_ptr(conn->secure.cipher_suite);

    return conn->secure.cipher_suite->name;
}

const char *s2n_connection_get_curve(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);

    if (!conn->secure.server_ecc_evp_params.negotiated_curve) {
        return "NONE";
    }

    return conn->secure.server_ecc_evp_params.negotiated_curve->name;
}

const char *s2n_connection_get_kem_name(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);

    if (!conn->secure.kem_params.kem) {
        return "NONE";
    }

    return conn->secure.kem_params.kem->name;
}

const char *s2n_connection_get_kem_group_name(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);

    if (!conn->secure.chosen_client_kem_group_params || !conn->secure.chosen_client_kem_group_params->kem_group) {
        return "NONE";
    }

    return conn->secure.chosen_client_kem_group_params->kem_group->name;
}

int s2n_connection_get_client_protocol_version(struct s2n_connection *conn)
{
    notnull_check(conn);

    return conn->client_protocol_version;
}

int s2n_connection_get_server_protocol_version(struct s2n_connection *conn)
{
    notnull_check(conn);

    return conn->server_protocol_version;
}

int s2n_connection_get_actual_protocol_version(struct s2n_connection *conn)
{
    notnull_check(conn);

    return conn->actual_protocol_version;
}

int s2n_connection_get_client_hello_version(struct s2n_connection *conn)
{
    notnull_check(conn);

    return conn->client_hello_version;
}

int s2n_connection_client_cert_used(struct s2n_connection *conn)
{
    notnull_check(conn);

    if ((conn->handshake.handshake_type & CLIENT_AUTH) && is_handshake_complete(conn)) {
        if (conn->handshake.handshake_type & NO_CLIENT_CERT) {
            return 0;
        }
        return 1;
    }
    return 0;
}

int s2n_connection_get_alert(struct s2n_connection *conn)
{
    notnull_check(conn);

    S2N_ERROR_IF(s2n_stuffer_data_available(&conn->alert_in) != 2, S2N_ERR_NO_ALERT);

    uint8_t alert_code = 0;
    GUARD(s2n_stuffer_read_uint8(&conn->alert_in, &alert_code));
    GUARD(s2n_stuffer_read_uint8(&conn->alert_in, &alert_code));

    return alert_code;
}

int s2n_set_server_name(struct s2n_connection *conn, const char *server_name)
{
    notnull_check(conn);
    notnull_check(server_name);

    S2N_ERROR_IF(conn->mode != S2N_CLIENT, S2N_ERR_CLIENT_MODE);

    int len = strlen(server_name);
    S2N_ERROR_IF(len > S2N_MAX_SERVER_NAME, S2N_ERR_SERVER_NAME_TOO_LONG);

    memcpy_check(conn->server_name, server_name, len);

    return 0;
}

const char *s2n_get_server_name(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);

    if (conn->server_name[0]) {
        return conn->server_name;
    }

    GUARD_PTR(s2n_extension_process(&s2n_client_server_name_extension, conn, &conn->client_hello.extensions));

    if (!conn->server_name[0]) {
        return NULL;
    }

    return conn->server_name;
}

const char *s2n_get_application_protocol(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);

    if (strlen(conn->application_protocol) == 0) {
        return NULL;
    }

    return conn->application_protocol;
}

int s2n_connection_get_session_id_length(struct s2n_connection *conn)
{
    notnull_check(conn);
    return conn->session_id_len;
}

int s2n_connection_get_session_id(struct s2n_connection *conn, uint8_t *session_id, size_t max_length)
{
    notnull_check(conn);
    notnull_check(session_id);

    int session_id_len = s2n_connection_get_session_id_length(conn);

    S2N_ERROR_IF(session_id_len > max_length, S2N_ERR_SESSION_ID_TOO_LONG);

    memcpy_check(session_id, conn->session_id, session_id_len);

    return session_id_len;
}

int s2n_connection_set_blinding(struct s2n_connection *conn, s2n_blinding blinding)
{
    notnull_check(conn);
    conn->blinding = blinding;

    return 0;
}

#define ONE_S  INT64_C(1000000000)
#define TEN_S  INT64_C(10000000000)

uint64_t s2n_connection_get_delay(struct s2n_connection *conn)
{
    if (!conn->delay) {
        return 0;
    }

    uint64_t elapsed;
    /* This will cast -1 to max uint64_t */
    GUARD_AS_POSIX(s2n_timer_elapsed(conn->config, &conn->write_timer, &elapsed));

    if (elapsed > conn->delay) {
        return 0;
    }

    return conn->delay - elapsed;
}

int s2n_connection_kill(struct s2n_connection *conn)
{
    notnull_check(conn);

    conn->closed = 1;

    /* Delay between 10 and 30 seconds in nanoseconds */
    int64_t min = TEN_S, max = 3 * TEN_S;

    /* Keep track of the delay so that it can be enforced */
    uint64_t rand_delay = 0;
    GUARD_AS_POSIX(s2n_public_random(max - min, &rand_delay));

    conn->delay = min + rand_delay;

    /* Restart the write timer */
    GUARD_AS_POSIX(s2n_timer_start(conn->config, &conn->write_timer));

    if (conn->blinding == S2N_BUILT_IN_BLINDING) {
        struct timespec sleep_time = {.tv_sec = conn->delay / ONE_S,.tv_nsec = conn->delay % ONE_S };
        int r;

        do {
            r = nanosleep(&sleep_time, &sleep_time);
        }
        while (r != 0);
    }

    return 0;
}

const uint8_t *s2n_connection_get_ocsp_response(struct s2n_connection *conn, uint32_t * length)
{
    notnull_check_ptr(conn);
    notnull_check_ptr(length);

    *length = conn->status_response.size;
    return conn->status_response.data;
}

int s2n_connection_prefer_throughput(struct s2n_connection *conn)
{
    notnull_check(conn);

    if (!conn->mfl_code) {
        conn->max_outgoing_fragment_length = S2N_LARGE_FRAGMENT_LENGTH;
    }

    return 0;
}

int s2n_connection_prefer_low_latency(struct s2n_connection *conn)
{
    notnull_check(conn);

    if (!conn->mfl_code) {
        conn->max_outgoing_fragment_length = S2N_SMALL_FRAGMENT_LENGTH;
    }

    return 0;
}

int s2n_connection_set_dynamic_record_threshold(struct s2n_connection *conn, uint32_t resize_threshold, uint16_t timeout_threshold)
{
    notnull_check(conn);
    S2N_ERROR_IF(resize_threshold > S2N_TLS_MAX_RESIZE_THRESHOLD, S2N_ERR_INVALID_DYNAMIC_THRESHOLD);

    conn->dynamic_record_resize_threshold = resize_threshold;
    conn->dynamic_record_timeout_threshold = timeout_threshold;
    return 0;
}

int s2n_connection_set_verify_host_callback(struct s2n_connection *conn, s2n_verify_host_fn verify_host_fn, void *data) {
    notnull_check(conn);

    conn->verify_host_fn = verify_host_fn;
    conn->data_for_verify_host = data;
    conn->verify_host_fn_overridden = 1;

    return 0;
}

int s2n_connection_recv_stuffer(struct s2n_stuffer *stuffer, struct s2n_connection *conn, uint32_t len)
{
    notnull_check(conn->recv);
    /* Make sure we have enough space to write */
    GUARD(s2n_stuffer_reserve_space(stuffer, len));

    int r = 0;
    do {
        errno = 0;
        r = conn->recv(conn->recv_io_context, stuffer->blob.data + stuffer->write_cursor, len);
        S2N_ERROR_IF(r < 0 && errno != EINTR, S2N_ERR_RECV_STUFFER_FROM_CONN);
    } while (r < 0);

    /* Record just how many bytes we have written */
    GUARD(s2n_stuffer_skip_write(stuffer, r));
    return r;
}

int s2n_connection_send_stuffer(struct s2n_stuffer *stuffer, struct s2n_connection *conn, uint32_t len)
{
    notnull_check(conn);
    notnull_check(conn->send);
    if (conn->write_fd_broken) {
        S2N_ERROR(S2N_ERR_SEND_STUFFER_TO_CONN);
    }
    /* Make sure we even have the data */
    S2N_ERROR_IF(s2n_stuffer_data_available(stuffer) < len, S2N_ERR_STUFFER_OUT_OF_DATA);

    int w = 0;
    do {
        errno = 0;
        w = conn->send(conn->send_io_context, stuffer->blob.data + stuffer->read_cursor, len);
	if (w < 0 && errno == EPIPE) {
            conn->write_fd_broken = 1;
        }
        S2N_ERROR_IF(w < 0 && errno != EINTR, S2N_ERR_SEND_STUFFER_TO_CONN);
    } while (w < 0);

    GUARD(s2n_stuffer_skip_read(stuffer, w));
    return w;
}

int s2n_connection_is_managed_corked(const struct s2n_connection *s2n_connection)
{
    notnull_check(s2n_connection);

    return (s2n_connection->managed_io && s2n_connection->corked_io);
}

const uint8_t *s2n_connection_get_sct_list(struct s2n_connection *conn, uint32_t *length)
{
    if (!length) {
        return NULL;
    }

    *length = conn->ct_response.size;
    return conn->ct_response.data;
}

int s2n_connection_is_client_auth_enabled(struct s2n_connection *s2n_connection)
{
    s2n_cert_auth_type auth_type;
    GUARD(s2n_connection_get_client_auth_type(s2n_connection, &auth_type));

    return (auth_type != S2N_CERT_AUTH_NONE);
}

struct s2n_cert_chain_and_key *s2n_connection_get_selected_cert(struct s2n_connection *conn)
{
    notnull_check_ptr(conn);
    return conn->handshake_params.our_chain_and_key;
}

uint8_t s2n_connection_get_protocol_version(const struct s2n_connection *conn)
{
    if (conn == NULL) {
        return S2N_UNKNOWN_PROTOCOL_VERSION;
    }

    if (conn->actual_protocol_version != S2N_UNKNOWN_PROTOCOL_VERSION) {
        return conn->actual_protocol_version;
    }

    if (conn->mode == S2N_CLIENT) {
        return conn->client_protocol_version;
    }
    return conn->server_protocol_version;
}

int s2n_connection_set_keyshare_by_name_for_testing(struct s2n_connection *conn, const char* curve_name)
{
    ENSURE_POSIX(S2N_IN_TEST, S2N_ERR_NOT_IN_TEST);
    notnull_check(conn);

    if (!strcmp(curve_name, "none")) {
        S2N_SET_KEY_SHARE_LIST_EMPTY(conn->preferred_key_shares);
        return S2N_SUCCESS;
    }

    const struct s2n_ecc_preferences *ecc_pref = NULL;
    GUARD(s2n_connection_get_ecc_preferences(conn, &ecc_pref));
    notnull_check(ecc_pref);

    for (size_t i = 0; i < ecc_pref->count; i++) {
        if (!strcmp(ecc_pref->ecc_curves[i]->name, curve_name)) {
            S2N_SET_KEY_SHARE_REQUEST(conn->preferred_key_shares, i);
            return S2N_SUCCESS;
        }
    }

    S2N_ERROR(S2N_ERR_ECDHE_UNSUPPORTED_CURVE);
}