Added gnutls_x509_crl_reason_flags_t.
[gnutls.git] / src / cli.c
blob6d99572f7513f33d18309a908d71a125b000a432
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);
608 gnutls_certificate_set_verify_flags (xcred, 0);
610 /* send the fingerprint */
611 #ifdef ENABLE_OPENPGP
612 if (fingerprint != 0)
613 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
614 #endif
616 /* use the max record size extension */
617 if (record_max_size > 0 && disable_extensions == 0)
619 if (gnutls_record_set_max_size (session, record_max_size) < 0)
621 fprintf (stderr,
622 "Cannot set the maximum record size to %d.\n",
623 record_max_size);
624 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
625 exit (1);
629 if (HAVE_OPT(HEARTBEAT))
630 gnutls_heartbeat_enable (session, GNUTLS_HB_PEER_ALLOWED_TO_SEND);
632 /* OCSP status-request TLS extension */
633 if (status_request_ocsp > 0 && disable_extensions == 0)
635 if (gnutls_ocsp_status_request_enable_client (session, NULL, 0, NULL) < 0)
637 fprintf (stderr, "Cannot set OCSP status request information.\n");
638 exit (1);
642 #ifdef ENABLE_SESSION_TICKET
643 if (disable_extensions == 0 && !HAVE_OPT(NOTICKET)t)
644 gnutls_session_ticket_enable_client (session);
645 #endif
647 return session;
650 static void cmd_parser (int argc, char **argv);
652 /* Returns zero if the error code was successfully handled.
654 static int
655 handle_error (socket_st * hd, int err)
657 int alert, ret;
658 const char *err_type, *str;
660 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
661 return 0;
663 if (gnutls_error_is_fatal (err) == 0)
665 ret = 0;
666 err_type = "Non fatal";
668 else
670 ret = err;
671 err_type = "Fatal";
674 str = gnutls_strerror (err);
675 if (str == NULL)
676 str = str_unknown;
677 fprintf (stderr, "*** %s error: %s\n", err_type, str);
679 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
680 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
682 alert = gnutls_alert_get (hd->session);
683 str = gnutls_alert_get_name (alert);
684 if (str == NULL)
685 str = str_unknown;
686 printf ("*** Received alert [%d]: %s\n", alert, str);
689 check_rehandshake (hd, err);
691 return ret;
694 int starttls_alarmed = 0;
696 #ifndef _WIN32
697 static void
698 starttls_alarm (int signum)
700 starttls_alarmed = 1;
702 #endif
704 static void
705 tls_log_func (int level, const char *str)
707 fprintf (stderr, "|<%d>| %s", level, str);
710 #define IN_KEYBOARD 1
711 #define IN_NET 2
712 #define IN_NONE 0
713 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
715 static int check_net_or_keyboard_input(socket_st* hd)
717 int maxfd;
718 fd_set rset;
719 int err;
720 struct timeval tv;
724 FD_ZERO (&rset);
725 FD_SET (hd->fd, &rset);
727 #ifndef _WIN32
728 FD_SET (fileno (stdin), &rset);
729 maxfd = MAX (fileno (stdin), hd->fd);
730 #else
731 maxfd = hd->fd;
732 #endif
734 tv.tv_sec = 0;
735 tv.tv_usec = 50 * 1000;
737 if (hd->secure == 1)
738 if (gnutls_record_check_pending(hd->session))
739 return IN_NET;
741 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
742 if (err < 0)
743 continue;
745 if (FD_ISSET (hd->fd, &rset))
746 return IN_NET;
748 #ifdef _WIN32
750 int state;
751 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
753 if (state == WAIT_OBJECT_0)
754 return IN_KEYBOARD;
756 #else
757 if (FD_ISSET (fileno (stdin), &rset))
758 return IN_KEYBOARD;
759 #endif
761 while(err == 0);
763 return IN_NONE;
767 main (int argc, char **argv)
769 int ret;
770 int ii, i, inp;
771 char buffer[MAX_BUF + 1];
772 char *session_data = NULL;
773 char *session_id = NULL;
774 size_t session_data_size;
775 size_t session_id_size = 0;
776 int user_term = 0, retval = 0;
777 socket_st hd;
778 ssize_t bytes;
780 set_program_name (argv[0]);
781 cmd_parser (argc, argv);
783 gnutls_global_set_log_function (tls_log_func);
784 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
786 if ((ret = gnutls_global_init ()) < 0)
788 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
789 exit (1);
792 #ifdef ENABLE_PKCS11
793 // pkcs11_common ();
794 #endif
796 if (hostname == NULL)
798 fprintf (stderr, "No hostname given\n");
799 exit (1);
802 sockets_init ();
804 init_global_tls_stuff ();
806 socket_open (&hd, hostname, service, udp);
807 socket_connect (&hd);
809 hd.session = init_tls_session (hostname);
810 if (starttls)
811 goto after_handshake;
813 for (i = 0; i < 2; i++)
817 if (i == 1)
819 hd.session = init_tls_session (hostname);
820 gnutls_session_set_data (hd.session, session_data,
821 session_data_size);
822 free (session_data);
825 ret = do_handshake (&hd);
827 if (ret < 0)
829 fprintf (stderr, "*** Handshake has failed\n");
830 gnutls_perror (ret);
831 gnutls_deinit (hd.session);
832 return 1;
834 else
836 printf ("- Handshake was completed\n");
837 if (gnutls_session_is_resumed (hd.session) != 0)
838 printf ("*** This is a resumed session\n");
841 if (resume != 0 && i == 0)
844 gnutls_session_get_data (hd.session, NULL, &session_data_size);
845 session_data = malloc (session_data_size);
847 gnutls_session_get_data (hd.session, session_data,
848 &session_data_size);
850 gnutls_session_get_id (hd.session, NULL, &session_id_size);
852 session_id = malloc (session_id_size);
853 gnutls_session_get_id (hd.session, session_id, &session_id_size);
855 printf ("- Disconnecting\n");
856 socket_bye (&hd);
858 printf
859 ("\n\n- Connecting again- trying to resume previous session\n");
860 socket_open (&hd, hostname, service, udp);
861 socket_connect (&hd);
863 else
865 break;
869 after_handshake:
871 /* Warning! Do not touch this text string, it is used by external
872 programs to search for when gnutls-cli has reached this point. */
873 printf ("\n- Simple Client Mode:\n\n");
875 if (rehandshake)
877 ret = do_handshake (&hd);
879 if (ret < 0)
881 fprintf (stderr, "*** ReHandshake has failed\n");
882 gnutls_perror (ret);
883 gnutls_deinit (hd.session);
884 return 1;
886 else
888 printf ("- ReHandshake was completed\n");
892 #ifndef _WIN32
893 signal (SIGALRM, &starttls_alarm);
894 #endif
896 fflush (stdout);
897 fflush (stderr);
899 /* do not buffer */
900 #ifndef _WIN32
901 setbuf (stdin, NULL);
902 #endif
903 setbuf (stdout, NULL);
904 setbuf (stderr, NULL);
906 for (;;)
908 if (starttls_alarmed && !hd.secure)
910 /* Warning! Do not touch this text string, it is used by
911 external programs to search for when gnutls-cli has
912 reached this point. */
913 fprintf (stderr, "*** Starting TLS handshake\n");
914 ret = do_handshake (&hd);
915 if (ret < 0)
917 fprintf (stderr, "*** Handshake has failed\n");
918 user_term = 1;
919 retval = 1;
920 break;
924 inp = check_net_or_keyboard_input(&hd);
926 if (inp == IN_NET)
928 memset (buffer, 0, MAX_BUF + 1);
929 ret = socket_recv (&hd, buffer, MAX_BUF);
931 if (ret == 0)
933 printf ("- Peer has closed the GnuTLS connection\n");
934 break;
936 else if (handle_error (&hd, ret) < 0 && user_term == 0)
938 fprintf (stderr,
939 "*** Server has terminated the connection abnormally.\n");
940 retval = 1;
941 break;
943 else if (ret > 0)
945 if (verbose != 0)
946 printf ("- Received[%d]: ", ret);
947 for (ii = 0; ii < ret; ii++)
949 fputc (buffer[ii], stdout);
951 fflush (stdout);
954 if (user_term != 0)
955 break;
958 if (inp == IN_KEYBOARD)
960 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
962 if (hd.secure == 0)
964 /* Warning! Do not touch this text string, it is
965 used by external programs to search for when
966 gnutls-cli has reached this point. */
967 fprintf (stderr, "*** Starting TLS handshake\n");
968 ret = do_handshake (&hd);
969 clearerr (stdin);
970 if (ret < 0)
972 fprintf (stderr, "*** Handshake has failed\n");
973 user_term = 1;
974 retval = 1;
975 break;
978 else
980 user_term = 1;
981 break;
983 continue;
986 buffer[bytes] = 0;
987 if (crlf != 0)
989 char *b = strchr (buffer, '\n');
990 if (b != NULL)
992 strcpy (b, "\r\n");
993 bytes++;
997 ret = socket_send (&hd, buffer, bytes);
999 if (ret > 0)
1001 if (verbose != 0)
1002 printf ("- Sent: %d bytes\n", ret);
1004 else
1005 handle_error (&hd, ret);
1010 if (user_term != 0)
1011 socket_bye (&hd);
1012 else
1013 gnutls_deinit (hd.session);
1015 #ifdef ENABLE_SRP
1016 if (srp_cred)
1017 gnutls_srp_free_client_credentials (srp_cred);
1018 #endif
1019 #ifdef ENABLE_PSK
1020 if (psk_cred)
1021 gnutls_psk_free_client_credentials (psk_cred);
1022 #endif
1024 gnutls_certificate_free_credentials (xcred);
1026 #ifdef ENABLE_ANON
1027 gnutls_anon_free_client_credentials (anon_cred);
1028 #endif
1030 gnutls_global_deinit ();
1032 return retval;
1035 static void
1036 cmd_parser (int argc, char **argv)
1038 const char* rest = NULL;
1040 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1041 argc -= optct;
1042 argv += optct;
1044 if (rest == NULL && argc > 0)
1045 rest = argv[0];
1047 if (HAVE_OPT(BENCHMARK_CIPHERS))
1049 benchmark_cipher(1, OPT_VALUE_DEBUG);
1050 exit(0);
1053 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1055 benchmark_cipher(0, OPT_VALUE_DEBUG);
1056 exit(0);
1059 if (HAVE_OPT(BENCHMARK_TLS_CIPHERS))
1061 benchmark_tls(OPT_VALUE_DEBUG, 1);
1062 exit(0);
1065 if (HAVE_OPT(BENCHMARK_TLS_KX))
1067 benchmark_tls(OPT_VALUE_DEBUG, 0);
1068 exit(0);
1071 if (HAVE_OPT(PRIORITY))
1073 priorities = OPT_ARG(PRIORITY);
1075 verbose = HAVE_OPT( VERBOSE);
1076 if (verbose)
1077 print_cert = 1;
1078 else
1079 print_cert = HAVE_OPT( PRINT_CERT);
1081 if (HAVE_OPT(LIST))
1083 print_list(priorities, verbose);
1084 exit(0);
1087 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1088 starttls = HAVE_OPT(STARTTLS);
1089 resume = HAVE_OPT(RESUME);
1090 rehandshake = HAVE_OPT(REHANDSHAKE);
1091 insecure = HAVE_OPT(INSECURE);
1093 udp = HAVE_OPT(UDP);
1094 mtu = OPT_VALUE_MTU;
1096 if (HAVE_OPT(PORT))
1098 service = OPT_ARG(PORT);
1100 else
1102 service = "443";
1105 record_max_size = OPT_VALUE_RECORDSIZE;
1106 status_request_ocsp = HAVE_OPT(OCSP_STATUS_REQUEST);
1107 if (ENABLED_OPT(OCSP))
1108 status_request_ocsp = 1;
1110 fingerprint = HAVE_OPT(FINGERPRINT);
1112 if (HAVE_OPT(X509FMTDER))
1113 x509ctype = GNUTLS_X509_FMT_DER;
1114 else
1115 x509ctype = GNUTLS_X509_FMT_PEM;
1117 if (HAVE_OPT(SRPUSERNAME))
1118 srp_username = OPT_ARG(SRPUSERNAME);
1120 if (HAVE_OPT(SRPPASSWD))
1121 srp_passwd = OPT_ARG(SRPPASSWD);
1123 if (HAVE_OPT(X509CAFILE))
1124 x509_cafile = OPT_ARG(X509CAFILE);
1126 if (HAVE_OPT(X509CRLFILE))
1127 x509_crlfile = OPT_ARG(X509CRLFILE);
1129 if (HAVE_OPT(X509KEYFILE))
1130 x509_keyfile = OPT_ARG(X509KEYFILE);
1132 if (HAVE_OPT(X509CERTFILE))
1133 x509_certfile = OPT_ARG(X509CERTFILE);
1135 if (HAVE_OPT(PGPKEYFILE))
1136 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1138 if (HAVE_OPT(PGPCERTFILE))
1139 pgp_certfile = OPT_ARG(PGPCERTFILE);
1141 if (HAVE_OPT(PSKUSERNAME))
1142 psk_username = OPT_ARG(PSKUSERNAME);
1144 if (HAVE_OPT(PSKKEY))
1146 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1147 psk_key.size = strlen (OPT_ARG(PSKKEY));
1149 else
1150 psk_key.size = 0;
1152 if (HAVE_OPT(PGPKEYRING))
1153 pgp_keyring = OPT_ARG(PGPKEYRING);
1155 crlf = HAVE_OPT(CRLF);
1157 if (rest != NULL)
1158 hostname = rest;
1160 if (hostname == NULL)
1162 fprintf(stderr, "No hostname specified\n");
1163 exit(1);
1167 static void
1168 check_rehandshake (socket_st * socket, int ret)
1170 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1172 /* There is a race condition here. If application
1173 * data is sent after the rehandshake request,
1174 * the server thinks we ignored his request.
1175 * This is a bad design of this client.
1177 printf ("*** Received rehandshake request\n");
1178 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1180 ret = do_handshake (socket);
1182 if (ret == 0)
1184 printf ("*** Rehandshake was performed.\n");
1186 else
1188 printf ("*** Rehandshake Failed.\n");
1194 static int
1195 do_handshake (socket_st * socket)
1197 int ret;
1199 gnutls_transport_set_ptr (socket->session,
1200 (gnutls_transport_ptr_t)
1201 gl_fd_to_handle (socket->fd));
1204 gnutls_handshake_set_timeout( socket->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
1205 ret = gnutls_handshake (socket->session);
1207 if (ret < 0)
1209 handle_error (socket, ret);
1212 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1214 if (ret == 0)
1216 /* print some information */
1217 print_info (socket->session, print_cert, verbose);
1218 socket->secure = 1;
1220 else
1222 print_cert_info (socket->session, verbose, print_cert);
1223 gnutls_alert_send_appropriate (socket->session, ret);
1224 shutdown (socket->fd, SHUT_RDWR);
1226 return ret;
1229 static int
1230 srp_username_callback (gnutls_session_t session,
1231 char **username, char **password)
1233 if (srp_username == NULL || srp_passwd == NULL)
1235 return -1;
1238 *username = gnutls_strdup (srp_username);
1239 *password = gnutls_strdup (srp_passwd);
1241 return 0;
1244 static int
1245 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1247 const char *hint = gnutls_psk_client_get_hint (session);
1248 char *rawkey;
1249 char *passwd;
1250 int ret;
1251 size_t res_size;
1252 gnutls_datum_t tmp;
1254 printf ("- PSK client callback. ");
1255 if (hint)
1256 printf ("PSK hint '%s'\n", hint);
1257 else
1258 printf ("No PSK hint\n");
1260 if (HAVE_OPT(PSKUSERNAME))
1261 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1262 else
1264 char *tmp = NULL;
1265 size_t n;
1267 printf ("Enter PSK identity: ");
1268 fflush (stdout);
1269 getline (&tmp, &n, stdin);
1271 if (tmp == NULL)
1273 fprintf (stderr, "No username given, aborting...\n");
1274 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1277 if (tmp[strlen (tmp) - 1] == '\n')
1278 tmp[strlen (tmp) - 1] = '\0';
1279 if (tmp[strlen (tmp) - 1] == '\r')
1280 tmp[strlen (tmp) - 1] = '\0';
1282 *username = gnutls_strdup (tmp);
1283 free (tmp);
1285 if (!*username)
1286 return GNUTLS_E_MEMORY_ERROR;
1288 passwd = getpass ("Enter key: ");
1289 if (passwd == NULL)
1291 fprintf (stderr, "No key given, aborting...\n");
1292 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1295 tmp.data = (void*)passwd;
1296 tmp.size = strlen (passwd);
1298 res_size = tmp.size / 2 + 1;
1299 rawkey = gnutls_malloc (res_size);
1300 if (rawkey == NULL)
1301 return GNUTLS_E_MEMORY_ERROR;
1303 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1304 if (ret < 0)
1306 fprintf (stderr, "Error deriving password: %s\n",
1307 gnutls_strerror (ret));
1308 gnutls_free (*username);
1309 return ret;
1312 key->data = (void*)rawkey;
1313 key->size = res_size;
1315 if (HAVE_OPT(DEBUG))
1317 char hexkey[41];
1318 res_size = sizeof (hexkey);
1319 gnutls_hex_encode (key, hexkey, &res_size);
1320 fprintf (stderr, "PSK username: %s\n", *username);
1321 fprintf (stderr, "PSK hint: %s\n", hint);
1322 fprintf (stderr, "PSK key: %s\n", hexkey);
1325 return 0;
1328 static void
1329 init_global_tls_stuff (void)
1331 int ret;
1333 /* X509 stuff */
1334 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1336 fprintf (stderr, "Certificate allocation memory error\n");
1337 exit (1);
1339 gnutls_certificate_set_pin_function(xcred, pin_callback, NULL);
1341 if (x509_cafile != NULL)
1343 ret = gnutls_certificate_set_x509_trust_file (xcred,
1344 x509_cafile, x509ctype);
1346 else
1348 ret = gnutls_certificate_set_x509_system_trust (xcred);
1350 if (ret < 0)
1352 fprintf (stderr, "Error setting the x509 trust file\n");
1354 else
1356 printf ("Processed %d CA certificate(s).\n", ret);
1359 if (x509_crlfile != NULL)
1361 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1362 x509ctype);
1363 if (ret < 0)
1365 fprintf (stderr, "Error setting the x509 CRL file\n");
1367 else
1369 printf ("Processed %d CRL(s).\n", ret);
1373 load_keys ();
1375 #ifdef ENABLE_OPENPGP
1376 if (pgp_keyring != NULL)
1378 ret =
1379 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1380 GNUTLS_OPENPGP_FMT_BASE64);
1381 if (ret < 0)
1383 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1386 #endif
1388 #ifdef ENABLE_SRP
1389 if (srp_username && srp_passwd)
1391 /* SRP stuff */
1392 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1394 fprintf (stderr, "SRP authentication error\n");
1397 gnutls_srp_set_client_credentials_function (srp_cred,
1398 srp_username_callback);
1400 #endif
1402 #ifdef ENABLE_PSK
1403 /* PSK stuff */
1404 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1406 fprintf (stderr, "PSK authentication error\n");
1409 if (psk_username && psk_key.data)
1411 ret = gnutls_psk_set_client_credentials (psk_cred,
1412 psk_username, &psk_key,
1413 GNUTLS_PSK_KEY_HEX);
1414 if (ret < 0)
1416 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1417 gnutls_strerror (ret));
1420 else
1421 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1422 #endif
1424 #ifdef ENABLE_ANON
1425 /* ANON stuff */
1426 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1428 fprintf (stderr, "Anonymous authentication error\n");
1430 #endif
1434 /* OCSP check for the peer's certificate. Should be called
1435 * only after the certificate list verication is complete.
1436 * Returns:
1437 * 0: certificate is revoked
1438 * 1: certificate is ok
1439 * -1: dunno
1441 static int
1442 cert_verify_ocsp (gnutls_session_t session)
1444 gnutls_x509_crt_t crt, issuer;
1445 const gnutls_datum_t *cert_list;
1446 unsigned int cert_list_size = 0;
1447 int deinit_issuer = 0;
1448 gnutls_datum_t resp;
1449 int ret;
1451 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1452 if (cert_list_size == 0)
1454 fprintf (stderr, "No certificates found!\n");
1455 return -1;
1458 gnutls_x509_crt_init (&crt);
1459 ret =
1460 gnutls_x509_crt_import (crt, &cert_list[0],
1461 GNUTLS_X509_FMT_DER);
1462 if (ret < 0)
1464 fprintf (stderr, "Decoding error: %s\n",
1465 gnutls_strerror (ret));
1466 return -1;
1469 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1470 if (ret < 0 && cert_list_size > 1)
1472 gnutls_x509_crt_init(&issuer);
1473 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1474 if (ret < 0)
1476 fprintf (stderr, "Decoding error: %s\n",
1477 gnutls_strerror (ret));
1478 return -1;
1480 deinit_issuer = 1;
1482 else if (ret < 0)
1484 fprintf(stderr, "Cannot find issuer\n");
1485 ret = -1;
1486 goto cleanup;
1489 if (status_request_ocsp)
1490 { /* try the server's OCSP response */
1491 ret = gnutls_ocsp_status_request_get(session, &resp);
1492 if (ret < 0 && !ENABLED_OPT(OCSP))
1494 if (ret != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1495 fprintf(stderr, "gnutls_ocsp_status_request_get: %s\n", gnutls_strerror(ret));
1496 ret = -1;
1497 goto cleanup;
1500 if (ret >= 0)
1502 ret = check_ocsp_response(crt, issuer, &resp);
1503 if (ret >= 0 || !ENABLED_OPT(OCSP))
1504 goto cleanup;
1509 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1510 if (ret < 0)
1512 fprintf(stderr, "Cannot contact OCSP server\n");
1513 ret = -1;
1514 goto cleanup;
1517 /* verify and check the response for revoked cert */
1518 ret = check_ocsp_response(crt, issuer, &resp);
1520 cleanup:
1521 if (deinit_issuer)
1522 gnutls_x509_crt_deinit (issuer);
1523 gnutls_x509_crt_deinit (crt);
1525 return ret;