summaryrefslogtreecommitdiff
path: root/src/cli.c
blob: de14c561127002d9762306381239929cbfa0275c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
 *      Copyright (C) 2000,2001,2002,2003 Nikos Mavroyanopoulos
 *
 * This file is part of GNUTLS.
 *
 * GNUTLS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GNUTLS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

#include <config.h>

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <gnutls/gnutls.h>
#include <gnutls/extra.h>
#include <gnutls/x509.h>
#include <sys/time.h>
#include <signal.h>
#include <netdb.h>
#include <common.h>
#include "cli-gaa.h"

#ifndef SHUT_WR
# define SHUT_WR 1
#endif

#ifndef SHUT_RDWR
# define SHUT_RDWR 2
#endif

#define SA struct sockaddr
#define ERR(err,s) if (err==-1) {perror(s);return(1);}
#define MAX_BUF 4096
#define GERR(ret) fprintf(stderr, "* Error: %s\n", gnutls_strerror(ret))

/* global stuff here */
int resume, starttls;
char *hostname = NULL;
int port;
int record_max_size;
int fingerprint;
int crlf;
int quiet = 0;
extern int xml;

char *srp_passwd = NULL;
char *srp_username;
char *pgp_keyfile;
char *pgp_certfile;
char *pgp_keyring;
char *pgp_trustdb;
char *x509_keyfile;
char *x509_certfile;
char *x509_cafile;
char *x509_crlfile = NULL;
static int x509ctype;
static int disable_extensions;
static int debug;

static gnutls_srp_client_credentials srp_cred;
static gnutls_anon_client_credentials anon_cred;
static gnutls_certificate_credentials xcred;

int protocol_priority[16] = { GNUTLS_TLS1, GNUTLS_SSL3, 0 };
int kx_priority[16] =
    { GNUTLS_KX_RSA, GNUTLS_KX_DHE_DSS, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP,
   /* Do not use anonymous authentication, unless you know what that means */
   GNUTLS_KX_ANON_DH, GNUTLS_KX_RSA_EXPORT, 0
};
int cipher_priority[16] =
    { GNUTLS_CIPHER_ARCFOUR_128, GNUTLS_CIPHER_RIJNDAEL_128_CBC,
   GNUTLS_CIPHER_3DES_CBC,
   GNUTLS_CIPHER_ARCFOUR_40, 0
};
int comp_priority[16] = { GNUTLS_COMP_ZLIB, GNUTLS_COMP_NULL, 0 };
int mac_priority[16] = { GNUTLS_MAC_SHA, GNUTLS_MAC_MD5, 0 };
int cert_type_priority[16] = { GNUTLS_CRT_X509, GNUTLS_CRT_OPENPGP, 0 };

/* end of global stuff */

/* prototypes */
typedef struct {
   int fd;
   gnutls_session session;
   int secure;
} socket_st;

ssize_t socket_recv(socket_st socket, void *buffer, int buffer_size);
ssize_t socket_send(socket_st socket, void *buffer, int buffer_size);
void socket_bye(socket_st *socket);
void check_rehandshake(socket_st socket, int ret);
void check_alert(socket_st socket, int ret);
int do_handshake(socket_st *socket);
void init_global_tls_stuff(void);


#define MAX(X,Y) (X >= Y ? X : Y);

/* A callback function to be used at the certificate selection time.
 */
static int cert_callback( gnutls_session session, const gnutls_datum* client_certs,
	int client_certs_num, const gnutls_datum * req_ca_rdn, int nreqs)
{
char issuer_dn[256];
int len, i, ret;

	/* Print the server's trusted CAs
	 */
	if (nreqs > 0)
		printf("- Server's trusted authorities:\n");
	else
		printf("- Server did not send us any trusted authorities names.\n");

	/* print the names (if any) */
	for (i=0;i<nreqs;i++) {
		len = sizeof(issuer_dn);
		ret = gnutls_x509_rdn_get( &req_ca_rdn[i], issuer_dn, &len);
		if ( ret >= 0) {
			printf("   [%d]: ", i);
			printf("%s\n", issuer_dn);
		}
	}

	if (client_certs_num > 0)
		return 0; /* use the first one */

	return -1;

}


