no need for default_ca_file
[gnutls.git] / src / cli.c
blobb9368dc0d166e00768183e897f73c26e492bb07d
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 #include <common.h>
59 #include <socket.h>
61 #include <cli-args.h>
62 #include <ocsptool-common.h>
64 #define MAX_BUF 4096
66 /* global stuff here */
67 int resume, starttls, insecure, rehandshake, udp, mtu;
68 const char *hostname = NULL;
69 const char *service = NULL;
70 int record_max_size;
71 int fingerprint;
72 int crlf;
73 unsigned int verbose = 0;
74 int print_cert;
76 const char *srp_passwd = NULL;
77 const char *srp_username = NULL;
78 const char *pgp_keyfile = NULL;
79 const char *pgp_certfile = NULL;
80 const char *pgp_keyring = NULL;
81 const char *x509_keyfile = NULL;
82 const char *x509_certfile = NULL;
83 const char *x509_cafile = NULL;
84 const char *x509_crlfile = NULL;
85 static int x509ctype;
86 static int disable_extensions;
87 static const char * priorities = NULL;
89 const char *psk_username = NULL;
90 gnutls_datum_t psk_key = { NULL, 0 };
92 static gnutls_srp_client_credentials_t srp_cred;
93 static gnutls_psk_client_credentials_t psk_cred;
94 static gnutls_anon_client_credentials_t anon_cred;
95 static gnutls_certificate_credentials_t xcred;
97 /* end of global stuff */
99 /* prototypes */
101 static void check_rehandshake (socket_st * socket, int ret);
102 static int do_handshake (socket_st * socket);
103 static void init_global_tls_stuff (void);
104 static int cert_verify_ocsp (gnutls_session_t session);
106 /* Helper functions to load a certificate and key
107 * files into memory.
109 static gnutls_datum_t
110 load_file (const char *file)
112 gnutls_datum_t loaded_file = { NULL, 0 };
113 size_t length;
115 loaded_file.data = (void*)read_binary_file (file, &length);
116 if (loaded_file.data)
117 loaded_file.size = (unsigned int) length;
119 return loaded_file;
122 static void
123 unload_file (gnutls_datum_t* data)
125 free (data->data);
128 #define MAX_CRT 6
129 static unsigned int x509_crt_size;
130 static gnutls_pcert_st x509_crt[MAX_CRT];
131 static gnutls_privkey_t x509_key = NULL;
133 static gnutls_pcert_st pgp_crt;
134 static gnutls_privkey_t pgp_key = NULL;
136 static void
137 get_keyid (gnutls_openpgp_keyid_t keyid, const char *str)
139 size_t keyid_size = sizeof (keyid);
141 if (strlen (str) != 16)
143 fprintf (stderr,
144 "The OpenPGP subkey ID has to be 16 hexadecimal characters.\n");
145 exit (1);
148 if (gnutls_hex2bin (str, strlen (str), keyid, &keyid_size) < 0)
150 fprintf (stderr, "Error converting hex string: %s.\n", str);
151 exit (1);
154 return;
157 /* Load the certificate and the private key.
159 static void
160 load_keys (void)
162 unsigned int crt_num;
163 int ret;
164 unsigned int i;
165 gnutls_datum_t data = { NULL, 0 };
166 gnutls_x509_crt_t crt_list[MAX_CRT];
167 #ifdef ENABLE_PKCS11
168 gnutls_pkcs11_privkey_t pkcs11_key;
169 #endif
170 gnutls_x509_privkey_t tmp_key;
171 unsigned char keyid[GNUTLS_OPENPGP_KEYID_SIZE];
173 if (x509_certfile != NULL && x509_keyfile != NULL)
175 #ifdef ENABLE_PKCS11
176 if (strncmp (x509_certfile, "pkcs11:", 7) == 0)
178 crt_num = 1;
179 gnutls_x509_crt_init (&crt_list[0]);
181 ret =
182 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile, 0);
184 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
185 ret =
186 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile,
187 GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
189 if (ret < 0)
191 fprintf (stderr, "*** Error loading cert file.\n");
192 exit (1);
194 x509_crt_size = 1;
196 else
197 #endif /* ENABLE_PKCS11 */
200 data = load_file (x509_certfile);
201 if (data.data == NULL)
203 fprintf (stderr, "*** Error loading cert file.\n");
204 exit (1);
207 crt_num = MAX_CRT;
208 ret =
209 gnutls_x509_crt_list_import (crt_list, &crt_num, &data,
210 x509ctype,
211 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
212 if (ret < 0)
214 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
216 fprintf (stderr,
217 "*** Error loading cert file: Too many certs %d\n",
218 crt_num);
221 else
223 fprintf (stderr,
224 "*** Error loading cert file: %s\n",
225 gnutls_strerror (ret));
227 exit (1);
229 x509_crt_size = ret;
232 for (i=0;i<x509_crt_size;i++)
234 ret = gnutls_pcert_import_x509(&x509_crt[i], crt_list[i], 0);
235 if (ret < 0)
237 fprintf(stderr, "*** Error importing crt to pcert: %s\n",
238 gnutls_strerror(ret));
239 exit(1);
241 gnutls_x509_crt_deinit(crt_list[i]);
244 unload_file (&data);
246 ret = gnutls_privkey_init(&x509_key);
247 if (ret < 0)
249 fprintf (stderr, "*** Error initializing key: %s\n",
250 gnutls_strerror (ret));
251 exit (1);
254 #ifdef ENABLE_PKCS11
255 if (strncmp (x509_keyfile, "pkcs11:", 7) == 0)
257 gnutls_pkcs11_privkey_init (&pkcs11_key);
259 ret =
260 gnutls_pkcs11_privkey_import_url (pkcs11_key, x509_keyfile, 0);
261 if (ret < 0)
263 fprintf (stderr, "*** Error loading url: %s\n",
264 gnutls_strerror (ret));
265 exit (1);
268 ret = gnutls_privkey_import_pkcs11( x509_key, pkcs11_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
269 if (ret < 0)
271 fprintf (stderr, "*** Error loading url: %s\n",
272 gnutls_strerror (ret));
273 exit (1);
276 else
277 #endif /* ENABLE_PKCS11 */
279 data = load_file (x509_keyfile);
280 if (data.data == NULL)
282 fprintf (stderr, "*** Error loading key file.\n");
283 exit (1);
286 gnutls_x509_privkey_init (&tmp_key);
288 ret =
289 gnutls_x509_privkey_import (tmp_key, &data, x509ctype);
290 if (ret < 0)
292 fprintf (stderr, "*** Error loading key file: %s\n",
293 gnutls_strerror (ret));
294 exit (1);
297 ret = gnutls_privkey_import_x509( x509_key, tmp_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
298 if (ret < 0)
300 fprintf (stderr, "*** Error loading url: %s\n",
301 gnutls_strerror (ret));
302 exit (1);
305 unload_file (&data);
308 fprintf (stdout, "Processed %d client X.509 certificates...\n",
309 x509_crt_size);
313 #ifdef ENABLE_OPENPGP
314 if (HAVE_OPT(PGPSUBKEY))
316 get_keyid (keyid, OPT_ARG(PGPSUBKEY));
319 if (pgp_certfile != NULL && pgp_keyfile != NULL)
321 gnutls_openpgp_crt_t tmp_pgp_crt;
323 data = load_file (pgp_certfile);
324 if (data.data == NULL)
326 fprintf (stderr, "*** Error loading PGP cert file.\n");
327 exit (1);
330 gnutls_openpgp_crt_init (&tmp_pgp_crt);
332 ret =
333 gnutls_pcert_import_openpgp_raw (&pgp_crt, &data, GNUTLS_OPENPGP_FMT_BASE64, HAVE_OPT(PGPSUBKEY)?keyid:NULL, 0);
334 if (ret < 0)
336 fprintf (stderr,
337 "*** Error loading PGP cert file: %s\n",
338 gnutls_strerror (ret));
339 exit (1);
342 unload_file (&data);
344 ret = gnutls_privkey_init(&pgp_key);
345 if (ret < 0)
347 fprintf (stderr, "*** Error initializing key: %s\n",
348 gnutls_strerror (ret));
349 exit (1);
352 #ifdef ENABLE_PKCS11
353 if (strncmp (pgp_keyfile, "pkcs11:", 7) == 0)
355 gnutls_pkcs11_privkey_init (&pkcs11_key);
357 ret = gnutls_pkcs11_privkey_import_url (pkcs11_key, pgp_keyfile, 0);
358 if (ret < 0)
360 fprintf (stderr, "*** Error loading url: %s\n",
361 gnutls_strerror (ret));
362 exit (1);
365 ret = gnutls_privkey_import_pkcs11( pgp_key, pkcs11_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
366 if (ret < 0)
368 fprintf (stderr, "*** Error loading url: %s\n",
369 gnutls_strerror (ret));
370 exit (1);
373 else
374 #endif /* ENABLE_PKCS11 */
376 gnutls_openpgp_privkey_t tmp_pgp_key;
378 data = load_file (pgp_keyfile);
379 if (data.data == NULL)
381 fprintf (stderr, "*** Error loading PGP key file.\n");
382 exit (1);
385 gnutls_openpgp_privkey_init (&tmp_pgp_key);
387 ret =
388 gnutls_openpgp_privkey_import (tmp_pgp_key, &data,
389 GNUTLS_OPENPGP_FMT_BASE64, NULL,
391 if (ret < 0)
393 fprintf (stderr,
394 "*** Error loading PGP key file: %s\n",
395 gnutls_strerror (ret));
396 exit (1);
399 if (HAVE_OPT(PGPSUBKEY))
401 ret =
402 gnutls_openpgp_privkey_set_preferred_key_id (tmp_pgp_key, keyid);
403 if (ret < 0)
405 fprintf (stderr,
406 "*** Error setting preferred sub key id (%s): %s\n",
407 OPT_ARG(PGPSUBKEY), gnutls_strerror (ret));
408 exit (1);
412 ret = gnutls_privkey_import_openpgp( pgp_key, tmp_pgp_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
413 if (ret < 0)
415 fprintf (stderr, "*** Error loading url: %s\n",
416 gnutls_strerror (ret));
417 exit (1);
420 unload_file (&data);
424 fprintf (stdout, "Processed 1 client PGP certificate...\n");
426 #endif
430 #define IS_NEWLINE(x) ((x[0] == '\n') || (x[0] == '\r'))
431 static int
432 read_yesno (const char *input_str)
434 char input[128];
436 fputs (input_str, stderr);
437 if (fgets (input, sizeof (input), stdin) == NULL)
438 return 0;
440 if (IS_NEWLINE(input))
441 return 0;
443 if (input[0] == 'y' || input[0] == 'Y')
444 return 1;
446 return 0;
449 /* converts a textual service or port to
450 * a service.
452 static const char* port_to_service(const char* sport)
454 unsigned int port;
455 struct servent * sr;
457 port = atoi(sport);
458 if (port == 0) return sport;
460 port = htons(port);
462 sr = getservbyport(port, udp?"udp":"tcp");
463 if (sr == NULL)
465 fprintf(stderr, "Warning: getservbyport() failed. Using port number as service.\n");
466 return sport;
469 return sr->s_name;
472 static int
473 cert_verify_callback (gnutls_session_t session)
475 int rc;
476 unsigned int status = 0;
477 int ssh = ENABLED_OPT(TOFU);
478 const char* txt_service;
480 rc = cert_verify(session, hostname);
481 if (rc == 0)
483 printf ("*** Verifying server certificate failed...\n");
484 if (!insecure && !ssh)
485 return -1;
487 else if (ENABLED_OPT(OCSP))
488 { /* off-line verification succeeded. Try OCSP */
489 rc = cert_verify_ocsp(session);
490 if (rc == 0)
492 printf ("*** Verifying (with OCSP) server certificate failed...\n");
493 if (!insecure && !ssh)
494 return -1;
496 else if (rc == -1)
497 printf("*** OCSP response ignored\n");
500 if (ssh) /* try ssh auth */
502 unsigned int list_size;
503 const gnutls_datum_t * cert;
505 cert = gnutls_certificate_get_peers(session, &list_size);
506 if (cert == NULL)
508 fprintf(stderr, "Cannot obtain peer's certificate!\n");
509 return -1;
512 txt_service = port_to_service(service);
514 rc = gnutls_verify_stored_pubkey(NULL, NULL, hostname, txt_service,
515 GNUTLS_CRT_X509, cert, 0);
516 if (rc == GNUTLS_E_NO_CERTIFICATE_FOUND)
518 print_cert_info_compact(session);
519 fprintf(stderr, "Host %s (%s) has never been contacted before.\n", hostname, txt_service);
520 if (status == 0)
521 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
523 rc = read_yesno("Are you sure you want to trust it? (y/N): ");
524 if (rc == 0)
525 return -1;
527 else if (rc == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
529 print_cert_info_compact(session);
530 fprintf(stderr, "Warning: host %s is known and it is associated with a different key.\n", hostname);
531 fprintf(stderr, "It might be that the server has multiple keys, or an attacker replaced the key to eavesdrop this connection .\n");
532 if (status == 0)
533 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
535 rc = read_yesno("Do you trust the received key? (y/N): ");
536 if (rc == 0)
537 return -1;
539 else if (rc < 0)
541 fprintf(stderr, "gnutls_verify_stored_pubkey: %s\n", gnutls_strerror(rc));
542 return -1;
545 if (rc != 0)
547 rc = gnutls_store_pubkey(NULL, NULL, hostname, txt_service,
548 GNUTLS_CRT_X509, cert, 0, 0);
549 if (rc < 0)
550 fprintf(stderr, "Could not store key: %s\n", gnutls_strerror(rc));
554 return 0;
557 /* This callback should be associated with a session by calling
558 * gnutls_certificate_client_set_retrieve_function( session, cert_callback),
559 * before a handshake.
562 static int
563 cert_callback (gnutls_session_t session,
564 const gnutls_datum_t * req_ca_rdn, int nreqs,
565 const gnutls_pk_algorithm_t * sign_algos,
566 int sign_algos_length, gnutls_pcert_st **pcert,
567 unsigned int *pcert_length, gnutls_privkey_t * pkey)
569 char issuer_dn[256];
570 int i, ret, cert_type;
571 size_t len;
573 if (verbose)
575 /* Print the server's trusted CAs
577 if (nreqs > 0)
578 printf ("- Server's trusted authorities:\n");
579 else
580 printf ("- Server did not send us any trusted authorities names.\n");
582 /* print the names (if any) */
583 for (i = 0; i < nreqs; i++)
585 len = sizeof (issuer_dn);
586 ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len);
587 if (ret >= 0)
589 printf (" [%d]: ", i);
590 printf ("%s\n", issuer_dn);
595 /* Select a certificate and return it.
596 * The certificate must be of any of the "sign algorithms"
597 * supported by the server.
600 cert_type = gnutls_certificate_type_get (session);
602 *pcert_length = 0;
604 if (cert_type == GNUTLS_CRT_X509)
606 if (x509_crt_size > 0)
608 if (x509_key != NULL)
610 *pkey = x509_key;
612 else
614 printf ("- Could not find a suitable key to send to server\n");
615 return -1;
618 *pcert_length = x509_crt_size;
619 *pcert = x509_crt;
623 else if (cert_type == GNUTLS_CRT_OPENPGP)
625 if (pgp_key != NULL)
627 *pkey = pgp_key;
629 *pcert_length = 1;
630 *pcert = &pgp_crt;
634 printf ("- Successfully sent %u certificate(s) to server.\n", *pcert_length);
635 return 0;
639 /* initializes a gnutls_session_t with some defaults.
641 static gnutls_session_t
642 init_tls_session (const char *hostname)
644 const char *err;
645 int ret;
646 gnutls_session_t session;
648 if (priorities == NULL)
649 priorities = "NORMAL";
651 if (udp)
653 gnutls_init (&session, GNUTLS_CLIENT|GNUTLS_DATAGRAM);
654 if (mtu)
655 gnutls_dtls_set_mtu(session, mtu);
657 else
658 gnutls_init (&session, GNUTLS_CLIENT);
660 if ((ret = gnutls_priority_set_direct (session, priorities, &err)) < 0)
662 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
663 else
664 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
665 exit (1);
668 /* allow the use of private ciphersuites.
670 if (disable_extensions == 0)
672 if (!isdigit(hostname[0]) && strchr(hostname, ':') == 0)
673 gnutls_server_name_set (session, GNUTLS_NAME_DNS, hostname,
674 strlen (hostname));
677 gnutls_dh_set_prime_bits (session, 512);
679 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anon_cred);
680 if (srp_cred)
681 gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
682 if (psk_cred)
683 gnutls_credentials_set (session, GNUTLS_CRD_PSK, psk_cred);
684 gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
686 gnutls_certificate_set_retrieve_function2 (xcred, cert_callback);
687 gnutls_certificate_set_verify_function (xcred, cert_verify_callback);
688 gnutls_certificate_set_verify_flags (xcred, 0);
690 /* send the fingerprint */
691 #ifdef ENABLE_OPENPGP
692 if (fingerprint != 0)
693 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
694 #endif
696 /* use the max record size extension */
697 if (record_max_size > 0 && disable_extensions == 0)
699 if (gnutls_record_set_max_size (session, record_max_size) < 0)
701 fprintf (stderr,
702 "Cannot set the maximum record size to %d.\n",
703 record_max_size);
704 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
705 exit (1);
709 #ifdef ENABLE_SESSION_TICKET
710 if (disable_extensions == 0 && !HAVE_OPT(NOTICKET)t)
711 gnutls_session_ticket_enable_client (session);
712 #endif
714 return session;
717 static void cmd_parser (int argc, char **argv);
719 /* Returns zero if the error code was successfully handled.
721 static int
722 handle_error (socket_st * hd, int err)
724 int alert, ret;
725 const char *err_type, *str;
727 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
728 return 0;
730 if (gnutls_error_is_fatal (err) == 0)
732 ret = 0;
733 err_type = "Non fatal";
735 else
737 ret = err;
738 err_type = "Fatal";
741 str = gnutls_strerror (err);
742 if (str == NULL)
743 str = str_unknown;
744 fprintf (stderr, "*** %s error: %s\n", err_type, str);
746 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
747 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
749 alert = gnutls_alert_get (hd->session);
750 str = gnutls_alert_get_name (alert);
751 if (str == NULL)
752 str = str_unknown;
753 printf ("*** Received alert [%d]: %s\n", alert, str);
756 check_rehandshake (hd, err);
758 return ret;
761 int starttls_alarmed = 0;
763 #ifndef _WIN32
764 static void
765 starttls_alarm (int signum)
767 starttls_alarmed = 1;
769 #endif
771 static void
772 tls_log_func (int level, const char *str)
774 fprintf (stderr, "|<%d>| %s", level, str);
777 #define IN_KEYBOARD 1
778 #define IN_NET 2
779 #define IN_NONE 0
780 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
782 static int check_net_or_keyboard_input(socket_st* hd)
784 int maxfd;
785 fd_set rset;
786 int err;
787 struct timeval tv;
791 FD_ZERO (&rset);
792 FD_SET (hd->fd, &rset);
794 #ifndef _WIN32
795 FD_SET (fileno (stdin), &rset);
796 maxfd = MAX (fileno (stdin), hd->fd);
797 #else
798 maxfd = hd->fd;
799 #endif
801 tv.tv_sec = 0;
802 tv.tv_usec = 50 * 1000;
804 if (hd->secure == 1)
805 if (gnutls_record_check_pending(hd->session))
806 return IN_NET;
808 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
809 if (err < 0)
810 continue;
812 if (FD_ISSET (hd->fd, &rset))
813 return IN_NET;
815 #ifdef _WIN32
817 int state;
818 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
820 if (state == WAIT_OBJECT_0)
821 return IN_KEYBOARD;
823 #else
824 if (FD_ISSET (fileno (stdin), &rset))
825 return IN_KEYBOARD;
826 #endif
828 while(err == 0);
830 return IN_NONE;
834 main (int argc, char **argv)
836 int ret;
837 int ii, i, inp;
838 char buffer[MAX_BUF + 1];
839 char *session_data = NULL;
840 char *session_id = NULL;
841 size_t session_data_size;
842 size_t session_id_size = 0;
843 int user_term = 0, retval = 0;
844 socket_st hd;
845 ssize_t bytes;
847 set_program_name (argv[0]);
848 cmd_parser (argc, argv);
850 gnutls_global_set_log_function (tls_log_func);
851 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
853 if ((ret = gnutls_global_init ()) < 0)
855 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
856 exit (1);
859 #ifdef ENABLE_PKCS11
860 pkcs11_common ();
861 #endif
863 if (hostname == NULL)
865 fprintf (stderr, "No hostname given\n");
866 exit (1);
869 sockets_init ();
871 init_global_tls_stuff ();
873 socket_open (&hd, hostname, service, udp);
874 socket_connect (&hd);
876 hd.session = init_tls_session (hostname);
877 if (starttls)
878 goto after_handshake;
880 for (i = 0; i < 2; i++)
884 if (i == 1)
886 hd.session = init_tls_session (hostname);
887 gnutls_session_set_data (hd.session, session_data,
888 session_data_size);
889 free (session_data);
892 ret = do_handshake (&hd);
894 if (ret < 0)
896 fprintf (stderr, "*** Handshake has failed\n");
897 gnutls_perror (ret);
898 gnutls_deinit (hd.session);
899 return 1;
901 else
903 printf ("- Handshake was completed\n");
904 if (gnutls_session_is_resumed (hd.session) != 0)
905 printf ("*** This is a resumed session\n");
908 if (resume != 0 && i == 0)
911 gnutls_session_get_data (hd.session, NULL, &session_data_size);
912 session_data = malloc (session_data_size);
914 gnutls_session_get_data (hd.session, session_data,
915 &session_data_size);
917 gnutls_session_get_id (hd.session, NULL, &session_id_size);
919 session_id = malloc (session_id_size);
920 gnutls_session_get_id (hd.session, session_id, &session_id_size);
922 printf ("- Disconnecting\n");
923 socket_bye (&hd);
925 printf
926 ("\n\n- Connecting again- trying to resume previous session\n");
927 socket_open (&hd, hostname, service, udp);
928 socket_connect (&hd);
930 else
932 break;
936 after_handshake:
938 /* Warning! Do not touch this text string, it is used by external
939 programs to search for when gnutls-cli has reached this point. */
940 printf ("\n- Simple Client Mode:\n\n");
942 if (rehandshake)
944 ret = do_handshake (&hd);
946 if (ret < 0)
948 fprintf (stderr, "*** ReHandshake has failed\n");
949 gnutls_perror (ret);
950 gnutls_deinit (hd.session);
951 return 1;
953 else
955 printf ("- ReHandshake was completed\n");
959 #ifndef _WIN32
960 signal (SIGALRM, &starttls_alarm);
961 #endif
963 fflush (stdout);
964 fflush (stderr);
966 /* do not buffer */
967 #if !(defined _WIN32 || defined __WIN32__)
968 setbuf (stdin, NULL);
969 #endif
970 setbuf (stdout, NULL);
971 setbuf (stderr, NULL);
973 for (;;)
975 if (starttls_alarmed && !hd.secure)
977 /* Warning! Do not touch this text string, it is used by
978 external programs to search for when gnutls-cli has
979 reached this point. */
980 fprintf (stderr, "*** Starting TLS handshake\n");
981 ret = do_handshake (&hd);
982 if (ret < 0)
984 fprintf (stderr, "*** Handshake has failed\n");
985 user_term = 1;
986 retval = 1;
987 break;
991 inp = check_net_or_keyboard_input(&hd);
993 if (inp == IN_NET)
995 memset (buffer, 0, MAX_BUF + 1);
996 ret = socket_recv (&hd, buffer, MAX_BUF);
998 if (ret == 0)
1000 printf ("- Peer has closed the GnuTLS connection\n");
1001 break;
1003 else if (handle_error (&hd, ret) < 0 && user_term == 0)
1005 fprintf (stderr,
1006 "*** Server has terminated the connection abnormally.\n");
1007 retval = 1;
1008 break;
1010 else if (ret > 0)
1012 if (verbose != 0)
1013 printf ("- Received[%d]: ", ret);
1014 for (ii = 0; ii < ret; ii++)
1016 fputc (buffer[ii], stdout);
1018 fflush (stdout);
1021 if (user_term != 0)
1022 break;
1025 if (inp == IN_KEYBOARD)
1027 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
1029 if (hd.secure == 0)
1031 /* Warning! Do not touch this text string, it is
1032 used by external programs to search for when
1033 gnutls-cli has reached this point. */
1034 fprintf (stderr, "*** Starting TLS handshake\n");
1035 ret = do_handshake (&hd);
1036 clearerr (stdin);
1037 if (ret < 0)
1039 fprintf (stderr, "*** Handshake has failed\n");
1040 user_term = 1;
1041 retval = 1;
1042 break;
1045 else
1047 user_term = 1;
1048 break;
1050 continue;
1053 buffer[bytes] = 0;
1054 if (crlf != 0)
1056 char *b = strchr (buffer, '\n');
1057 if (b != NULL)
1059 strcpy (b, "\r\n");
1060 bytes++;
1064 ret = socket_send (&hd, buffer, bytes);
1066 if (ret > 0)
1068 if (verbose != 0)
1069 printf ("- Sent: %d bytes\n", ret);
1071 else
1072 handle_error (&hd, ret);
1077 if (user_term != 0)
1078 socket_bye (&hd);
1079 else
1080 gnutls_deinit (hd.session);
1082 #ifdef ENABLE_SRP
1083 if (srp_cred)
1084 gnutls_srp_free_client_credentials (srp_cred);
1085 #endif
1086 #ifdef ENABLE_PSK
1087 if (psk_cred)
1088 gnutls_psk_free_client_credentials (psk_cred);
1089 #endif
1091 gnutls_certificate_free_credentials (xcred);
1093 #ifdef ENABLE_ANON
1094 gnutls_anon_free_client_credentials (anon_cred);
1095 #endif
1097 gnutls_global_deinit ();
1099 return retval;
1102 static void
1103 cmd_parser (int argc, char **argv)
1105 const char* rest = NULL;
1107 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1108 argc -= optct;
1109 argv += optct;
1111 if (rest == NULL && argc > 0)
1112 rest = argv[0];
1114 if (HAVE_OPT(BENCHMARK_CIPHERS))
1116 benchmark_cipher(1, OPT_VALUE_DEBUG);
1117 exit(0);
1120 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1122 benchmark_cipher(0, OPT_VALUE_DEBUG);
1123 exit(0);
1126 if (HAVE_OPT(BENCHMARK_TLS))
1128 benchmark_tls(OPT_VALUE_DEBUG);
1129 exit(0);
1132 if (HAVE_OPT(PRIORITY))
1134 priorities = OPT_ARG(PRIORITY);
1136 verbose = HAVE_OPT( VERBOSE);
1137 if (verbose)
1138 print_cert = 1;
1139 else
1140 print_cert = HAVE_OPT( PRINT_CERT);
1142 if (HAVE_OPT(LIST))
1144 print_list(priorities, verbose);
1145 exit(0);
1148 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1149 starttls = HAVE_OPT(STARTTLS);
1150 resume = HAVE_OPT(RESUME);
1151 rehandshake = HAVE_OPT(REHANDSHAKE);
1152 insecure = HAVE_OPT(INSECURE);
1154 udp = HAVE_OPT(UDP);
1155 mtu = OPT_VALUE_MTU;
1157 if (HAVE_OPT(PORT))
1159 service = OPT_ARG(PORT);
1161 else
1163 service = "443";
1166 record_max_size = OPT_VALUE_RECORDSIZE;
1167 fingerprint = HAVE_OPT(FINGERPRINT);
1169 if (HAVE_OPT(X509FMTDER))
1170 x509ctype = GNUTLS_X509_FMT_DER;
1171 else
1172 x509ctype = GNUTLS_X509_FMT_PEM;
1174 if (HAVE_OPT(SRPUSERNAME))
1175 srp_username = OPT_ARG(SRPUSERNAME);
1177 if (HAVE_OPT(SRPPASSWD))
1178 srp_passwd = OPT_ARG(SRPPASSWD);
1180 if (HAVE_OPT(X509CAFILE))
1181 x509_cafile = OPT_ARG(X509CAFILE);
1183 if (HAVE_OPT(X509CRLFILE))
1184 x509_crlfile = OPT_ARG(X509CRLFILE);
1186 if (HAVE_OPT(X509KEYFILE))
1187 x509_keyfile = OPT_ARG(X509KEYFILE);
1189 if (HAVE_OPT(X509CERTFILE))
1190 x509_certfile = OPT_ARG(X509CERTFILE);
1192 if (HAVE_OPT(PGPKEYFILE))
1193 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1195 if (HAVE_OPT(PGPCERTFILE))
1196 pgp_certfile = OPT_ARG(PGPCERTFILE);
1198 if (HAVE_OPT(PSKUSERNAME))
1199 psk_username = OPT_ARG(PSKUSERNAME);
1201 if (HAVE_OPT(PSKKEY))
1203 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1204 psk_key.size = strlen (OPT_ARG(PSKKEY));
1206 else
1207 psk_key.size = 0;
1209 if (HAVE_OPT(PGPKEYRING))
1210 pgp_keyring = OPT_ARG(PGPKEYRING);
1212 crlf = HAVE_OPT(CRLF);
1214 if (rest != NULL)
1215 hostname = rest;
1217 if (hostname == NULL)
1219 fprintf(stderr, "No hostname specified\n");
1220 exit(1);
1224 void cli_version (void);
1226 void
1227 cli_version (void)
1229 const char *p = PACKAGE_NAME;
1230 if (strcmp (gnutls_check_version (NULL), PACKAGE_VERSION) != 0)
1231 p = PACKAGE_STRING;
1232 version_etc (stdout, program_name, p, gnutls_check_version (NULL),
1233 "Nikos Mavrogiannopoulos", (char *) NULL);
1237 static void
1238 check_rehandshake (socket_st * socket, int ret)
1240 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1242 /* There is a race condition here. If application
1243 * data is sent after the rehandshake request,
1244 * the server thinks we ignored his request.
1245 * This is a bad design of this client.
1247 printf ("*** Received rehandshake request\n");
1248 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1250 ret = do_handshake (socket);
1252 if (ret == 0)
1254 printf ("*** Rehandshake was performed.\n");
1256 else
1258 printf ("*** Rehandshake Failed.\n");
1264 static int
1265 do_handshake (socket_st * socket)
1267 int ret;
1269 gnutls_transport_set_ptr (socket->session,
1270 (gnutls_transport_ptr_t)
1271 gl_fd_to_handle (socket->fd));
1274 ret = gnutls_handshake (socket->session);
1276 if (ret < 0)
1278 handle_error (socket, ret);
1281 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1283 if (ret == 0)
1285 /* print some information */
1286 print_info (socket->session, print_cert);
1287 socket->secure = 1;
1289 else
1291 print_cert_info (socket->session, verbose, print_cert);
1292 gnutls_alert_send_appropriate (socket->session, ret);
1293 shutdown (socket->fd, SHUT_RDWR);
1295 return ret;
1298 static int
1299 srp_username_callback (gnutls_session_t session,
1300 char **username, char **password)
1302 if (srp_username == NULL || srp_passwd == NULL)
1304 return -1;
1307 *username = gnutls_strdup (srp_username);
1308 *password = gnutls_strdup (srp_passwd);
1310 return 0;
1313 static int
1314 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1316 const char *hint = gnutls_psk_client_get_hint (session);
1317 char *rawkey;
1318 char *passwd;
1319 int ret;
1320 size_t res_size;
1321 gnutls_datum_t tmp;
1323 printf ("- PSK client callback. ");
1324 if (hint)
1325 printf ("PSK hint '%s'\n", hint);
1326 else
1327 printf ("No PSK hint\n");
1329 if (HAVE_OPT(PSKUSERNAME))
1330 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1331 else
1333 char *tmp = NULL;
1334 size_t n;
1336 printf ("Enter PSK identity: ");
1337 fflush (stdout);
1338 getline (&tmp, &n, stdin);
1340 if (tmp == NULL)
1342 fprintf (stderr, "No username given, aborting...\n");
1343 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1346 if (tmp[strlen (tmp) - 1] == '\n')
1347 tmp[strlen (tmp) - 1] = '\0';
1348 if (tmp[strlen (tmp) - 1] == '\r')
1349 tmp[strlen (tmp) - 1] = '\0';
1351 *username = gnutls_strdup (tmp);
1352 free (tmp);
1354 if (!*username)
1355 return GNUTLS_E_MEMORY_ERROR;
1357 passwd = getpass ("Enter key: ");
1358 if (passwd == NULL)
1360 fprintf (stderr, "No key given, aborting...\n");
1361 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1364 tmp.data = (void*)passwd;
1365 tmp.size = strlen (passwd);
1367 res_size = tmp.size / 2 + 1;
1368 rawkey = gnutls_malloc (res_size);
1369 if (rawkey == NULL)
1370 return GNUTLS_E_MEMORY_ERROR;
1372 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1373 if (ret < 0)
1375 fprintf (stderr, "Error deriving password: %s\n",
1376 gnutls_strerror (ret));
1377 gnutls_free (*username);
1378 return ret;
1381 key->data = (void*)rawkey;
1382 key->size = res_size;
1384 if (HAVE_OPT(DEBUG))
1386 char hexkey[41];
1387 res_size = sizeof (hexkey);
1388 gnutls_hex_encode (key, hexkey, &res_size);
1389 fprintf (stderr, "PSK username: %s\n", *username);
1390 fprintf (stderr, "PSK hint: %s\n", hint);
1391 fprintf (stderr, "PSK key: %s\n", hexkey);
1394 return 0;
1397 static void
1398 init_global_tls_stuff (void)
1400 int ret;
1402 /* X509 stuff */
1403 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1405 fprintf (stderr, "Certificate allocation memory error\n");
1406 exit (1);
1409 if (x509_cafile != NULL)
1411 ret = gnutls_certificate_set_x509_trust_file (xcred,
1412 x509_cafile, x509ctype);
1414 else
1416 ret = gnutls_certificate_set_x509_system_trust (xcred);
1418 if (ret < 0)
1420 fprintf (stderr, "Error setting the x509 trust file\n");
1422 else
1424 printf ("Processed %d CA certificate(s).\n", ret);
1427 if (x509_crlfile != NULL)
1429 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1430 x509ctype);
1431 if (ret < 0)
1433 fprintf (stderr, "Error setting the x509 CRL file\n");
1435 else
1437 printf ("Processed %d CRL(s).\n", ret);
1441 load_keys ();
1443 #ifdef ENABLE_OPENPGP
1444 if (pgp_keyring != NULL)
1446 ret =
1447 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1448 GNUTLS_OPENPGP_FMT_BASE64);
1449 if (ret < 0)
1451 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1454 #endif
1456 #ifdef ENABLE_SRP
1457 if (srp_username && srp_passwd)
1459 /* SRP stuff */
1460 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1462 fprintf (stderr, "SRP authentication error\n");
1465 gnutls_srp_set_client_credentials_function (srp_cred,
1466 srp_username_callback);
1468 #endif
1470 #ifdef ENABLE_PSK
1471 /* PSK stuff */
1472 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1474 fprintf (stderr, "PSK authentication error\n");
1477 if (psk_username && psk_key.data)
1479 ret = gnutls_psk_set_client_credentials (psk_cred,
1480 psk_username, &psk_key,
1481 GNUTLS_PSK_KEY_HEX);
1482 if (ret < 0)
1484 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1485 gnutls_strerror (ret));
1488 else
1489 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1490 #endif
1492 #ifdef ENABLE_ANON
1493 /* ANON stuff */
1494 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1496 fprintf (stderr, "Anonymous authentication error\n");
1498 #endif
1502 /* OCSP check for the peer's certificate. Should be called
1503 * only after the certificate list verication is complete.
1504 * Returns:
1505 * 0: certificate is revoked
1506 * 1: certificate is ok
1507 * -1: dunno
1509 static int
1510 cert_verify_ocsp (gnutls_session_t session)
1512 gnutls_x509_crt_t crt, issuer;
1513 const gnutls_datum_t *cert_list;
1514 unsigned int cert_list_size = 0;
1515 int deinit_issuer = 0;
1516 gnutls_datum_t resp;
1517 int ret;
1519 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1520 if (cert_list_size == 0)
1522 fprintf (stderr, "No certificates found!\n");
1523 return -1;
1526 gnutls_x509_crt_init (&crt);
1527 ret =
1528 gnutls_x509_crt_import (crt, &cert_list[0],
1529 GNUTLS_X509_FMT_DER);
1530 if (ret < 0)
1532 fprintf (stderr, "Decoding error: %s\n",
1533 gnutls_strerror (ret));
1534 return -1;
1537 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1538 if (ret < 0 && cert_list_size > 1)
1540 gnutls_x509_crt_init(&issuer);
1541 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1542 if (ret < 0)
1544 fprintf (stderr, "Decoding error: %s\n",
1545 gnutls_strerror (ret));
1546 return -1;
1548 deinit_issuer = 1;
1550 else if (ret < 0)
1552 fprintf(stderr, "Cannot find issuer\n");
1553 ret = -1;
1554 goto cleanup;
1557 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1558 if (ret < 0)
1560 fprintf(stderr, "Cannot contact OCSP server\n");
1561 ret = -1;
1562 goto cleanup;
1565 /* verify and check the response for revoked cert */
1566 ret = check_ocsp_response(issuer, &resp);
1568 cleanup:
1569 if (deinit_issuer)
1570 gnutls_x509_crt_deinit (issuer);
1571 gnutls_x509_crt_deinit (crt);
1573 return ret;