Check for errors while setting an SRTP profile.
[gnutls.git] / src / cli.c
blob6064ad4e31b0aeec16bf8316a32f20222bbf94f3
1 /*
2 * Copyright (C) 2000-2012 Free Software Foundation, Inc.
4 * This file is part of GnuTLS.
6 * GnuTLS is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuTLS is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <string.h>
27 #include <sys/time.h>
28 #include <sys/stat.h>
29 #if HAVE_SYS_SOCKET_H
30 # include <sys/socket.h>
31 #elif HAVE_WS2TCPIP_H
32 # include <ws2tcpip.h>
33 #endif
34 #include <sys/select.h>
35 #include <unistd.h>
36 #include <stdint.h>
37 #include <fcntl.h>
38 #include <netdb.h>
39 #include <ctype.h>
41 #include <gnutls/gnutls.h>
42 #include <gnutls/abstract.h>
43 #include <gnutls/dtls.h>
44 #include <gnutls/x509.h>
45 #include <gnutls/openpgp.h>
46 #include <gnutls/pkcs11.h>
48 /* Gnulib portability files. */
49 #include <progname.h>
50 #include <version-etc.h>
51 #include <read-file.h>
52 #include <getpass.h>
53 #include <minmax.h>
55 #include "sockets.h"
56 #include "benchmark.h"
58 #ifdef HAVE_DANE
59 #include <gnutls/dane.h>
60 #endif
62 #include <common.h>
63 #include <socket.h>
65 #include <cli-args.h>
66 #include <ocsptool-common.h>
68 #define MAX_BUF 4096
70 /* global stuff here */
71 int resume, starttls, insecure, rehandshake, udp, mtu;
72 const char *hostname = NULL;
73 const char *service = NULL;
74 int record_max_size;
75 int status_request_ocsp;
76 int fingerprint;
77 int crlf;
78 unsigned int verbose = 0;
79 int print_cert;
81 const char *srp_passwd = NULL;
82 const char *srp_username = NULL;
83 const char *pgp_keyfile = NULL;
84 const char *pgp_certfile = NULL;
85 const char *pgp_keyring = NULL;
86 const char *x509_keyfile = NULL;
87 const char *x509_certfile = NULL;
88 const char *x509_cafile = NULL;
89 const char *x509_crlfile = NULL;
90 static int x509ctype;
91 static int disable_extensions;
92 static unsigned int init_flags = GNUTLS_CLIENT;
93 static const char * priorities = NULL;
95 const char *psk_username = NULL;
96 gnutls_datum_t psk_key = { NULL, 0 };
98 static gnutls_srp_client_credentials_t srp_cred;
99 static gnutls_psk_client_credentials_t psk_cred;
100 static gnutls_anon_client_credentials_t anon_cred;
101 static gnutls_certificate_credentials_t xcred;
103 /* end of global stuff */
105 /* prototypes */
107 static void check_rehandshake (socket_st * socket, int ret);
108 static int do_handshake (socket_st * socket);
109 static void init_global_tls_stuff (void);
110 static int cert_verify_ocsp (gnutls_session_t session);
112 #define MAX_CRT 6
113 static unsigned int x509_crt_size;
114 static gnutls_pcert_st x509_crt[MAX_CRT];
115 static gnutls_privkey_t x509_key = NULL;
117 static gnutls_pcert_st pgp_crt;
118 static gnutls_privkey_t pgp_key = NULL;
120 static void
121 get_keyid (gnutls_openpgp_keyid_t keyid, const char *str)
123 size_t keyid_size = sizeof (keyid);
125 if (strlen (str) != 16)
127 fprintf (stderr,
128 "The OpenPGP subkey ID has to be 16 hexadecimal characters.\n");
129 exit (1);
132 if (gnutls_hex2bin (str, strlen (str), keyid, &keyid_size) < 0)
134 fprintf (stderr, "Error converting hex string: %s.\n", str);
135 exit (1);
138 return;
141 /* Load the certificate and the private key.
143 static void
144 load_keys (void)
146 unsigned int crt_num;
147 int ret;
148 unsigned int i;
149 gnutls_datum_t data = { NULL, 0 };
150 gnutls_x509_crt_t crt_list[MAX_CRT];
151 unsigned char keyid[GNUTLS_OPENPGP_KEYID_SIZE];
153 if (x509_certfile != NULL && x509_keyfile != NULL)
155 #ifdef ENABLE_PKCS11
156 if (strncmp (x509_certfile, "pkcs11:", 7) == 0)
158 crt_num = 1;
159 gnutls_x509_crt_init (&crt_list[0]);
160 gnutls_x509_crt_set_pin_function(crt_list[0], pin_callback, NULL);
162 ret =
163 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile, 0);
165 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
166 ret =
167 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile,
168 GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
170 if (ret < 0)
172 fprintf (stderr, "*** Error loading cert file.\n");
173 exit (1);
175 x509_crt_size = 1;
177 else
178 #endif /* ENABLE_PKCS11 */
181 ret = gnutls_load_file (x509_certfile, &data);
182 if (ret < 0)
184 fprintf (stderr, "*** Error loading cert file.\n");
185 exit (1);
188 crt_num = MAX_CRT;
189 ret =
190 gnutls_x509_crt_list_import (crt_list, &crt_num, &data,
191 x509ctype,
192 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
193 if (ret < 0)
195 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
197 fprintf (stderr,
198 "*** Error loading cert file: Too many certs %d\n",
199 crt_num);
202 else
204 fprintf (stderr,
205 "*** Error loading cert file: %s\n",
206 gnutls_strerror (ret));
208 exit (1);
210 x509_crt_size = ret;
213 for (i=0;i<x509_crt_size;i++)
215 ret = gnutls_pcert_import_x509(&x509_crt[i], crt_list[i], 0);
216 if (ret < 0)
218 fprintf(stderr, "*** Error importing crt to pcert: %s\n",
219 gnutls_strerror(ret));
220 exit(1);
222 gnutls_x509_crt_deinit(crt_list[i]);
225 gnutls_free (data.data);
227 ret = gnutls_privkey_init(&x509_key);
228 if (ret < 0)
230 fprintf (stderr, "*** Error initializing key: %s\n",
231 gnutls_strerror (ret));
232 exit (1);
235 gnutls_privkey_set_pin_function(x509_key, pin_callback, NULL);
237 if (gnutls_url_is_supported(x509_keyfile) != 0)
239 ret =
240 gnutls_privkey_import_url (x509_key, x509_keyfile, 0);
241 if (ret < 0)
243 fprintf (stderr, "*** Error loading url: %s\n",
244 gnutls_strerror (ret));
245 exit (1);
248 else
250 ret = gnutls_load_file (x509_keyfile, &data);
251 if (ret < 0)
253 fprintf (stderr, "*** Error loading key file.\n");
254 exit (1);
257 ret = gnutls_privkey_import_x509_raw( x509_key, &data, x509ctype, NULL, 0);
258 if (ret < 0)
260 fprintf (stderr, "*** Error loading url: %s\n",
261 gnutls_strerror (ret));
262 exit (1);
265 gnutls_free(data.data);
268 fprintf (stdout, "Processed %d client X.509 certificates...\n",
269 x509_crt_size);
273 #ifdef ENABLE_OPENPGP
274 if (HAVE_OPT(PGPSUBKEY))
276 get_keyid (keyid, OPT_ARG(PGPSUBKEY));
279 if (pgp_certfile != NULL && pgp_keyfile != NULL)
281 gnutls_openpgp_crt_t tmp_pgp_crt;
283 ret = gnutls_load_file (pgp_certfile, &data);
284 if (ret < 0)
286 fprintf (stderr, "*** Error loading PGP cert file.\n");
287 exit (1);
290 gnutls_openpgp_crt_init (&tmp_pgp_crt);
292 ret =
293 gnutls_pcert_import_openpgp_raw (&pgp_crt, &data, GNUTLS_OPENPGP_FMT_BASE64, HAVE_OPT(PGPSUBKEY)?keyid:NULL, 0);
294 if (ret < 0)
296 fprintf (stderr,
297 "*** Error loading PGP cert file: %s\n",
298 gnutls_strerror (ret));
299 exit (1);
302 gnutls_free (data.data);
304 ret = gnutls_privkey_init(&pgp_key);
305 if (ret < 0)
307 fprintf (stderr, "*** Error initializing key: %s\n",
308 gnutls_strerror (ret));
309 exit (1);
312 gnutls_privkey_set_pin_function(pgp_key, pin_callback, NULL);
314 if (gnutls_url_is_supported (pgp_keyfile))
316 ret = gnutls_privkey_import_url( pgp_key, pgp_keyfile, 0);
317 if (ret < 0)
319 fprintf (stderr, "*** Error loading url: %s\n",
320 gnutls_strerror (ret));
321 exit (1);
324 else
326 ret = gnutls_load_file (pgp_keyfile, &data);
327 if (ret < 0)
329 fprintf (stderr, "*** Error loading key file.\n");
330 exit (1);
333 if (HAVE_OPT(PGPSUBKEY))
334 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, keyid, NULL);
335 else
336 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, NULL, NULL);
337 if (ret < 0)
339 fprintf (stderr, "*** Error loading url: %s\n",
340 gnutls_strerror (ret));
341 exit (1);
344 gnutls_free(data.data);
348 fprintf (stdout, "Processed 1 client PGP certificate...\n");
350 #endif
354 #define IS_NEWLINE(x) ((x[0] == '\n') || (x[0] == '\r'))
355 static int
356 read_yesno (const char *input_str)
358 char input[128];
360 fputs (input_str, stderr);
361 if (fgets (input, sizeof (input), stdin) == NULL)
362 return 0;
364 if (IS_NEWLINE(input))
365 return 0;
367 if (input[0] == 'y' || input[0] == 'Y')
368 return 1;
370 return 0;
373 /* converts a textual service or port to
374 * a service.
376 static const char* port_to_service(const char* sport)
378 unsigned int port;
379 struct servent * sr;
381 port = atoi(sport);
382 if (port == 0) return sport;
384 port = htons(port);
386 sr = getservbyport(port, udp?"udp":"tcp");
387 if (sr == NULL)
389 fprintf(stderr, "Warning: getservbyport() failed. Using port number as service.\n");
390 return sport;
393 return sr->s_name;
396 static int
397 cert_verify_callback (gnutls_session_t session)
399 int rc;
400 unsigned int status = 0;
401 int ssh = ENABLED_OPT(TOFU);
402 #ifdef HAVE_DANE
403 int dane = ENABLED_OPT(DANE);
404 #endif
405 int ca_verify = ENABLED_OPT(CA_VERIFICATION);
406 const char* txt_service;
408 print_cert_info (session, verbose, print_cert);
410 if (ca_verify)
412 rc = cert_verify(session, hostname);
413 if (rc == 0)
415 printf ("*** Verifying server certificate failed...\n");
416 if (!insecure && !ssh)
417 return -1;
419 else if (ENABLED_OPT(OCSP))
420 { /* off-line verification succeeded. Try OCSP */
421 rc = cert_verify_ocsp(session);
422 if (rc == 0)
424 printf ("*** Verifying (with OCSP) server certificate failed...\n");
425 if (!insecure && !ssh)
426 return -1;
428 else if (rc == -1)
429 printf("*** OCSP response ignored\n");
433 if (ssh) /* try ssh auth */
435 unsigned int list_size;
436 const gnutls_datum_t * cert;
438 cert = gnutls_certificate_get_peers(session, &list_size);
439 if (cert == NULL)
441 fprintf(stderr, "Cannot obtain peer's certificate!\n");
442 return -1;
445 txt_service = port_to_service(service);
447 rc = gnutls_verify_stored_pubkey(NULL, NULL, hostname, txt_service,
448 GNUTLS_CRT_X509, cert, 0);
449 if (rc == GNUTLS_E_NO_CERTIFICATE_FOUND)
451 print_cert_info_compact(session);
452 fprintf(stderr, "Host %s (%s) has never been contacted before.\n", hostname, txt_service);
453 if (status == 0)
454 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
456 rc = read_yesno("Are you sure you want to trust it? (y/N): ");
457 if (rc == 0)
458 return -1;
460 else if (rc == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
462 print_cert_info_compact(session);
463 fprintf(stderr, "Warning: host %s is known and it is associated with a different key.\n", hostname);
464 fprintf(stderr, "It might be that the server has multiple keys, or an attacker replaced the key to eavesdrop this connection .\n");
465 if (status == 0)
466 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
468 rc = read_yesno("Do you trust the received key? (y/N): ");
469 if (rc == 0)
470 return -1;
472 else if (rc < 0)
474 fprintf(stderr, "gnutls_verify_stored_pubkey: %s\n", gnutls_strerror(rc));
475 return -1;
478 if (rc != 0)
480 rc = gnutls_store_pubkey(NULL, NULL, hostname, txt_service,
481 GNUTLS_CRT_X509, cert, 0, 0);
482 if (rc < 0)
483 fprintf(stderr, "Could not store key: %s\n", gnutls_strerror(rc));
487 #ifdef HAVE_DANE
488 if (dane) /* try DANE auth */
490 unsigned int sflags = ENABLED_OPT(LOCAL_DNS)?0:DANE_F_IGNORE_LOCAL_RESOLVER;
491 rc = dane_verify_session_crt( NULL, session, hostname, udp?"udp":"tcp", atoi(service),
492 sflags, 0, &status);
493 if (rc < 0)
495 fprintf(stderr, "*** DANE verification error: %s\n", dane_strerror(rc));
496 if (!insecure)
497 return -1;
499 else
501 if (status != 0)
503 fprintf(stderr, "*** DANE certificate verification failed (flags %x).\n", status);
504 if (status & DANE_VERIFY_CA_CONSTRAINS_VIOLATED)
505 fprintf(stderr, "- CA constrains were violated.\n");
506 if (status & DANE_VERIFY_CERT_DIFFERS)
507 fprintf(stderr, "- The certificate differs.\n");
508 if (status & DANE_VERIFY_NO_DANE_INFO)
509 fprintf(stderr, "- There was no DANE information.\n");
510 if (!insecure)
511 return -1;
513 else
514 printf("- DANE verification didn't reject the certificate.\n");
518 #endif
520 return 0;
523 /* This callback should be associated with a session by calling
524 * gnutls_certificate_client_set_retrieve_function( session, cert_callback),
525 * before a handshake.
528 static int
529 cert_callback (gnutls_session_t session,
530 const gnutls_datum_t * req_ca_rdn, int nreqs,
531 const gnutls_pk_algorithm_t * sign_algos,
532 int sign_algos_length, gnutls_pcert_st **pcert,
533 unsigned int *pcert_length, gnutls_privkey_t * pkey)
535 char issuer_dn[256];
536 int i, ret, cert_type;
537 size_t len;
539 if (verbose)
541 /* Print the server's trusted CAs
543 if (nreqs > 0)
544 printf ("- Server's trusted authorities:\n");
545 else
546 printf ("- Server did not send us any trusted authorities names.\n");
548 /* print the names (if any) */
549 for (i = 0; i < nreqs; i++)
551 len = sizeof (issuer_dn);
552 ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len);
553 if (ret >= 0)
555 printf (" [%d]: ", i);
556 printf ("%s\n", issuer_dn);
561 /* Select a certificate and return it.
562 * The certificate must be of any of the "sign algorithms"
563 * supported by the server.
566 cert_type = gnutls_certificate_type_get (session);
568 *pcert_length = 0;
570 if (cert_type == GNUTLS_CRT_X509)
572 if (x509_crt_size > 0)
574 if (x509_key != NULL)
576 *pkey = x509_key;
578 else
580 printf ("- Could not find a suitable key to send to server\n");
581 return -1;
584 *pcert_length = x509_crt_size;
585 *pcert = x509_crt;
589 else if (cert_type == GNUTLS_CRT_OPENPGP)
591 if (pgp_key != NULL)
593 *pkey = pgp_key;
595 *pcert_length = 1;
596 *pcert = &pgp_crt;
600 printf ("- Successfully sent %u certificate(s) to server.\n", *pcert_length);
601 return 0;
605 /* initializes a gnutls_session_t with some defaults.
607 static gnutls_session_t
608 init_tls_session (const char *hostname)
610 const char *err;
611 int ret;
612 gnutls_session_t session;
614 if (priorities == NULL)
615 priorities = "NORMAL";
617 if (udp)
619 gnutls_init (&session, GNUTLS_DATAGRAM|init_flags);
620 if (mtu)
621 gnutls_dtls_set_mtu(session, mtu);
623 else
624 gnutls_init (&session, init_flags);
626 if ((ret = gnutls_priority_set_direct (session, priorities, &err)) < 0)
628 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
629 else
630 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
631 exit (1);
634 /* allow the use of private ciphersuites.
636 if (disable_extensions == 0)
638 if (!isdigit(hostname[0]) && strchr(hostname, ':') == 0)
639 gnutls_server_name_set (session, GNUTLS_NAME_DNS, hostname,
640 strlen (hostname));
643 if (HAVE_OPT(DH_BITS))
644 gnutls_dh_set_prime_bits( session, OPT_VALUE_DH_BITS);
646 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anon_cred);
647 if (srp_cred)
648 gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
649 if (psk_cred)
650 gnutls_credentials_set (session, GNUTLS_CRD_PSK, psk_cred);
651 gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
653 gnutls_certificate_set_retrieve_function2 (xcred, cert_callback);
654 gnutls_certificate_set_verify_function (xcred, cert_verify_callback);
656 /* send the fingerprint */
657 #ifdef ENABLE_OPENPGP
658 if (fingerprint != 0)
659 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
660 #endif
662 /* use the max record size extension */
663 if (record_max_size > 0 && disable_extensions == 0)
665 if (gnutls_record_set_max_size (session, record_max_size) < 0)
667 fprintf (stderr,
668 "Cannot set the maximum record size to %d.\n",
669 record_max_size);
670 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
671 exit (1);
675 if (HAVE_OPT(HEARTBEAT))
676 gnutls_heartbeat_enable (session, GNUTLS_HB_PEER_ALLOWED_TO_SEND);
678 if (HAVE_OPT(SRTP_PROFILES))
680 ret = gnutls_srtp_set_profile_direct (session, OPT_ARG(SRTP_PROFILES), &err);
681 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
682 else
683 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
684 exit (1);
687 return session;
690 static void cmd_parser (int argc, char **argv);
692 /* Returns zero if the error code was successfully handled.
694 static int
695 handle_error (socket_st * hd, int err)
697 int alert, ret;
698 const char *err_type, *str;
700 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
701 return 0;
703 if (gnutls_error_is_fatal (err) == 0)
705 ret = 0;
706 err_type = "Non fatal";
708 else
710 ret = err;
711 err_type = "Fatal";
714 str = gnutls_strerror (err);
715 if (str == NULL)
716 str = str_unknown;
717 fprintf (stderr, "*** %s error: %s\n", err_type, str);
719 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
720 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
722 alert = gnutls_alert_get (hd->session);
723 str = gnutls_alert_get_name (alert);
724 if (str == NULL)
725 str = str_unknown;
726 printf ("*** Received alert [%d]: %s\n", alert, str);
729 check_rehandshake (hd, err);
731 return ret;
734 int starttls_alarmed = 0;
736 #ifndef _WIN32
737 static void
738 starttls_alarm (int signum)
740 starttls_alarmed = 1;
742 #endif
744 static void
745 tls_log_func (int level, const char *str)
747 fprintf (stderr, "|<%d>| %s", level, str);
750 #define IN_KEYBOARD 1
751 #define IN_NET 2
752 #define IN_NONE 0
753 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
755 static int check_net_or_keyboard_input(socket_st* hd)
757 int maxfd;
758 fd_set rset;
759 int err;
760 struct timeval tv;
764 FD_ZERO (&rset);
765 FD_SET (hd->fd, &rset);
767 #ifndef _WIN32
768 FD_SET (fileno (stdin), &rset);
769 maxfd = MAX (fileno (stdin), hd->fd);
770 #else
771 maxfd = hd->fd;
772 #endif
774 tv.tv_sec = 0;
775 tv.tv_usec = 50 * 1000;
777 if (hd->secure == 1)
778 if (gnutls_record_check_pending(hd->session))
779 return IN_NET;
781 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
782 if (err < 0)
783 continue;
785 if (FD_ISSET (hd->fd, &rset))
786 return IN_NET;
788 #ifdef _WIN32
790 int state;
791 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
793 if (state == WAIT_OBJECT_0)
794 return IN_KEYBOARD;
796 #else
797 if (FD_ISSET (fileno (stdin), &rset))
798 return IN_KEYBOARD;
799 #endif
801 while(err == 0);
803 return IN_NONE;
807 main (int argc, char **argv)
809 int ret;
810 int ii, i, inp;
811 char buffer[MAX_BUF + 1];
812 char *session_data = NULL;
813 char *session_id = NULL;
814 size_t session_data_size;
815 size_t session_id_size = 0;
816 int user_term = 0, retval = 0;
817 socket_st hd;
818 ssize_t bytes;
820 set_program_name (argv[0]);
821 cmd_parser (argc, argv);
823 gnutls_global_set_log_function (tls_log_func);
824 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
826 if ((ret = gnutls_global_init ()) < 0)
828 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
829 exit (1);
832 #ifdef ENABLE_PKCS11
833 // pkcs11_common ();
834 #endif
836 if (hostname == NULL)
838 fprintf (stderr, "No hostname given\n");
839 exit (1);
842 sockets_init ();
844 init_global_tls_stuff ();
846 socket_open (&hd, hostname, service, udp);
847 socket_connect (&hd);
849 hd.session = init_tls_session (hostname);
850 if (starttls)
851 goto after_handshake;
853 for (i = 0; i < 2; i++)
857 if (i == 1)
859 hd.session = init_tls_session (hostname);
860 gnutls_session_set_data (hd.session, session_data,
861 session_data_size);
862 free (session_data);
865 ret = do_handshake (&hd);
867 if (ret < 0)
869 fprintf (stderr, "*** Handshake has failed\n");
870 gnutls_perror (ret);
871 gnutls_deinit (hd.session);
872 return 1;
874 else
876 printf ("- Handshake was completed\n");
877 if (gnutls_session_is_resumed (hd.session) != 0)
878 printf ("*** This is a resumed session\n");
881 if (resume != 0 && i == 0)
884 gnutls_session_get_data (hd.session, NULL, &session_data_size);
885 session_data = malloc (session_data_size);
887 gnutls_session_get_data (hd.session, session_data,
888 &session_data_size);
890 gnutls_session_get_id (hd.session, NULL, &session_id_size);
892 session_id = malloc (session_id_size);
893 gnutls_session_get_id (hd.session, session_id, &session_id_size);
895 printf ("- Disconnecting\n");
896 socket_bye (&hd);
898 printf
899 ("\n\n- Connecting again- trying to resume previous session\n");
900 socket_open (&hd, hostname, service, udp);
901 socket_connect (&hd);
903 else
905 break;
909 after_handshake:
911 /* Warning! Do not touch this text string, it is used by external
912 programs to search for when gnutls-cli has reached this point. */
913 printf ("\n- Simple Client Mode:\n\n");
915 if (rehandshake)
917 ret = do_handshake (&hd);
919 if (ret < 0)
921 fprintf (stderr, "*** ReHandshake has failed\n");
922 gnutls_perror (ret);
923 gnutls_deinit (hd.session);
924 return 1;
926 else
928 printf ("- ReHandshake was completed\n");
932 #ifndef _WIN32
933 signal (SIGALRM, &starttls_alarm);
934 #endif
936 fflush (stdout);
937 fflush (stderr);
939 /* do not buffer */
940 #ifndef _WIN32
941 setbuf (stdin, NULL);
942 #endif
943 setbuf (stdout, NULL);
944 setbuf (stderr, NULL);
946 for (;;)
948 if (starttls_alarmed && !hd.secure)
950 /* Warning! Do not touch this text string, it is used by
951 external programs to search for when gnutls-cli has
952 reached this point. */
953 fprintf (stderr, "*** Starting TLS handshake\n");
954 ret = do_handshake (&hd);
955 if (ret < 0)
957 fprintf (stderr, "*** Handshake has failed\n");
958 user_term = 1;
959 retval = 1;
960 break;
964 inp = check_net_or_keyboard_input(&hd);
966 if (inp == IN_NET)
968 memset (buffer, 0, MAX_BUF + 1);
969 ret = socket_recv (&hd, buffer, MAX_BUF);
971 if (ret == 0)
973 printf ("- Peer has closed the GnuTLS connection\n");
974 break;
976 else if (handle_error (&hd, ret) < 0 && user_term == 0)
978 fprintf (stderr,
979 "*** Server has terminated the connection abnormally.\n");
980 retval = 1;
981 break;
983 else if (ret > 0)
985 if (verbose != 0)
986 printf ("- Received[%d]: ", ret);
987 for (ii = 0; ii < ret; ii++)
989 fputc (buffer[ii], stdout);
991 fflush (stdout);
994 if (user_term != 0)
995 break;
998 if (inp == IN_KEYBOARD)
1000 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
1002 if (hd.secure == 0)
1004 /* Warning! Do not touch this text string, it is
1005 used by external programs to search for when
1006 gnutls-cli has reached this point. */
1007 fprintf (stderr, "*** Starting TLS handshake\n");
1008 ret = do_handshake (&hd);
1009 clearerr (stdin);
1010 if (ret < 0)
1012 fprintf (stderr, "*** Handshake has failed\n");
1013 user_term = 1;
1014 retval = 1;
1015 break;
1018 else
1020 user_term = 1;
1021 break;
1023 continue;
1026 buffer[bytes] = 0;
1027 if (crlf != 0)
1029 char *b = strchr (buffer, '\n');
1030 if (b != NULL)
1032 strcpy (b, "\r\n");
1033 bytes++;
1037 ret = socket_send (&hd, buffer, bytes);
1039 if (ret > 0)
1041 if (verbose != 0)
1042 printf ("- Sent: %d bytes\n", ret);
1044 else
1045 handle_error (&hd, ret);
1050 if (user_term != 0)
1051 socket_bye (&hd);
1052 else
1053 gnutls_deinit (hd.session);
1055 #ifdef ENABLE_SRP
1056 if (srp_cred)
1057 gnutls_srp_free_client_credentials (srp_cred);
1058 #endif
1059 #ifdef ENABLE_PSK
1060 if (psk_cred)
1061 gnutls_psk_free_client_credentials (psk_cred);
1062 #endif
1064 gnutls_certificate_free_credentials (xcred);
1066 #ifdef ENABLE_ANON
1067 gnutls_anon_free_client_credentials (anon_cred);
1068 #endif
1070 gnutls_global_deinit ();
1072 return retval;
1075 static void
1076 cmd_parser (int argc, char **argv)
1078 const char* rest = NULL;
1080 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1081 argc -= optct;
1082 argv += optct;
1084 if (rest == NULL && argc > 0)
1085 rest = argv[0];
1087 if (HAVE_OPT(BENCHMARK_CIPHERS))
1089 benchmark_cipher(1, OPT_VALUE_DEBUG);
1090 exit(0);
1093 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1095 benchmark_cipher(0, OPT_VALUE_DEBUG);
1096 exit(0);
1099 if (HAVE_OPT(BENCHMARK_TLS_CIPHERS))
1101 benchmark_tls(OPT_VALUE_DEBUG, 1);
1102 exit(0);
1105 if (HAVE_OPT(BENCHMARK_TLS_KX))
1107 benchmark_tls(OPT_VALUE_DEBUG, 0);
1108 exit(0);
1111 if (HAVE_OPT(PRIORITY))
1113 priorities = OPT_ARG(PRIORITY);
1115 verbose = HAVE_OPT( VERBOSE);
1116 if (verbose)
1117 print_cert = 1;
1118 else
1119 print_cert = HAVE_OPT( PRINT_CERT);
1121 if (HAVE_OPT(LIST))
1123 print_list(priorities, verbose);
1124 exit(0);
1127 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1128 if (disable_extensions)
1129 init_flags |= GNUTLS_NO_EXTENSIONS;
1131 starttls = HAVE_OPT(STARTTLS);
1132 resume = HAVE_OPT(RESUME);
1133 rehandshake = HAVE_OPT(REHANDSHAKE);
1134 insecure = HAVE_OPT(INSECURE);
1136 udp = HAVE_OPT(UDP);
1137 mtu = OPT_VALUE_MTU;
1139 if (HAVE_OPT(PORT))
1141 service = OPT_ARG(PORT);
1143 else
1145 service = "443";
1148 record_max_size = OPT_VALUE_RECORDSIZE;
1149 status_request_ocsp = ENABLED_OPT(OCSP_STATUS_REQUEST);
1150 if (ENABLED_OPT(OCSP))
1151 status_request_ocsp = 1;
1153 fingerprint = HAVE_OPT(FINGERPRINT);
1155 if (HAVE_OPT(X509FMTDER))
1156 x509ctype = GNUTLS_X509_FMT_DER;
1157 else
1158 x509ctype = GNUTLS_X509_FMT_PEM;
1160 if (HAVE_OPT(SRPUSERNAME))
1161 srp_username = OPT_ARG(SRPUSERNAME);
1163 if (HAVE_OPT(SRPPASSWD))
1164 srp_passwd = OPT_ARG(SRPPASSWD);
1166 if (HAVE_OPT(X509CAFILE))
1167 x509_cafile = OPT_ARG(X509CAFILE);
1169 if (HAVE_OPT(X509CRLFILE))
1170 x509_crlfile = OPT_ARG(X509CRLFILE);
1172 if (HAVE_OPT(X509KEYFILE))
1173 x509_keyfile = OPT_ARG(X509KEYFILE);
1175 if (HAVE_OPT(X509CERTFILE))
1176 x509_certfile = OPT_ARG(X509CERTFILE);
1178 if (HAVE_OPT(PGPKEYFILE))
1179 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1181 if (HAVE_OPT(PGPCERTFILE))
1182 pgp_certfile = OPT_ARG(PGPCERTFILE);
1184 if (HAVE_OPT(PSKUSERNAME))
1185 psk_username = OPT_ARG(PSKUSERNAME);
1187 if (HAVE_OPT(PSKKEY))
1189 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1190 psk_key.size = strlen (OPT_ARG(PSKKEY));
1192 else
1193 psk_key.size = 0;
1195 if (HAVE_OPT(PGPKEYRING))
1196 pgp_keyring = OPT_ARG(PGPKEYRING);
1198 crlf = HAVE_OPT(CRLF);
1200 if (rest != NULL)
1201 hostname = rest;
1203 if (hostname == NULL)
1205 fprintf(stderr, "No hostname specified\n");
1206 exit(1);
1210 static void
1211 check_rehandshake (socket_st * socket, int ret)
1213 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1215 /* There is a race condition here. If application
1216 * data is sent after the rehandshake request,
1217 * the server thinks we ignored his request.
1218 * This is a bad design of this client.
1220 printf ("*** Received rehandshake request\n");
1221 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1223 ret = do_handshake (socket);
1225 if (ret == 0)
1227 printf ("*** Rehandshake was performed.\n");
1229 else
1231 printf ("*** Rehandshake Failed.\n");
1237 static int
1238 do_handshake (socket_st * socket)
1240 int ret;
1242 gnutls_transport_set_ptr (socket->session,
1243 (gnutls_transport_ptr_t)
1244 gl_fd_to_handle (socket->fd));
1247 gnutls_handshake_set_timeout( socket->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
1248 ret = gnutls_handshake (socket->session);
1250 if (ret < 0)
1252 handle_error (socket, ret);
1255 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1257 if (ret == 0)
1259 /* print some information */
1260 print_info (socket->session, verbose, 0);
1261 socket->secure = 1;
1263 else
1265 gnutls_alert_send_appropriate (socket->session, ret);
1266 shutdown (socket->fd, SHUT_RDWR);
1268 return ret;
1271 static int
1272 srp_username_callback (gnutls_session_t session,
1273 char **username, char **password)
1275 if (srp_username == NULL || srp_passwd == NULL)
1277 return -1;
1280 *username = gnutls_strdup (srp_username);
1281 *password = gnutls_strdup (srp_passwd);
1283 return 0;
1286 static int
1287 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1289 const char *hint = gnutls_psk_client_get_hint (session);
1290 char *rawkey;
1291 char *passwd;
1292 int ret;
1293 size_t res_size;
1294 gnutls_datum_t tmp;
1296 printf ("- PSK client callback. ");
1297 if (hint)
1298 printf ("PSK hint '%s'\n", hint);
1299 else
1300 printf ("No PSK hint\n");
1302 if (HAVE_OPT(PSKUSERNAME))
1303 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1304 else
1306 char *tmp = NULL;
1307 size_t n;
1309 printf ("Enter PSK identity: ");
1310 fflush (stdout);
1311 getline (&tmp, &n, stdin);
1313 if (tmp == NULL)
1315 fprintf (stderr, "No username given, aborting...\n");
1316 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1319 if (tmp[strlen (tmp) - 1] == '\n')
1320 tmp[strlen (tmp) - 1] = '\0';
1321 if (tmp[strlen (tmp) - 1] == '\r')
1322 tmp[strlen (tmp) - 1] = '\0';
1324 *username = gnutls_strdup (tmp);
1325 free (tmp);
1327 if (!*username)
1328 return GNUTLS_E_MEMORY_ERROR;
1330 passwd = getpass ("Enter key: ");
1331 if (passwd == NULL)
1333 fprintf (stderr, "No key given, aborting...\n");
1334 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1337 tmp.data = (void*)passwd;
1338 tmp.size = strlen (passwd);
1340 res_size = tmp.size / 2 + 1;
1341 rawkey = gnutls_malloc (res_size);
1342 if (rawkey == NULL)
1343 return GNUTLS_E_MEMORY_ERROR;
1345 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1346 if (ret < 0)
1348 fprintf (stderr, "Error deriving password: %s\n",
1349 gnutls_strerror (ret));
1350 gnutls_free (*username);
1351 return ret;
1354 key->data = (void*)rawkey;
1355 key->size = res_size;
1357 if (HAVE_OPT(DEBUG))
1359 char hexkey[41];
1360 res_size = sizeof (hexkey);
1361 gnutls_hex_encode (key, hexkey, &res_size);
1362 fprintf (stderr, "PSK username: %s\n", *username);
1363 fprintf (stderr, "PSK hint: %s\n", hint);
1364 fprintf (stderr, "PSK key: %s\n", hexkey);
1367 return 0;
1370 static void
1371 init_global_tls_stuff (void)
1373 int ret;
1375 /* X509 stuff */
1376 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1378 fprintf (stderr, "Certificate allocation memory error\n");
1379 exit (1);
1381 gnutls_certificate_set_pin_function(xcred, pin_callback, NULL);
1383 if (x509_cafile != NULL)
1385 ret = gnutls_certificate_set_x509_trust_file (xcred,
1386 x509_cafile, x509ctype);
1388 else
1390 ret = gnutls_certificate_set_x509_system_trust (xcred);
1392 if (ret < 0)
1394 fprintf (stderr, "Error setting the x509 trust file\n");
1396 else
1398 printf ("Processed %d CA certificate(s).\n", ret);
1401 if (x509_crlfile != NULL)
1403 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1404 x509ctype);
1405 if (ret < 0)
1407 fprintf (stderr, "Error setting the x509 CRL file\n");
1409 else
1411 printf ("Processed %d CRL(s).\n", ret);
1415 load_keys ();
1417 #ifdef ENABLE_OPENPGP
1418 if (pgp_keyring != NULL)
1420 ret =
1421 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1422 GNUTLS_OPENPGP_FMT_BASE64);
1423 if (ret < 0)
1425 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1428 #endif
1430 #ifdef ENABLE_SRP
1431 if (srp_username && srp_passwd)
1433 /* SRP stuff */
1434 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1436 fprintf (stderr, "SRP authentication error\n");
1439 gnutls_srp_set_client_credentials_function (srp_cred,
1440 srp_username_callback);
1442 #endif
1444 #ifdef ENABLE_PSK
1445 /* PSK stuff */
1446 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1448 fprintf (stderr, "PSK authentication error\n");
1451 if (psk_username && psk_key.data)
1453 ret = gnutls_psk_set_client_credentials (psk_cred,
1454 psk_username, &psk_key,
1455 GNUTLS_PSK_KEY_HEX);
1456 if (ret < 0)
1458 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1459 gnutls_strerror (ret));
1462 else
1463 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1464 #endif
1466 #ifdef ENABLE_ANON
1467 /* ANON stuff */
1468 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1470 fprintf (stderr, "Anonymous authentication error\n");
1472 #endif
1476 /* OCSP check for the peer's certificate. Should be called
1477 * only after the certificate list verication is complete.
1478 * Returns:
1479 * 0: certificate is revoked
1480 * 1: certificate is ok
1481 * -1: dunno
1483 static int
1484 cert_verify_ocsp (gnutls_session_t session)
1486 gnutls_x509_crt_t crt, issuer;
1487 const gnutls_datum_t *cert_list;
1488 unsigned int cert_list_size = 0;
1489 int deinit_issuer = 0;
1490 gnutls_datum_t resp;
1491 int ret;
1493 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1494 if (cert_list_size == 0)
1496 fprintf (stderr, "No certificates found!\n");
1497 return -1;
1500 gnutls_x509_crt_init (&crt);
1501 ret =
1502 gnutls_x509_crt_import (crt, &cert_list[0],
1503 GNUTLS_X509_FMT_DER);
1504 if (ret < 0)
1506 fprintf (stderr, "Decoding error: %s\n",
1507 gnutls_strerror (ret));
1508 return -1;
1511 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1512 if (ret < 0 && cert_list_size > 1)
1514 gnutls_x509_crt_init(&issuer);
1515 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1516 if (ret < 0)
1518 fprintf (stderr, "Decoding error: %s\n",
1519 gnutls_strerror (ret));
1520 return -1;
1522 deinit_issuer = 1;
1524 else if (ret < 0)
1526 fprintf(stderr, "Cannot find issuer\n");
1527 ret = -1;
1528 goto cleanup;
1531 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1532 if (ret < 0)
1534 fprintf(stderr, "Cannot contact OCSP server\n");
1535 ret = -1;
1536 goto cleanup;
1539 /* verify and check the response for revoked cert */
1540 ret = check_ocsp_response(crt, issuer, &resp);
1542 cleanup:
1543 if (deinit_issuer)
1544 gnutls_x509_crt_deinit (issuer);
1545 gnutls_x509_crt_deinit (crt);
1547 return ret;