/* initializes a gnutls_session with some defaults.
 */
static gnutls_session init_tls_session( const char* hostname)
{
   gnutls_session session;

   gnutls_init(&session, GNUTLS_CLIENT);

   /* allow the use of private ciphersuites.
    */
   if (disable_extensions == 0)
      gnutls_handshake_set_private_extensions(session, 1);

   if (disable_extensions == 0)
      gnutls_server_name_set( session, GNUTLS_NAME_DNS, hostname, strlen(hostname));

   gnutls_cipher_set_priority(session, cipher_priority);
   gnutls_compression_set_priority(session, comp_priority);
   gnutls_kx_set_priority(session, kx_priority);
   gnutls_protocol_set_priority(session, protocol_priority);
   gnutls_mac_set_priority(session, mac_priority);
   gnutls_certificate_type_set_priority(session, cert_type_priority);

   gnutls_dh_set_prime_bits(session, 512);

   gnutls_credentials_set(session, GNUTLS_CRD_ANON, anon_cred);
   gnutls_credentials_set(session, GNUTLS_CRD_SRP, srp_cred);
   gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);

   gnutls_certificate_client_set_select_function( session, cert_callback);

   /* send the fingerprint */
   if (fingerprint != 0)
      gnutls_openpgp_send_key(session, GNUTLS_OPENPGP_KEY_FINGERPRINT);

   /* use the max record size extension */
   if (record_max_size > 0 && disable_extensions == 0) {
      if (gnutls_record_set_max_size(session, record_max_size) < 0) {
	 fprintf(stderr,
		 "Cannot set the maximum record size to %d.\n",
		 record_max_size);
	 exit(1);
      }
   }

   return session;
}


static void gaa_parser(int argc, char **argv);

