Added doc-skip to skip certain functions from documentation.
[gnutls.git] / src / cli.c
blob3f13a46812d692fa5e1a6b8f361361ef43e4e3e4
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 <gettext.h>
62 #include <cli-args.h>
63 #include <ocsptool-common.h>
65 #define MAX_BUF 4096
67 /* global stuff here */
68 int resume, starttls, insecure, rehandshake, udp, mtu;
69 const char *hostname = NULL;
70 const char *service = NULL;
71 int record_max_size;
72 int fingerprint;
73 int crlf;
74 unsigned int verbose = 0;
75 int print_cert;
77 #define DEFAULT_CA_FILE "/etc/ssl/certs/ca-certificates.crt"
79 const char *srp_passwd = NULL;
80 const char *srp_username = NULL;
81 const char *pgp_keyfile = NULL;
82 const char *pgp_certfile = NULL;
83 const char *pgp_keyring = NULL;
84 const char *x509_keyfile = NULL;
85 const char *x509_certfile = NULL;
86 const char *x509_cafile = NULL;
87 const char *x509_crlfile = NULL;
88 static int x509ctype;
89 static int disable_extensions;
90 static const char * priorities = NULL;
92 const char *psk_username = NULL;
93 gnutls_datum_t psk_key = { NULL, 0 };
95 static gnutls_srp_client_credentials_t srp_cred;
96 static gnutls_psk_client_credentials_t psk_cred;
97 static gnutls_anon_client_credentials_t anon_cred;
98 static gnutls_certificate_credentials_t xcred;
100 /* end of global stuff */
102 /* prototypes */
104 static void check_rehandshake (socket_st * socket, int ret);
105 static int do_handshake (socket_st * socket);
106 static void init_global_tls_stuff (void);
107 static int cert_verify_ocsp (gnutls_session_t session);
109 /* Helper functions to load a certificate and key
110 * files into memory.
112 static gnutls_datum_t
113 load_file (const char *file)
115 gnutls_datum_t loaded_file = { NULL, 0 };
116 size_t length;
118 loaded_file.data = (void*)read_binary_file (file, &length);
119 if (loaded_file.data)
120 loaded_file.size = (unsigned int) length;
122 return loaded_file;
125 static void
126 unload_file (gnutls_datum_t* data)
128 free (data->data);
131 #define MAX_CRT 6
132 static unsigned int x509_crt_size;
133 static gnutls_pcert_st x509_crt[MAX_CRT];
134 static gnutls_privkey_t x509_key = NULL;
136 static gnutls_pcert_st pgp_crt;
137 static gnutls_privkey_t pgp_key = NULL;
139 static void
140 get_keyid (gnutls_openpgp_keyid_t keyid, const char *str)
142 size_t keyid_size = sizeof (keyid);
144 if (strlen (str) != 16)
146 fprintf (stderr,
147 "The OpenPGP subkey ID has to be 16 hexadecimal characters.\n");
148 exit (1);
151 if (gnutls_hex2bin (str, strlen (str), keyid, &keyid_size) < 0)
153 fprintf (stderr, "Error converting hex string: %s.\n", str);
154 exit (1);
157 return;
160 /* Load the certificate and the private key.
162 static void
163 load_keys (void)
165 unsigned int crt_num;
166 int ret;
167 unsigned int i;
168 gnutls_datum_t data = { NULL, 0 };
169 gnutls_x509_crt_t crt_list[MAX_CRT];
170 #ifdef ENABLE_PKCS11
171 gnutls_pkcs11_privkey_t pkcs11_key;
172 #endif
173 gnutls_x509_privkey_t tmp_key;
174 unsigned char keyid[GNUTLS_OPENPGP_KEYID_SIZE];
176 if (x509_certfile != NULL && x509_keyfile != NULL)
178 #ifdef ENABLE_PKCS11
179 if (strncmp (x509_certfile, "pkcs11:", 7) == 0)
181 crt_num = 1;
182 gnutls_x509_crt_init (&crt_list[0]);
184 ret =
185 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile, 0);
187 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
188 ret =
189 gnutls_x509_crt_import_pkcs11_url (crt_list[0], x509_certfile,
190 GNUTLS_PKCS11_OBJ_FLAG_LOGIN);
192 if (ret < 0)
194 fprintf (stderr, "*** Error loading cert file.\n");
195 exit (1);
197 x509_crt_size = 1;
199 else
200 #endif /* ENABLE_PKCS11 */
203 data = load_file (x509_certfile);
204 if (data.data == NULL)
206 fprintf (stderr, "*** Error loading cert file.\n");
207 exit (1);
210 crt_num = MAX_CRT;
211 ret =
212 gnutls_x509_crt_list_import (crt_list, &crt_num, &data,
213 x509ctype,
214 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
215 if (ret < 0)
217 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
219 fprintf (stderr,
220 "*** Error loading cert file: Too many certs %d\n",
221 crt_num);
224 else
226 fprintf (stderr,
227 "*** Error loading cert file: %s\n",
228 gnutls_strerror (ret));
230 exit (1);
232 x509_crt_size = ret;
235 for (i=0;i<x509_crt_size;i++)
237 ret = gnutls_pcert_import_x509(&x509_crt[i], crt_list[i], 0);
238 if (ret < 0)
240 fprintf(stderr, "*** Error importing crt to pcert: %s\n",
241 gnutls_strerror(ret));
242 exit(1);
244 gnutls_x509_crt_deinit(crt_list[i]);
247 unload_file (&data);
249 ret = gnutls_privkey_init(&x509_key);
250 if (ret < 0)
252 fprintf (stderr, "*** Error initializing key: %s\n",
253 gnutls_strerror (ret));
254 exit (1);
257 #ifdef ENABLE_PKCS11
258 if (strncmp (x509_keyfile, "pkcs11:", 7) == 0)
260 gnutls_pkcs11_privkey_init (&pkcs11_key);
262 ret =
263 gnutls_pkcs11_privkey_import_url (pkcs11_key, x509_keyfile, 0);
264 if (ret < 0)
266 fprintf (stderr, "*** Error loading url: %s\n",
267 gnutls_strerror (ret));
268 exit (1);
271 ret = gnutls_privkey_import_pkcs11( x509_key, pkcs11_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
272 if (ret < 0)
274 fprintf (stderr, "*** Error loading url: %s\n",
275 gnutls_strerror (ret));
276 exit (1);
279 else
280 #endif /* ENABLE_PKCS11 */
282 data = load_file (x509_keyfile);
283 if (data.data == NULL)
285 fprintf (stderr, "*** Error loading key file.\n");
286 exit (1);
289 gnutls_x509_privkey_init (&tmp_key);
291 ret =
292 gnutls_x509_privkey_import (tmp_key, &data, x509ctype);
293 if (ret < 0)
295 fprintf (stderr, "*** Error loading key file: %s\n",
296 gnutls_strerror (ret));
297 exit (1);
300 ret = gnutls_privkey_import_x509( x509_key, tmp_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
301 if (ret < 0)
303 fprintf (stderr, "*** Error loading url: %s\n",
304 gnutls_strerror (ret));
305 exit (1);
308 unload_file (&data);
311 fprintf (stdout, "Processed %d client X.509 certificates...\n",
312 x509_crt_size);
316 #ifdef ENABLE_OPENPGP
317 if (HAVE_OPT(PGPSUBKEY))
319 get_keyid (keyid, OPT_ARG(PGPSUBKEY));
322 if (pgp_certfile != NULL && pgp_keyfile != NULL)
324 gnutls_openpgp_crt_t tmp_pgp_crt;
326 data = load_file (pgp_certfile);
327 if (data.data == NULL)
329 fprintf (stderr, "*** Error loading PGP cert file.\n");
330 exit (1);
333 gnutls_openpgp_crt_init (&tmp_pgp_crt);
335 ret =
336 gnutls_pcert_import_openpgp_raw (&pgp_crt, &data, GNUTLS_OPENPGP_FMT_BASE64, HAVE_OPT(PGPSUBKEY)?keyid:NULL, 0);
337 if (ret < 0)
339 fprintf (stderr,
340 "*** Error loading PGP cert file: %s\n",
341 gnutls_strerror (ret));
342 exit (1);
345 unload_file (&data);
347 ret = gnutls_privkey_init(&pgp_key);
348 if (ret < 0)
350 fprintf (stderr, "*** Error initializing key: %s\n",
351 gnutls_strerror (ret));
352 exit (1);
355 #ifdef ENABLE_PKCS11
356 if (strncmp (pgp_keyfile, "pkcs11:", 7) == 0)
358 gnutls_pkcs11_privkey_init (&pkcs11_key);
360 ret = gnutls_pkcs11_privkey_import_url (pkcs11_key, pgp_keyfile, 0);
361 if (ret < 0)
363 fprintf (stderr, "*** Error loading url: %s\n",
364 gnutls_strerror (ret));
365 exit (1);
368 ret = gnutls_privkey_import_pkcs11( pgp_key, pkcs11_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
369 if (ret < 0)
371 fprintf (stderr, "*** Error loading url: %s\n",
372 gnutls_strerror (ret));
373 exit (1);
376 else
377 #endif /* ENABLE_PKCS11 */
379 gnutls_openpgp_privkey_t tmp_pgp_key;
381 data = load_file (pgp_keyfile);
382 if (data.data == NULL)
384 fprintf (stderr, "*** Error loading PGP key file.\n");
385 exit (1);
388 gnutls_openpgp_privkey_init (&tmp_pgp_key);
390 ret =
391 gnutls_openpgp_privkey_import (tmp_pgp_key, &data,
392 GNUTLS_OPENPGP_FMT_BASE64, NULL,
394 if (ret < 0)
396 fprintf (stderr,
397 "*** Error loading PGP key file: %s\n",
398 gnutls_strerror (ret));
399 exit (1);
402 if (HAVE_OPT(PGPSUBKEY))
404 ret =
405 gnutls_openpgp_privkey_set_preferred_key_id (tmp_pgp_key, keyid);
406 if (ret < 0)
408 fprintf (stderr,
409 "*** Error setting preferred sub key id (%s): %s\n",
410 OPT_ARG(PGPSUBKEY), gnutls_strerror (ret));
411 exit (1);
415 ret = gnutls_privkey_import_openpgp( pgp_key, tmp_pgp_key, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE);
416 if (ret < 0)
418 fprintf (stderr, "*** Error loading url: %s\n",
419 gnutls_strerror (ret));
420 exit (1);
423 unload_file (&data);
427 fprintf (stdout, "Processed 1 client PGP certificate...\n");
429 #endif
433 #define IS_NEWLINE(x) ((x[0] == '\n') || (x[0] == '\r'))
434 static int
435 read_yesno (const char *input_str)
437 char input[128];
439 fputs (input_str, stderr);
440 if (fgets (input, sizeof (input), stdin) == NULL)
441 return 0;
443 if (IS_NEWLINE(input))
444 return 0;
446 if (input[0] == 'y' || input[0] == 'Y')
447 return 1;
449 return 0;
452 /* converts a textual service or port to
453 * a service.
455 static const char* port_to_service(const char* sport)
457 unsigned int port;
458 struct servent * sr;
460 port = atoi(sport);
461 if (port == 0) return sport;
463 port = htons(port);
465 sr = getservbyport(port, udp?"udp":"tcp");
466 if (sr == NULL)
468 fprintf(stderr, "Warning: getservbyport() failed. Using port number as service.\n");
469 return sport;
472 return sr->s_name;
475 static int
476 cert_verify_callback (gnutls_session_t session)
478 int rc;
479 unsigned int status = 0;
480 int ssh = ENABLED_OPT(TOFU);
481 const char* txt_service;
483 if (!x509_cafile && !pgp_keyring)
484 return 0;
486 rc = cert_verify(session, hostname);
487 if (rc == 0)
489 printf ("*** Verifying server certificate failed...\n");
490 if (!insecure && !ssh)
491 return -1;
493 else if (ENABLED_OPT(OCSP))
494 { /* off-line verification succeeded. Try OCSP */
495 rc = cert_verify_ocsp(session);
496 if (rc == 0)
498 printf ("*** Verifying (with OCSP) server certificate failed...\n");
499 if (!insecure && !ssh)
500 return -1;
502 else if (rc == -1)
503 printf("*** OCSP response ignored\n");
506 if (ssh) /* try ssh auth */
508 unsigned int list_size;
509 const gnutls_datum_t * cert;
511 cert = gnutls_certificate_get_peers(session, &list_size);
512 if (cert == NULL)
514 fprintf(stderr, "Cannot obtain peer's certificate!\n");
515 return -1;
518 txt_service = port_to_service(service);
520 rc = gnutls_verify_stored_pubkey(NULL, NULL, hostname, txt_service,
521 GNUTLS_CRT_X509, cert, 0);
522 if (rc == GNUTLS_E_NO_CERTIFICATE_FOUND)
524 print_cert_info_compact(session);
525 fprintf(stderr, "Host %s (%s) has never been contacted before.\n", hostname, txt_service);
526 if (status == 0)
527 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
529 rc = read_yesno("Are you sure you want to trust it? (y/N): ");
530 if (rc == 0)
531 return -1;
533 else if (rc == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
535 print_cert_info_compact(session);
536 fprintf(stderr, "Warning: host %s is known and it is associated with a different key.\n", hostname);
537 fprintf(stderr, "It might be that the server has multiple keys, or an attacker replaced the key to eavesdrop this connection .\n");
538 if (status == 0)
539 fprintf(stderr, "Its certificate is valid for %s.\n", hostname);
541 rc = read_yesno("Do you trust the received key? (y/N): ");
542 if (rc == 0)
543 return -1;
545 else if (rc < 0)
547 fprintf(stderr, "gnutls_verify_stored_pubkey: %s\n", gnutls_strerror(rc));
548 return -1;
551 if (rc != 0)
553 rc = gnutls_store_pubkey(NULL, NULL, hostname, txt_service,
554 GNUTLS_CRT_X509, cert, 0, 0);
555 if (rc < 0)
556 fprintf(stderr, "Could not store key: %s\n", gnutls_strerror(rc));
560 return 0;
563 /* This callback should be associated with a session by calling
564 * gnutls_certificate_client_set_retrieve_function( session, cert_callback),
565 * before a handshake.
568 static int
569 cert_callback (gnutls_session_t session,
570 const gnutls_datum_t * req_ca_rdn, int nreqs,
571 const gnutls_pk_algorithm_t * sign_algos,
572 int sign_algos_length, gnutls_pcert_st **pcert,
573 unsigned int *pcert_length, gnutls_privkey_t * pkey)
575 char issuer_dn[256];
576 int i, ret, cert_type;
577 size_t len;
579 if (verbose)
581 /* Print the server's trusted CAs
583 if (nreqs > 0)
584 printf ("- Server's trusted authorities:\n");
585 else
586 printf ("- Server did not send us any trusted authorities names.\n");
588 /* print the names (if any) */
589 for (i = 0; i < nreqs; i++)
591 len = sizeof (issuer_dn);
592 ret = gnutls_x509_rdn_get (&req_ca_rdn[i], issuer_dn, &len);
593 if (ret >= 0)
595 printf (" [%d]: ", i);
596 printf ("%s\n", issuer_dn);
601 /* Select a certificate and return it.
602 * The certificate must be of any of the "sign algorithms"
603 * supported by the server.
606 cert_type = gnutls_certificate_type_get (session);
608 *pcert_length = 0;
610 if (cert_type == GNUTLS_CRT_X509)
612 if (x509_crt_size > 0)
614 if (x509_key != NULL)
616 *pkey = x509_key;
618 else
620 printf ("- Could not find a suitable key to send to server\n");
621 return -1;
624 *pcert_length = x509_crt_size;
625 *pcert = x509_crt;
629 else if (cert_type == GNUTLS_CRT_OPENPGP)
631 if (pgp_key != NULL)
633 *pkey = pgp_key;
635 *pcert_length = 1;
636 *pcert = &pgp_crt;
640 printf ("- Successfully sent %u certificate(s) to server.\n", *pcert_length);
641 return 0;
645 /* initializes a gnutls_session_t with some defaults.
647 static gnutls_session_t
648 init_tls_session (const char *hostname)
650 const char *err;
651 int ret;
652 gnutls_session_t session;
654 if (priorities == NULL)
655 priorities = "NORMAL";
657 if (udp)
659 gnutls_init (&session, GNUTLS_CLIENT|GNUTLS_DATAGRAM);
660 if (mtu)
661 gnutls_dtls_set_mtu(session, mtu);
663 else
664 gnutls_init (&session, GNUTLS_CLIENT);
666 if ((ret = gnutls_priority_set_direct (session, priorities, &err)) < 0)
668 if (ret == GNUTLS_E_INVALID_REQUEST) fprintf (stderr, "Syntax error at: %s\n", err);
669 else
670 fprintf(stderr, "Error in priorities: %s\n", gnutls_strerror(ret));
671 exit (1);
674 /* allow the use of private ciphersuites.
676 if (disable_extensions == 0)
678 if (!isdigit(hostname[0]) && strchr(hostname, ':') == 0)
679 gnutls_server_name_set (session, GNUTLS_NAME_DNS, hostname,
680 strlen (hostname));
683 gnutls_dh_set_prime_bits (session, 512);
685 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anon_cred);
686 if (srp_cred)
687 gnutls_credentials_set (session, GNUTLS_CRD_SRP, srp_cred);
688 if (psk_cred)
689 gnutls_credentials_set (session, GNUTLS_CRD_PSK, psk_cred);
690 gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
692 gnutls_certificate_set_retrieve_function2 (xcred, cert_callback);
693 gnutls_certificate_set_verify_function (xcred, cert_verify_callback);
694 gnutls_certificate_set_verify_flags (xcred, 0);
696 /* send the fingerprint */
697 #ifdef ENABLE_OPENPGP
698 if (fingerprint != 0)
699 gnutls_openpgp_send_cert (session, GNUTLS_OPENPGP_CERT_FINGERPRINT);
700 #endif
702 /* use the max record size extension */
703 if (record_max_size > 0 && disable_extensions == 0)
705 if (gnutls_record_set_max_size (session, record_max_size) < 0)
707 fprintf (stderr,
708 "Cannot set the maximum record size to %d.\n",
709 record_max_size);
710 fprintf (stderr, "Possible values: 512, 1024, 2048, 4096.\n");
711 exit (1);
715 #ifdef ENABLE_SESSION_TICKET
716 if (disable_extensions == 0 && !HAVE_OPT(NOTICKET)t)
717 gnutls_session_ticket_enable_client (session);
718 #endif
720 return session;
723 static void cmd_parser (int argc, char **argv);
725 /* Returns zero if the error code was successfully handled.
727 static int
728 handle_error (socket_st * hd, int err)
730 int alert, ret;
731 const char *err_type, *str;
733 if (err >= 0 || err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
734 return 0;
736 if (gnutls_error_is_fatal (err) == 0)
738 ret = 0;
739 err_type = "Non fatal";
741 else
743 ret = err;
744 err_type = "Fatal";
747 str = gnutls_strerror (err);
748 if (str == NULL)
749 str = str_unknown;
750 fprintf (stderr, "*** %s error: %s\n", err_type, str);
752 if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
753 || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
755 alert = gnutls_alert_get (hd->session);
756 str = gnutls_alert_get_name (alert);
757 if (str == NULL)
758 str = str_unknown;
759 printf ("*** Received alert [%d]: %s\n", alert, str);
762 check_rehandshake (hd, err);
764 return ret;
767 int starttls_alarmed = 0;
769 #ifndef _WIN32
770 static void
771 starttls_alarm (int signum)
773 starttls_alarmed = 1;
775 #endif
777 static void
778 tls_log_func (int level, const char *str)
780 fprintf (stderr, "|<%d>| %s", level, str);
783 #define IN_KEYBOARD 1
784 #define IN_NET 2
785 #define IN_NONE 0
786 /* returns IN_KEYBOARD for keyboard input and IN_NET for network input
788 static int check_net_or_keyboard_input(socket_st* hd)
790 int maxfd;
791 fd_set rset;
792 int err;
793 struct timeval tv;
797 FD_ZERO (&rset);
798 FD_SET (hd->fd, &rset);
800 #ifndef _WIN32
801 FD_SET (fileno (stdin), &rset);
802 maxfd = MAX (fileno (stdin), hd->fd);
803 #else
804 maxfd = hd->fd;
805 #endif
807 tv.tv_sec = 0;
808 tv.tv_usec = 50 * 1000;
810 if (hd->secure == 1)
811 if (gnutls_record_check_pending(hd->session))
812 return IN_NET;
814 err = select (maxfd + 1, &rset, NULL, NULL, &tv);
815 if (err < 0)
816 continue;
818 if (FD_ISSET (hd->fd, &rset))
819 return IN_NET;
821 #ifdef _WIN32
823 int state;
824 state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 200);
826 if (state == WAIT_OBJECT_0)
827 return IN_KEYBOARD;
829 #else
830 if (FD_ISSET (fileno (stdin), &rset))
831 return IN_KEYBOARD;
832 #endif
834 while(err == 0);
836 return IN_NONE;
840 main (int argc, char **argv)
842 int ret;
843 int ii, i, inp;
844 char buffer[MAX_BUF + 1];
845 char *session_data = NULL;
846 char *session_id = NULL;
847 size_t session_data_size;
848 size_t session_id_size = 0;
849 int user_term = 0, retval = 0;
850 socket_st hd;
851 ssize_t bytes;
853 set_program_name (argv[0]);
854 cmd_parser (argc, argv);
856 gnutls_global_set_log_function (tls_log_func);
857 gnutls_global_set_log_level (OPT_VALUE_DEBUG);
859 if ((ret = gnutls_global_init ()) < 0)
861 fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
862 exit (1);
865 #ifdef ENABLE_PKCS11
866 pkcs11_common ();
867 #endif
869 if (hostname == NULL)
871 fprintf (stderr, "No hostname given\n");
872 exit (1);
875 sockets_init ();
877 init_global_tls_stuff ();
879 socket_open (&hd, hostname, service, udp);
880 socket_connect (&hd);
882 hd.session = init_tls_session (hostname);
883 if (starttls)
884 goto after_handshake;
886 for (i = 0; i < 2; i++)
890 if (i == 1)
892 hd.session = init_tls_session (hostname);
893 gnutls_session_set_data (hd.session, session_data,
894 session_data_size);
895 free (session_data);
898 ret = do_handshake (&hd);
900 if (ret < 0)
902 fprintf (stderr, "*** Handshake has failed\n");
903 gnutls_perror (ret);
904 gnutls_deinit (hd.session);
905 return 1;
907 else
909 printf ("- Handshake was completed\n");
910 if (gnutls_session_is_resumed (hd.session) != 0)
911 printf ("*** This is a resumed session\n");
914 if (resume != 0 && i == 0)
917 gnutls_session_get_data (hd.session, NULL, &session_data_size);
918 session_data = malloc (session_data_size);
920 gnutls_session_get_data (hd.session, session_data,
921 &session_data_size);
923 gnutls_session_get_id (hd.session, NULL, &session_id_size);
925 session_id = malloc (session_id_size);
926 gnutls_session_get_id (hd.session, session_id, &session_id_size);
928 printf ("- Disconnecting\n");
929 socket_bye (&hd);
931 printf
932 ("\n\n- Connecting again- trying to resume previous session\n");
933 socket_open (&hd, hostname, service, udp);
934 socket_connect (&hd);
936 else
938 break;
942 after_handshake:
944 /* Warning! Do not touch this text string, it is used by external
945 programs to search for when gnutls-cli has reached this point. */
946 printf ("\n- Simple Client Mode:\n\n");
948 if (rehandshake)
950 ret = do_handshake (&hd);
952 if (ret < 0)
954 fprintf (stderr, "*** ReHandshake has failed\n");
955 gnutls_perror (ret);
956 gnutls_deinit (hd.session);
957 return 1;
959 else
961 printf ("- ReHandshake was completed\n");
965 #ifndef _WIN32
966 signal (SIGALRM, &starttls_alarm);
967 #endif
969 fflush (stdout);
970 fflush (stderr);
972 /* do not buffer */
973 #if !(defined _WIN32 || defined __WIN32__)
974 setbuf (stdin, NULL);
975 #endif
976 setbuf (stdout, NULL);
977 setbuf (stderr, NULL);
979 for (;;)
981 if (starttls_alarmed && !hd.secure)
983 /* Warning! Do not touch this text string, it is used by
984 external programs to search for when gnutls-cli has
985 reached this point. */
986 fprintf (stderr, "*** Starting TLS handshake\n");
987 ret = do_handshake (&hd);
988 if (ret < 0)
990 fprintf (stderr, "*** Handshake has failed\n");
991 user_term = 1;
992 retval = 1;
993 break;
997 inp = check_net_or_keyboard_input(&hd);
999 if (inp == IN_NET)
1001 memset (buffer, 0, MAX_BUF + 1);
1002 ret = socket_recv (&hd, buffer, MAX_BUF);
1004 if (ret == 0)
1006 printf ("- Peer has closed the GnuTLS connection\n");
1007 break;
1009 else if (handle_error (&hd, ret) < 0 && user_term == 0)
1011 fprintf (stderr,
1012 "*** Server has terminated the connection abnormally.\n");
1013 retval = 1;
1014 break;
1016 else if (ret > 0)
1018 if (verbose != 0)
1019 printf ("- Received[%d]: ", ret);
1020 for (ii = 0; ii < ret; ii++)
1022 fputc (buffer[ii], stdout);
1024 fflush (stdout);
1027 if (user_term != 0)
1028 break;
1031 if (inp == IN_KEYBOARD)
1033 if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
1035 if (hd.secure == 0)
1037 /* Warning! Do not touch this text string, it is
1038 used by external programs to search for when
1039 gnutls-cli has reached this point. */
1040 fprintf (stderr, "*** Starting TLS handshake\n");
1041 ret = do_handshake (&hd);
1042 clearerr (stdin);
1043 if (ret < 0)
1045 fprintf (stderr, "*** Handshake has failed\n");
1046 user_term = 1;
1047 retval = 1;
1048 break;
1051 else
1053 user_term = 1;
1054 break;
1056 continue;
1059 buffer[bytes] = 0;
1060 if (crlf != 0)
1062 char *b = strchr (buffer, '\n');
1063 if (b != NULL)
1065 strcpy (b, "\r\n");
1066 bytes++;
1070 ret = socket_send (&hd, buffer, bytes);
1072 if (ret > 0)
1074 if (verbose != 0)
1075 printf ("- Sent: %d bytes\n", ret);
1077 else
1078 handle_error (&hd, ret);
1083 if (user_term != 0)
1084 socket_bye (&hd);
1085 else
1086 gnutls_deinit (hd.session);
1088 #ifdef ENABLE_SRP
1089 if (srp_cred)
1090 gnutls_srp_free_client_credentials (srp_cred);
1091 #endif
1092 #ifdef ENABLE_PSK
1093 if (psk_cred)
1094 gnutls_psk_free_client_credentials (psk_cred);
1095 #endif
1097 gnutls_certificate_free_credentials (xcred);
1099 #ifdef ENABLE_ANON
1100 gnutls_anon_free_client_credentials (anon_cred);
1101 #endif
1103 gnutls_global_deinit ();
1105 return retval;
1108 static void
1109 cmd_parser (int argc, char **argv)
1111 const char* rest = NULL;
1113 int optct = optionProcess( &gnutls_cliOptions, argc, argv);
1114 argc -= optct;
1115 argv += optct;
1117 if (rest == NULL && argc > 0)
1118 rest = argv[0];
1120 if (HAVE_OPT(BENCHMARK_CIPHERS))
1122 benchmark_cipher(1, OPT_VALUE_DEBUG);
1123 exit(0);
1126 if (HAVE_OPT(BENCHMARK_SOFT_CIPHERS))
1128 benchmark_cipher(0, OPT_VALUE_DEBUG);
1129 exit(0);
1132 if (HAVE_OPT(BENCHMARK_TLS))
1134 benchmark_tls(OPT_VALUE_DEBUG);
1135 exit(0);
1138 if (HAVE_OPT(PRIORITY))
1140 priorities = OPT_ARG(PRIORITY);
1142 verbose = HAVE_OPT( VERBOSE);
1143 if (verbose)
1144 print_cert = 1;
1145 else
1146 print_cert = HAVE_OPT( PRINT_CERT);
1148 if (HAVE_OPT(LIST))
1150 print_list(priorities, verbose);
1151 exit(0);
1154 disable_extensions = HAVE_OPT( DISABLE_EXTENSIONS);
1155 starttls = HAVE_OPT(STARTTLS);
1156 resume = HAVE_OPT(RESUME);
1157 rehandshake = HAVE_OPT(REHANDSHAKE);
1158 insecure = HAVE_OPT(INSECURE);
1160 udp = HAVE_OPT(UDP);
1161 mtu = OPT_VALUE_MTU;
1163 if (HAVE_OPT(PORT))
1165 service = OPT_ARG(PORT);
1167 else
1169 service = "443";
1172 record_max_size = OPT_VALUE_RECORDSIZE;
1173 fingerprint = HAVE_OPT(FINGERPRINT);
1175 if (HAVE_OPT(X509FMTDER))
1176 x509ctype = GNUTLS_X509_FMT_DER;
1177 else
1178 x509ctype = GNUTLS_X509_FMT_PEM;
1180 if (HAVE_OPT(SRPUSERNAME))
1181 srp_username = OPT_ARG(SRPUSERNAME);
1183 if (HAVE_OPT(SRPPASSWD))
1184 srp_passwd = OPT_ARG(SRPPASSWD);
1186 if (HAVE_OPT(X509CAFILE))
1187 x509_cafile = OPT_ARG(X509CAFILE);
1188 else
1190 if (access(DEFAULT_CA_FILE, R_OK) == 0)
1191 x509_cafile = DEFAULT_CA_FILE;
1194 if (HAVE_OPT(X509CRLFILE))
1195 x509_crlfile = OPT_ARG(X509CRLFILE);
1197 if (HAVE_OPT(X509KEYFILE))
1198 x509_keyfile = OPT_ARG(X509KEYFILE);
1200 if (HAVE_OPT(X509CERTFILE))
1201 x509_certfile = OPT_ARG(X509CERTFILE);
1203 if (HAVE_OPT(PGPKEYFILE))
1204 pgp_keyfile = OPT_ARG(PGPKEYFILE);
1206 if (HAVE_OPT(PGPCERTFILE))
1207 pgp_certfile = OPT_ARG(PGPCERTFILE);
1209 if (HAVE_OPT(PSKUSERNAME))
1210 psk_username = OPT_ARG(PSKUSERNAME);
1212 if (HAVE_OPT(PSKKEY))
1214 psk_key.data = (unsigned char *) OPT_ARG(PSKKEY);
1215 psk_key.size = strlen (OPT_ARG(PSKKEY));
1217 else
1218 psk_key.size = 0;
1220 if (HAVE_OPT(PGPKEYRING))
1221 pgp_keyring = OPT_ARG(PGPKEYRING);
1223 crlf = HAVE_OPT(CRLF);
1225 if (rest != NULL)
1226 hostname = rest;
1228 if (hostname == NULL)
1230 fprintf(stderr, "No hostname specified\n");
1231 exit(1);
1235 void cli_version (void);
1237 void
1238 cli_version (void)
1240 const char *p = PACKAGE_NAME;
1241 if (strcmp (gnutls_check_version (NULL), PACKAGE_VERSION) != 0)
1242 p = PACKAGE_STRING;
1243 version_etc (stdout, program_name, p, gnutls_check_version (NULL),
1244 "Nikos Mavrogiannopoulos", (char *) NULL);
1248 static void
1249 check_rehandshake (socket_st * socket, int ret)
1251 if (socket->secure && ret == GNUTLS_E_REHANDSHAKE)
1253 /* There is a race condition here. If application
1254 * data is sent after the rehandshake request,
1255 * the server thinks we ignored his request.
1256 * This is a bad design of this client.
1258 printf ("*** Received rehandshake request\n");
1259 /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */
1261 ret = do_handshake (socket);
1263 if (ret == 0)
1265 printf ("*** Rehandshake was performed.\n");
1267 else
1269 printf ("*** Rehandshake Failed.\n");
1275 static int
1276 do_handshake (socket_st * socket)
1278 int ret;
1280 gnutls_transport_set_ptr (socket->session,
1281 (gnutls_transport_ptr_t)
1282 gl_fd_to_handle (socket->fd));
1285 ret = gnutls_handshake (socket->session);
1287 if (ret < 0)
1289 handle_error (socket, ret);
1292 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
1294 if (ret == 0)
1296 /* print some information */
1297 print_info (socket->session, print_cert);
1298 socket->secure = 1;
1300 else
1302 gnutls_alert_send_appropriate (socket->session, ret);
1303 shutdown (socket->fd, SHUT_RDWR);
1305 return ret;
1308 static int
1309 srp_username_callback (gnutls_session_t session,
1310 char **username, char **password)
1312 if (srp_username == NULL || srp_passwd == NULL)
1314 return -1;
1317 *username = gnutls_strdup (srp_username);
1318 *password = gnutls_strdup (srp_passwd);
1320 return 0;
1323 static int
1324 psk_callback (gnutls_session_t session, char **username, gnutls_datum_t * key)
1326 const char *hint = gnutls_psk_client_get_hint (session);
1327 char *rawkey;
1328 char *passwd;
1329 int ret;
1330 size_t res_size;
1331 gnutls_datum_t tmp;
1333 printf ("- PSK client callback. ");
1334 if (hint)
1335 printf ("PSK hint '%s'\n", hint);
1336 else
1337 printf ("No PSK hint\n");
1339 if (HAVE_OPT(PSKUSERNAME))
1340 *username = gnutls_strdup (OPT_ARG(PSKUSERNAME));
1341 else
1343 char *tmp = NULL;
1344 size_t n;
1346 printf ("Enter PSK identity: ");
1347 fflush (stdout);
1348 getline (&tmp, &n, stdin);
1350 if (tmp == NULL)
1352 fprintf (stderr, "No username given, aborting...\n");
1353 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1356 if (tmp[strlen (tmp) - 1] == '\n')
1357 tmp[strlen (tmp) - 1] = '\0';
1358 if (tmp[strlen (tmp) - 1] == '\r')
1359 tmp[strlen (tmp) - 1] = '\0';
1361 *username = gnutls_strdup (tmp);
1362 free (tmp);
1364 if (!*username)
1365 return GNUTLS_E_MEMORY_ERROR;
1367 passwd = getpass ("Enter key: ");
1368 if (passwd == NULL)
1370 fprintf (stderr, "No key given, aborting...\n");
1371 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1374 tmp.data = (void*)passwd;
1375 tmp.size = strlen (passwd);
1377 res_size = tmp.size / 2 + 1;
1378 rawkey = gnutls_malloc (res_size);
1379 if (rawkey == NULL)
1380 return GNUTLS_E_MEMORY_ERROR;
1382 ret = gnutls_hex_decode (&tmp, rawkey, &res_size);
1383 if (ret < 0)
1385 fprintf (stderr, "Error deriving password: %s\n",
1386 gnutls_strerror (ret));
1387 gnutls_free (*username);
1388 return ret;
1391 key->data = (void*)rawkey;
1392 key->size = res_size;
1394 if (HAVE_OPT(DEBUG))
1396 char hexkey[41];
1397 res_size = sizeof (hexkey);
1398 gnutls_hex_encode (key, hexkey, &res_size);
1399 fprintf (stderr, "PSK username: %s\n", *username);
1400 fprintf (stderr, "PSK hint: %s\n", hint);
1401 fprintf (stderr, "PSK key: %s\n", hexkey);
1404 return 0;
1407 static void
1408 init_global_tls_stuff (void)
1410 int ret;
1412 /* X509 stuff */
1413 if (gnutls_certificate_allocate_credentials (&xcred) < 0)
1415 fprintf (stderr, "Certificate allocation memory error\n");
1416 exit (1);
1419 if (x509_cafile != NULL)
1421 ret = gnutls_certificate_set_x509_trust_file (xcred,
1422 x509_cafile, x509ctype);
1423 if (ret < 0)
1425 fprintf (stderr, "Error setting the x509 trust file\n");
1427 else
1429 printf ("Processed %d CA certificate(s).\n", ret);
1432 if (x509_crlfile != NULL)
1434 ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
1435 x509ctype);
1436 if (ret < 0)
1438 fprintf (stderr, "Error setting the x509 CRL file\n");
1440 else
1442 printf ("Processed %d CRL(s).\n", ret);
1446 load_keys ();
1448 #ifdef ENABLE_OPENPGP
1449 if (pgp_keyring != NULL)
1451 ret =
1452 gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
1453 GNUTLS_OPENPGP_FMT_BASE64);
1454 if (ret < 0)
1456 fprintf (stderr, "Error setting the OpenPGP keyring file\n");
1459 #endif
1461 #ifdef ENABLE_SRP
1462 if (srp_username && srp_passwd)
1464 /* SRP stuff */
1465 if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
1467 fprintf (stderr, "SRP authentication error\n");
1470 gnutls_srp_set_client_credentials_function (srp_cred,
1471 srp_username_callback);
1473 #endif
1475 #ifdef ENABLE_PSK
1476 /* PSK stuff */
1477 if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
1479 fprintf (stderr, "PSK authentication error\n");
1482 if (psk_username && psk_key.data)
1484 ret = gnutls_psk_set_client_credentials (psk_cred,
1485 psk_username, &psk_key,
1486 GNUTLS_PSK_KEY_HEX);
1487 if (ret < 0)
1489 fprintf (stderr, "Error setting the PSK credentials: %s\n",
1490 gnutls_strerror (ret));
1493 else
1494 gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
1495 #endif
1497 #ifdef ENABLE_ANON
1498 /* ANON stuff */
1499 if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
1501 fprintf (stderr, "Anonymous authentication error\n");
1503 #endif
1507 /* OCSP check for the peer's certificate. Should be called
1508 * only after the certificate list verication is complete.
1509 * Returns:
1510 * 0: certificate is revoked
1511 * 1: certificate is ok
1512 * -1: dunno
1514 static int
1515 cert_verify_ocsp (gnutls_session_t session)
1517 gnutls_x509_crt_t crt, issuer;
1518 const gnutls_datum_t *cert_list;
1519 unsigned int cert_list_size = 0;
1520 int deinit_issuer = 0;
1521 gnutls_datum_t resp;
1522 int ret;
1524 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
1525 if (cert_list_size == 0)
1527 fprintf (stderr, "No certificates found!\n");
1528 return -1;
1531 gnutls_x509_crt_init (&crt);
1532 ret =
1533 gnutls_x509_crt_import (crt, &cert_list[0],
1534 GNUTLS_X509_FMT_DER);
1535 if (ret < 0)
1537 fprintf (stderr, "Decoding error: %s\n",
1538 gnutls_strerror (ret));
1539 return -1;
1542 ret = gnutls_certificate_get_issuer(xcred, crt, &issuer, 0);
1543 if (ret < 0 && cert_list_size > 1)
1545 gnutls_x509_crt_init(&issuer);
1546 ret = gnutls_x509_crt_import(issuer, &cert_list[1], GNUTLS_X509_FMT_DER);
1547 if (ret < 0)
1549 fprintf (stderr, "Decoding error: %s\n",
1550 gnutls_strerror (ret));
1551 return -1;
1553 deinit_issuer = 1;
1555 else if (ret < 0)
1557 fprintf(stderr, "Cannot find issuer\n");
1558 ret = -1;
1559 goto cleanup;
1562 ret = send_ocsp_request(NULL, crt, issuer, &resp, 1);
1563 if (ret < 0)
1565 fprintf(stderr, "Cannot contact OCSP server\n");
1566 ret = -1;
1567 goto cleanup;
1570 /* verify and check the response for revoked cert */
1571 ret = check_ocsp_response(issuer, &resp);
1573 cleanup:
1574 if (deinit_issuer)
1575 gnutls_x509_crt_deinit (issuer);
1576 gnutls_x509_crt_deinit (crt);
1578 return ret;