doc update
[gnutls.git] / src / cli.c
blob954cde1da4efa5c2bf4f5b5544e8c06b15557ec0
1 /*
2 * Copyright (C) 2000-2012 Free Software Foundation, Inc.
4 * This file is part of GnuTLS.
6 * GnuTLS is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuTLS is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <string.h>
27 #include <sys/time.h>
28 #include <sys/stat.h>
29 #if HAVE_SYS_SOCKET_H
30 # include <sys/socket.h>
31 #elif HAVE_WS2TCPIP_H
32 # include <ws2tcpip.h>
33 #endif
34 #include <sys/select.h>
35 #include <unistd.h>
36 #include <stdint.h>
37 #include <fcntl.h>
38 #include <netdb.h>
39 #include <ctype.h>
41 #include <gnutls/gnutls.h>
42 #include <gnutls/abstract.h>
43 #include <gnutls/dtls.h>
44 #include <gnutls/x509.h>
45 #include <gnutls/openpgp.h>
46 #include <gnutls/pkcs11.h>
48 /* Gnulib portability files. */
49 #include <progname.h>
50 #include <version-etc.h>
51 #include <read-file.h>
52 #include <getpass.h>
53 #include <minmax.h>
55 #include "sockets.h"
56 #include "benchmark.h"
58 #ifdef HAVE_DANE
59 #include <gnutls/dane.h>
60 #endif
62 #include <common.h>
63 #include <socket.h>
65 #include <cli-args.h>
66 #include <ocsptool-common.h>
68 #define MAX_BUF 4096
70 /* global stuff here */
71 int resume, starttls, insecure, rehandshake, udp, mtu;
72 const char *hostname = NULL;
73 const char *service = NULL;
74 int record_max_size;
75 int status_request_ocsp;
76 int fingerprint;
77 int crlf;
78 unsigned int verbose = 0;
79 int print_cert;
81 const char *srp_passwd = NULL;
82 const char *srp_username = NULL;
83 const char *pgp_keyfile = NULL;
84 const char *pgp_certfile = NULL;
85 const char *pgp_keyring = NULL;
86 const char *x509_keyfile = NULL;
87 const char *x509_certfile = NULL;
88 const char *x509_cafile = NULL;
89 const char *x509_crlfile = NULL;
90 static int x509ctype;
91 static int disable_extensions;
92 static unsigned int init_flags = GNUTLS_CLIENT;
93 static const char * priorities = NULL;
95 const char *psk_username = NULL;
96 gnutls_datum_t psk_key = { NULL, 0 };
98 static gnutls_srp_client_credentials_t srp_cred;
99 static gnutls_psk_client_credentials_t psk_cred;
100 static gnutls_anon_client_credentials_t anon_cred;
101 static gnutls_certificate_credentials_t xcred;
103 /* end of global stuff */
105 /* prototypes */
107 static void check_rehandshake (socket_st * socket, int ret);
108 static int do_handshake (socket_st * socket);
109 static void init_global_tls_stuff (void);
110 static int cert_verify_ocsp (gnutls_session_t session);
112 #define MAX_CRT 6
113 static unsigned int x509_crt_size;
114 static gnutls_pcert_st x509_crt[MAX_CRT];
115 static gnutls_privkey_t x509_key = NULL;
117 static gnutls_pcert_st pgp_crt;
118 static gnutls_privkey_t pgp_key = NULL;
120 static void
121 get_keyid (gnutls_openpgp_keyid_t keyid, const char *str)
123 size_t keyid_size = sizeof (keyid);
125 if (strlen (str) != 16)
127 fprintf (stderr,
128 "The OpenPGP subkey ID has to be 16 hexadecimal characters.\n");
129 exit (1);
132 if (gnutls_hex2bin (str, strlen (str), keyid, &keyid_size) < 0)
134 fprintf (stderr, "Error converting hex string: %s.\n", str);
135 exit (1);
138 return;
141 /* Load the certificate and the private key.
143 static void
144 load_keys (void)
146 unsigned int crt_num;
147 int ret;
148 unsigned int i;
149 gnutls_datum_t data = { NULL, 0 };
150 gnutls_x509_crt_t crt_list[MAX_CRT];
151 unsigned char keyid[GNUTLS_OPENPGP_KEYID_SIZE];
153 if (x509_certfile != NULL && x509_keyfile != NULL)
155 #ifdef ENABLE_PKCS11
156 if (strncmp (x509_certfile, "pkcs11:", 7) == 0)
158 crt_num = 1;
159 gnutls_x509_crt_init (&crt_list[0]);
160 gnutls_x509_crt_set_pin_function(crt_list[0], pin_callback, NULL);
162 ret =
163 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile, 0);
165 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
166 ret =
167 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile,
168 GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
170 if (ret < 0)
172 fprintf (stderr, "*** Error loading cert file.\n");
173 exit (1);
175 x509_crt_size = 1;
177 else
178 #endif /* ENABLE_PKCS11 */
181 ret = gnutls_load_file (x509_certfile, &data);
182 if (ret < 0)
184 fprintf (stderr, "*** Error loading cert file.\n");
185 exit (1);
188 crt_num = MAX_CRT;
189 ret =
190 gnutls_x509_crt_list_import (crt_list, &crt_num, &data,
191 x509ctype,
192 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
193 if (ret < 0)
195 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
197 fprintf (stderr,
198 "*** Error loading cert file: Too many certs %d\n",
199 crt_num);
202 else
204 fprintf (stderr,
205 "*** Error loading cert file: %s\n",
206 gnutls_strerror (ret));
208 exit (1);
210 x509_crt_size = ret;
213 for (i=0;i<x509_crt_size;i++)
215 ret = gnutls_pcert_import_x509(&x509_crt[i], crt_list[i], 0);
216 if (ret < 0)
218 fprintf(stderr, "*** Error importing crt to pcert: %s\n",
219 gnutls_strerror(ret));
220 exit(1);
222 gnutls_x509_crt_deinit(crt_list[i]);
225 gnutls_free (data.data);
227 ret = gnutls_privkey_init(&x509_key);
228 if (ret < 0)
230 fprintf (stderr, "*** Error initializing key: %s\n",
231 gnutls_strerror (ret));
232 exit (1);
235 gnutls_privkey_set_pin_function(x509_key, pin_callback, NULL);
237 if (gnutls_url_is_supported(x509_keyfile) != 0)
239 ret =
240 gnutls_privkey_import_url (x509_key, x509_keyfile, 0);
241 if (ret < 0)
243 fprintf (stderr, "*** Error loading url: %s\n",
244 gnutls_strerror (ret));
245 exit (1);
248 else
250 ret = gnutls_load_file (x509_keyfile, &data);
251 if (ret < 0)
253 fprintf (stderr, "*** Error loading key file.\n");
254 exit (1);
257 ret = gnutls_privkey_import_x509_raw( x509_key, &data, x509ctype, NULL, 0);
258 if (ret < 0)
260 fprintf (stderr, "*** Error loading url: %s\n",
261 gnutls_strerror (ret));
262 exit (1);
265 gnutls_free(data.data);
268 fprintf (stdout, "Processed %d client X.509 certificates...\n",
269 x509_crt_size);
273 #ifdef ENABLE_OPENPGP
274 if (HAVE_OPT(PGPSUBKEY))
276 get_keyid (keyid, OPT_ARG(PGPSUBKEY));
279 if (pgp_certfile != NULL && pgp_keyfile != NULL)
281 gnutls_openpgp_crt_t tmp_pgp_crt;
283 ret = gnutls_load_file (pgp_certfile, &data);
284 if (ret < 0)
286 fprintf (stderr, "*** Error loading PGP cert file.\n");
287 exit (1);
290 gnutls_openpgp_crt_init (&tmp_pgp_crt);
292 ret =
293 gnutls_pcert_import_openpgp_raw (&pgp_crt, &data, GNUTLS_OPENPGP_FMT_BASE64, HAVE_OPT(PGPSUBKEY)?keyid:NULL, 0);
294 if (ret < 0)
296 fprintf (stderr,
297 "*** Error loading PGP cert file: %s\n",
298 gnutls_strerror (ret));
299 exit (1);
302 gnutls_free (data.data);
304 ret = gnutls_privkey_init(&pgp_key);
305 if (ret < 0)
307 fprintf (stderr, "*** Error initializing key: %s\n",
308 gnutls_strerror (ret));
309 exit (1);
312 gnutls_privkey_set_pin_function(pgp_key, pin_callback, NULL);
314 if (gnutls_url_is_supported (pgp_keyfile))
316 ret = gnutls_privkey_import_url( pgp_key, pgp_keyfile, 0);
317 if (ret < 0)
319 fprintf (stderr, "*** Error loading url: %s\n",
320 gnutls_strerror (ret));
321 exit (1);
324 else
326 ret = gnutls_load_file (pgp_keyfile, &data);
327 if (ret < 0)
329 fprintf (stderr, "*** Error loading key file.\n");
330 exit (1);
333 if (HAVE_OPT(PGPSUBKEY))
334 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, keyid, NULL);
335 else
336 ret = gnutls_privkey_import_openpgp_raw( pgp_key, &data, x509ctype, NULL, NULL);
337 if (ret < 0)
339 fprintf (stderr, "*** Error loading url: %s\n",
340 gnutls_strerror (ret));
341 exit (1);
344 gnutls_free(data.data);
348 fprintf (stdout, "Processed 1 client PGP certificate...\n");
350 #endif
354 #define IS_NEWLINE(x) ((x[0] == '\n') || (x[0] == '\r'))
355 static int
356 read_yesno (const char *input_str)
358 char input[128];
360 fputs (input_str, stderr);
361 if (fgets (input, sizeof (input), stdin) == NULL)
362 return 0;
364 if (IS_NEWLINE(input))
365 return 0;
367 if (input[0] == 'y' || input[0] == 'Y')
368 return 1;
370 return 0;
373 /* converts a textual service or port to
374 * a service.
376 static const char* port_to_service(const char* sport)
378 unsigned int port;
379 struct servent * sr;
381 port = atoi(sport);
382 if (port == 0) return sport;
384 port = htons(port);
386 sr = getservbyport(port, udp?"udp":"tcp");
387 if (sr == NULL)
389 fprintf(stderr, "Warning: getservbyport() failed. Using port number as service.\n");
390 return sport;
393 return sr->s_name;
396 static int
397 cert_verify_callback (gnutls_session_t session)
399 int rc;
400 unsigned int status = 0;
401 int ssh = ENABLED_OPT(TOFU);
402 #ifdef HAVE_DANE
403 int dane = ENABLED_OPT(DANE);
404 #endif
405 int ca_verify = ENABLED_OPT(CA_VERIFICATION);
406 const char* txt_service;
408 print_cert_info (session, verbose, print_cert);
410 if (ca_verify)
412 rc = cert_verify(session, hostname);
413 if (rc == 0)
415 printf ("*** Verifying server certificate failed...\n");
416 if (!insecure && !ssh)
417 return -1;
419 else if (ENABLED_OPT(OCSP))
420 { /* off-line verification succeeded. Try OCSP */
421 rc = cert_verify_ocsp(session);
422 if (rc == 0)
424 printf ("*** Verifying (with OCSP) server certificate failed...\n");
425 if (!insecure && !ssh)
426 return -1;
428 else if (rc == -1)
429 printf("*** OCSP response ignored\n");
433 if (ssh) /* try ssh auth */
435 unsigned int list_size;
436 const gnutls_datum_t * cert;
438 cert = gnutls_certificate_get_peers(session, &list_size);
439 if (cert == NULL)
441 fprintf(stderr, "Cannot obtain peer's certificate!\n");
442 return -1;
445 txt_service = port_to_service(service);
447 rc = gnutls_verify_stored_pubkey(NULL, NULL, hostname, txt_service,
448 GNUTLS_CRT_X509, cert, 0);
449 if (rc == GNUTLS_E_NO_CERTIFICATE_FOUND)
451 print_cert_info_compact(session);
452 fprintf(stderr, "Host %s (%s) has never been contacted before.\n", hostname, txt_service);
453 if (status == 0)
454 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
456 rc = read_yesno("Are you sure you want to trust it? (y/N): ");
457 if (rc == 0)
458 return -1;
460 else if (rc == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
462 print_cert_info_compact(session);
463 fprintf(stderr, "Warning: host %s is known and it is associated with a different key.\n", hostname);
464 fprintf(stderr, "It might be that the server has multiple keys, or an attacker replaced the key to eavesdrop this connection .\n");
465 if (status == 0)
466 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
468 rc = read_yesno("Do you trust the received key? (y/N): ");
469 if (rc == 0)
470 return -1;
472 else if (rc < 0)
474 fprintf(stderr, "gnutls_verify_stored_pubkey: %s\n", gnutls_strerror(rc));
475 return -1;
478 if (rc != 0)
480 rc = gnutls_store_pubkey(NULL, NULL, hostname, txt_service,
481 GNUTLS_CRT_X509, cert, 0, 0);
482 if (rc < 0)
483 fprintf(stderr, "Could not store key: %s\n", gnutls_strerror(rc));
487 #ifdef HAVE_DANE
488 if (dane) /* try DANE auth */
490 unsigned int sflags = ENABLED_OPT(LOCAL_DNS)?0:DANE_F_IGNORE_LOCAL_RESOLVER;
491 rc = dane_verify_session_crt( NULL, session, hostname, udp?"udp":"tcp", atoi(service),
492 sflags, 0, &status);
493 if (rc < 0)
495 fprintf(stderr, "*** DANE verification error: %s\n", dane_strerror(rc));
496 if (!insecure)
497 return -1;
499 else
501 gnutls_datum_t out;
503 rc = dane_verification_status_print( status, &out, 0);
504 if (rc < 0)
506 fprintf(stderr, "*** DANE error: %s\n", dane_strerror(rc));
507 if (!insecure)
508 return -1;
511 fprintf(stderr, "- %s\n", out.data);
512 gnutls_free(out.data);
516 #endif
518 return 0;
521 /* This callback should be associated with a session by calling
522 * gnutls_certificate_client_set_retrieve_function( session, cert_callback),
523 * before a handshake.
526 static int
527 cert_callback (gnutls_session_t session,
528 const gnutls_datum_t * req_ca_rdn, int nreqs,
529 const gnutls_pk_algorithm_t * sign_algos,
530 int sign_algos_length, gnutls_pcert_st **pcert,
531 unsigned int *pcert_length, gnutls_privkey_t * pkey)
533 char issuer_dn[256];
534 int i, ret, cert_type;
535 size_t len;
537 if (verbose)
539 /* Print the server's trusted CAs
541 if (nreqs > 0)
542 printf ("- Server's trusted authorities:\n");
543 else
544 printf ("- Server did not send us any trusted authorities names.\n");
546 /* print the names (if any) */
547 for (i = 0; i < nreqs; i++)
549 len = sizeof (issuer_dn);
550 ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len);
551 if (ret >= 0)
553 printf (" [%d]: ", i);
554 printf ("%s\n", issuer_dn);
559 /* Select a certificate and return it.
560 * The certificate must be of any of the "sign algorithms"
561 * supported by the server.
564 cert_type = gnutls_certificate_type_get (session);
566 *pcert_length = 0;
568 if (cert_type == GNUTLS_CRT_X509)
570 if (x509_crt_size > 0)
572 if (x509_key != NULL)
574 *pkey = x509_key;
576 else
578 printf ("- Could not find a suitable key to send to server\n");
579 return -1;
582 *pcert_length = x509_crt_size;
583 *pcert = x509_crt;
587 else if (cert_type == GNUTLS_CRT_OPENPGP)
589 if (pgp_key != NULL)
591 *pkey = pgp_key;
593 *pcert_length = 1;
594 *pcert = &pgp_crt;
598 printf ("- Successfully sent %u certificate(s) to server.\n", *pcert_length);
599 return 0;
603 /* initializes a gnutls_session_t with some defaults.
605 static gnutls_session_t
606 init_tls_session (const char *hostname)
608 const char *err;
609 int ret;
610 gnutls_session_t session;
612 if (priorities == NULL)
613 priorities = "NORMAL";
615 if (udp)
617 gnutls_init (&session, GNUTLS_DATAGRAM|init_flags);
618 if (mtu)
619 gnutls_dtls_set_mtu(session, mtu);
621 else
622 gnutls_init (&session, init_flags);
624 if ((ret = gnutls_priority_set_direct (session, priorities, &err)) < 0)
626 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
627 else
628 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
629 exit (1);
632 /* allow the use of private ciphersuites.
634 if (disable_extensions == 0)
636 if (!isdigit(hostname[0]) && strchr(hostname, ':') == 0)
637 gnutls_server_name_set (session, GNUTLS_NAME_DNS, hostname,
638 strlen (hostname));
641 if (HAVE_OPT(DH_BITS))
642 gnutls_dh_set_prime_bits( session, OPT_VALUE_DH_BITS);
644 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anon_cred);
645 if (srp_cred)
646 gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
647 if (psk_cred)
648 gnutls_credentials_set (session, GNUTLS_CRD_PSK, psk_cred);
649 gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
651 gnutls_certificate_set_retrieve_function2 (xcred, cert_callback);
652 gnutls_certificate_set_verify_function (xcred, cert_verify_callback);
654 /* send the fingerprint */
655 #ifdef ENABLE_OPENPGP
656 if (fingerprint != 0)
657 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
658 #endif
660 /* use the max record size extension */
661 if (record_max_size > 0 && disable_extensions == 0)
663 if (gnutls_record_set_max_size (session, record_max_size) < 0)
665 fprintf (stderr,
666 "Cannot set the maximum record size to %d.\n",
667 record_max_size);
668 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
669 exit (1);
673 if (HAVE_OPT(HEARTBEAT))
674 gnutls_heartbeat_enable (session, GNUTLS_HB_PEER_ALLOWED_TO_SEND);
676 if (HAVE_OPT(SRTP_PROFILES))
678 ret = gnutls_srtp_set_profile_direct (session, OPT_ARG(SRTP_PROFILES), &err);
679 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
680 else
681 fprintf(stderr, "Error in profiles: %s\n", gnutls_strerror(ret));
682 exit (1);
685 return session;
688 static void cmd_parser (int argc, char **argv);
690 /* Returns zero if the error code was successfully handled.
692 static int
693 handle_error (socket_st * hd, int err)
695 int alert, ret;
696 const char *err_type, *str;
698 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
699 return 0;
701 if (gnutls_error_is_fatal (err) == 0)
703 ret = 0;
704 err_type = "Non fatal";
706 else
708 ret = err;
709 err_type = "Fatal";
712 str = gnutls_strerror (err);
713 if (str == NULL)
714 str = str_unknown;
715 fprintf (stderr, "*** %s error: %s\n", err_type, str);
717 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
718 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
720 alert = gnutls_alert_get (hd->session);
721 str = gnutls_alert_get_name (alert);
722 if (str == NULL)
723 str = str_unknown;
724 printf ("*** Received alert [%d]: %s\n", alert, str);
727 check_rehandshake (hd, err);
729 return ret;
732 int starttls_alarmed = 0;
734 #ifndef _WIN32
735 static void
736 starttls_alarm (int signum)
738 starttls_alarmed = 1;
740 #endif
742 static void
743 tls_log_func (int level, const char *str)
745 fprintf (stderr, "|<%d>| %s", level, str);
748 #define IN_KEYBOARD 1
749 #define IN_NET 2
750 #define IN_NONE 0
751 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
753 static int check_net_or_keyboard_input(socket_st* hd)
755 int maxfd;
756 fd_set rset;
757 int err;
758 struct timeval tv;
762 FD_ZERO (&rset);
763 FD_SET (hd->fd, &rset);
765 #ifndef _WIN32
766 FD_SET (fileno (stdin), &rset);
767 maxfd = MAX (fileno (stdin), hd->fd);
768 #else
769 maxfd = hd->fd;
770 #endif
772 tv.tv_sec = 0;
773 tv.tv_usec = 50 * 1000;
775 if (hd->secure == 1)
776 if (gnutls_record_check_pending(hd->session))
777 return IN_NET;
779 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
780 if (err < 0)
781 continue;
783 if (FD_ISSET (hd->fd, &rset))
784 return IN_NET;
786 #ifdef _WIN32
788 int state;
789 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
791 if (state == WAIT_OBJECT_0)
792 return IN_KEYBOARD;
794 #else
795 if (FD_ISSET (fileno (stdin), &rset))
796 return IN_KEYBOARD;
797 #endif
799 while(err == 0);
801 return IN_NONE;
805 main (int argc, char **argv)
807 int ret;
808 int ii, i, inp;
809 char buffer[MAX_BUF + 1];
810 char *session_data = NULL;
811 char *session_id = NULL;
812 size_t session_data_size;
813 size_t session_id_size = 0;
814 int user_term = 0, retval = 0;
815 socket_st hd;
816 ssize_t bytes;
818 set_program_name (argv[0]);
819 cmd_parser (argc, argv);
821 gnutls_global_set_log_function (tls_log_func);
822 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
824 if ((ret = gnutls_global_init ()) < 0)
826 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
827 exit (1);
830 #ifdef ENABLE_PKCS11
831 // pkcs11_common ();
832 #endif
834 if (hostname == NULL)
836 fprintf (stderr, "No hostname given\n");
837 exit (1);
840 sockets_init ();
842 init_global_tls_stuff ();
844 socket_open (&hd, hostname, service, udp);
845 socket_connect (&hd);
847 hd.session = init_tls_session (hostname);
848 if (starttls)
849 goto after_handshake;
851 for (i = 0; i < 2; i++)
855 if (i == 1)
857 hd.session = init_tls_session (hostname);
858 gnutls_session_set_data (hd.session, session_data,
859 session_data_size);
860 free (session_data);
863 ret = do_handshake (&hd);
865 if (ret < 0)
867 fprintf (stderr, "*** Handshake has failed\n");
868 gnutls_perror (ret);
869 gnutls_deinit (hd.session);
870 return 1;
872 else
874 printf ("- Handshake was completed\n");
875 if (gnutls_session_is_resumed (hd.session) != 0)
876 printf ("*** This is a resumed session\n");
879 if (resume != 0 && i == 0)
882 gnutls_session_get_data (hd.session, NULL, &session_data_size);
883 session_data = malloc (session_data_size);
885 gnutls_session_get_data (hd.session, session_data,
886 &session_data_size);
888 gnutls_session_get_id (hd.session, NULL, &session_id_size);
890 session_id = malloc (session_id_size);
891 gnutls_session_get_id (hd.session, session_id, &session_id_size);
893 printf ("- Disconnecting\n");
894 socket_bye (&hd);
896 printf
897 ("\n\n- Connecting again- trying to resume previous session\n");
898 socket_open (&hd, hostname, service, udp);
899 socket_connect (&hd);
901 else
903 break;
907 after_handshake:
909 /* Warning! Do not touch this text string, it is used by external
910 programs to search for when gnutls-cli has reached this point. */
911 printf ("\n- Simple Client Mode:\n\n");
913 if (rehandshake)
915 ret = do_handshake (&hd);
917 if (ret < 0)
919 fprintf (stderr, "*** ReHandshake has failed\n");
920 gnutls_perror (ret);
921 gnutls_deinit (hd.session);
922 return 1;
924 else
926 printf ("- ReHandshake was completed\n");
930 #ifndef _WIN32
931 signal (SIGALRM, &starttls_alarm);
932 #endif
934 fflush (stdout);
935 fflush (stderr);
937 /* do not buffer */
938 #ifndef _WIN32
939 setbuf (stdin, NULL);
940 #endif
941 setbuf (stdout, NULL);
942 setbuf (stderr, NULL);
944 for (;;)
946 if (starttls_alarmed && !hd.secure)
948 /* Warning! Do not touch this text string, it is used by
949 external programs to search for when gnutls-cli has
950 reached this point. */
951 fprintf (stderr, "*** Starting TLS handshake\n");
952 ret = do_handshake (&hd);
953 if (ret < 0)
955 fprintf (stderr, "*** Handshake has failed\n");
956 user_term = 1;
957 retval = 1;
958 break;
962 inp = check_net_or_keyboard_input(&hd);
964 if (inp == IN_NET)
966 memset (buffer, 0, MAX_BUF + 1);
967 ret = socket_recv (&hd, buffer, MAX_BUF);
969 if (ret == 0)
971 printf ("- Peer has closed the GnuTLS connection\n");
972 break;
974 else if (handle_error (&hd, ret) < 0 && user_term == 0)
976 fprintf (stderr,
977 "*** Server has terminated the connection abnormally.\n");
978 retval = 1;
979 break;
981 else if (ret > 0)
983 if (verbose != 0)
984 printf ("- Received[%d]: ", ret);
985 for (ii = 0; ii < ret; ii++)
987 fputc (buffer[ii], stdout);
989 fflush (stdout);
992 if (user_term != 0)
993 break;
996 if (inp == IN_KEYBOARD)
998 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
1000 if (hd.secure == 0)
1002 /* Warning! Do not touch this text string, it is
1003 used by external programs to search for when
1004 gnutls-cli has reached this point. */
1005 fprintf (stderr, "*** Starting TLS handshake\n");
1006 ret = do_handshake (&hd);
1007 clearerr (stdin);
1008 if (ret < 0)
1010 fprintf (stderr, "*** Handshake has failed\n");
1011 user_term = 1;
1012 retval = 1;
1013 break;
1016 else
1018 user_term = 1;
1019 break;
1021 continue;
1024 buffer[bytes] = 0;
1025 if (crlf != 0)
1027 char *b = strchr (buffer, '\n');
1028 if (b != NULL)
1030 strcpy (b, "\r\n");
1031 bytes++;
1035 ret = socket_send (&hd, buffer, bytes);
1037 if (ret > 0)
1039 if (verbose != 0)
1040 printf ("- Sent: %d bytes\n", ret);
1042 else
1043 handle_error (&hd, ret);
1048 if (user_term != 0)
1049 socket_bye (&hd);
1050 else
1051 gnutls_deinit (hd.session);
1053 #ifdef ENABLE_SRP
1054 if (srp_cred)
1055 gnutls_srp_free_client_credentials (srp_cred);
1056 #endif
1057 #ifdef ENABLE_PSK
1058 if (psk_cred)
1059 gnutls_psk_free_client_credentials (psk_cred);
1060 #endif
1062 gnutls_certificate_free_credentials (xcred);
1064 #ifdef ENABLE_ANON
1065 gnutls_anon_free_client_credentials (anon_cred);
1066 #endif
1068 gnutls_global_deinit ();
1070 return retval;
1073 static void
1074 cmd_parser (int argc, char **argv)
1076 const char* rest = NULL;
1078 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1079 argc -= optct;
1080 argv += optct;
1082 if (rest == NULL && argc > 0)
1083 rest = argv[0];
1085 if (HAVE_OPT(BENCHMARK_CIPHERS))
1087 benchmark_cipher(1, OPT_VALUE_DEBUG);
1088 exit(0);
1091 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1093 benchmark_cipher(0, OPT_VALUE_DEBUG);
1094 exit(0);
1097 if (HAVE_OPT(BENCHMARK_TLS_CIPHERS))
1099 benchmark_tls(OPT_VALUE_DEBUG, 1);
1100 exit(0);
1103 if (HAVE_OPT(BENCHMARK_TLS_KX))
1105 benchmark_tls(OPT_VALUE_DEBUG, 0);
1106 exit(0);
1109 if (HAVE_OPT(PRIORITY))
1111 priorities = OPT_ARG(PRIORITY);
1113 verbose = HAVE_OPT( VERBOSE);
1114 if (verbose)
1115 print_cert = 1;
1116 else
1117 print_cert = HAVE_OPT( PRINT_CERT);
1119 if (HAVE_OPT(LIST))
1121 print_list(priorities, verbose);
1122 exit(0);
1125 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1126 if (disable_extensions)
1127 init_flags |= GNUTLS_NO_EXTENSIONS;
1129 starttls = HAVE_OPT(STARTTLS);
1130 resume = HAVE_OPT(RESUME);
1131 rehandshake = HAVE_OPT(REHANDSHAKE);
1132 insecure = HAVE_OPT(INSECURE);
1134 udp = HAVE_OPT(UDP);
1135 mtu = OPT_VALUE_MTU;
1137 if (HAVE_OPT(PORT))
1139 service = OPT_ARG(PORT);
1141 else
1143 service = "443";
1146 record_max_size = OPT_VALUE_RECORDSIZE;
1147 status_request_ocsp = ENABLED_OPT(OCSP_STATUS_REQUEST);
1148 if (ENABLED_OPT(OCSP))
1149 status_request_ocsp = 1;
1151 fingerprint = HAVE_OPT(FINGERPRINT);
1153 if (HAVE_OPT(X509FMTDER))
1154 x509ctype = GNUTLS_X509_FMT_DER;
1155 else
1156 x509ctype = GNUTLS_X509_FMT_PEM;
1158 if (HAVE_OPT(SRPUSERNAME))
1159 srp_username = OPT_ARG(SRPUSERNAME);
1161 if (HAVE_OPT(SRPPASSWD))
1162 srp_passwd = OPT_ARG(SRPPASSWD);
1164 if (HAVE_OPT(X509CAFILE))
1165 x509_cafile = OPT_ARG(X509CAFILE);
1167 if (HAVE_OPT(X509CRLFILE))
1168 x509_crlfile = OPT_ARG(X509CRLFILE);
1170 if (HAVE_OPT(X509KEYFILE))
1171 x509_keyfile = OPT_ARG(X509KEYFILE);
1173 if (HAVE_OPT(X509CERTFILE))
1174 x509_certfile = OPT_ARG(X509CERTFILE);
1176 if (HAVE_OPT(PGPKEYFILE))
1177 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1179 if (HAVE_OPT(PGPCERTFILE))
1180 pgp_certfile = OPT_ARG(PGPCERTFILE);
1182 if (HAVE_OPT(PSKUSERNAME))
1183 psk_username = OPT_ARG(PSKUSERNAME);
1185 if (HAVE_OPT(PSKKEY))
1187 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1188 psk_key.size = strlen (OPT_ARG(PSKKEY));
1190 else
1191 psk_key.size = 0;
1193 if (HAVE_OPT(PGPKEYRING))
1194 pgp_keyring = OPT_ARG(PGPKEYRING);
1196 crlf = HAVE_OPT(CRLF);
1198 if (rest != NULL)
1199 hostname = rest;
1201 if (hostname == NULL)
1203 fprintf(stderr, "No hostname specified\n");
1204 exit(1);
1208 static void
1209 check_rehandshake (socket_st * socket, int ret)
1211 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1213 /* There is a race condition here. If application
1214 * data is sent after the rehandshake request,
1215 * the server thinks we ignored his request.
1216 * This is a bad design of this client.
1218 printf ("*** Received rehandshake request\n");
1219 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1221 ret = do_handshake (socket);
1223 if (ret == 0)
1225 printf ("*** Rehandshake was performed.\n");
1227 else
1229 printf ("*** Rehandshake Failed.\n");
1235 static int
1236 do_handshake (socket_st * socket)
1238 int ret;
1240 gnutls_transport_set_ptr (socket->session,
1241 (gnutls_transport_ptr_t)
1242 gl_fd_to_handle (socket->fd));
1245 gnutls_handshake_set_timeout( socket->session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
1246 ret = gnutls_handshake (socket->session);
1248 if (ret < 0)
1250 handle_error (socket, ret);
1253 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1255 if (ret == 0)
1257 /* print some information */
1258 print_info (socket->session, verbose, 0);
1259 socket->secure = 1;
1261 else
1263 gnutls_alert_send_appropriate (socket->session, ret);
1264 shutdown (socket->fd, SHUT_RDWR);
1266 return ret;
1269 static int
1270 srp_username_callback (gnutls_session_t session,
1271 char **username, char **password)
1273 if (srp_username == NULL || srp_passwd == NULL)
1275 return -1;
1278 *username = gnutls_strdup (srp_username);
1279 *password = gnutls_strdup (srp_passwd);
1281 return 0;
1284 static int
1285 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1287 const char *hint = gnutls_psk_client_get_hint (session);
1288 char *rawkey;
1289 char *passwd;
1290 int ret;
1291 size_t res_size;
1292 gnutls_datum_t tmp;
1294 printf ("- PSK client callback. ");
1295 if (hint)
1296 printf ("PSK hint '%s'\n", hint);
1297 else
1298 printf ("No PSK hint\n");
1300 if (HAVE_OPT(PSKUSERNAME))
1301 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1302 else
1304 char *tmp = NULL;
1305 size_t n;
1307 printf ("Enter PSK identity: ");
1308 fflush (stdout);
1309 getline (&tmp, &n, stdin);
1311 if (tmp == NULL)
1313 fprintf (stderr, "No username given, aborting...\n");
1314 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1317 if (tmp[strlen (tmp) - 1] == '\n')
1318 tmp[strlen (tmp) - 1] = '\0';
1319 if (tmp[strlen (tmp) - 1] == '\r')
1320 tmp[strlen (tmp) - 1] = '\0';
1322 *username = gnutls_strdup (tmp);
1323 free (tmp);
1325 if (!*username)
1326 return GNUTLS_E_MEMORY_ERROR;
1328 passwd = getpass ("Enter key: ");
1329 if (passwd == NULL)
1331 fprintf (stderr, "No key given, aborting...\n");
1332 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1335 tmp.data = (void*)passwd;
1336 tmp.size = strlen (passwd);
1338 res_size = tmp.size / 2 + 1;
1339 rawkey = gnutls_malloc (res_size);
1340 if (rawkey == NULL)
1341 return GNUTLS_E_MEMORY_ERROR;
1343 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1344 if (ret < 0)
1346 fprintf (stderr, "Error deriving password: %s\n",
1347 gnutls_strerror (ret));
1348 gnutls_free (*username);
1349 return ret;
1352 key->data = (void*)rawkey;
1353 key->size = res_size;
1355 if (HAVE_OPT(DEBUG))
1357 char hexkey[41];
1358 res_size = sizeof (hexkey);
1359 gnutls_hex_encode (key, hexkey, &res_size);
1360 fprintf (stderr, "PSK username: %s\n", *username);
1361 fprintf (stderr, "PSK hint: %s\n", hint);
1362 fprintf (stderr, "PSK key: %s\n", hexkey);
1365 return 0;
1368 static void
1369 init_global_tls_stuff (void)
1371 int ret;
1373 /* X509 stuff */
1374 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1376 fprintf (stderr, "Certificate allocation memory error\n");
1377 exit (1);
1379 gnutls_certificate_set_pin_function(xcred, pin_callback, NULL);
1381 if (x509_cafile != NULL)
1383 ret = gnutls_certificate_set_x509_trust_file (xcred,
1384 x509_cafile, x509ctype);
1386 else
1388 ret = gnutls_certificate_set_x509_system_trust (xcred);
1390 if (ret < 0)
1392 fprintf (stderr, "Error setting the x509 trust file\n");
1394 else
1396 printf ("Processed %d CA certificate(s).\n", ret);
1399 if (x509_crlfile != NULL)
1401 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1402 x509ctype);
1403 if (ret < 0)
1405 fprintf (stderr, "Error setting the x509 CRL file\n");
1407 else
1409 printf ("Processed %d CRL(s).\n", ret);
1413 load_keys ();
1415 #ifdef ENABLE_OPENPGP
1416 if (pgp_keyring != NULL)
1418 ret =
1419 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1420 GNUTLS_OPENPGP_FMT_BASE64);
1421 if (ret < 0)
1423 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1426 #endif
1428 #ifdef ENABLE_SRP
1429 if (srp_username && srp_passwd)
1431 /* SRP stuff */
1432 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1434 fprintf (stderr, "SRP authentication error\n");
1437 gnutls_srp_set_client_credentials_function (srp_cred,
1438 srp_username_callback);
1440 #endif
1442 #ifdef ENABLE_PSK
1443 /* PSK stuff */
1444 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1446 fprintf (stderr, "PSK authentication error\n");
1449 if (psk_username && psk_key.data)
1451 ret = gnutls_psk_set_client_credentials (psk_cred,
1452 psk_username, &psk_key,
1453 GNUTLS_PSK_KEY_HEX);
1454 if (ret < 0)
1456 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1457 gnutls_strerror (ret));
1460 else
1461 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1462 #endif
1464 #ifdef ENABLE_ANON
1465 /* ANON stuff */
1466 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1468 fprintf (stderr, "Anonymous authentication error\n");
1470 #endif
1474 /* OCSP check for the peer's certificate. Should be called
1475 * only after the certificate list verication is complete.
1476 * Returns:
1477 * 0: certificate is revoked
1478 * 1: certificate is ok
1479 * -1: dunno
1481 static int
1482 cert_verify_ocsp (gnutls_session_t session)
1484 gnutls_x509_crt_t crt, issuer;
1485 const gnutls_datum_t *cert_list;
1486 unsigned int cert_list_size = 0;
1487 int deinit_issuer = 0;
1488 gnutls_datum_t resp;
1489 int ret;
1491 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1492 if (cert_list_size == 0)
1494 fprintf (stderr, "No certificates found!\n");
1495 return -1;
1498 gnutls_x509_crt_init (&crt);
1499 ret =
1500 gnutls_x509_crt_import (crt, &cert_list[0],
1501 GNUTLS_X509_FMT_DER);
1502 if (ret < 0)
1504 fprintf (stderr, "Decoding error: %s\n",
1505 gnutls_strerror (ret));
1506 return -1;
1509 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1510 if (ret < 0 && cert_list_size > 1)
1512 gnutls_x509_crt_init(&issuer);
1513 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1514 if (ret < 0)
1516 fprintf (stderr, "Decoding error: %s\n",
1517 gnutls_strerror (ret));
1518 return -1;
1520 deinit_issuer = 1;
1522 else if (ret < 0)
1524 fprintf(stderr, "Cannot find issuer\n");
1525 ret = -1;
1526 goto cleanup;
1529 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1530 if (ret < 0)
1532 fprintf(stderr, "Cannot contact OCSP server\n");
1533 ret = -1;
1534 goto cleanup;
1537 /* verify and check the response for revoked cert */
1538 ret = check_ocsp_response(crt, issuer, &resp);
1540 cleanup:
1541 if (deinit_issuer)
1542 gnutls_x509_crt_deinit (issuer);
1543 gnutls_x509_crt_deinit (crt);
1545 return ret;