int main(int argc, char **argv)
{
   int err, ret;
   int sd, ii, i;
   struct sockaddr_in sa;
   char buffer[MAX_BUF + 1];
   char *session_data = NULL;
   char *session_id = NULL;
   int session_data_size, alert;
   int session_id_size;
   fd_set rset;
   int maxfd;
   struct timeval tv;
   int user_term = 0;
   struct hostent *server_host;
   socket_st hd;

   gaa_parser(argc, argv);

   signal(SIGPIPE, SIG_IGN);

   init_global_tls_stuff();


   printf("Resolving '%s'...\n", hostname);
   /* get server name */
   server_host = gethostbyname(hostname);
   if (server_host == NULL) {
      fprintf(stderr, "Cannot resolve %s\n", hostname);
      exit(1);
   }

   sd = socket(AF_INET, SOCK_STREAM, 0);
   ERR(sd, "socket");

   memset(&sa, '\0', sizeof(sa));
   sa.sin_family = AF_INET;
   sa.sin_port = htons(port);

   sa.sin_addr.s_addr = *((unsigned int *) server_host->h_addr);

   inet_ntop(AF_INET, &sa.sin_addr, buffer, MAX_BUF);
   fprintf(stderr, "Connecting to '%s:%d'...\n", buffer, port);

   err = connect(sd, (SA *) & sa, sizeof(sa));
   ERR(err, "connect");

   hd.secure = 0;
   hd.fd = sd;

   hd.session = init_tls_session(hostname);
   if (starttls)
      goto after_handshake;

   for (i = 0; i < 2; i++) {


      if (i == 1) {
	 hd.session = init_tls_session(hostname);
	 gnutls_session_set_data(hd.session, session_data,
				 session_data_size);
	 free(session_data);
      }

      ret = do_handshake(&hd);

      if (ret < 0) {
	 if (ret == GNUTLS_E_WARNING_ALERT_RECEIVED
	     || ret == GNUTLS_E_FATAL_ALERT_RECEIVED) {
	    alert = gnutls_alert_get(hd.session);
	    printf("*** Received alert [%d]: %s\n",
		   alert, gnutls_alert_get_name(alert));
	 }
	 fprintf(stderr, "*** Handshake has failed\n");
	 gnutls_perror(ret);
	 gnutls_deinit(hd.session);
	 return 1;
      } else {
	 printf("- Handshake was completed\n");
	 if (gnutls_session_is_resumed(hd.session) != 0)
	    printf("*** This is a resumed session\n");
      }



      if (resume != 0 && i == 0) {

	 gnutls_session_get_data(hd.session, NULL, &session_data_size);
	 session_data = malloc(session_data_size);

	 gnutls_session_get_data(hd.session, session_data,
				 &session_data_size);

	 gnutls_session_get_id(hd.session, NULL, &session_id_size);
	 session_id = malloc(session_id_size);
	 gnutls_session_get_id(hd.session, session_id, &session_id_size);

	 /* print some information */
	 print_info(hd.session);

	 printf("- Disconnecting\n");
	 socket_bye(&hd);

	 printf
	     ("\n\n- Connecting again- trying to resume previous session\n");
	 sd = socket(AF_INET, SOCK_STREAM, 0);
	 ERR(sd, "socket");

	 err = connect(sd, (SA *) & sa, sizeof(sa));
	 ERR(err, "connect");
	 
	 hd.fd = sd;
	 hd.secure = 0;
      } else {
	 break;
      }
   }


 after_handshake:

   printf("\n- Simple Client Mode:\n\n");

   FD_ZERO(&rset);
   for (;;) {
      FD_SET(fileno(stdin), &rset);
      FD_SET(sd, &rset);

      maxfd = MAX(fileno(stdin), sd);
      tv.tv_sec = 3;
      tv.tv_usec = 0;
      select(maxfd + 1, &rset, NULL, NULL, &tv);

      if (FD_ISSET(sd, &rset)) {
	 bzero(buffer, MAX_BUF + 1);
	 ret = socket_recv(hd, buffer, MAX_BUF);

	 if (ret == 0) {
	    printf("- Peer has closed the GNUTLS connection\n");
	    break;
	 } else if (ret < 0 && user_term == 0) {
	    fprintf(stderr,
		    "*** Received corrupted data(%d) - server has terminated the connection abnormally\n",
		    ret);
	    break;
	 } else if (ret > 0) {
	    if (quiet != 0)
	       printf("- Received[%d]: ", ret);
	    for (ii = 0; ii < ret; ii++) {
	       fputc(buffer[ii], stdout);
	    }
	    fflush(stdout);
	 }

	 if (user_term != 0)
	    break;
      }

      if (FD_ISSET(fileno(stdin), &rset)) {
	 if (fgets(buffer, MAX_BUF, stdin) == NULL) {
  	    if (hd.secure == 0) {
  	       fprintf(stderr, "*** Starting TLS handshake\n");
	       ret = do_handshake(&hd);
	       if (ret < 0) {
 		 fprintf(stderr, "*** Handshake has failed\n");
		 gnutls_perror(ret);
		 socket_bye(&hd);
		 user_term = 1;
	       }
	       continue;
            } else {
	       user_term = 1;
	       continue;
	    }
	 }

	 if (crlf != 0) {
	    char *b = strchr(buffer, '\n');
	    if (b != NULL)
	       strcpy(b, "\r\n");
	 }

	 ret = socket_send(hd, buffer, strlen(buffer));

	 if (ret > 0) {
	    if (quiet != 0)
	       printf("- Sent: %d bytes\n", ret);
	 } else
	    GERR(ret);

      }
   }

   if (user_term != 0)
      socket_bye(&hd);


#ifdef ENABLE_SRP
   gnutls_srp_free_client_credentials(srp_cred);
#endif

   gnutls_certificate_free_credentials(xcred);

#ifdef ENABLE_ANON
   gnutls_anon_free_client_credentials(anon_cred);
#endif

   gnutls_global_deinit();

   return 0;
}

