Debian Codegraph @

crt/s2n/bin/s2nc.c

raw symbols SCIP
1 /*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 #include <fcntl.h>
17 #include <getopt.h>
18 #include <inttypes.h>
19 #include <netdb.h>
20 #include <stdbool.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <sys/param.h>
24 #include <sys/socket.h>
25 #include <unistd.h>
26
27 #ifndef S2N_INTERN_LIBCRYPTO
28 #include <openssl/crypto.h>
29 #include <openssl/err.h>
30 #endif
31
32 #include "api/s2n.h"
33 #include "api/unstable/npn.h"
34 #include "api/unstable/renegotiate.h"
35 #include "common.h"
36 #include "crypto/s2n_libcrypto.h"
37 #include "error/s2n_errno.h"
38 #include "tls/s2n_connection.h"
39
40 #define OPT_TICKET_IN 1000
41 #define OPT_TICKET_OUT 1001
42 #define OPT_SEND_FILE 1002
43 #define OPT_RENEG 1003
44 #define OPT_NPN 1004
45 #define OPT_PREFER_LOW_LATENCY 1005
46 #define OPT_PREFER_THROUGHPUT 1006
47 #define OPT_BUFFERED_SEND 1007
48 #define OPT_SERIALIZE_OUT 1008
49 #define OPT_DESERIALIZE_IN 1009
50
51 /* This should match the final cert in the s2nd default_certificate_chain */
52 const char default_trusted_cert[] =
53 "-----BEGIN CERTIFICATE-----"
54 "MIIC/jCCAeagAwIBAgIUFFjxpSf0mUsrVbyLPQhccDYfixowDQYJKoZIhvcNAQEL"
55 "BQAwFjEUMBIGA1UEAwwLczJuVGVzdFJvb3QwIBcNMjAwMTI0MDEwODIyWhgPMjEx"
56 "OTEyMzEwMTA4MjJaMBYxFDASBgNVBAMMC3MyblRlc3RSb290MIIBIjANBgkqhkiG"
57 "9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz3AaOAlkcxJHryCI9SfwB9q4PA53hv5tz4ZL"
58 "be37b69v58mfP+D18cWIBHUmkmN6gWWoWZ/9hv75pxcNXW0zPn7+wOVvXLUjtmkq"
59 "1IGT/mykhasw00viaBFAuBHZ5iLwfc4/cjUFAPVCKLmfv5Xs7TJVzWA/0mR4r1h8"
60 "uFqqXczkVMklIbsOIrlZXz8ifQs3DpFA2FeoziEh+Pcb4c3QBPgCHFDEGyTSdqo9"
61 "+NbS+iRlw0T6tqUOpC0DdKXo/3mJNBmy4XPahTi9zgsu7b+UVqemL7eXXf/iSr5y"
62 "iwJKJjz+N/rLpcF1VJtF8q0fpHagzljQaN7/emjg7BplUUyLawIDAQABo0IwQDAP"
63 "BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTDmXkyQEJ7ZciyE4KF7wAJKDxMfDAO"
64 "BgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggEBAFobyhsc7mYoGaA7N4Pp"
65 "it+MQZZNzWte5vWal/3/2V7ZGrJsgeCPwLblzzTmey85RilX6ovMQHEqT1vBFSHq"
66 "nntMZnHkEl2QLU8XopJWR4MXK7LzjjQYaXiZhGbJbtylVSfATAa/ZzdgjBx1C8aD"
67 "IM1+ELGCP/UHD0YEJkFoxSUwXGAXoV8I+cPDAWHC6VnC4mY8qubhx95FpX02ERnz"
68 "1Cw2YWtntyO8P52dEJD1+0EJjtVX4Bj5wwgJHHbDkPP1IzFrR/uBC2LCjtRY+UtZ"
69 "kfoDfWu2tslkLK7/LaC5qZyCPKnpPHLLz8gUWKlvbuejM99FTlBg/tcH+bv5x7WB"
70 "MZ8="
71 "-----END CERTIFICATE-----";
72
73 /*
74 * s2nc is an example client that uses many s2n-tls APIs.
75 * It is intended for testing purposes only, and should not be used in production.
76 */
77 void usage()
78 {
79 /* clang-format off */
80 fprintf(stderr, "s2nc is an s2n-tls client testing utility.\n");
81 fprintf(stderr, "It is not intended for production use.\n");
82 fprintf(stderr, "\n");
83 fprintf(stderr, "usage: s2nc [options] host [port]\n");
84 fprintf(stderr, " host: hostname or IP address to connect to\n");
85 fprintf(stderr, " port: port to connect to\n");
86 fprintf(stderr, "\n Options:\n\n");
87 fprintf(stderr, " -a [protocols]\n");
88 fprintf(stderr, " --alpn [protocols]\n");
89 fprintf(stderr, " Sets the application protocols supported by this client, as a comma separated list.\n");
90 fprintf(stderr, " -c [version_string]\n");
91 fprintf(stderr, " --ciphers [version_string]\n");
92 fprintf(stderr, " Set the cipher preference version string. Defaults to \"default\" \n");
93 fprintf(stderr, " --enter-fips-mode\n");
94 fprintf(stderr, " Enter libcrypto's FIPS mode. The linked version of OpenSSL must be built with the FIPS module.\n");
95 fprintf(stderr, " -e,--echo\n");
96 fprintf(stderr, " Listen to stdin after TLS Connection is established and echo it to the Server\n");
97 fprintf(stderr, " --send-file [file path]\n");
98 fprintf(stderr, " Sends the contents of the provided file to the server after connecting.\n");
99 fprintf(stderr, " -h,--help\n");
100 fprintf(stderr, " Display this message and quit.\n");
101 fprintf(stderr, " -n [server name]\n");
102 fprintf(stderr, " --name [server name]\n");
103 fprintf(stderr, " Sets the SNI server name header for this client. If not specified, the host value is used.\n");
104 fprintf(stderr, " -s,--status\n");
105 fprintf(stderr, " Request the OCSP status of the remote server certificate\n");
106 fprintf(stderr, " -m,--mfl\n");
107 fprintf(stderr, " Request maximum fragment length from: 512, 1024, 2048, 4096\n");
108 fprintf(stderr, " -f,--ca-file [file path]\n");
109 fprintf(stderr, " Location of trust store CA file (PEM format). If neither -f or -d are specified. System defaults will be used.\n");
110 fprintf(stderr, " -d,--ca-dir [directory path]\n");
111 fprintf(stderr, " Directory containing hashed trusted certs. If neither -f or -d are specified. System defaults will be used.\n");
112 fprintf(stderr, " -i,--insecure\n");
113 fprintf(stderr, " Turns off certification validation altogether.\n");
114 fprintf(stderr, " -l,--cert [file path]\n");
115 fprintf(stderr, " Path to a PEM encoded certificate. Optional. Will only be used for client auth\n");
116 fprintf(stderr, " -k,--key [file path]\n");
117 fprintf(stderr, " Path to a PEM encoded private key that matches cert. Will only be used for client auth\n");
118 fprintf(stderr, " -r,--reconnect\n");
119 fprintf(stderr, " Drop and re-make the connection using Session ticket. If session ticket is disabled, then re-make the connection using Session-ID \n");
120 fprintf(stderr, " -T,--no-session-ticket \n");
121 fprintf(stderr, " Disable session ticket for resumption.\n");
122 fprintf(stderr, " --ticket-out [file path]\n");
123 fprintf(stderr, " Path to a file where the session ticket can be stored.\n");
124 fprintf(stderr, " --ticket-in [file path]\n");
125 fprintf(stderr, " Path to session ticket file to resume connection.\n");
126 fprintf(stderr, " -D,--dynamic\n");
127 fprintf(stderr, " Set dynamic record resize threshold\n");
128 fprintf(stderr, " -t,--timeout\n");
129 fprintf(stderr, " Set dynamic record timeout threshold\n");
130 fprintf(stderr, " -C,--corked-io\n");
131 fprintf(stderr, " Turn on corked io\n");
132 fprintf(stderr, " -B,--non-blocking\n");
133 fprintf(stderr, " Set the non-blocking flag on the connection's socket.\n");
134 fprintf(stderr, " -L --key-log <path>\n");
135 fprintf(stderr, " Enable NSS key logging into the provided path\n");
136 fprintf(stderr, " -P --psk <psk-identity,psk-secret,psk-hmac-alg> \n"
137 " A comma-separated list of psk parameters in this order: psk_identity, psk_secret and psk_hmac_alg.\n"
138 " Note that the maximum number of permitted psks is 10, the psk-secret is hex-encoded, and whitespace is not allowed before or after the commas.\n"
139 " Ex: --psk psk_id,psk_secret,SHA256 --psk shared_id,shared_secret,SHA384.\n");
140 fprintf(stderr, " -E ,--early-data <file path>\n");
141 fprintf(stderr, " Sends data in file path as early data to the server. Early data will only be sent if s2nc receives a session ticket and resumes a session.\n");
142 fprintf(stderr, " --renegotiation [accept|reject]\n"
143 " accept: Accept all server requests for a new handshake\n"
144 " reject: Reject all server requests for a new handshake\n");
145 fprintf(stderr, " --npn \n");
146 fprintf(stderr, " Indicates support for the NPN extension. The '--alpn' option MUST be used with this option to signal the protocols supported.");
147 fprintf(stderr, "\n");
148 fprintf(stderr, " --buffered-send <buffer size>\n");
149 fprintf(stderr, " Set s2n_send to buffer up to <buffer size> bytes before sending records over the wire.\n");
150 fprintf(stderr, " --prefer-low-latency\n");
151 fprintf(stderr, " Prefer low latency by clamping maximum outgoing record size at 1500.\n");
152 fprintf(stderr, " --prefer-throughput\n");
153 fprintf(stderr, " Prefer throughput by raising maximum outgoing record size to 16k\n");
154 /* clang-format on */
155 exit(1);
156 }
157
158 size_t session_state_length = 0;
159 uint8_t *session_state = NULL;
160 static int test_session_ticket_cb(struct s2n_connection *conn, void *ctx, struct s2n_session_ticket *ticket)
161 {
162 GUARD_EXIT_NULL(conn);
163 GUARD_EXIT_NULL(ticket);
164
165 GUARD_EXIT(s2n_session_ticket_get_data_len(ticket, &session_state_length), "Error getting ticket length ");
166 session_state = realloc(session_state, session_state_length);
167 if (session_state == NULL) {
168 print_s2n_error("Error getting new session state");
169 exit(1);
170 }
171 GUARD_EXIT(s2n_session_ticket_get_data(ticket, session_state_length, session_state), "Error getting ticket data");
172
173 bool *session_ticket_recv = (bool *) ctx;
174 *session_ticket_recv = 1;
175
176 return S2N_SUCCESS;
177 }
178
179 struct reneg_req_ctx {
180 bool do_renegotiate;
181 s2n_renegotiate_response response;
182 };
183
184 static int reneg_req_cb(struct s2n_connection *conn, void *context, s2n_renegotiate_response *response)
185 {
186 GUARD_EXIT_NULL(conn);
187 GUARD_EXIT_NULL(context);
188 GUARD_EXIT_NULL(response);
189 struct reneg_req_ctx *reneg_ctx = (struct reneg_req_ctx *) context;
190
191 *response = reneg_ctx->response;
192 if (*response == S2N_RENEGOTIATE_ACCEPT) {
193 reneg_ctx->do_renegotiate = true;
194 }
195 return S2N_SUCCESS;
196 }
197
198 static void setup_s2n_config(struct s2n_config *config, const char *cipher_prefs, s2n_status_request_type type,
199 struct verify_data *unsafe_verify_data, const char *host, const char *alpn_protocols, uint16_t mfl_value)
200 {
201 if (config == NULL) {
202 print_s2n_error("Error getting new config");
203 exit(1);
204 }
205
206 /* The s2n-tls blinding security feature is disabled for testing purposes to make debugging easier. */
207 GUARD_EXIT(s2n_config_set_max_blinding_delay(config, 0), "Error setting blinding delay");
208
209 GUARD_EXIT(s2n_config_set_cipher_preferences(config, cipher_prefs), "Error setting cipher prefs");
210
211 GUARD_EXIT(s2n_config_set_status_request_type(config, type), "OCSP validation is not supported by the linked libCrypto implementation. It cannot be set.");
212
213 if (s2n_config_set_verify_host_callback(config, unsafe_verify_host, unsafe_verify_data) < 0) {
214 print_s2n_error("Error setting host name verification function.");
215 }
216
217 if (type == S2N_STATUS_REQUEST_OCSP) {
218 if (s2n_config_set_check_stapled_ocsp_response(config, 1)) {
219 print_s2n_error("OCSP validation is not supported by the linked libCrypto implementation. It cannot be set.");
220 }
221 }
222
223 unsafe_verify_data->trusted_host = host;
224
225 if (alpn_protocols) {
226 /* Count the number of commas, this tells us how many protocols there
227 are in the list */
228 const char *ptr = alpn_protocols;
229 int protocol_count = 1;
230 while (*ptr) {
231 if (*ptr == ',') {
232 protocol_count++;
233 }
234 ptr++;
235 }
236
237 char **protocols = malloc(sizeof(char *) * protocol_count);
238 if (!protocols) {
239 fprintf(stderr, "Error allocating memory\n");
240 exit(1);
241 }
242
243 const char *next = alpn_protocols;
244 int idx = 0;
245 int length = 0;
246 ptr = alpn_protocols;
247 while (*ptr) {
248 if (*ptr == ',') {
249 protocols[idx] = malloc(length + 1);
250 if (!protocols[idx]) {
251 fprintf(stderr, "Error allocating memory\n");
252 exit(1);
253 }
254 memmove(protocols[idx], next, length);
255 protocols[idx][length] = '\0';
256 length = 0;
257 idx++;
258 ptr++;
259 next = ptr;
260 } else {
261 length++;
262 ptr++;
263 }
264 }
265 if (ptr != next) {
266 protocols[idx] = malloc(length + 1);
267 if (!protocols[idx]) {
268 fprintf(stderr, "Error allocating memory\n");
269 exit(1);
270 }
271 memmove(protocols[idx], next, length);
272 protocols[idx][length] = '\0';
273 }
274
275 GUARD_EXIT(s2n_config_set_protocol_preferences(config, (const char *const *) protocols, protocol_count), "Failed to set protocol preferences");
276
277 while (protocol_count) {
278 protocol_count--;
279 free(protocols[protocol_count]);
280 }
281 free(protocols);
282 }
283
284 uint8_t mfl_code = 0;
285 if (mfl_value > 0) {
286 switch (mfl_value) {
287 case 512:
288 mfl_code = S2N_TLS_MAX_FRAG_LEN_512;
289 break;
290 case 1024:
291 mfl_code = S2N_TLS_MAX_FRAG_LEN_1024;
292 break;
293 case 2048:
294 mfl_code = S2N_TLS_MAX_FRAG_LEN_2048;
295 break;
296 case 4096:
297 mfl_code = S2N_TLS_MAX_FRAG_LEN_4096;
298 break;
299 default:
300 fprintf(stderr, "Invalid maximum fragment length value\n");
301 exit(1);
302 }
303 }
304
305 GUARD_EXIT(s2n_config_send_max_fragment_length(config, mfl_code), "Error setting maximum fragment length");
306 }
307
308 int main(int argc, char *const *argv)
309 {
310 struct addrinfo hints, *ai_list = NULL, *ai = NULL;
311 int r = 0, sockfd = 0;
312 bool session_ticket_recv = 0;
313 /* Optional args */
314 const char *alpn_protocols = NULL;
315 const char *server_name = NULL;
316 const char *ca_file = NULL;
317 const char *ca_dir = NULL;
318 const char *client_cert = NULL;
319 const char *client_key = NULL;
320 bool client_cert_input = false;
321 bool client_key_input = false;
322 const char *ticket_out = NULL;
323 char *ticket_in = NULL;
324 const char *serialize_out = NULL;
325 const char *deserialize_in = NULL;
326 uint16_t mfl_value = 0;
327 uint8_t insecure = 0;
328 int reconnect = 0;
329 uint8_t session_ticket = 1;
330 s2n_status_request_type type = S2N_STATUS_REQUEST_NONE;
331 uint32_t dyn_rec_threshold = 0;
332 uint8_t dyn_rec_timeout = 0;
333 /* required args */
334 const char *cipher_prefs = "default";
335 int fips_mode = 0;
336 const char *host = NULL;
337 struct verify_data unsafe_verify_data;
338 const char *port = "443";
339 bool echo_input = false;
340 const char *send_file = NULL;
341 int use_corked_io = 0;
342 uint8_t non_blocking = 0;
343 const char *key_log_path = NULL;
344 FILE *key_log_file = NULL;
345 char *psk_optarg_list[S2N_MAX_PSK_LIST_LENGTH];
346 size_t psk_list_len = 0;
347 char *early_data = NULL;
348 bool setup_reneg_cb = false;
349 struct reneg_req_ctx reneg_ctx = { 0 };
350 bool npn = false;
351 uint32_t send_buffer_size = 0;
352 bool prefer_low_latency = false;
353 bool prefer_throughput = false;
354
355 static struct option long_options[] = {
356 { "alpn", required_argument, 0, 'a' },
357 { "ciphers", required_argument, 0, 'c' },
358 { "enter-fips-mode", no_argument, NULL, 'F' },
359 { "echo", no_argument, 0, 'e' },
360 { "send-file", required_argument, 0, OPT_SEND_FILE },
361 { "help", no_argument, 0, 'h' },
362 { "name", required_argument, 0, 'n' },
363 { "status", no_argument, 0, 's' },
364 { "mfl", required_argument, 0, 'm' },
365 { "ca-file", required_argument, 0, 'f' },
366 { "ca-dir", required_argument, 0, 'd' },
367 { "cert", required_argument, 0, 'l' },
368 { "key", required_argument, 0, 'k' },
369 { "insecure", no_argument, 0, 'i' },
370 { "reconnect", no_argument, 0, 'r' },
371 { "ticket-out", required_argument, 0, OPT_TICKET_OUT },
372 { "ticket-in", required_argument, 0, OPT_TICKET_IN },
373 { "no-session-ticket", no_argument, 0, 'T' },
374 { "serialize-out", required_argument, 0, OPT_SERIALIZE_OUT },
375 { "deserialize-in", required_argument, 0, OPT_DESERIALIZE_IN },
376 { "dynamic", required_argument, 0, 'D' },
377 { "timeout", required_argument, 0, 't' },
378 { "corked-io", no_argument, 0, 'C' },
379 { "tls13", no_argument, 0, '3' },
380 { "non-blocking", no_argument, 0, 'B' },
381 { "key-log", required_argument, 0, 'L' },
382 { "psk", required_argument, 0, 'P' },
383 { "early-data", required_argument, 0, 'E' },
384 { "renegotiation", required_argument, 0, OPT_RENEG },
385 { "npn", no_argument, 0, OPT_NPN },
386 { "buffered-send", required_argument, 0, OPT_BUFFERED_SEND },
387 { "prefer-low-latency", no_argument, NULL, OPT_PREFER_LOW_LATENCY },
388 { "prefer-throughput", no_argument, NULL, OPT_PREFER_THROUGHPUT },
389 { 0 },
390 };
391
392 while (1) {
393 int option_index = 0;
394 int c = getopt_long(argc, argv, "a:c:ehn:m:sf:d:l:k:D:t:irTCBL:P:E:", long_options, &option_index);
395 if (c == -1) {
396 break;
397 }
398 switch (c) {
399 case 'a':
400 alpn_protocols = optarg;
401 break;
402 case 'C':
403 use_corked_io = 1;
404 break;
405 case 'c':
406 cipher_prefs = optarg;
407 break;
408 case 'F':
409 fips_mode = 1;
410 break;
411 case 'e':
412 echo_input = true;
413 break;
414 case OPT_SEND_FILE:
415 send_file = load_file_to_cstring(optarg);
416 break;
417 case 'h':
418 usage();
419 break;
420 case 'n':
421 server_name = optarg;
422 break;
423 case 's':
424 type = S2N_STATUS_REQUEST_OCSP;
425 break;
426 case 'm':
427 mfl_value = (uint16_t) atoi(optarg);
428 break;
429 case 'f':
430 ca_file = optarg;
431 break;
432 case 'd':
433 ca_dir = optarg;
434 break;
435 case 'l':
436 client_cert = load_file_to_cstring(optarg);
437 client_cert_input = true;
438 break;
439 case 'k':
440 client_key = load_file_to_cstring(optarg);
441 client_key_input = true;
442 break;
443 case 'i':
444 insecure = 1;
445 break;
446 case 'r':
447 reconnect = 5;
448 break;
449 case OPT_TICKET_OUT:
450 ticket_out = optarg;
451 break;
452 case OPT_TICKET_IN:
453 ticket_in = optarg;
454 break;
455 /* The serialize_out and deserialize_in options are not documented
456 * in the usage section as they are not intended to work correctly
457 * using s2nc by itself. s2nc and s2nd are processes which close
458 * their TCP connection upon exit. This will cause an error if one
459 * peer serializes and exits and the other doesn't, as serialization
460 * depends on a continuous TCP connection with the peer. Therefore, our
461 * only usage of this feature is in our integ test framework,
462 * which serializes and deserializes both client and server at the
463 * same time. Do not expect these options to work when using s2nc alone.
464 */
465 case OPT_SERIALIZE_OUT:
466 serialize_out = optarg;
467 break;
468 case OPT_DESERIALIZE_IN:
469 deserialize_in = optarg;
470 break;
471 case 'T':
472 session_ticket = 0;
473 break;
474 case 't':
475 dyn_rec_timeout = (uint8_t) MIN(255, atoi(optarg));
476 break;
477 case 'D':
478 errno = 0;
479 dyn_rec_threshold = strtoul(optarg, 0, 10);
480 if (errno == ERANGE) {
481 dyn_rec_threshold = 0;
482 }
483 break;
484 case '3':
485 /* Do nothing -- this argument is deprecated. */
486 break;
487 case 'B':
488 non_blocking = 1;
489 break;
490 case 'L':
491 key_log_path = optarg;
492 break;
493 case 'P':
494 if (psk_list_len >= S2N_MAX_PSK_LIST_LENGTH) {
495 fprintf(stderr, "Error setting psks, maximum number of psks permitted is 10.\n");
496 exit(1);
497 }
498 psk_optarg_list[psk_list_len++] = optarg;
499 break;
500 case 'E':
501 early_data = load_file_to_cstring(optarg);
502 GUARD_EXIT_NULL(early_data);
503 break;
504 case OPT_RENEG:
505 setup_reneg_cb = true;
506 if (strcmp(optarg, "accept") == 0) {
507 reneg_ctx.response = S2N_RENEGOTIATE_ACCEPT;
508 } else if (strcmp(optarg, "reject") == 0) {
509 reneg_ctx.response = S2N_RENEGOTIATE_REJECT;
510 } else {
511 fprintf(stderr, "Unrecognized option: %s\n", optarg);
512 exit(1);
513 }
514 break;
515 case OPT_NPN:
516 npn = true;
517 break;
518 case OPT_BUFFERED_SEND: {
519 intmax_t send_buffer_size_scanned_value = strtoimax(optarg, 0, 10);
520 if (send_buffer_size_scanned_value > UINT32_MAX || send_buffer_size_scanned_value < 0) {
521 fprintf(stderr, "<buffer size> must be a positive 32 bit value\n");
522 exit(1);
523 }
524 send_buffer_size = (uint32_t) send_buffer_size_scanned_value;
525 break;
526 }
527 case OPT_PREFER_LOW_LATENCY:
528 prefer_low_latency = true;
529 break;
530 case OPT_PREFER_THROUGHPUT:
531 prefer_throughput = true;
532 break;
533 case '?':
534 default:
535 usage();
536 break;
537 }
538 }
539
540 if (optind < argc) {
541 host = argv[optind++];
542 }
543
544 /* cppcheck-suppress duplicateCondition */
545 if (optind < argc) {
546 port = argv[optind++];
547 }
548
549 if (!host) {
550 usage();
551 }
552
553 if (!server_name) {
554 server_name = host;
555 }
556
557 memset(&hints, 0, sizeof(hints));
558
559 hints.ai_family = AF_UNSPEC;
560 hints.ai_socktype = SOCK_STREAM;
561
562 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
563 fprintf(stderr, "Error disabling SIGPIPE\n");
564 exit(1);
565 }
566
567 if (prefer_low_latency && prefer_throughput) {
568 fprintf(stderr, "prefer-throughput and prefer-low-latency options are mutually exclusive\n");
569 exit(1);
570 }
571
572 GUARD_EXIT(s2n_init(), "Error running s2n_init()");
573 printf("libcrypto: %s\n", s2n_libcrypto_get_version_name());
574
575 if (fips_mode) {
576 s2n_fips_mode mode = 0;
577 GUARD_EXIT(s2n_get_fips_mode(&mode), "Unable to retrieve FIPS mode");
578 if (mode != S2N_FIPS_MODE_ENABLED) {
579 fprintf(stderr, "FIPS mode not enabled: libcrypto does not support FIPS\n");
580 exit(1);
581 }
582 printf("s2nc entered FIPS mode\n");
583 }
584
585 if ((r = getaddrinfo(host, port, &hints, &ai_list)) != 0) {
586 fprintf(stderr, "error: %s\n", gai_strerror(r));
587 exit(1);
588 }
589
590 do {
591 int connected = 0;
592 for (ai = ai_list; ai != NULL; ai = ai->ai_next) {
593 if ((sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
594 continue;
595 }
596
597 if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) == -1) {
598 close(sockfd);
599 continue;
600 }
601
602 connected = 1;
603 /* connect() succeeded */
604 break;
605 }
606
607 if (connected == 0) {
608 fprintf(stderr, "Failed to connect to %s:%s\n", host, port);
609 exit(1);
610 }
611
612 if (non_blocking) {
613 int flags = fcntl(sockfd, F_GETFL, 0);
614 if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) {
615 fprintf(stderr, "fcntl error: %s\n", strerror(errno));
616 exit(1);
617 }
618 }
619
620 struct s2n_config *config = s2n_config_new();
621 setup_s2n_config(config, cipher_prefs, type, &unsafe_verify_data, host, alpn_protocols, mfl_value);
622
623 if (send_buffer_size != 0) {
624 GUARD_EXIT(s2n_config_set_send_buffer_size(config, send_buffer_size), "Error setting send buffer size");
625 }
626
627 if (client_cert_input != client_key_input) {
628 print_s2n_error("Client cert/key pair must be given.");
629 }
630
631 if (client_cert_input) {
632 struct s2n_cert_chain_and_key *chain_and_key = s2n_cert_chain_and_key_new();
633 GUARD_EXIT(s2n_cert_chain_and_key_load_pem(chain_and_key, client_cert, client_key), "Error getting certificate/key");
634 GUARD_EXIT(s2n_config_add_cert_chain_and_key_to_store(config, chain_and_key), "Error setting certificate/key");
635 }
636
637 GUARD_EXIT(s2n_config_add_pem_to_trust_store(config, default_trusted_cert),
638 "Error adding default cert to trust store.");
639 if (ca_file || ca_dir) {
640 GUARD_EXIT(s2n_config_wipe_trust_store(config), "Error wiping trust store");
641 if (s2n_config_set_verification_ca_location(config, ca_file, ca_dir) < 0) {
642 print_s2n_error("Error setting CA file for trust store.");
643 }
644 } else if (insecure) {
645 GUARD_EXIT(s2n_config_disable_x509_verification(config), "Error disabling X.509 validation");
646 }
647
648 if (session_ticket) {
649 GUARD_EXIT(s2n_config_set_session_tickets_onoff(config, 1), "Error enabling session tickets");
650 GUARD_EXIT(s2n_config_set_session_ticket_cb(config, test_session_ticket_cb, &session_ticket_recv), "Error setting session ticket callback");
651 session_ticket_recv = 0;
652 }
653
654 if (key_log_path) {
655 key_log_file = fopen(key_log_path, "a");
656 GUARD_EXIT(key_log_file == NULL ? S2N_FAILURE : S2N_SUCCESS, "Failed to open key log file");
657 GUARD_EXIT(
658 s2n_config_set_key_log_cb(
659 config,
660 key_log_callback,
661 (void *) key_log_file),
662 "Failed to set key log callback");
663 }
664
665 if (setup_reneg_cb) {
666 GUARD_EXIT(s2n_config_set_renegotiate_request_cb(config, reneg_req_cb, &reneg_ctx),
667 "Error setting renegotiation request callback");
668 }
669
670 if (npn) {
671 GUARD_EXIT(s2n_config_set_npn(config, 1), "Error setting npn support");
672 }
673
674 if (serialize_out) {
675 GUARD_EXIT(s2n_config_set_serialization_version(config, S2N_SERIALIZED_CONN_V1),
676 "Error setting serialized version");
677 }
678
679 struct s2n_connection *conn = s2n_connection_new(S2N_CLIENT);
680
681 if (conn == NULL) {
682 print_s2n_error("Error getting new connection");
683 exit(1);
684 }
685
686 if (deserialize_in) {
687 GUARD_EXIT(s2n_connection_deserialize_in(conn, deserialize_in), "Failed to deserialize file");
688 }
689
690 GUARD_EXIT(s2n_connection_set_config(conn, config), "Error setting configuration");
691
692 GUARD_EXIT(s2n_set_server_name(conn, server_name), "Error setting server name");
693
694 GUARD_EXIT(s2n_connection_set_fd(conn, sockfd), "Error setting file descriptor");
695
696 GUARD_EXIT(s2n_connection_set_client_auth_type(conn, S2N_CERT_AUTH_OPTIONAL), "Error setting ClientAuth optional");
697
698 if (use_corked_io) {
699 GUARD_EXIT(s2n_connection_use_corked_io(conn), "Error setting corked io");
700 }
701
702 /* Read in session ticket from previous session */
703 if (ticket_in) {
704 GUARD_EXIT(get_file_size(ticket_in, &session_state_length), "Failed to read ticket-in file");
705 free(session_state);
706 session_state = calloc(session_state_length, sizeof(uint8_t));
707 GUARD_EXIT_NULL(session_state);
708 GUARD_EXIT(load_file_to_array(ticket_in, session_state, session_state_length), "Failed to read ticket-in file");
709 }
710
711 /* Update session state in connection if exists */
712 if (session_state_length > 0) {
713 GUARD_EXIT(s2n_connection_set_session(conn, session_state, session_state_length), "Error setting session state in connection");
714 }
715
716 GUARD_EXIT(s2n_setup_external_psk_list(conn, psk_optarg_list, psk_list_len), "Error setting external psk list");
717
718 if (prefer_throughput) {
719 GUARD_RETURN(s2n_connection_prefer_throughput(conn), "Error setting prefer throughput");
720 }
721
722 if (prefer_low_latency) {
723 GUARD_RETURN(s2n_connection_prefer_low_latency(conn), "Error setting prefer low latency");
724 }
725
726 if (early_data) {
727 if (!session_ticket) {
728 print_s2n_error("Early data can only be used with session tickets.");
729 exit(1);
730 }
731 /* Send early data if we have a received a session ticket from the server */
732 if (session_state_length) {
733 uint32_t early_data_length = strlen(early_data);
734 GUARD_EXIT(early_data_send(conn, (uint8_t *) early_data, early_data_length), "Error sending early data");
735 }
736 }
737
738 if (!deserialize_in && negotiate(conn, sockfd) != 0) {
739 /* Error is printed in negotiate */
740 S2N_ERROR_PRESERVE_ERRNO();
741 }
742
743 printf("Connected to %s:%s\n", host, port);
744
745 /* Save session state from connection if reconnect is enabled. */
746 if (reconnect > 0 || ticket_out) {
747 if (conn->actual_protocol_version >= S2N_TLS13) {
748 if (!session_ticket) {
749 print_s2n_error("s2nc can only reconnect in TLS1.3 with session tickets.");
750 exit(1);
751 }
752 GUARD_EXIT(echo(conn, sockfd, &session_ticket_recv), "Error calling echo");
753 } else {
754 if (!session_ticket && s2n_connection_get_session_id_length(conn) <= 0) {
755 print_s2n_error("Endpoint sent empty session id so cannot resume session");
756 exit(1);
757 }
758 free(session_state);
759 session_state_length = s2n_connection_get_session_length(conn);
760 session_state = calloc(session_state_length, sizeof(uint8_t));
761 GUARD_EXIT_NULL(session_state);
762 if (s2n_connection_get_session(conn, session_state, session_state_length) != session_state_length) {
763 print_s2n_error("Error getting serialized session state");
764 exit(1);
765 }
766 }
767 if (ticket_out) {
768 GUARD_EXIT(write_array_to_file(ticket_out, session_state, session_state_length), "Failed to write to ticket-out file");
769 }
770 }
771
772 if (dyn_rec_threshold > 0 && dyn_rec_timeout > 0) {
773 s2n_connection_set_dynamic_record_threshold(conn, dyn_rec_threshold, dyn_rec_timeout);
774 }
775
776 GUARD_EXIT(s2n_connection_free_handshake(conn), "Error freeing handshake memory after negotiation");
777
778 if (send_file != NULL) {
779 printf("Sending file contents:\n%s\n", send_file);
780
781 unsigned long send_file_len = strlen(send_file);
782 s2n_blocked_status blocked = S2N_NOT_BLOCKED;
783 send_data(conn, sockfd, send_file, send_file_len, &blocked);
784 }
785
786 while (echo_input) {
787 fflush(stdout);
788 fflush(stderr);
789 echo(conn, sockfd, &reneg_ctx.do_renegotiate);
790
791 if (!reneg_ctx.do_renegotiate) {
792 break;
793 }
794
795 reneg_ctx.do_renegotiate = false;
796 GUARD_EXIT(renegotiate(conn, sockfd), "Renegotiation failed");
797 }
798
799 if (serialize_out) {
800 GUARD_EXIT(s2n_connection_serialize_out(conn, serialize_out), "Error serializing connection");
801 } else {
802 GUARD_EXIT(wait_for_shutdown(conn, sockfd), "Error closing connection");
803 }
804
805 GUARD_EXIT(s2n_connection_free(conn), "Error freeing connection");
806
807 GUARD_EXIT(s2n_config_free(config), "Error freeing configuration");
808
809 close(sockfd);
810 reconnect--;
811
812 } while (reconnect >= 0);
813
814 if (key_log_file) {
815 fclose(key_log_file);
816 }
817
818 GUARD_EXIT(s2n_cleanup(), "Error running s2n_cleanup()");
819
820 free(early_data);
821 free(session_state);
822 freeaddrinfo(ai_list);
823 return 0;
824 }