The status-request option was eliminated. Check OCSP only when the status response...
[gnutls.git] / src / cli.c
blob95fe8e0ce59b4c04ab76fec84ab1b57453e098b5
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 fingerprint;
76 int crlf;
77 unsigned int verbose = 0;
78 int print_cert;
80 const char *srp_passwd = NULL;
81 const char *srp_username = NULL;
82 const char *pgp_keyfile = NULL;
83 const char *pgp_certfile = NULL;
84 const char *pgp_keyring = NULL;
85 const char *x509_keyfile = NULL;
86 const char *x509_certfile = NULL;
87 const char *x509_cafile = NULL;
88 const char *x509_crlfile = NULL;
89 static int x509ctype;
90 static int disable_extensions;
91 static unsigned int init_flags = GNUTLS_CLIENT;
92 static const char * priorities = NULL;
94 const char *psk_username = NULL;
95 gnutls_datum_t psk_key = { NULL, 0 };
97 static gnutls_srp_client_credentials_t srp_cred;
98 static gnutls_psk_client_credentials_t psk_cred;
99 static gnutls_anon_client_credentials_t anon_cred;
100 static gnutls_certificate_credentials_t xcred;
102 /* end of global stuff */
104 /* prototypes */
106 static void check_rehandshake (socket_st * socket, int ret);
107 static int do_handshake (socket_st * socket);
108 static void init_global_tls_stuff (void);
109 static int cert_verify_ocsp (gnutls_session_t session);
111 #define MAX_CRT 6
112 static unsigned int x509_crt_size;
113 static gnutls_pcert_st x509_crt[MAX_CRT];
114 static gnutls_privkey_t x509_key = NULL;
116 static gnutls_pcert_st pgp_crt;
117 static gnutls_privkey_t pgp_key = NULL;
119 static void
120 get_keyid (gnutls_openpgp_keyid_t keyid, const char *str)
122 size_t keyid_size = sizeof (keyid);
124 if (strlen (str) != 16)
126 fprintf (stderr,
127 "The OpenPGP subkey ID has to be 16 hexadecimal characters.\n");
128 exit (1);
131 if (gnutls_hex2bin (str, strlen (str), keyid, &keyid_size) < 0)
133 fprintf (stderr, "Error converting hex string: %s.\n", str);
134 exit (1);
137 return;
140 /* Load the certificate and the private key.
142 static void
143 load_keys (void)
145 unsigned int crt_num;
146 int ret;
147 unsigned int i;
148 gnutls_datum_t data = { NULL, 0 };
149 gnutls_x509_crt_t crt_list[MAX_CRT];
150 unsigned char keyid[GNUTLS_OPENPGP_KEYID_SIZE];
152 if (x509_certfile != NULL && x509_keyfile != NULL)
154 #ifdef ENABLE_PKCS11
155 if (strncmp (x509_certfile, "pkcs11:", 7) == 0)
157 crt_num = 1;
158 gnutls_x509_crt_init (&crt_list[0]);
159 gnutls_x509_crt_set_pin_function(crt_list[0], pin_callback, NULL);
161 ret =
162 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile, 0);
164 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
165 ret =
166 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile,
167 GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
169 if (ret < 0)
171 fprintf (stderr, "*** Error loading cert file.\n");
172 exit (1);
174 x509_crt_size = 1;
176 else
177 #endif /* ENABLE_PKCS11 */
180 ret = gnutls_load_file (x509_certfile, &data);
181 if (ret < 0)
183 fprintf (stderr, "*** Error loading cert file.\n");
184 exit (1);
187 crt_num = MAX_CRT;
188 ret =
189 gnutls_x509_crt_list_import (crt_list, &crt_num, &data,
190 x509ctype,
191 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
192 if (ret < 0)
194 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
196 fprintf (stderr,
197 "*** Error loading cert file: Too many certs %d\n",
198 crt_num);
201 else
203 fprintf (stderr,
204 "*** Error loading cert file: %s\n",
205 gnutls_strerror (ret));
207 exit (1);
209 x509_crt_size = ret;
212 for (i=0;i<x509_crt_size;i++)
214 ret = gnutls_pcert_import_x509(&x509_crt[i], crt_list[i], 0);
215 if (ret < 0)
217 fprintf(stderr, "*** Error importing crt to pcert: %s\n",
218 gnutls_strerror(ret));
219 exit(1);
221 gnutls_x509_crt_deinit(crt_list[i]);
224 gnutls_free (data.data);
226 ret = gnutls_privkey_init(&x509_key);
227 if (ret < 0)
229 fprintf (stderr, "*** Error initializing key: %s\n",
230 gnutls_strerror (ret));
231 exit (1);
234 gnutls_privkey_set_pin_function(x509_key, pin_callback, NULL);
236 if (gnutls_url_is_supported(x509_keyfile) != 0)
238 ret =
239 gnutls_privkey_import_url (x509_key, x509_keyfile, 0);
240 if (ret < 0)
242 fprintf (stderr, "*** Error loading url: %s\n",
243 gnutls_strerror (ret));
244 exit (1);
247 else
249 ret = gnutls_load_file (x509_keyfile, &data);
250 if (ret < 0)
252 fprintf (stderr, "*** Error loading key file.\n");
253 exit (1);
256 ret = gnutls_privkey_import_x509_raw( x509_key, &data, x509ctype, NULL, 0);
257 if (ret < 0)
259 fprintf (stderr, "*** Error loading url: %s\n",
260 gnutls_strerror (ret));
261 exit (1);
264 gnutls_free(data.data);
267 fprintf (stdout, "Processed %d client X.509 certificates...\n",
268 x509_crt_size);
272 #ifdef ENABLE_OPENPGP
273 if (HAVE_OPT(PGPSUBKEY))
275 get_keyid (keyid, OPT_ARG(PGPSUBKEY));
278 if (pgp_certfile != NULL && pgp_keyfile != NULL)
280 gnutls_openpgp_crt_t tmp_pgp_crt;
282 ret = gnutls_load_file (pgp_certfile, &data);
283 if (ret < 0)
285 fprintf (stderr, "*** Error loading PGP cert file.\n");
286 exit (1);
289 gnutls_openpgp_crt_init (&tmp_pgp_crt);
291 ret =
292 gnutls_pcert_import_openpgp_raw (&pgp_crt, &data, GNUTLS_OPENPGP_FMT_BASE64, HAVE_OPT(PGPSUBKEY)?keyid:NULL, 0);
293 if (ret < 0)
295 fprintf (stderr,
296 "*** Error loading PGP cert file: %s\n",
297 gnutls_strerror (ret));
298 exit (1);
301 gnutls_free (data.data);
303 ret = gnutls_privkey_init(&pgp_key);
304 if (ret < 0)
306 fprintf (stderr, "*** Error initializing key: %s\n",
307 gnutls_strerror (ret));
308 exit (1);
311 gnutls_privkey_set_pin_function(pgp_key, pin_callback, NULL);
313 if (gnutls_url_is_supported (pgp_keyfile))
315 ret = gnutls_privkey_import_url( pgp_key, pgp_keyfile, 0);
316 if (ret < 0)
318 fprintf (stderr, "*** Error loading url: %s\n",
319 gnutls_strerror (ret));
320 exit (1);
323 else
325 ret = gnutls_load_file (pgp_keyfile, &data);
326 if (ret < 0)
328 fprintf (stderr, "*** Error loading key file.\n");
329 exit (1);
332 if (HAVE_OPT(PGPSUBKEY))
333 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, keyid, NULL);
334 else
335 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, NULL, NULL);
336 if (ret < 0)
338 fprintf (stderr, "*** Error loading url: %s\n",
339 gnutls_strerror (ret));
340 exit (1);
343 gnutls_free(data.data);
347 fprintf (stdout, "Processed 1 client PGP certificate...\n");
349 #endif
353 #define IS_NEWLINE(x) ((x[0] == '\n') || (x[0] == '\r'))
354 static int
355 read_yesno (const char *input_str)
357 char input[128];
359 fputs (input_str, stderr);
360 if (fgets (input, sizeof (input), stdin) == NULL)
361 return 0;
363 if (IS_NEWLINE(input))
364 return 0;
366 if (input[0] == 'y' || input[0] == 'Y')
367 return 1;
369 return 0;
372 /* converts a textual service or port to
373 * a service.
375 static const char* port_to_service(const char* sport)
377 unsigned int port;
378 struct servent * sr;
380 port = atoi(sport);
381 if (port == 0) return sport;
383 port = htons(port);
385 sr = getservbyport(port, udp?"udp":"tcp");
386 if (sr == NULL)
388 fprintf(stderr, "Warning: getservbyport() failed. Using port number as service.\n");
389 return sport;
392 return sr->s_name;
395 static int
396 cert_verify_callback (gnutls_session_t session)
398 int rc;
399 unsigned int status = 0;
400 int ssh = ENABLED_OPT(TOFU);
401 #ifdef HAVE_DANE
402 int dane = ENABLED_OPT(DANE);
403 #endif
404 int ca_verify = ENABLED_OPT(CA_VERIFICATION);
405 const char* txt_service;
407 print_cert_info (session, verbose, print_cert);
409 if (ca_verify)
411 rc = cert_verify(session, hostname);
412 if (rc == 0)
414 printf ("*** Verifying server certificate failed...\n");
415 if (!insecure && !ssh)
416 return -1;
418 else if (ENABLED_OPT(OCSP) && gnutls_ocsp_status_request_is_checked(session, 0) == 0)
419 { /* off-line verification succeeded. Try OCSP */
420 rc = cert_verify_ocsp(session);
421 if (rc == 0)
423 printf ("*** Verifying (with OCSP) server certificate failed...\n");
424 if (!insecure && !ssh)
425 return -1;
427 else if (rc == -1)
428 printf("*** OCSP response ignored\n");
432 if (ssh) /* try ssh auth */
434 unsigned int list_size;
435 const gnutls_datum_t * cert;
437 cert = gnutls_certificate_get_peers(session, &list_size);
438 if (cert == NULL)
440 fprintf(stderr, "Cannot obtain peer's certificate!\n");
441 return -1;
444 txt_service = port_to_service(service);
446 rc = gnutls_verify_stored_pubkey(NULL, NULL, hostname, txt_service,
447 GNUTLS_CRT_X509, cert, 0);
448 if (rc == GNUTLS_E_NO_CERTIFICATE_FOUND)
450 print_cert_info_compact(session);
451 fprintf(stderr, "Host %s (%s) has never been contacted before.\n", hostname, txt_service);
452 if (status == 0)
453 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
455 rc = read_yesno("Are you sure you want to trust it? (y/N): ");
456 if (rc == 0)
457 return -1;
459 else if (rc == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
461 print_cert_info_compact(session);
462 fprintf(stderr, "Warning: host %s is known and it is associated with a different key.\n", hostname);
463 fprintf(stderr, "It might be that the server has multiple keys, or an attacker replaced the key to eavesdrop this connection .\n");
464 if (status == 0)
465 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
467 rc = read_yesno("Do you trust the received key? (y/N): ");
468 if (rc == 0)
469 return -1;
471 else if (rc < 0)
473 fprintf(stderr, "gnutls_verify_stored_pubkey: %s\n", gnutls_strerror(rc));
474 return -1;
477 if (rc != 0)
479 rc = gnutls_store_pubkey(NULL, NULL, hostname, txt_service,
480 GNUTLS_CRT_X509, cert, 0, 0);
481 if (rc < 0)
482 fprintf(stderr, "Could not store key: %s\n", gnutls_strerror(rc));
486 #ifdef HAVE_DANE
487 if (dane) /* try DANE auth */
489 unsigned int sflags = ENABLED_OPT(LOCAL_DNS)?0:DANE_F_IGNORE_LOCAL_RESOLVER;
490 rc = dane_verify_session_crt( NULL, session, hostname, udp?"udp":"tcp", atoi(service),
491 sflags, 0, &status);
492 if (rc < 0)
494 fprintf(stderr, "*** DANE verification error: %s\n", dane_strerror(rc));
495 if (!insecure)
496 return -1;
498 else
500 gnutls_datum_t out;
502 rc = dane_verification_status_print( status, &out, 0);
503 if (rc < 0)
505 fprintf(stderr, "*** DANE error: %s\n", dane_strerror(rc));
506 if (!insecure)
507 return -1;
510 fprintf(stderr, "- %s\n", out.data);
511 gnutls_free(out.data);
515 #endif
517 return 0;
520 /* This callback should be associated with a session by calling
521 * gnutls_certificate_client_set_retrieve_function( session, cert_callback),
522 * before a handshake.
525 static int
526 cert_callback (gnutls_session_t session,
527 const gnutls_datum_t * req_ca_rdn, int nreqs,
528 const gnutls_pk_algorithm_t * sign_algos,
529 int sign_algos_length, gnutls_pcert_st **pcert,
530 unsigned int *pcert_length, gnutls_privkey_t * pkey)
532 char issuer_dn[256];
533 int i, ret, cert_type;
534 size_t len;
536 if (verbose)
538 /* Print the server's trusted CAs
540 if (nreqs > 0)
541 printf ("- Server's trusted authorities:\n");
542 else
543 printf ("- Server did not send us any trusted authorities names.\n");
545 /* print the names (if any) */
546 for (i = 0; i < nreqs; i++)
548 len = sizeof (issuer_dn);
549 ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len);
550 if (ret >= 0)
552 printf (" [%d]: ", i);
553 printf ("%s\n", issuer_dn);
558 /* Select a certificate and return it.
559 * The certificate must be of any of the "sign algorithms"
560 * supported by the server.
563 cert_type = gnutls_certificate_type_get (session);
565 *pcert_length = 0;
567 if (cert_type == GNUTLS_CRT_X509)
569 if (x509_crt_size > 0)
571 if (x509_key != NULL)
573 *pkey = x509_key;
575 else
577 printf ("- Could not find a suitable key to send to server\n");
578 return -1;
581 *pcert_length = x509_crt_size;
582 *pcert = x509_crt;
586 else if (cert_type == GNUTLS_CRT_OPENPGP)
588 if (pgp_key != NULL)
590 *pkey = pgp_key;
592 *pcert_length = 1;
593 *pcert = &pgp_crt;
597 printf ("- Successfully sent %u certificate(s) to server.\n", *pcert_length);
598 return 0;
602 /* initializes a gnutls_session_t with some defaults.
604 static gnutls_session_t
605 init_tls_session (const char *hostname)
607 const char *err;
608 int ret;
609 gnutls_session_t session;
611 if (priorities == NULL)
612 priorities = "NORMAL";
614 if (udp)
616 gnutls_init (&session, GNUTLS_DATAGRAM|init_flags);
617 if (mtu)
618 gnutls_dtls_set_mtu(session, mtu);
620 else
621 gnutls_init (&session, init_flags);
623 if ((ret = gnutls_priority_set_direct (session, priorities, &err)) < 0)
625 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
626 else
627 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
628 exit (1);
631 /* allow the use of private ciphersuites.
633 if (disable_extensions == 0)
635 if (!isdigit(hostname[0]) && strchr(hostname, ':') == 0)
636 gnutls_server_name_set (session, GNUTLS_NAME_DNS, hostname,
637 strlen (hostname));
640 if (HAVE_OPT(DH_BITS))
641 gnutls_dh_set_prime_bits( session, OPT_VALUE_DH_BITS);
643 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anon_cred);
644 if (srp_cred)
645 gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
646 if (psk_cred)
647 gnutls_credentials_set (session, GNUTLS_CRD_PSK, psk_cred);
648 gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
650 gnutls_certificate_set_retrieve_function2 (xcred, cert_callback);
651 gnutls_certificate_set_verify_function (xcred, cert_verify_callback);
653 /* send the fingerprint */
654 #ifdef ENABLE_OPENPGP
655 if (fingerprint != 0)
656 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
657 #endif
659 /* use the max record size extension */
660 if (record_max_size > 0 && disable_extensions == 0)
662 if (gnutls_record_set_max_size (session, record_max_size) < 0)
664 fprintf (stderr,
665 "Cannot set the maximum record size to %d.\n",
666 record_max_size);
667 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
668 exit (1);
672 if (HAVE_OPT(HEARTBEAT))
673 gnutls_heartbeat_enable (session, GNUTLS_HB_PEER_ALLOWED_TO_SEND);
675 #ifdef ENABLE_DTLS_SRTP
676 if (HAVE_OPT(SRTP_PROFILES))
678 ret = gnutls_srtp_set_profile_direct (session, OPT_ARG(SRTP_PROFILES), &err);
679 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
680 else
681 fprintf(stderr, "Error in profiles: %s\n", gnutls_strerror(ret));
682 exit (1);
684 #endif
686 return session;
689 static void cmd_parser (int argc, char **argv);
691 /* Returns zero if the error code was successfully handled.
693 static int
694 handle_error (socket_st * hd, int err)
696 int alert, ret;
697 const char *err_type, *str;
699 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
700 return 0;
702 if (gnutls_error_is_fatal (err) == 0)
704 ret = 0;
705 err_type = "Non fatal";
707 else
709 ret = err;
710 err_type = "Fatal";
713 str = gnutls_strerror (err);
714 if (str == NULL)
715 str = str_unknown;
716 fprintf (stderr, "*** %s error: %s\n", err_type, str);
718 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
719 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
721 alert = gnutls_alert_get (hd->session);
722 str = gnutls_alert_get_name (alert);
723 if (str == NULL)
724 str = str_unknown;
725 printf ("*** Received alert [%d]: %s\n", alert, str);
728 check_rehandshake (hd, err);
730 return ret;
733 int starttls_alarmed = 0;
735 #ifndef _WIN32
736 static void
737 starttls_alarm (int signum)
739 starttls_alarmed = 1;
741 #endif
743 static void
744 tls_log_func (int level, const char *str)
746 fprintf (stderr, "|<%d>| %s", level, str);
749 #define IN_KEYBOARD 1
750 #define IN_NET 2
751 #define IN_NONE 0
752 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
754 static int check_net_or_keyboard_input(socket_st* hd)
756 int maxfd;
757 fd_set rset;
758 int err;
759 struct timeval tv;
763 FD_ZERO (&rset);
764 FD_SET (hd->fd, &rset);
766 #ifndef _WIN32
767 FD_SET (fileno (stdin), &rset);
768 maxfd = MAX (fileno (stdin), hd->fd);
769 #else
770 maxfd = hd->fd;
771 #endif
773 tv.tv_sec = 0;
774 tv.tv_usec = 50 * 1000;
776 if (hd->secure == 1)
777 if (gnutls_record_check_pending(hd->session))
778 return IN_NET;
780 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
781 if (err < 0)
782 continue;
784 if (FD_ISSET (hd->fd, &rset))
785 return IN_NET;
787 #ifdef _WIN32
789 int state;
790 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
792 if (state == WAIT_OBJECT_0)
793 return IN_KEYBOARD;
795 #else
796 if (FD_ISSET (fileno (stdin), &rset))
797 return IN_KEYBOARD;
798 #endif
800 while(err == 0);
802 return IN_NONE;
806 main (int argc, char **argv)
808 int ret;
809 int ii, i, inp;
810 char buffer[MAX_BUF + 1];
811 char *session_data = NULL;
812 char *session_id = NULL;
813 size_t session_data_size;
814 size_t session_id_size = 0;
815 int user_term = 0, retval = 0;
816 socket_st hd;
817 ssize_t bytes;
819 set_program_name (argv[0]);
820 cmd_parser (argc, argv);
822 gnutls_global_set_log_function (tls_log_func);
823 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
825 if ((ret = gnutls_global_init ()) < 0)
827 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
828 exit (1);
831 #ifdef ENABLE_PKCS11
832 // pkcs11_common ();
833 #endif
835 if (hostname == NULL)
837 fprintf (stderr, "No hostname given\n");
838 exit (1);
841 sockets_init ();
843 init_global_tls_stuff ();
845 socket_open (&hd, hostname, service, udp);
846 socket_connect (&hd);
848 hd.session = init_tls_session (hostname);
849 if (starttls)
850 goto after_handshake;
852 for (i = 0; i < 2; i++)
856 if (i == 1)
858 hd.session = init_tls_session (hostname);
859 gnutls_session_set_data (hd.session, session_data,
860 session_data_size);
861 free (session_data);
864 ret = do_handshake (&hd);
866 if (ret < 0)
868 fprintf (stderr, "*** Handshake has failed\n");
869 gnutls_perror (ret);
870 gnutls_deinit (hd.session);
871 return 1;
873 else
875 printf ("- Handshake was completed\n");
876 if (gnutls_session_is_resumed (hd.session) != 0)
877 printf ("*** This is a resumed session\n");
880 if (resume != 0 && i == 0)
883 gnutls_session_get_data (hd.session, NULL, &session_data_size);
884 session_data = malloc (session_data_size);
886 gnutls_session_get_data (hd.session, session_data,
887 &session_data_size);
889 gnutls_session_get_id (hd.session, NULL, &session_id_size);
891 session_id = malloc (session_id_size);
892 gnutls_session_get_id (hd.session, session_id, &session_id_size);
894 printf ("- Disconnecting\n");
895 socket_bye (&hd);
897 printf
898 ("\n\n- Connecting again- trying to resume previous session\n");
899 socket_open (&hd, hostname, service, udp);
900 socket_connect (&hd);
902 else
904 break;
908 after_handshake:
910 /* Warning! Do not touch this text string, it is used by external
911 programs to search for when gnutls-cli has reached this point. */
912 printf ("\n- Simple Client Mode:\n\n");
914 if (rehandshake)
916 ret = do_handshake (&hd);
918 if (ret < 0)
920 fprintf (stderr, "*** ReHandshake has failed\n");
921 gnutls_perror (ret);
922 gnutls_deinit (hd.session);
923 return 1;
925 else
927 printf ("- ReHandshake was completed\n");
931 #ifndef _WIN32
932 signal (SIGALRM, &starttls_alarm);
933 #endif
935 fflush (stdout);
936 fflush (stderr);
938 /* do not buffer */
939 #ifndef _WIN32
940 setbuf (stdin, NULL);
941 #endif
942 setbuf (stdout, NULL);
943 setbuf (stderr, NULL);
945 for (;;)
947 if (starttls_alarmed && !hd.secure)
949 /* Warning! Do not touch this text string, it is used by
950 external programs to search for when gnutls-cli has
951 reached this point. */
952 fprintf (stderr, "*** Starting TLS handshake\n");
953 ret = do_handshake (&hd);
954 if (ret < 0)
956 fprintf (stderr, "*** Handshake has failed\n");
957 user_term = 1;
958 retval = 1;
959 break;
963 inp = check_net_or_keyboard_input(&hd);
965 if (inp == IN_NET)
967 memset (buffer, 0, MAX_BUF + 1);
968 ret = socket_recv (&hd, buffer, MAX_BUF);
970 if (ret == 0)
972 printf ("- Peer has closed the GnuTLS connection\n");
973 break;
975 else if (handle_error (&hd, ret) < 0 && user_term == 0)
977 fprintf (stderr,
978 "*** Server has terminated the connection abnormally.\n");
979 retval = 1;
980 break;
982 else if (ret > 0)
984 if (verbose != 0)
985 printf ("- Received[%d]: ", ret);
986 for (ii = 0; ii < ret; ii++)
988 fputc (buffer[ii], stdout);
990 fflush (stdout);
993 if (user_term != 0)
994 break;
997 if (inp == IN_KEYBOARD)
999 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
1001 if (hd.secure == 0)
1003 /* Warning! Do not touch this text string, it is
1004 used by external programs to search for when
1005 gnutls-cli has reached this point. */
1006 fprintf (stderr, "*** Starting TLS handshake\n");
1007 ret = do_handshake (&hd);
1008 clearerr (stdin);
1009 if (ret < 0)
1011 fprintf (stderr, "*** Handshake has failed\n");
1012 user_term = 1;
1013 retval = 1;
1014 break;
1017 else
1019 user_term = 1;
1020 break;
1022 continue;
1025 buffer[bytes] = 0;
1026 if (crlf != 0)
1028 char *b = strchr (buffer, '\n');
1029 if (b != NULL)
1031 strcpy (b, "\r\n");
1032 bytes++;
1036 ret = socket_send (&hd, buffer, bytes);
1038 if (ret > 0)
1040 if (verbose != 0)
1041 printf ("- Sent: %d bytes\n", ret);
1043 else
1044 handle_error (&hd, ret);
1049 if (user_term != 0)
1050 socket_bye (&hd);
1051 else
1052 gnutls_deinit (hd.session);
1054 #ifdef ENABLE_SRP
1055 if (srp_cred)
1056 gnutls_srp_free_client_credentials (srp_cred);
1057 #endif
1058 #ifdef ENABLE_PSK
1059 if (psk_cred)
1060 gnutls_psk_free_client_credentials (psk_cred);
1061 #endif
1063 gnutls_certificate_free_credentials (xcred);
1065 #ifdef ENABLE_ANON
1066 gnutls_anon_free_client_credentials (anon_cred);
1067 #endif
1069 gnutls_global_deinit ();
1071 return retval;
1074 static void
1075 cmd_parser (int argc, char **argv)
1077 const char* rest = NULL;
1079 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1080 argc -= optct;
1081 argv += optct;
1083 if (rest == NULL && argc > 0)
1084 rest = argv[0];
1086 if (HAVE_OPT(BENCHMARK_CIPHERS))
1088 benchmark_cipher(1, OPT_VALUE_DEBUG);
1089 exit(0);
1092 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1094 benchmark_cipher(0, OPT_VALUE_DEBUG);
1095 exit(0);
1098 if (HAVE_OPT(BENCHMARK_TLS_CIPHERS))
1100 benchmark_tls(OPT_VALUE_DEBUG, 1);
1101 exit(0);
1104 if (HAVE_OPT(BENCHMARK_TLS_KX))
1106 benchmark_tls(OPT_VALUE_DEBUG, 0);
1107 exit(0);
1110 if (HAVE_OPT(PRIORITY))
1112 priorities = OPT_ARG(PRIORITY);
1114 verbose = HAVE_OPT( VERBOSE);
1115 if (verbose)
1116 print_cert = 1;
1117 else
1118 print_cert = HAVE_OPT( PRINT_CERT);
1120 if (HAVE_OPT(LIST))
1122 print_list(priorities, verbose);
1123 exit(0);
1126 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1127 if (disable_extensions)
1128 init_flags |= GNUTLS_NO_EXTENSIONS;
1130 starttls = HAVE_OPT(STARTTLS);
1131 resume = HAVE_OPT(RESUME);
1132 rehandshake = HAVE_OPT(REHANDSHAKE);
1133 insecure = HAVE_OPT(INSECURE);
1135 udp = HAVE_OPT(UDP);
1136 mtu = OPT_VALUE_MTU;
1138 if (HAVE_OPT(PORT))
1140 service = OPT_ARG(PORT);
1142 else
1144 service = "443";
1147 record_max_size = OPT_VALUE_RECORDSIZE;
1149 fingerprint = HAVE_OPT(FINGERPRINT);
1151 if (HAVE_OPT(X509FMTDER))
1152 x509ctype = GNUTLS_X509_FMT_DER;
1153 else
1154 x509ctype = GNUTLS_X509_FMT_PEM;
1156 if (HAVE_OPT(SRPUSERNAME))
1157 srp_username = OPT_ARG(SRPUSERNAME);
1159 if (HAVE_OPT(SRPPASSWD))
1160 srp_passwd = OPT_ARG(SRPPASSWD);
1162 if (HAVE_OPT(X509CAFILE))
1163 x509_cafile = OPT_ARG(X509CAFILE);
1165 if (HAVE_OPT(X509CRLFILE))
1166 x509_crlfile = OPT_ARG(X509CRLFILE);
1168 if (HAVE_OPT(X509KEYFILE))
1169 x509_keyfile = OPT_ARG(X509KEYFILE);
1171 if (HAVE_OPT(X509CERTFILE))
1172 x509_certfile = OPT_ARG(X509CERTFILE);
1174 if (HAVE_OPT(PGPKEYFILE))
1175 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1177 if (HAVE_OPT(PGPCERTFILE))
1178 pgp_certfile = OPT_ARG(PGPCERTFILE);
1180 if (HAVE_OPT(PSKUSERNAME))
1181 psk_username = OPT_ARG(PSKUSERNAME);
1183 if (HAVE_OPT(PSKKEY))
1185 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1186 psk_key.size = strlen (OPT_ARG(PSKKEY));
1188 else
1189 psk_key.size = 0;
1191 if (HAVE_OPT(PGPKEYRING))
1192 pgp_keyring = OPT_ARG(PGPKEYRING);
1194 crlf = HAVE_OPT(CRLF);
1196 if (rest != NULL)
1197 hostname = rest;
1199 if (hostname == NULL)
1201 fprintf(stderr, "No hostname specified\n");
1202 exit(1);
1206 static void
1207 check_rehandshake (socket_st * socket, int ret)
1209 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1211 /* There is a race condition here. If application
1212 * data is sent after the rehandshake request,
1213 * the server thinks we ignored his request.
1214 * This is a bad design of this client.
1216 printf ("*** Received rehandshake request\n");
1217 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1219 ret = do_handshake (socket);
1221 if (ret == 0)
1223 printf ("*** Rehandshake was performed.\n");
1225 else
1227 printf ("*** Rehandshake Failed.\n");
1233 static int
1234 do_handshake (socket_st * socket)
1236 int ret;
1238 gnutls_transport_set_ptr (socket->session,
1239 (gnutls_transport_ptr_t)
1240 gl_fd_to_handle (socket->fd));
1243 gnutls_handshake_set_timeout( socket->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
1244 ret = gnutls_handshake (socket->session);
1246 if (ret < 0)
1248 handle_error (socket, ret);
1251 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1253 if (ret == 0)
1255 /* print some information */
1256 print_info (socket->session, verbose, 0);
1257 socket->secure = 1;
1259 else
1261 gnutls_alert_send_appropriate (socket->session, ret);
1262 shutdown (socket->fd, SHUT_RDWR);
1264 return ret;
1267 static int
1268 srp_username_callback (gnutls_session_t session,
1269 char **username, char **password)
1271 if (srp_username == NULL || srp_passwd == NULL)
1273 return -1;
1276 *username = gnutls_strdup (srp_username);
1277 *password = gnutls_strdup (srp_passwd);
1279 return 0;
1282 static int
1283 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1285 const char *hint = gnutls_psk_client_get_hint (session);
1286 char *rawkey;
1287 char *passwd;
1288 int ret;
1289 size_t res_size;
1290 gnutls_datum_t tmp;
1292 printf ("- PSK client callback. ");
1293 if (hint)
1294 printf ("PSK hint '%s'\n", hint);
1295 else
1296 printf ("No PSK hint\n");
1298 if (HAVE_OPT(PSKUSERNAME))
1299 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1300 else
1302 char *tmp = NULL;
1303 size_t n;
1305 printf ("Enter PSK identity: ");
1306 fflush (stdout);
1307 getline (&tmp, &n, stdin);
1309 if (tmp == NULL)
1311 fprintf (stderr, "No username given, aborting...\n");
1312 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1315 if (tmp[strlen (tmp) - 1] == '\n')
1316 tmp[strlen (tmp) - 1] = '\0';
1317 if (tmp[strlen (tmp) - 1] == '\r')
1318 tmp[strlen (tmp) - 1] = '\0';
1320 *username = gnutls_strdup (tmp);
1321 free (tmp);
1323 if (!*username)
1324 return GNUTLS_E_MEMORY_ERROR;
1326 passwd = getpass ("Enter key: ");
1327 if (passwd == NULL)
1329 fprintf (stderr, "No key given, aborting...\n");
1330 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1333 tmp.data = (void*)passwd;
1334 tmp.size = strlen (passwd);
1336 res_size = tmp.size / 2 + 1;
1337 rawkey = gnutls_malloc (res_size);
1338 if (rawkey == NULL)
1339 return GNUTLS_E_MEMORY_ERROR;
1341 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1342 if (ret < 0)
1344 fprintf (stderr, "Error deriving password: %s\n",
1345 gnutls_strerror (ret));
1346 gnutls_free (*username);
1347 return ret;
1350 key->data = (void*)rawkey;
1351 key->size = res_size;
1353 if (HAVE_OPT(DEBUG))
1355 char hexkey[41];
1356 res_size = sizeof (hexkey);
1357 gnutls_hex_encode (key, hexkey, &res_size);
1358 fprintf (stderr, "PSK username: %s\n", *username);
1359 fprintf (stderr, "PSK hint: %s\n", hint);
1360 fprintf (stderr, "PSK key: %s\n", hexkey);
1363 return 0;
1366 static void
1367 init_global_tls_stuff (void)
1369 int ret;
1371 /* X509 stuff */
1372 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1374 fprintf (stderr, "Certificate allocation memory error\n");
1375 exit (1);
1377 gnutls_certificate_set_pin_function(xcred, pin_callback, NULL);
1379 if (x509_cafile != NULL)
1381 ret = gnutls_certificate_set_x509_trust_file (xcred,
1382 x509_cafile, x509ctype);
1384 else
1386 ret = gnutls_certificate_set_x509_system_trust (xcred);
1388 if (ret < 0)
1390 fprintf (stderr, "Error setting the x509 trust file\n");
1392 else
1394 printf ("Processed %d CA certificate(s).\n", ret);
1397 if (x509_crlfile != NULL)
1399 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1400 x509ctype);
1401 if (ret < 0)
1403 fprintf (stderr, "Error setting the x509 CRL file\n");
1405 else
1407 printf ("Processed %d CRL(s).\n", ret);
1411 load_keys ();
1413 #ifdef ENABLE_OPENPGP
1414 if (pgp_keyring != NULL)
1416 ret =
1417 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1418 GNUTLS_OPENPGP_FMT_BASE64);
1419 if (ret < 0)
1421 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1424 #endif
1426 #ifdef ENABLE_SRP
1427 if (srp_username && srp_passwd)
1429 /* SRP stuff */
1430 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1432 fprintf (stderr, "SRP authentication error\n");
1435 gnutls_srp_set_client_credentials_function (srp_cred,
1436 srp_username_callback);
1438 #endif
1440 #ifdef ENABLE_PSK
1441 /* PSK stuff */
1442 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1444 fprintf (stderr, "PSK authentication error\n");
1447 if (psk_username && psk_key.data)
1449 ret = gnutls_psk_set_client_credentials (psk_cred,
1450 psk_username, &psk_key,
1451 GNUTLS_PSK_KEY_HEX);
1452 if (ret < 0)
1454 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1455 gnutls_strerror (ret));
1458 else
1459 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1460 #endif
1462 #ifdef ENABLE_ANON
1463 /* ANON stuff */
1464 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1466 fprintf (stderr, "Anonymous authentication error\n");
1468 #endif
1472 /* OCSP check for the peer's certificate. Should be called
1473 * only after the certificate list verication is complete.
1474 * Returns:
1475 * 0: certificate is revoked
1476 * 1: certificate is ok
1477 * -1: dunno
1479 static int
1480 cert_verify_ocsp (gnutls_session_t session)
1482 gnutls_x509_crt_t crt, issuer;
1483 const gnutls_datum_t *cert_list;
1484 unsigned int cert_list_size = 0;
1485 int deinit_issuer = 0;
1486 gnutls_datum_t resp;
1487 int ret;
1489 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1490 if (cert_list_size == 0)
1492 fprintf (stderr, "No certificates found!\n");
1493 return -1;
1496 gnutls_x509_crt_init (&crt);
1497 ret =
1498 gnutls_x509_crt_import (crt, &cert_list[0],
1499 GNUTLS_X509_FMT_DER);
1500 if (ret < 0)
1502 fprintf (stderr, "Decoding error: %s\n",
1503 gnutls_strerror (ret));
1504 return -1;
1507 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1508 if (ret < 0 && cert_list_size > 1)
1510 gnutls_x509_crt_init(&issuer);
1511 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1512 if (ret < 0)
1514 fprintf (stderr, "Decoding error: %s\n",
1515 gnutls_strerror (ret));
1516 return -1;
1518 deinit_issuer = 1;
1520 else if (ret < 0)
1522 fprintf(stderr, "Cannot find issuer\n");
1523 ret = -1;
1524 goto cleanup;
1527 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1528 if (ret < 0)
1530 fprintf(stderr, "Cannot contact OCSP server\n");
1531 ret = -1;
1532 goto cleanup;
1535 /* verify and check the response for revoked cert */
1536 ret = check_ocsp_response(crt, issuer, &resp);
1538 cleanup:
1539 if (deinit_issuer)
1540 gnutls_x509_crt_deinit (issuer);
1541 gnutls_x509_crt_deinit (crt);
1543 return ret;