do not set verify_flags
[gnutls.git] / src / cli.c
blob2ca5b26a9680ff36904dfa2596e3619ea81c0de7
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 status_request_ocsp;
72 int fingerprint;
73 int crlf;
74 unsigned int verbose = 0;
75 int print_cert;
77 const char *srp_passwd = NULL;
78 const char *srp_username = NULL;
79 const char *pgp_keyfile = NULL;
80 const char *pgp_certfile = NULL;
81 const char *pgp_keyring = NULL;
82 const char *x509_keyfile = NULL;
83 const char *x509_certfile = NULL;
84 const char *x509_cafile = NULL;
85 const char *x509_crlfile = NULL;
86 static int x509ctype;
87 static int disable_extensions;
88 static const char * priorities = NULL;
90 const char *psk_username = NULL;
91 gnutls_datum_t psk_key = { NULL, 0 };
93 static gnutls_srp_client_credentials_t srp_cred;
94 static gnutls_psk_client_credentials_t psk_cred;
95 static gnutls_anon_client_credentials_t anon_cred;
96 static gnutls_certificate_credentials_t xcred;
98 /* end of global stuff */
100 /* prototypes */
102 static void check_rehandshake (socket_st * socket, int ret);
103 static int do_handshake (socket_st * socket);
104 static void init_global_tls_stuff (void);
105 static int cert_verify_ocsp (gnutls_session_t session);
107 #define MAX_CRT 6
108 static unsigned int x509_crt_size;
109 static gnutls_pcert_st x509_crt[MAX_CRT];
110 static gnutls_privkey_t x509_key = NULL;
112 static gnutls_pcert_st pgp_crt;
113 static gnutls_privkey_t pgp_key = NULL;
115 static void
116 get_keyid (gnutls_openpgp_keyid_t keyid, const char *str)
118 size_t keyid_size = sizeof (keyid);
120 if (strlen (str) != 16)
122 fprintf (stderr,
123 "The OpenPGP subkey ID has to be 16 hexadecimal characters.\n");
124 exit (1);
127 if (gnutls_hex2bin (str, strlen (str), keyid, &keyid_size) < 0)
129 fprintf (stderr, "Error converting hex string: %s.\n", str);
130 exit (1);
133 return;
136 /* Load the certificate and the private key.
138 static void
139 load_keys (void)
141 unsigned int crt_num;
142 int ret;
143 unsigned int i;
144 gnutls_datum_t data = { NULL, 0 };
145 gnutls_x509_crt_t crt_list[MAX_CRT];
146 unsigned char keyid[GNUTLS_OPENPGP_KEYID_SIZE];
148 if (x509_certfile != NULL && x509_keyfile != NULL)
150 #ifdef ENABLE_PKCS11
151 if (strncmp (x509_certfile, "pkcs11:", 7) == 0)
153 crt_num = 1;
154 gnutls_x509_crt_init (&crt_list[0]);
155 gnutls_x509_crt_set_pin_function(crt_list[0], pin_callback, NULL);
157 ret =
158 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile, 0);
160 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
161 ret =
162 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile,
163 GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
165 if (ret < 0)
167 fprintf (stderr, "*** Error loading cert file.\n");
168 exit (1);
170 x509_crt_size = 1;
172 else
173 #endif /* ENABLE_PKCS11 */
176 ret = gnutls_load_file (x509_certfile, &data);
177 if (ret < 0)
179 fprintf (stderr, "*** Error loading cert file.\n");
180 exit (1);
183 crt_num = MAX_CRT;
184 ret =
185 gnutls_x509_crt_list_import (crt_list, &crt_num, &data,
186 x509ctype,
187 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
188 if (ret < 0)
190 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
192 fprintf (stderr,
193 "*** Error loading cert file: Too many certs %d\n",
194 crt_num);
197 else
199 fprintf (stderr,
200 "*** Error loading cert file: %s\n",
201 gnutls_strerror (ret));
203 exit (1);
205 x509_crt_size = ret;
208 for (i=0;i<x509_crt_size;i++)
210 ret = gnutls_pcert_import_x509(&x509_crt[i], crt_list[i], 0);
211 if (ret < 0)
213 fprintf(stderr, "*** Error importing crt to pcert: %s\n",
214 gnutls_strerror(ret));
215 exit(1);
217 gnutls_x509_crt_deinit(crt_list[i]);
220 gnutls_free (data.data);
222 ret = gnutls_privkey_init(&x509_key);
223 if (ret < 0)
225 fprintf (stderr, "*** Error initializing key: %s\n",
226 gnutls_strerror (ret));
227 exit (1);
230 gnutls_privkey_set_pin_function(x509_key, pin_callback, NULL);
232 if (gnutls_url_is_supported(x509_keyfile) != 0)
234 ret =
235 gnutls_privkey_import_url (x509_key, x509_keyfile, 0);
236 if (ret < 0)
238 fprintf (stderr, "*** Error loading url: %s\n",
239 gnutls_strerror (ret));
240 exit (1);
243 else
245 ret = gnutls_load_file (x509_keyfile, &data);
246 if (ret < 0)
248 fprintf (stderr, "*** Error loading key file.\n");
249 exit (1);
252 ret = gnutls_privkey_import_x509_raw( x509_key, &data, x509ctype, NULL, 0);
253 if (ret < 0)
255 fprintf (stderr, "*** Error loading url: %s\n",
256 gnutls_strerror (ret));
257 exit (1);
260 gnutls_free(data.data);
263 fprintf (stdout, "Processed %d client X.509 certificates...\n",
264 x509_crt_size);
268 #ifdef ENABLE_OPENPGP
269 if (HAVE_OPT(PGPSUBKEY))
271 get_keyid (keyid, OPT_ARG(PGPSUBKEY));
274 if (pgp_certfile != NULL && pgp_keyfile != NULL)
276 gnutls_openpgp_crt_t tmp_pgp_crt;
278 ret = gnutls_load_file (pgp_certfile, &data);
279 if (ret < 0)
281 fprintf (stderr, "*** Error loading PGP cert file.\n");
282 exit (1);
285 gnutls_openpgp_crt_init (&tmp_pgp_crt);
287 ret =
288 gnutls_pcert_import_openpgp_raw (&pgp_crt, &data, GNUTLS_OPENPGP_FMT_BASE64, HAVE_OPT(PGPSUBKEY)?keyid:NULL, 0);
289 if (ret < 0)
291 fprintf (stderr,
292 "*** Error loading PGP cert file: %s\n",
293 gnutls_strerror (ret));
294 exit (1);
297 gnutls_free (data.data);
299 ret = gnutls_privkey_init(&pgp_key);
300 if (ret < 0)
302 fprintf (stderr, "*** Error initializing key: %s\n",
303 gnutls_strerror (ret));
304 exit (1);
307 gnutls_privkey_set_pin_function(pgp_key, pin_callback, NULL);
309 if (gnutls_url_is_supported (pgp_keyfile))
311 ret = gnutls_privkey_import_url( pgp_key, pgp_keyfile, 0);
312 if (ret < 0)
314 fprintf (stderr, "*** Error loading url: %s\n",
315 gnutls_strerror (ret));
316 exit (1);
319 else
321 ret = gnutls_load_file (pgp_keyfile, &data);
322 if (ret < 0)
324 fprintf (stderr, "*** Error loading key file.\n");
325 exit (1);
328 if (HAVE_OPT(PGPSUBKEY))
329 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, keyid, NULL);
330 else
331 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, NULL, NULL);
332 if (ret < 0)
334 fprintf (stderr, "*** Error loading url: %s\n",
335 gnutls_strerror (ret));
336 exit (1);
339 gnutls_free(data.data);
343 fprintf (stdout, "Processed 1 client PGP certificate...\n");
345 #endif
349 #define IS_NEWLINE(x) ((x[0] == '\n') || (x[0] == '\r'))
350 static int
351 read_yesno (const char *input_str)
353 char input[128];
355 fputs (input_str, stderr);
356 if (fgets (input, sizeof (input), stdin) == NULL)
357 return 0;
359 if (IS_NEWLINE(input))
360 return 0;
362 if (input[0] == 'y' || input[0] == 'Y')
363 return 1;
365 return 0;
368 /* converts a textual service or port to
369 * a service.
371 static const char* port_to_service(const char* sport)
373 unsigned int port;
374 struct servent * sr;
376 port = atoi(sport);
377 if (port == 0) return sport;
379 port = htons(port);
381 sr = getservbyport(port, udp?"udp":"tcp");
382 if (sr == NULL)
384 fprintf(stderr, "Warning: getservbyport() failed. Using port number as service.\n");
385 return sport;
388 return sr->s_name;
391 static int
392 cert_verify_callback (gnutls_session_t session)
394 int rc;
395 unsigned int status = 0;
396 int ssh = ENABLED_OPT(TOFU);
397 const char* txt_service;
399 rc = cert_verify(session, hostname);
400 if (rc == 0)
402 printf ("*** Verifying server certificate failed...\n");
403 if (!insecure && !ssh)
404 return -1;
406 else if (ENABLED_OPT(OCSP) || status_request_ocsp)
407 { /* off-line verification succeeded. Try OCSP */
408 rc = cert_verify_ocsp(session);
409 if (rc == 0)
411 printf ("*** Verifying (with OCSP) server certificate failed...\n");
412 if (!insecure && !ssh)
413 return -1;
415 else if (rc == -1)
416 printf("*** OCSP response ignored\n");
419 if (ssh) /* try ssh auth */
421 unsigned int list_size;
422 const gnutls_datum_t * cert;
424 cert = gnutls_certificate_get_peers(session, &list_size);
425 if (cert == NULL)
427 fprintf(stderr, "Cannot obtain peer's certificate!\n");
428 return -1;
431 txt_service = port_to_service(service);
433 rc = gnutls_verify_stored_pubkey(NULL, NULL, hostname, txt_service,
434 GNUTLS_CRT_X509, cert, 0);
435 if (rc == GNUTLS_E_NO_CERTIFICATE_FOUND)
437 print_cert_info_compact(session);
438 fprintf(stderr, "Host %s (%s) has never been contacted before.\n", hostname, txt_service);
439 if (status == 0)
440 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
442 rc = read_yesno("Are you sure you want to trust it? (y/N): ");
443 if (rc == 0)
444 return -1;
446 else if (rc == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
448 print_cert_info_compact(session);
449 fprintf(stderr, "Warning: host %s is known and it is associated with a different key.\n", hostname);
450 fprintf(stderr, "It might be that the server has multiple keys, or an attacker replaced the key to eavesdrop this connection .\n");
451 if (status == 0)
452 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
454 rc = read_yesno("Do you trust the received key? (y/N): ");
455 if (rc == 0)
456 return -1;
458 else if (rc < 0)
460 fprintf(stderr, "gnutls_verify_stored_pubkey: %s\n", gnutls_strerror(rc));
461 return -1;
464 if (rc != 0)
466 rc = gnutls_store_pubkey(NULL, NULL, hostname, txt_service,
467 GNUTLS_CRT_X509, cert, 0, 0);
468 if (rc < 0)
469 fprintf(stderr, "Could not store key: %s\n", gnutls_strerror(rc));
473 return 0;
476 /* This callback should be associated with a session by calling
477 * gnutls_certificate_client_set_retrieve_function( session, cert_callback),
478 * before a handshake.
481 static int
482 cert_callback (gnutls_session_t session,
483 const gnutls_datum_t * req_ca_rdn, int nreqs,
484 const gnutls_pk_algorithm_t * sign_algos,
485 int sign_algos_length, gnutls_pcert_st **pcert,
486 unsigned int *pcert_length, gnutls_privkey_t * pkey)
488 char issuer_dn[256];
489 int i, ret, cert_type;
490 size_t len;
492 if (verbose)
494 /* Print the server's trusted CAs
496 if (nreqs > 0)
497 printf ("- Server's trusted authorities:\n");
498 else
499 printf ("- Server did not send us any trusted authorities names.\n");
501 /* print the names (if any) */
502 for (i = 0; i < nreqs; i++)
504 len = sizeof (issuer_dn);
505 ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len);
506 if (ret >= 0)
508 printf (" [%d]: ", i);
509 printf ("%s\n", issuer_dn);
514 /* Select a certificate and return it.
515 * The certificate must be of any of the "sign algorithms"
516 * supported by the server.
519 cert_type = gnutls_certificate_type_get (session);
521 *pcert_length = 0;
523 if (cert_type == GNUTLS_CRT_X509)
525 if (x509_crt_size > 0)
527 if (x509_key != NULL)
529 *pkey = x509_key;
531 else
533 printf ("- Could not find a suitable key to send to server\n");
534 return -1;
537 *pcert_length = x509_crt_size;
538 *pcert = x509_crt;
542 else if (cert_type == GNUTLS_CRT_OPENPGP)
544 if (pgp_key != NULL)
546 *pkey = pgp_key;
548 *pcert_length = 1;
549 *pcert = &pgp_crt;
553 printf ("- Successfully sent %u certificate(s) to server.\n", *pcert_length);
554 return 0;
558 /* initializes a gnutls_session_t with some defaults.
560 static gnutls_session_t
561 init_tls_session (const char *hostname)
563 const char *err;
564 int ret;
565 gnutls_session_t session;
567 if (priorities == NULL)
568 priorities = "NORMAL";
570 if (udp)
572 gnutls_init (&session, GNUTLS_CLIENT|GNUTLS_DATAGRAM);
573 if (mtu)
574 gnutls_dtls_set_mtu(session, mtu);
576 else
577 gnutls_init (&session, GNUTLS_CLIENT);
579 if ((ret = gnutls_priority_set_direct (session, priorities, &err)) < 0)
581 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
582 else
583 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
584 exit (1);
587 /* allow the use of private ciphersuites.
589 if (disable_extensions == 0)
591 if (!isdigit(hostname[0]) && strchr(hostname, ':') == 0)
592 gnutls_server_name_set (session, GNUTLS_NAME_DNS, hostname,
593 strlen (hostname));
596 if (HAVE_OPT(DH_BITS))
597 gnutls_dh_set_prime_bits( session, OPT_VALUE_DH_BITS);
599 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anon_cred);
600 if (srp_cred)
601 gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
602 if (psk_cred)
603 gnutls_credentials_set (session, GNUTLS_CRD_PSK, psk_cred);
604 gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
606 gnutls_certificate_set_retrieve_function2 (xcred, cert_callback);
607 gnutls_certificate_set_verify_function (xcred, cert_verify_callback);
609 /* send the fingerprint */
610 #ifdef ENABLE_OPENPGP
611 if (fingerprint != 0)
612 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
613 #endif
615 /* use the max record size extension */
616 if (record_max_size > 0 && disable_extensions == 0)
618 if (gnutls_record_set_max_size (session, record_max_size) < 0)
620 fprintf (stderr,
621 "Cannot set the maximum record size to %d.\n",
622 record_max_size);
623 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
624 exit (1);
628 if (HAVE_OPT(HEARTBEAT))
629 gnutls_heartbeat_enable (session, GNUTLS_HB_PEER_ALLOWED_TO_SEND);
631 /* OCSP status-request TLS extension */
632 if (status_request_ocsp > 0 && disable_extensions == 0)
634 if (gnutls_ocsp_status_request_enable_client (session, NULL, 0, NULL) < 0)
636 fprintf (stderr, "Cannot set OCSP status request information.\n");
637 exit (1);
641 #ifdef ENABLE_SESSION_TICKET
642 if (disable_extensions == 0 && !HAVE_OPT(NOTICKET)t)
643 gnutls_session_ticket_enable_client (session);
644 #endif
646 return session;
649 static void cmd_parser (int argc, char **argv);
651 /* Returns zero if the error code was successfully handled.
653 static int
654 handle_error (socket_st * hd, int err)
656 int alert, ret;
657 const char *err_type, *str;
659 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
660 return 0;
662 if (gnutls_error_is_fatal (err) == 0)
664 ret = 0;
665 err_type = "Non fatal";
667 else
669 ret = err;
670 err_type = "Fatal";
673 str = gnutls_strerror (err);
674 if (str == NULL)
675 str = str_unknown;
676 fprintf (stderr, "*** %s error: %s\n", err_type, str);
678 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
679 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
681 alert = gnutls_alert_get (hd->session);
682 str = gnutls_alert_get_name (alert);
683 if (str == NULL)
684 str = str_unknown;
685 printf ("*** Received alert [%d]: %s\n", alert, str);
688 check_rehandshake (hd, err);
690 return ret;
693 int starttls_alarmed = 0;
695 #ifndef _WIN32
696 static void
697 starttls_alarm (int signum)
699 starttls_alarmed = 1;
701 #endif
703 static void
704 tls_log_func (int level, const char *str)
706 fprintf (stderr, "|<%d>| %s", level, str);
709 #define IN_KEYBOARD 1
710 #define IN_NET 2
711 #define IN_NONE 0
712 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
714 static int check_net_or_keyboard_input(socket_st* hd)
716 int maxfd;
717 fd_set rset;
718 int err;
719 struct timeval tv;
723 FD_ZERO (&rset);
724 FD_SET (hd->fd, &rset);
726 #ifndef _WIN32
727 FD_SET (fileno (stdin), &rset);
728 maxfd = MAX (fileno (stdin), hd->fd);
729 #else
730 maxfd = hd->fd;
731 #endif
733 tv.tv_sec = 0;
734 tv.tv_usec = 50 * 1000;
736 if (hd->secure == 1)
737 if (gnutls_record_check_pending(hd->session))
738 return IN_NET;
740 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
741 if (err < 0)
742 continue;
744 if (FD_ISSET (hd->fd, &rset))
745 return IN_NET;
747 #ifdef _WIN32
749 int state;
750 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
752 if (state == WAIT_OBJECT_0)
753 return IN_KEYBOARD;
755 #else
756 if (FD_ISSET (fileno (stdin), &rset))
757 return IN_KEYBOARD;
758 #endif
760 while(err == 0);
762 return IN_NONE;
766 main (int argc, char **argv)
768 int ret;
769 int ii, i, inp;
770 char buffer[MAX_BUF + 1];
771 char *session_data = NULL;
772 char *session_id = NULL;
773 size_t session_data_size;
774 size_t session_id_size = 0;
775 int user_term = 0, retval = 0;
776 socket_st hd;
777 ssize_t bytes;
779 set_program_name (argv[0]);
780 cmd_parser (argc, argv);
782 gnutls_global_set_log_function (tls_log_func);
783 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
785 if ((ret = gnutls_global_init ()) < 0)
787 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
788 exit (1);
791 #ifdef ENABLE_PKCS11
792 // pkcs11_common ();
793 #endif
795 if (hostname == NULL)
797 fprintf (stderr, "No hostname given\n");
798 exit (1);
801 sockets_init ();
803 init_global_tls_stuff ();
805 socket_open (&hd, hostname, service, udp);
806 socket_connect (&hd);
808 hd.session = init_tls_session (hostname);
809 if (starttls)
810 goto after_handshake;
812 for (i = 0; i < 2; i++)
816 if (i == 1)
818 hd.session = init_tls_session (hostname);
819 gnutls_session_set_data (hd.session, session_data,
820 session_data_size);
821 free (session_data);
824 ret = do_handshake (&hd);
826 if (ret < 0)
828 fprintf (stderr, "*** Handshake has failed\n");
829 gnutls_perror (ret);
830 gnutls_deinit (hd.session);
831 return 1;
833 else
835 printf ("- Handshake was completed\n");
836 if (gnutls_session_is_resumed (hd.session) != 0)
837 printf ("*** This is a resumed session\n");
840 if (resume != 0 && i == 0)
843 gnutls_session_get_data (hd.session, NULL, &session_data_size);
844 session_data = malloc (session_data_size);
846 gnutls_session_get_data (hd.session, session_data,
847 &session_data_size);
849 gnutls_session_get_id (hd.session, NULL, &session_id_size);
851 session_id = malloc (session_id_size);
852 gnutls_session_get_id (hd.session, session_id, &session_id_size);
854 printf ("- Disconnecting\n");
855 socket_bye (&hd);
857 printf
858 ("\n\n- Connecting again- trying to resume previous session\n");
859 socket_open (&hd, hostname, service, udp);
860 socket_connect (&hd);
862 else
864 break;
868 after_handshake:
870 /* Warning! Do not touch this text string, it is used by external
871 programs to search for when gnutls-cli has reached this point. */
872 printf ("\n- Simple Client Mode:\n\n");
874 if (rehandshake)
876 ret = do_handshake (&hd);
878 if (ret < 0)
880 fprintf (stderr, "*** ReHandshake has failed\n");
881 gnutls_perror (ret);
882 gnutls_deinit (hd.session);
883 return 1;
885 else
887 printf ("- ReHandshake was completed\n");
891 #ifndef _WIN32
892 signal (SIGALRM, &starttls_alarm);
893 #endif
895 fflush (stdout);
896 fflush (stderr);
898 /* do not buffer */
899 #ifndef _WIN32
900 setbuf (stdin, NULL);
901 #endif
902 setbuf (stdout, NULL);
903 setbuf (stderr, NULL);
905 for (;;)
907 if (starttls_alarmed && !hd.secure)
909 /* Warning! Do not touch this text string, it is used by
910 external programs to search for when gnutls-cli has
911 reached this point. */
912 fprintf (stderr, "*** Starting TLS handshake\n");
913 ret = do_handshake (&hd);
914 if (ret < 0)
916 fprintf (stderr, "*** Handshake has failed\n");
917 user_term = 1;
918 retval = 1;
919 break;
923 inp = check_net_or_keyboard_input(&hd);
925 if (inp == IN_NET)
927 memset (buffer, 0, MAX_BUF + 1);
928 ret = socket_recv (&hd, buffer, MAX_BUF);
930 if (ret == 0)
932 printf ("- Peer has closed the GnuTLS connection\n");
933 break;
935 else if (handle_error (&hd, ret) < 0 && user_term == 0)
937 fprintf (stderr,
938 "*** Server has terminated the connection abnormally.\n");
939 retval = 1;
940 break;
942 else if (ret > 0)
944 if (verbose != 0)
945 printf ("- Received[%d]: ", ret);
946 for (ii = 0; ii < ret; ii++)
948 fputc (buffer[ii], stdout);
950 fflush (stdout);
953 if (user_term != 0)
954 break;
957 if (inp == IN_KEYBOARD)
959 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
961 if (hd.secure == 0)
963 /* Warning! Do not touch this text string, it is
964 used by external programs to search for when
965 gnutls-cli has reached this point. */
966 fprintf (stderr, "*** Starting TLS handshake\n");
967 ret = do_handshake (&hd);
968 clearerr (stdin);
969 if (ret < 0)
971 fprintf (stderr, "*** Handshake has failed\n");
972 user_term = 1;
973 retval = 1;
974 break;
977 else
979 user_term = 1;
980 break;
982 continue;
985 buffer[bytes] = 0;
986 if (crlf != 0)
988 char *b = strchr (buffer, '\n');
989 if (b != NULL)
991 strcpy (b, "\r\n");
992 bytes++;
996 ret = socket_send (&hd, buffer, bytes);
998 if (ret > 0)
1000 if (verbose != 0)
1001 printf ("- Sent: %d bytes\n", ret);
1003 else
1004 handle_error (&hd, ret);
1009 if (user_term != 0)
1010 socket_bye (&hd);
1011 else
1012 gnutls_deinit (hd.session);
1014 #ifdef ENABLE_SRP
1015 if (srp_cred)
1016 gnutls_srp_free_client_credentials (srp_cred);
1017 #endif
1018 #ifdef ENABLE_PSK
1019 if (psk_cred)
1020 gnutls_psk_free_client_credentials (psk_cred);
1021 #endif
1023 gnutls_certificate_free_credentials (xcred);
1025 #ifdef ENABLE_ANON
1026 gnutls_anon_free_client_credentials (anon_cred);
1027 #endif
1029 gnutls_global_deinit ();
1031 return retval;
1034 static void
1035 cmd_parser (int argc, char **argv)
1037 const char* rest = NULL;
1039 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1040 argc -= optct;
1041 argv += optct;
1043 if (rest == NULL && argc > 0)
1044 rest = argv[0];
1046 if (HAVE_OPT(BENCHMARK_CIPHERS))
1048 benchmark_cipher(1, OPT_VALUE_DEBUG);
1049 exit(0);
1052 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1054 benchmark_cipher(0, OPT_VALUE_DEBUG);
1055 exit(0);
1058 if (HAVE_OPT(BENCHMARK_TLS_CIPHERS))
1060 benchmark_tls(OPT_VALUE_DEBUG, 1);
1061 exit(0);
1064 if (HAVE_OPT(BENCHMARK_TLS_KX))
1066 benchmark_tls(OPT_VALUE_DEBUG, 0);
1067 exit(0);
1070 if (HAVE_OPT(PRIORITY))
1072 priorities = OPT_ARG(PRIORITY);
1074 verbose = HAVE_OPT( VERBOSE);
1075 if (verbose)
1076 print_cert = 1;
1077 else
1078 print_cert = HAVE_OPT( PRINT_CERT);
1080 if (HAVE_OPT(LIST))
1082 print_list(priorities, verbose);
1083 exit(0);
1086 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1087 starttls = HAVE_OPT(STARTTLS);
1088 resume = HAVE_OPT(RESUME);
1089 rehandshake = HAVE_OPT(REHANDSHAKE);
1090 insecure = HAVE_OPT(INSECURE);
1092 udp = HAVE_OPT(UDP);
1093 mtu = OPT_VALUE_MTU;
1095 if (HAVE_OPT(PORT))
1097 service = OPT_ARG(PORT);
1099 else
1101 service = "443";
1104 record_max_size = OPT_VALUE_RECORDSIZE;
1105 status_request_ocsp = HAVE_OPT(OCSP_STATUS_REQUEST);
1106 if (ENABLED_OPT(OCSP))
1107 status_request_ocsp = 1;
1109 fingerprint = HAVE_OPT(FINGERPRINT);
1111 if (HAVE_OPT(X509FMTDER))
1112 x509ctype = GNUTLS_X509_FMT_DER;
1113 else
1114 x509ctype = GNUTLS_X509_FMT_PEM;
1116 if (HAVE_OPT(SRPUSERNAME))
1117 srp_username = OPT_ARG(SRPUSERNAME);
1119 if (HAVE_OPT(SRPPASSWD))
1120 srp_passwd = OPT_ARG(SRPPASSWD);
1122 if (HAVE_OPT(X509CAFILE))
1123 x509_cafile = OPT_ARG(X509CAFILE);
1125 if (HAVE_OPT(X509CRLFILE))
1126 x509_crlfile = OPT_ARG(X509CRLFILE);
1128 if (HAVE_OPT(X509KEYFILE))
1129 x509_keyfile = OPT_ARG(X509KEYFILE);
1131 if (HAVE_OPT(X509CERTFILE))
1132 x509_certfile = OPT_ARG(X509CERTFILE);
1134 if (HAVE_OPT(PGPKEYFILE))
1135 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1137 if (HAVE_OPT(PGPCERTFILE))
1138 pgp_certfile = OPT_ARG(PGPCERTFILE);
1140 if (HAVE_OPT(PSKUSERNAME))
1141 psk_username = OPT_ARG(PSKUSERNAME);
1143 if (HAVE_OPT(PSKKEY))
1145 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1146 psk_key.size = strlen (OPT_ARG(PSKKEY));
1148 else
1149 psk_key.size = 0;
1151 if (HAVE_OPT(PGPKEYRING))
1152 pgp_keyring = OPT_ARG(PGPKEYRING);
1154 crlf = HAVE_OPT(CRLF);
1156 if (rest != NULL)
1157 hostname = rest;
1159 if (hostname == NULL)
1161 fprintf(stderr, "No hostname specified\n");
1162 exit(1);
1166 static void
1167 check_rehandshake (socket_st * socket, int ret)
1169 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1171 /* There is a race condition here. If application
1172 * data is sent after the rehandshake request,
1173 * the server thinks we ignored his request.
1174 * This is a bad design of this client.
1176 printf ("*** Received rehandshake request\n");
1177 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1179 ret = do_handshake (socket);
1181 if (ret == 0)
1183 printf ("*** Rehandshake was performed.\n");
1185 else
1187 printf ("*** Rehandshake Failed.\n");
1193 static int
1194 do_handshake (socket_st * socket)
1196 int ret;
1198 gnutls_transport_set_ptr (socket->session,
1199 (gnutls_transport_ptr_t)
1200 gl_fd_to_handle (socket->fd));
1203 gnutls_handshake_set_timeout( socket->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
1204 ret = gnutls_handshake (socket->session);
1206 if (ret < 0)
1208 handle_error (socket, ret);
1211 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1213 if (ret == 0)
1215 /* print some information */
1216 print_info (socket->session, print_cert, verbose);
1217 socket->secure = 1;
1219 else
1221 print_cert_info (socket->session, verbose, print_cert);
1222 gnutls_alert_send_appropriate (socket->session, ret);
1223 shutdown (socket->fd, SHUT_RDWR);
1225 return ret;
1228 static int
1229 srp_username_callback (gnutls_session_t session,
1230 char **username, char **password)
1232 if (srp_username == NULL || srp_passwd == NULL)
1234 return -1;
1237 *username = gnutls_strdup (srp_username);
1238 *password = gnutls_strdup (srp_passwd);
1240 return 0;
1243 static int
1244 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1246 const char *hint = gnutls_psk_client_get_hint (session);
1247 char *rawkey;
1248 char *passwd;
1249 int ret;
1250 size_t res_size;
1251 gnutls_datum_t tmp;
1253 printf ("- PSK client callback. ");
1254 if (hint)
1255 printf ("PSK hint '%s'\n", hint);
1256 else
1257 printf ("No PSK hint\n");
1259 if (HAVE_OPT(PSKUSERNAME))
1260 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1261 else
1263 char *tmp = NULL;
1264 size_t n;
1266 printf ("Enter PSK identity: ");
1267 fflush (stdout);
1268 getline (&tmp, &n, stdin);
1270 if (tmp == NULL)
1272 fprintf (stderr, "No username given, aborting...\n");
1273 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1276 if (tmp[strlen (tmp) - 1] == '\n')
1277 tmp[strlen (tmp) - 1] = '\0';
1278 if (tmp[strlen (tmp) - 1] == '\r')
1279 tmp[strlen (tmp) - 1] = '\0';
1281 *username = gnutls_strdup (tmp);
1282 free (tmp);
1284 if (!*username)
1285 return GNUTLS_E_MEMORY_ERROR;
1287 passwd = getpass ("Enter key: ");
1288 if (passwd == NULL)
1290 fprintf (stderr, "No key given, aborting...\n");
1291 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1294 tmp.data = (void*)passwd;
1295 tmp.size = strlen (passwd);
1297 res_size = tmp.size / 2 + 1;
1298 rawkey = gnutls_malloc (res_size);
1299 if (rawkey == NULL)
1300 return GNUTLS_E_MEMORY_ERROR;
1302 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1303 if (ret < 0)
1305 fprintf (stderr, "Error deriving password: %s\n",
1306 gnutls_strerror (ret));
1307 gnutls_free (*username);
1308 return ret;
1311 key->data = (void*)rawkey;
1312 key->size = res_size;
1314 if (HAVE_OPT(DEBUG))
1316 char hexkey[41];
1317 res_size = sizeof (hexkey);
1318 gnutls_hex_encode (key, hexkey, &res_size);
1319 fprintf (stderr, "PSK username: %s\n", *username);
1320 fprintf (stderr, "PSK hint: %s\n", hint);
1321 fprintf (stderr, "PSK key: %s\n", hexkey);
1324 return 0;
1327 static void
1328 init_global_tls_stuff (void)
1330 int ret;
1332 /* X509 stuff */
1333 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1335 fprintf (stderr, "Certificate allocation memory error\n");
1336 exit (1);
1338 gnutls_certificate_set_pin_function(xcred, pin_callback, NULL);
1340 if (x509_cafile != NULL)
1342 ret = gnutls_certificate_set_x509_trust_file (xcred,
1343 x509_cafile, x509ctype);
1345 else
1347 ret = gnutls_certificate_set_x509_system_trust (xcred);
1349 if (ret < 0)
1351 fprintf (stderr, "Error setting the x509 trust file\n");
1353 else
1355 printf ("Processed %d CA certificate(s).\n", ret);
1358 if (x509_crlfile != NULL)
1360 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1361 x509ctype);
1362 if (ret < 0)
1364 fprintf (stderr, "Error setting the x509 CRL file\n");
1366 else
1368 printf ("Processed %d CRL(s).\n", ret);
1372 load_keys ();
1374 #ifdef ENABLE_OPENPGP
1375 if (pgp_keyring != NULL)
1377 ret =
1378 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1379 GNUTLS_OPENPGP_FMT_BASE64);
1380 if (ret < 0)
1382 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1385 #endif
1387 #ifdef ENABLE_SRP
1388 if (srp_username && srp_passwd)
1390 /* SRP stuff */
1391 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1393 fprintf (stderr, "SRP authentication error\n");
1396 gnutls_srp_set_client_credentials_function (srp_cred,
1397 srp_username_callback);
1399 #endif
1401 #ifdef ENABLE_PSK
1402 /* PSK stuff */
1403 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1405 fprintf (stderr, "PSK authentication error\n");
1408 if (psk_username && psk_key.data)
1410 ret = gnutls_psk_set_client_credentials (psk_cred,
1411 psk_username, &psk_key,
1412 GNUTLS_PSK_KEY_HEX);
1413 if (ret < 0)
1415 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1416 gnutls_strerror (ret));
1419 else
1420 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1421 #endif
1423 #ifdef ENABLE_ANON
1424 /* ANON stuff */
1425 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1427 fprintf (stderr, "Anonymous authentication error\n");
1429 #endif
1433 /* OCSP check for the peer's certificate. Should be called
1434 * only after the certificate list verication is complete.
1435 * Returns:
1436 * 0: certificate is revoked
1437 * 1: certificate is ok
1438 * -1: dunno
1440 static int
1441 cert_verify_ocsp (gnutls_session_t session)
1443 gnutls_x509_crt_t crt, issuer;
1444 const gnutls_datum_t *cert_list;
1445 unsigned int cert_list_size = 0;
1446 int deinit_issuer = 0;
1447 gnutls_datum_t resp;
1448 int ret;
1450 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1451 if (cert_list_size == 0)
1453 fprintf (stderr, "No certificates found!\n");
1454 return -1;
1457 gnutls_x509_crt_init (&crt);
1458 ret =
1459 gnutls_x509_crt_import (crt, &cert_list[0],
1460 GNUTLS_X509_FMT_DER);
1461 if (ret < 0)
1463 fprintf (stderr, "Decoding error: %s\n",
1464 gnutls_strerror (ret));
1465 return -1;
1468 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1469 if (ret < 0 && cert_list_size > 1)
1471 gnutls_x509_crt_init(&issuer);
1472 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1473 if (ret < 0)
1475 fprintf (stderr, "Decoding error: %s\n",
1476 gnutls_strerror (ret));
1477 return -1;
1479 deinit_issuer = 1;
1481 else if (ret < 0)
1483 fprintf(stderr, "Cannot find issuer\n");
1484 ret = -1;
1485 goto cleanup;
1488 if (status_request_ocsp)
1489 { /* try the server's OCSP response */
1490 ret = gnutls_ocsp_status_request_get(session, &resp);
1491 if (ret < 0 && !ENABLED_OPT(OCSP))
1493 if (ret != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1494 fprintf(stderr, "gnutls_ocsp_status_request_get: %s\n", gnutls_strerror(ret));
1495 ret = -1;
1496 goto cleanup;
1499 if (ret >= 0)
1501 ret = check_ocsp_response(crt, issuer, &resp);
1502 if (ret >= 0 || !ENABLED_OPT(OCSP))
1503 goto cleanup;
1508 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1509 if (ret < 0)
1511 fprintf(stderr, "Cannot contact OCSP server\n");
1512 ret = -1;
1513 goto cleanup;
1516 /* verify and check the response for revoked cert */
1517 ret = check_ocsp_response(crt, issuer, &resp);
1519 cleanup:
1520 if (deinit_issuer)
1521 gnutls_x509_crt_deinit (issuer);
1522 gnutls_x509_crt_deinit (crt);
1524 return ret;