static gaainfo info;
void gaa_parser(int argc, char **argv)
{
   if (gaa(argc, argv, &info) != -1) {
      fprintf(stderr,
	      "Error in the arguments. Use the --help or -h parameters to get more information.\n");
      exit(1);
   }

   debug = info.debug;
   disable_extensions = info.disable_extensions;
   xml = info.xml;
   starttls = info.starttls;
   resume = info.resume;
   port = info.port;
   record_max_size = info.record_size;
   fingerprint = info.fingerprint;

   if (info.fmtder == 0)
      x509ctype = GNUTLS_X509_FMT_PEM;
   else
      x509ctype = GNUTLS_X509_FMT_DER;

   srp_username = info.srp_username;
   srp_passwd = info.srp_passwd;
   x509_cafile = info.x509_cafile;
   x509_crlfile = info.x509_crlfile;
   x509_keyfile = info.x509_keyfile;
   x509_certfile = info.x509_certfile;
   pgp_keyfile = info.pgp_keyfile;
   pgp_certfile = info.pgp_certfile;

   pgp_keyring = info.pgp_keyring;
   pgp_trustdb = info.pgp_trustdb;

   crlf = info.crlf;

   if (info.rest_args == NULL)
      hostname = "localhost";
   else
      hostname = info.rest_args;

   parse_protocols( info.proto, info.nproto, protocol_priority);
   parse_ciphers( info.ciphers, info.nciphers, cipher_priority);
   parse_macs( info.macs, info.nmacs, mac_priority);
   parse_ctypes( info.ctype, info.nctype, cert_type_priority);
   parse_kx( info.kx, info.nkx, kx_priority);
   parse_comp( info.comp, info.ncomp, comp_priority);


}

void cli_version(void)
{
   fprintf(stderr, "GNU TLS test client, ");
   fprintf(stderr, "version %s. Libgnutls %s.\n", LIBGNUTLS_VERSION, gnutls_check_version(NULL));
}



/* Functions to manipulate sockets
 */

ssize_t socket_recv(socket_st socket, void *buffer, int buffer_size)
{
   int ret;

   if (socket.secure)
      do {
	 ret = gnutls_record_recv(socket.session, buffer, buffer_size);
      } while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
   else
      do {
	 ret = recv(socket.fd, buffer, buffer_size, 0);
      } while (ret == -1 && errno == EINTR);

   return ret;
}

