corrected copyright notices
[gnutls.git] / src / cli.c
blob142c8831d232e6c18ec83646a8376ebd130ed6a3
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);
847 hd.session = init_tls_session (hostname);
848 if (starttls)
849 goto after_handshake;
851 for (i = 0; i < 2; i++)
855 if (i == 1)
857 hd.session = init_tls_session (hostname);
858 gnutls_session_set_data (hd.session, session_data,
859 session_data_size);
860 free (session_data);
863 ret = do_handshake (&hd);
865 if (ret < 0)
867 fprintf (stderr, "*** Handshake has failed\n");
868 gnutls_perror (ret);
869 gnutls_deinit (hd.session);
870 return 1;
872 else
874 printf ("- Handshake was completed\n");
875 if (gnutls_session_is_resumed (hd.session) != 0)
876 printf ("*** This is a resumed session\n");
879 if (resume != 0 && i == 0)
882 gnutls_session_get_data (hd.session, NULL, &session_data_size);
883 session_data = malloc (session_data_size);
885 gnutls_session_get_data (hd.session, session_data,
886 &session_data_size);
888 gnutls_session_get_id (hd.session, NULL, &session_id_size);
890 session_id = malloc (session_id_size);
891 gnutls_session_get_id (hd.session, session_id, &session_id_size);
893 printf ("- Disconnecting\n");
894 socket_bye (&hd);
896 printf
897 ("\n\n- Connecting again- trying to resume previous session\n");
898 socket_open (&hd, hostname, service, udp);
900 else
902 break;
906 after_handshake:
908 /* Warning! Do not touch this text string, it is used by external
909 programs to search for when gnutls-cli has reached this point. */
910 printf ("\n- Simple Client Mode:\n\n");
912 if (rehandshake)
914 ret = do_handshake (&hd);
916 if (ret < 0)
918 fprintf (stderr, "*** ReHandshake has failed\n");
919 gnutls_perror (ret);
920 gnutls_deinit (hd.session);
921 return 1;
923 else
925 printf ("- ReHandshake was completed\n");
929 #ifndef _WIN32
930 signal (SIGALRM, &starttls_alarm);
931 #endif
933 fflush (stdout);
934 fflush (stderr);
936 /* do not buffer */
937 #ifndef _WIN32
938 setbuf (stdin, NULL);
939 #endif
940 setbuf (stdout, NULL);
941 setbuf (stderr, NULL);
943 for (;;)
945 if (starttls_alarmed && !hd.secure)
947 /* Warning! Do not touch this text string, it is used by
948 external programs to search for when gnutls-cli has
949 reached this point. */
950 fprintf (stderr, "*** Starting TLS handshake\n");
951 ret = do_handshake (&hd);
952 if (ret < 0)
954 fprintf (stderr, "*** Handshake has failed\n");
955 user_term = 1;
956 retval = 1;
957 break;
961 inp = check_net_or_keyboard_input(&hd);
963 if (inp == IN_NET)
965 memset (buffer, 0, MAX_BUF + 1);
966 ret = socket_recv (&hd, buffer, MAX_BUF);
968 if (ret == 0)
970 printf ("- Peer has closed the GnuTLS connection\n");
971 break;
973 else if (handle_error (&hd, ret) < 0 && user_term == 0)
975 fprintf (stderr,
976 "*** Server has terminated the connection abnormally.\n");
977 retval = 1;
978 break;
980 else if (ret > 0)
982 if (verbose != 0)
983 printf ("- Received[%d]: ", ret);
984 for (ii = 0; ii < ret; ii++)
986 fputc (buffer[ii], stdout);
988 fflush (stdout);
991 if (user_term != 0)
992 break;
995 if (inp == IN_KEYBOARD)
997 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
999 if (hd.secure == 0)
1001 /* Warning! Do not touch this text string, it is
1002 used by external programs to search for when
1003 gnutls-cli has reached this point. */
1004 fprintf (stderr, "*** Starting TLS handshake\n");
1005 ret = do_handshake (&hd);
1006 clearerr (stdin);
1007 if (ret < 0)
1009 fprintf (stderr, "*** Handshake has failed\n");
1010 user_term = 1;
1011 retval = 1;
1012 break;
1015 else
1017 user_term = 1;
1018 break;
1020 continue;
1023 buffer[bytes] = 0;
1024 if (crlf != 0)
1026 char *b = strchr (buffer, '\n');
1027 if (b != NULL)
1029 strcpy (b, "\r\n");
1030 bytes++;
1034 ret = socket_send (&hd, buffer, bytes);
1036 if (ret > 0)
1038 if (verbose != 0)
1039 printf ("- Sent: %d bytes\n", ret);
1041 else
1042 handle_error (&hd, ret);
1047 if (user_term != 0)
1048 socket_bye (&hd);
1049 else
1050 gnutls_deinit (hd.session);
1052 #ifdef ENABLE_SRP
1053 if (srp_cred)
1054 gnutls_srp_free_client_credentials (srp_cred);
1055 #endif
1056 #ifdef ENABLE_PSK
1057 if (psk_cred)
1058 gnutls_psk_free_client_credentials (psk_cred);
1059 #endif
1061 gnutls_certificate_free_credentials (xcred);
1063 #ifdef ENABLE_ANON
1064 gnutls_anon_free_client_credentials (anon_cred);
1065 #endif
1067 gnutls_global_deinit ();
1069 return retval;
1072 static void
1073 cmd_parser (int argc, char **argv)
1075 const char* rest = NULL;
1077 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1078 argc -= optct;
1079 argv += optct;
1081 if (rest == NULL && argc > 0)
1082 rest = argv[0];
1084 if (HAVE_OPT(BENCHMARK_CIPHERS))
1086 benchmark_cipher(1, OPT_VALUE_DEBUG);
1087 exit(0);
1090 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1092 benchmark_cipher(0, OPT_VALUE_DEBUG);
1093 exit(0);
1096 if (HAVE_OPT(BENCHMARK_TLS_CIPHERS))
1098 benchmark_tls(OPT_VALUE_DEBUG, 1);
1099 exit(0);
1102 if (HAVE_OPT(BENCHMARK_TLS_KX))
1104 benchmark_tls(OPT_VALUE_DEBUG, 0);
1105 exit(0);
1108 if (HAVE_OPT(PRIORITY))
1110 priorities = OPT_ARG(PRIORITY);
1112 verbose = HAVE_OPT( VERBOSE);
1113 if (verbose)
1114 print_cert = 1;
1115 else
1116 print_cert = HAVE_OPT( PRINT_CERT);
1118 if (HAVE_OPT(LIST))
1120 print_list(priorities, verbose);
1121 exit(0);
1124 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1125 if (disable_extensions)
1126 init_flags |= GNUTLS_NO_EXTENSIONS;
1128 starttls = HAVE_OPT(STARTTLS);
1129 resume = HAVE_OPT(RESUME);
1130 rehandshake = HAVE_OPT(REHANDSHAKE);
1131 insecure = HAVE_OPT(INSECURE);
1133 udp = HAVE_OPT(UDP);
1134 mtu = OPT_VALUE_MTU;
1136 if (HAVE_OPT(PORT))
1138 service = OPT_ARG(PORT);
1140 else
1142 service = "443";
1145 record_max_size = OPT_VALUE_RECORDSIZE;
1147 fingerprint = HAVE_OPT(FINGERPRINT);
1149 if (HAVE_OPT(X509FMTDER))
1150 x509ctype = GNUTLS_X509_FMT_DER;
1151 else
1152 x509ctype = GNUTLS_X509_FMT_PEM;
1154 if (HAVE_OPT(SRPUSERNAME))
1155 srp_username = OPT_ARG(SRPUSERNAME);
1157 if (HAVE_OPT(SRPPASSWD))
1158 srp_passwd = OPT_ARG(SRPPASSWD);
1160 if (HAVE_OPT(X509CAFILE))
1161 x509_cafile = OPT_ARG(X509CAFILE);
1163 if (HAVE_OPT(X509CRLFILE))
1164 x509_crlfile = OPT_ARG(X509CRLFILE);
1166 if (HAVE_OPT(X509KEYFILE))
1167 x509_keyfile = OPT_ARG(X509KEYFILE);
1169 if (HAVE_OPT(X509CERTFILE))
1170 x509_certfile = OPT_ARG(X509CERTFILE);
1172 if (HAVE_OPT(PGPKEYFILE))
1173 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1175 if (HAVE_OPT(PGPCERTFILE))
1176 pgp_certfile = OPT_ARG(PGPCERTFILE);
1178 if (HAVE_OPT(PSKUSERNAME))
1179 psk_username = OPT_ARG(PSKUSERNAME);
1181 if (HAVE_OPT(PSKKEY))
1183 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1184 psk_key.size = strlen (OPT_ARG(PSKKEY));
1186 else
1187 psk_key.size = 0;
1189 if (HAVE_OPT(PGPKEYRING))
1190 pgp_keyring = OPT_ARG(PGPKEYRING);
1192 crlf = HAVE_OPT(CRLF);
1194 if (rest != NULL)
1195 hostname = rest;
1197 if (hostname == NULL)
1199 fprintf(stderr, "No hostname specified\n");
1200 exit(1);
1204 static void
1205 check_rehandshake (socket_st * socket, int ret)
1207 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1209 /* There is a race condition here. If application
1210 * data is sent after the rehandshake request,
1211 * the server thinks we ignored his request.
1212 * This is a bad design of this client.
1214 printf ("*** Received rehandshake request\n");
1215 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1217 ret = do_handshake (socket);
1219 if (ret == 0)
1221 printf ("*** Rehandshake was performed.\n");
1223 else
1225 printf ("*** Rehandshake Failed.\n");
1231 static int
1232 do_handshake (socket_st * socket)
1234 int ret;
1236 gnutls_transport_set_ptr (socket->session,
1237 (gnutls_transport_ptr_t)
1238 gl_fd_to_handle (socket->fd));
1241 gnutls_handshake_set_timeout( socket->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
1242 ret = gnutls_handshake (socket->session);
1244 if (ret < 0)
1246 handle_error (socket, ret);
1249 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1251 if (ret == 0)
1253 /* print some information */
1254 print_info (socket->session, verbose, 0);
1255 socket->secure = 1;
1257 else
1259 gnutls_alert_send_appropriate (socket->session, ret);
1260 shutdown (socket->fd, SHUT_RDWR);
1262 return ret;
1265 static int
1266 srp_username_callback (gnutls_session_t session,
1267 char **username, char **password)
1269 if (srp_username == NULL || srp_passwd == NULL)
1271 return -1;
1274 *username = gnutls_strdup (srp_username);
1275 *password = gnutls_strdup (srp_passwd);
1277 return 0;
1280 static int
1281 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1283 const char *hint = gnutls_psk_client_get_hint (session);
1284 char *rawkey;
1285 char *passwd;
1286 int ret;
1287 size_t res_size;
1288 gnutls_datum_t tmp;
1290 printf ("- PSK client callback. ");
1291 if (hint)
1292 printf ("PSK hint '%s'\n", hint);
1293 else
1294 printf ("No PSK hint\n");
1296 if (HAVE_OPT(PSKUSERNAME))
1297 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1298 else
1300 char *tmp = NULL;
1301 size_t n;
1303 printf ("Enter PSK identity: ");
1304 fflush (stdout);
1305 getline (&tmp, &n, stdin);
1307 if (tmp == NULL)
1309 fprintf (stderr, "No username given, aborting...\n");
1310 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1313 if (tmp[strlen (tmp) - 1] == '\n')
1314 tmp[strlen (tmp) - 1] = '\0';
1315 if (tmp[strlen (tmp) - 1] == '\r')
1316 tmp[strlen (tmp) - 1] = '\0';
1318 *username = gnutls_strdup (tmp);
1319 free (tmp);
1321 if (!*username)
1322 return GNUTLS_E_MEMORY_ERROR;
1324 passwd = getpass ("Enter key: ");
1325 if (passwd == NULL)
1327 fprintf (stderr, "No key given, aborting...\n");
1328 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1331 tmp.data = (void*)passwd;
1332 tmp.size = strlen (passwd);
1334 res_size = tmp.size / 2 + 1;
1335 rawkey = gnutls_malloc (res_size);
1336 if (rawkey == NULL)
1337 return GNUTLS_E_MEMORY_ERROR;
1339 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1340 if (ret < 0)
1342 fprintf (stderr, "Error deriving password: %s\n",
1343 gnutls_strerror (ret));
1344 gnutls_free (*username);
1345 return ret;
1348 key->data = (void*)rawkey;
1349 key->size = res_size;
1351 if (HAVE_OPT(DEBUG))
1353 char hexkey[41];
1354 res_size = sizeof (hexkey);
1355 gnutls_hex_encode (key, hexkey, &res_size);
1356 fprintf (stderr, "PSK username: %s\n", *username);
1357 fprintf (stderr, "PSK hint: %s\n", hint);
1358 fprintf (stderr, "PSK key: %s\n", hexkey);
1361 return 0;
1364 static void
1365 init_global_tls_stuff (void)
1367 int ret;
1369 /* X509 stuff */
1370 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1372 fprintf (stderr, "Certificate allocation memory error\n");
1373 exit (1);
1375 gnutls_certificate_set_pin_function(xcred, pin_callback, NULL);
1377 if (x509_cafile != NULL)
1379 ret = gnutls_certificate_set_x509_trust_file (xcred,
1380 x509_cafile, x509ctype);
1382 else
1384 ret = gnutls_certificate_set_x509_system_trust (xcred);
1386 if (ret < 0)
1388 fprintf (stderr, "Error setting the x509 trust file\n");
1390 else
1392 printf ("Processed %d CA certificate(s).\n", ret);
1395 if (x509_crlfile != NULL)
1397 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1398 x509ctype);
1399 if (ret < 0)
1401 fprintf (stderr, "Error setting the x509 CRL file\n");
1403 else
1405 printf ("Processed %d CRL(s).\n", ret);
1409 load_keys ();
1411 #ifdef ENABLE_OPENPGP
1412 if (pgp_keyring != NULL)
1414 ret =
1415 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1416 GNUTLS_OPENPGP_FMT_BASE64);
1417 if (ret < 0)
1419 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1422 #endif
1424 #ifdef ENABLE_SRP
1425 if (srp_username && srp_passwd)
1427 /* SRP stuff */
1428 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1430 fprintf (stderr, "SRP authentication error\n");
1433 gnutls_srp_set_client_credentials_function (srp_cred,
1434 srp_username_callback);
1436 #endif
1438 #ifdef ENABLE_PSK
1439 /* PSK stuff */
1440 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1442 fprintf (stderr, "PSK authentication error\n");
1445 if (psk_username && psk_key.data)
1447 ret = gnutls_psk_set_client_credentials (psk_cred,
1448 psk_username, &psk_key,
1449 GNUTLS_PSK_KEY_HEX);
1450 if (ret < 0)
1452 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1453 gnutls_strerror (ret));
1456 else
1457 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1458 #endif
1460 #ifdef ENABLE_ANON
1461 /* ANON stuff */
1462 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1464 fprintf (stderr, "Anonymous authentication error\n");
1466 #endif
1470 /* OCSP check for the peer's certificate. Should be called
1471 * only after the certificate list verication is complete.
1472 * Returns:
1473 * 0: certificate is revoked
1474 * 1: certificate is ok
1475 * -1: dunno
1477 static int
1478 cert_verify_ocsp (gnutls_session_t session)
1480 gnutls_x509_crt_t crt, issuer;
1481 const gnutls_datum_t *cert_list;
1482 unsigned int cert_list_size = 0;
1483 int deinit_issuer = 0;
1484 gnutls_datum_t resp;
1485 int ret;
1487 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1488 if (cert_list_size == 0)
1490 fprintf (stderr, "No certificates found!\n");
1491 return -1;
1494 gnutls_x509_crt_init (&crt);
1495 ret =
1496 gnutls_x509_crt_import (crt, &cert_list[0],
1497 GNUTLS_X509_FMT_DER);
1498 if (ret < 0)
1500 fprintf (stderr, "Decoding error: %s\n",
1501 gnutls_strerror (ret));
1502 return -1;
1505 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1506 if (ret < 0 && cert_list_size > 1)
1508 gnutls_x509_crt_init(&issuer);
1509 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1510 if (ret < 0)
1512 fprintf (stderr, "Decoding error: %s\n",
1513 gnutls_strerror (ret));
1514 return -1;
1516 deinit_issuer = 1;
1518 else if (ret < 0)
1520 fprintf(stderr, "Cannot find issuer\n");
1521 ret = -1;
1522 goto cleanup;
1525 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1526 if (ret < 0)
1528 fprintf(stderr, "Cannot contact OCSP server\n");
1529 ret = -1;
1530 goto cleanup;
1533 /* verify and check the response for revoked cert */
1534 ret = check_ocsp_response(crt, issuer, &resp);
1536 cleanup:
1537 if (deinit_issuer)
1538 gnutls_x509_crt_deinit (issuer);
1539 gnutls_x509_crt_deinit (crt);
1541 return ret;