ssize_t socket_send(socket_st socket, void *buffer, int buffer_size)
{
   int ret;

   if (socket.secure)
      do {
	 ret = gnutls_record_send(socket.session, buffer, buffer_size);
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
   else
      do {
	 ret = send(socket.fd, buffer, buffer_size, 0);
      } while (ret == -1 && errno == EINTR);


   return ret;
}

void socket_bye(socket_st *socket)
{
   int ret;
   if (socket->secure) {
      do
	 ret = gnutls_bye(socket->session, GNUTLS_SHUT_RDWR);
      while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
      gnutls_deinit(socket->session);
      socket->session = NULL;
   }

   shutdown(socket->fd, SHUT_RDWR);	/* no more receptions */
   close(socket->fd);
   
   socket->fd = -1;
   socket->secure = 0;
}

void check_rehandshake(socket_st socket, int ret)
{
   if (socket.secure && ret == GNUTLS_E_REHANDSHAKE) {
      /* There is a race condition here. If application
       * data is sent after the rehandshake request,
       * the server thinks we ignored his request.
       * This is a bad design of this client.
       */
      printf("* Received rehandshake request\n");
      /* gnutls_alert_send( session, GNUTLS_AL_WARNING, GNUTLS_A_NO_RENEGOTIATION); */

      do {
	 ret = gnutls_handshake(socket.session);
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

      if (ret == 0) {
	 printf("* Rehandshake was performed\n");
      } else {
	 printf("* Rehandshake Failed [%d]\n", ret);
      }
   }
}

void check_alert(socket_st socket, int ret)
{
   if (ret == GNUTLS_E_WARNING_ALERT_RECEIVED
       || ret == GNUTLS_E_FATAL_ALERT_RECEIVED) {
      printf("* Received alert [%d]\n", gnutls_alert_get(socket.session));

      check_rehandshake(socket, ret);
   }
}

int do_handshake(socket_st* socket)
{
   int ret;
   gnutls_transport_set_ptr(socket->session, socket->fd);
   do {
      ret = gnutls_handshake(socket->session);
   } while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);

   if (ret==0) {
      socket->secure = 1;
      /* print some information */
      print_info(socket->session);
   }
   return ret;
}


static void tls_log_func( int level, const char* str)
{
	fprintf(stderr, "|<%d>| %s", level, str);
}

void init_global_tls_stuff()
{
int ret;

   if (gnutls_global_init() < 0) {
      fprintf(stderr, "global state initialization error\n");
      exit(1);
   }
   gnutls_global_set_log_function( tls_log_func);
   gnutls_global_set_log_level(debug);

   if (gnutls_global_init_extra() < 0) {
      fprintf(stderr, "global state (extra) initialization error\n");
      exit(1);
   }

   /* X509 stuff */
   if (gnutls_certificate_allocate_credentials(&xcred) < 0) {
      fprintf(stderr, "Certificate allocation memory error\n");
      exit(1);
   }

   /* there are some intermediate CAs that have a v1 certificate *%&@#*%&
    */
   gnutls_certificate_set_verify_flags( xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);

   if (x509_cafile != NULL) {
      ret =
	  gnutls_certificate_set_x509_trust_file(xcred,
						 x509_cafile, x509ctype);
      if (ret < 0) {
	 fprintf(stderr, "Error setting the x509 trust file\n");
      } else {
	 printf("Processed %d CA certificate(s).\n", ret);
      }
   }

#ifdef ENABLE_PKI
   if (x509_crlfile != NULL) {
      ret =
	  gnutls_certificate_set_x509_crl_file(xcred,
						 x509_crlfile, x509ctype);
      if (ret < 0) {
	 fprintf(stderr, "Error setting the x509 CRL file\n");
      } else {
	 printf("Processed %d CRL(s).\n", ret);
      }
   }
#endif

   if (x509_certfile != NULL) {
      ret =
	  gnutls_certificate_set_x509_key_file(xcred,
					       x509_certfile,
					       x509_keyfile, x509ctype);
      if (ret < 0) {
	 fprintf(stderr,
		 "Error setting the x509 key files ('%s', '%s')\n",
		 x509_certfile, x509_keyfile);
      }
   }

   if (pgp_certfile != NULL) {
      ret =
	  gnutls_certificate_set_openpgp_key_file(xcred,
						  pgp_certfile,
						  pgp_keyfile);
      if (ret < 0) {
	 fprintf(stderr,
		 "Error setting the x509 key files ('%s', '%s')\n",
		 pgp_certfile, pgp_keyfile);
      }
   }

   if (pgp_keyring != NULL) {
      ret =
	  gnutls_certificate_set_openpgp_keyring_file(xcred, pgp_keyring);
      if (ret < 0) {
	 fprintf(stderr, "Error setting the OpenPGP keyring file\n");
      }
   }

   if (pgp_trustdb != NULL) {
      ret = gnutls_certificate_set_openpgp_trustdb(xcred, pgp_trustdb);
      if (ret < 0) {
	 fprintf(stderr, "Error setting the OpenPGP trustdb file\n");
      }
   }

#ifdef ENABLE_SRP
   /* SRP stuff */
   if (gnutls_srp_allocate_client_credentials(&srp_cred) < 0) {
	fprintf(stderr, "SRP authentication error\n");
   }

   if (srp_username != NULL) {
      if ((ret=gnutls_srp_set_client_credentials(srp_cred, srp_username, srp_passwd)) < 0) {
	 fprintf(stderr, "SRP credentials set error [%d]\n", ret);
      }
   }
#endif


#ifdef ENABLE_ANON
   /* ANON stuff */
   if (gnutls_anon_allocate_client_credentials(&anon_cred) < 0) {
      fprintf(stderr, "Anonymous authentication error\n");
   }
#endif

}