tls_m.c 67.5 KB
Newer Older
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* tls_m.c - Handle tls/ssl using Mozilla NSS. */
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 2008-2009 The OpenLDAP Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
16
17
/* ACKNOWLEDGEMENTS: Initial version written by Howard Chu. 
 * Additional support by Rich Megginson.
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
18
19
20
21
22
23
24
25
26
27
 */

#include "portable.h"

#ifdef HAVE_MOZNSS

#include "ldap_config.h"

#include <stdio.h>

28
29
30
31
#if defined( HAVE_FCNTL_H )
#include <fcntl.h>
#endif

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <ac/stdlib.h>
#include <ac/errno.h>
#include <ac/socket.h>
#include <ac/string.h>
#include <ac/ctype.h>
#include <ac/time.h>
#include <ac/unistd.h>
#include <ac/param.h>
#include <ac/dirent.h>

#include "ldap-int.h"
#include "ldap-tls.h"

#ifdef LDAP_R_COMPILE
#include <ldap_pvt_thread.h>
#endif

49
50
51
52
53
54
55
#define READ_PASSWORD_FROM_STDIN
#define READ_PASSWORD_FROM_FILE

#ifdef READ_PASSWORD_FROM_STDIN
#include <termios.h> /* for echo on/off */
#endif

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
56
57
58
59
60
61
62
63
64
65
#include <nspr/nspr.h>
#include <nspr/private/pprio.h>
#include <nss/nss.h>
#include <nss/ssl.h>
#include <nss/sslerr.h>
#include <nss/sslproto.h>
#include <nss/pk11pub.h>
#include <nss/secerr.h>
#include <nss/keyhi.h>
#include <nss/secmod.h>
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
66
67
68
69

typedef struct tlsm_ctx {
	PRFileDesc *tc_model;
	int tc_refcnt;
70
71
72
73
74
75
76
77
	PRBool tc_verify_cert;
	CERTCertDBHandle *tc_certdb;
	char *tc_certname;
	char *tc_pin_file;
	struct ldaptls *tc_config;
	int tc_is_server;
	int tc_require_cert;
	PRCallOnceType tc_callonce;
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
78
79
	PRBool tc_using_pem;
	char *tc_slotname; /* if using pem */
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
80
81
82
83
84
85
86
87
88
89
90
#ifdef LDAP_R_COMPILE
	ldap_pvt_thread_mutex_t tc_refmutex;
#endif
} tlsm_ctx;

typedef PRFileDesc tlsm_session;

static PRDescIdentity	tlsm_layer_id;

static const PRIOMethods tlsm_PR_methods;

91
92
static int tlsm_did_init;

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
93
94
95
static const char* pem_library = "nsspem";
static SECMODModule* pemMod = NULL;

96
#define DEFAULT_TOKEN_NAME "default"
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
97
98
99
100
101
102
103
/* sprintf format used to create token name */
#define TLSM_PEM_TOKEN_FMT "PEM Token #%ld"

static int tlsm_slot_count;

#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
                (x)->pValue=(v); (x)->ulValueLen = (l);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
104

105
106
/* forward declaration */
static int tlsm_init( void );
107

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
108
109
110
111
112
113
114
115
116
#ifdef LDAP_R_COMPILE

static void
tlsm_thr_init( void )
{
}

#endif /* LDAP_R_COMPILE */

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
static const char *
tlsm_dump_cipher_info(PRFileDesc *fd)
{
	PRUint16 ii;

	for (ii = 0; ii < SSL_NumImplementedCiphers; ++ii) {
		PRInt32 cipher = (PRInt32)SSL_ImplementedCiphers[ii];
		PRBool enabled = PR_FALSE;
		PRInt32 policy = 0;
		SSLCipherSuiteInfo info;

		if (fd) {
			SSL_CipherPrefGet(fd, cipher, &enabled);
		} else {
			SSL_CipherPrefGetDefault(cipher, &enabled);
		}
		SSL_CipherPolicyGet(cipher, &policy);
		SSL_GetCipherSuiteInfo(cipher, &info, (PRUintn)sizeof(info));
		Debug( LDAP_DEBUG_TRACE,
			   "TLS: cipher: %d - %s, enabled: %d, ",
			   info.cipherSuite, info.cipherSuiteName, enabled );
		Debug( LDAP_DEBUG_TRACE,
			   "policy: %d\n", policy, 0, 0 );
	}

	return "";
}

/* Cipher definitions */
typedef struct {
	char *ossl_name;    /* The OpenSSL cipher name */
	int num;            /* The cipher id */
	int attr;           /* cipher attributes: algorithms, etc */
	int version;        /* protocol version valid for this cipher */
	int bits;           /* bits of strength */
	int alg_bits;       /* bits of the algorithm */
	int strength;       /* LOW, MEDIUM, HIGH */
	int enabled;        /* Enabled by default? */
} cipher_properties;

/* cipher attributes  */
#define SSL_kRSA  0x00000001L
#define SSL_aRSA  0x00000002L
#define SSL_aDSS  0x00000004L
#define SSL_DSS   SSL_aDSS
#define SSL_eNULL 0x00000008L
#define SSL_DES   0x00000010L
#define SSL_3DES  0x00000020L
#define SSL_RC4   0x00000040L
#define SSL_RC2   0x00000080L
#define SSL_AES   0x00000100L
#define SSL_MD5   0x00000200L
#define SSL_SHA1  0x00000400L
#define SSL_SHA   SSL_SHA1
#define SSL_RSA   (SSL_kRSA|SSL_aRSA)

/* cipher strength */
#define SSL_NULL      0x00000001L
#define SSL_EXPORT40  0x00000002L
#define SSL_EXPORT56  0x00000004L
#define SSL_LOW       0x00000008L
#define SSL_MEDIUM    0x00000010L
#define SSL_HIGH      0x00000020L

#define SSL2  0x00000001L
#define SSL3  0x00000002L
/* OpenSSL treats SSL3 and TLSv1 the same */
#define TLS1  SSL3

/* Cipher translation */
static cipher_properties ciphers_def[] = {
	/* SSL 2 ciphers */
	{"DES-CBC3-MD5", SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_3DES|SSL_MD5, SSL2, 168, 168, SSL_HIGH, SSL_ALLOWED},
	{"RC2-CBC-MD5", SSL_EN_RC2_128_CBC_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC2|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
	{"RC4-MD5", SSL_EN_RC4_128_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
	{"DES-CBC-MD5", SSL_EN_DES_64_CBC_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_MD5, SSL2, 56, 56, SSL_LOW, SSL_ALLOWED},
	{"EXP-RC2-CBC-MD5", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC2|SSL_MD5, SSL2, 40, 128, SSL_EXPORT40, SSL_ALLOWED},
	{"EXP-RC4-MD5", SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 40, 128, SSL_EXPORT40, SSL_ALLOWED},

	/* SSL3 ciphers */
	{"RC4-MD5", SSL_RSA_WITH_RC4_128_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
	{"RC4-SHA", SSL_RSA_WITH_RC4_128_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA1, SSL3, 128, 128, SSL_MEDIUM, SSL_NOT_ALLOWED},
	{"DES-CBC3-SHA", SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_3DES|SSL_SHA1, SSL3, 168, 168, SSL_HIGH, SSL_ALLOWED},
	{"DES-CBC-SHA", SSL_RSA_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA1, SSL3, 56, 56, SSL_LOW, SSL_ALLOWED},
	{"EXP-RC4-MD5", SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 40, 128, SSL_EXPORT40, SSL_ALLOWED},
	{"EXP-RC2-CBC-MD5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_kRSA|SSL_aRSA|SSL_RC2|SSL_MD5, SSL3, 0, 0, SSL_EXPORT40, SSL_ALLOWED},
	{"NULL-MD5", SSL_RSA_WITH_NULL_MD5, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_MD5, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
	{"NULL-SHA", SSL_RSA_WITH_NULL_SHA, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_SHA1, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},

	/* TLSv1 ciphers */
	{"EXP1024-DES-CBC-SHA", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA, TLS1, 56, 56, SSL_EXPORT56, SSL_ALLOWED},
	{"EXP1024-RC4-SHA", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA, TLS1, 56, 56, SSL_EXPORT56, SSL_ALLOWED},
	{"AES128-SHA", TLS_RSA_WITH_AES_128_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_AES|SSL_SHA, TLS1, 128, 128, SSL_HIGH, SSL_NOT_ALLOWED},
	{"AES256-SHA", TLS_RSA_WITH_AES_256_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_AES|SSL_SHA, TLS1, 256, 256, SSL_HIGH, SSL_NOT_ALLOWED},
};

#define ciphernum (sizeof(ciphers_def)/sizeof(cipher_properties))

/* given err which is the current errno, calls PR_SetError with
   the corresponding NSPR error code */
static void 
tlsm_map_error(int err)
{
	PRErrorCode prError;

	switch ( err ) {
	case EACCES:
		prError = PR_NO_ACCESS_RIGHTS_ERROR;
		break;
	case EADDRINUSE:
		prError = PR_ADDRESS_IN_USE_ERROR;
		break;
	case EADDRNOTAVAIL:
		prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
		break;
	case EAFNOSUPPORT:
		prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
		break;
	case EAGAIN:
		prError = PR_WOULD_BLOCK_ERROR;
		break;
	/*
	 * On QNX and Neutrino, EALREADY is defined as EBUSY.
	 */
#if EALREADY != EBUSY
	case EALREADY:
		prError = PR_ALREADY_INITIATED_ERROR;
		break;
#endif
	case EBADF:
		prError = PR_BAD_DESCRIPTOR_ERROR;
		break;
#ifdef EBADMSG
	case EBADMSG:
		prError = PR_IO_ERROR;
		break;
#endif
	case EBUSY:
		prError = PR_FILESYSTEM_MOUNTED_ERROR;
		break;
	case ECONNABORTED:
		prError = PR_CONNECT_ABORTED_ERROR;
		break;
	case ECONNREFUSED:
		prError = PR_CONNECT_REFUSED_ERROR;
		break;
	case ECONNRESET:
		prError = PR_CONNECT_RESET_ERROR;
		break;
	case EDEADLK:
		prError = PR_DEADLOCK_ERROR;
		break;
#ifdef EDIRCORRUPTED
	case EDIRCORRUPTED:
		prError = PR_DIRECTORY_CORRUPTED_ERROR;
		break;
#endif
#ifdef EDQUOT
	case EDQUOT:
		prError = PR_NO_DEVICE_SPACE_ERROR;
		break;
#endif
	case EEXIST:
		prError = PR_FILE_EXISTS_ERROR;
		break;
	case EFAULT:
		prError = PR_ACCESS_FAULT_ERROR;
		break;
	case EFBIG:
		prError = PR_FILE_TOO_BIG_ERROR;
		break;
	case EHOSTUNREACH:
		prError = PR_HOST_UNREACHABLE_ERROR;
		break;
	case EINPROGRESS:
		prError = PR_IN_PROGRESS_ERROR;
		break;
	case EINTR:
		prError = PR_PENDING_INTERRUPT_ERROR;
		break;
	case EINVAL:
		prError = PR_INVALID_ARGUMENT_ERROR;
		break;
	case EIO:
		prError = PR_IO_ERROR;
		break;
	case EISCONN:
		prError = PR_IS_CONNECTED_ERROR;
		break;
	case EISDIR:
		prError = PR_IS_DIRECTORY_ERROR;
		break;
	case ELOOP:
		prError = PR_LOOP_ERROR;
		break;
	case EMFILE:
		prError = PR_PROC_DESC_TABLE_FULL_ERROR;
		break;
	case EMLINK:
		prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
		break;
	case EMSGSIZE:
		prError = PR_INVALID_ARGUMENT_ERROR;
		break;
#ifdef EMULTIHOP
	case EMULTIHOP:
		prError = PR_REMOTE_FILE_ERROR;
		break;
#endif
	case ENAMETOOLONG:
		prError = PR_NAME_TOO_LONG_ERROR;
		break;
	case ENETUNREACH:
		prError = PR_NETWORK_UNREACHABLE_ERROR;
		break;
	case ENFILE:
		prError = PR_SYS_DESC_TABLE_FULL_ERROR;
		break;
	/*
	 * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
	 */
#if defined(ENOBUFS) && (ENOBUFS != ENOSR)
	case ENOBUFS:
		prError = PR_INSUFFICIENT_RESOURCES_ERROR;
		break;
#endif
	case ENODEV:
		prError = PR_FILE_NOT_FOUND_ERROR;
		break;
	case ENOENT:
		prError = PR_FILE_NOT_FOUND_ERROR;
		break;
	case ENOLCK:
		prError = PR_FILE_IS_LOCKED_ERROR;
		break;
#ifdef ENOLINK 
	case ENOLINK:
		prError = PR_REMOTE_FILE_ERROR;
		break;
#endif
	case ENOMEM:
		prError = PR_OUT_OF_MEMORY_ERROR;
		break;
	case ENOPROTOOPT:
		prError = PR_INVALID_ARGUMENT_ERROR;
		break;
	case ENOSPC:
		prError = PR_NO_DEVICE_SPACE_ERROR;
		break;
#ifdef ENOSR
	case ENOSR:
		prError = PR_INSUFFICIENT_RESOURCES_ERROR;
		break;
#endif
	case ENOTCONN:
		prError = PR_NOT_CONNECTED_ERROR;
		break;
	case ENOTDIR:
		prError = PR_NOT_DIRECTORY_ERROR;
		break;
	case ENOTSOCK:
		prError = PR_NOT_SOCKET_ERROR;
		break;
	case ENXIO:
		prError = PR_FILE_NOT_FOUND_ERROR;
		break;
	case EOPNOTSUPP:
		prError = PR_NOT_TCP_SOCKET_ERROR;
		break;
#ifdef EOVERFLOW
	case EOVERFLOW:
		prError = PR_BUFFER_OVERFLOW_ERROR;
		break;
#endif
	case EPERM:
		prError = PR_NO_ACCESS_RIGHTS_ERROR;
		break;
	case EPIPE:
		prError = PR_CONNECT_RESET_ERROR;
		break;
#ifdef EPROTO
	case EPROTO:
		prError = PR_IO_ERROR;
		break;
#endif
	case EPROTONOSUPPORT:
		prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
		break;
	case EPROTOTYPE:
		prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
		break;
	case ERANGE:
		prError = PR_INVALID_METHOD_ERROR;
		break;
	case EROFS:
		prError = PR_READ_ONLY_FILESYSTEM_ERROR;
		break;
	case ESPIPE:
		prError = PR_INVALID_METHOD_ERROR;
		break;
	case ETIMEDOUT:
		prError = PR_IO_TIMEOUT_ERROR;
		break;
#if EWOULDBLOCK != EAGAIN
	case EWOULDBLOCK:
		prError = PR_WOULD_BLOCK_ERROR;
		break;
#endif
	case EXDEV:
		prError = PR_NOT_SAME_DEVICE_ERROR;
		break;
	default:
		prError = PR_UNKNOWN_ERROR;
		break;
	}
	PR_SetError( prError, err );
}

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
435
/*
436
437
438
439
 * cipher_list is an integer array with the following values:
 *   -1: never enable this cipher
 *    0: cipher disabled
 *    1: cipher enabled
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
440
441
 */
static int
442
nss_parse_ciphers(const char *cipherstr, int cipher_list[ciphernum])
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
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
	int i;
	char *cipher;
	char *ciphers;
	char *ciphertip;
	int action;
	int rv;

	/* All disabled to start */
	for (i=0; i<ciphernum; i++)
		cipher_list[i] = 0;

	ciphertip = strdup(cipherstr);
	cipher = ciphers = ciphertip;

	while (ciphers && (strlen(ciphers))) {
		while ((*cipher) && (isspace(*cipher)))
			++cipher;

		action = 1;
		switch(*cipher) {
		case '+': /* Add something */
			action = 1;
			cipher++;
			break;
		case '-': /* Subtract something */
			action = 0;
			cipher++;
			break;
		case '!':  /* Disable something */
			action = -1;
			cipher++;
			break;
		default:
			/* do nothing */
			break;
		}

		if ((ciphers = strchr(cipher, ':'))) {
			*ciphers++ = '\0';
		}

		/* Do the easy one first */
		if (!strcmp(cipher, "ALL")) {
			for (i=0; i<ciphernum; i++) {
				if (!(ciphers_def[i].attr & SSL_eNULL))
					cipher_list[i] = action;
			}
		} else if (!strcmp(cipher, "COMPLEMENTOFALL")) {
			for (i=0; i<ciphernum; i++) {
				if ((ciphers_def[i].attr & SSL_eNULL))
					cipher_list[i] = action;
			}
		} else if (!strcmp(cipher, "DEFAULT")) {
			for (i=0; i<ciphernum; i++) {
				cipher_list[i] = ciphers_def[i].enabled == SSL_ALLOWED ? 1 : 0;
			}
		} else {
			int mask = 0;
			int strength = 0;
			int protocol = 0;
			char *c;

			c = cipher;
			while (c && (strlen(c))) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
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
				if ((c = strchr(cipher, '+'))) {
					*c++ = '\0';
				}

				if (!strcmp(cipher, "RSA")) {
					mask |= SSL_RSA;
				} else if ((!strcmp(cipher, "NULL")) || (!strcmp(cipher, "eNULL"))) {
					mask |= SSL_eNULL;
				} else if (!strcmp(cipher, "AES")) {
					mask |= SSL_AES;
				} else if (!strcmp(cipher, "3DES")) {
					mask |= SSL_3DES;
				} else if (!strcmp(cipher, "DES")) {
					mask |= SSL_DES;
				} else if (!strcmp(cipher, "RC4")) {
					mask |= SSL_RC4;
				} else if (!strcmp(cipher, "RC2")) {
					mask |= SSL_RC2;
				} else if (!strcmp(cipher, "MD5")) {
					mask |= SSL_MD5;
				} else if ((!strcmp(cipher, "SHA")) || (!strcmp(cipher, "SHA1"))) {
					mask |= SSL_SHA1;
				} else if (!strcmp(cipher, "SSLv2")) {
					protocol |= SSL2;
				} else if (!strcmp(cipher, "SSLv3")) {
					protocol |= SSL3;
				} else if (!strcmp(cipher, "TLSv1")) {
					protocol |= TLS1;
				} else if (!strcmp(cipher, "HIGH")) {
					strength |= SSL_HIGH;
				} else if (!strcmp(cipher, "MEDIUM")) {
					strength |= SSL_MEDIUM;
				} else if (!strcmp(cipher, "LOW")) {
					strength |= SSL_LOW;
				} else if ((!strcmp(cipher, "EXPORT")) || (!strcmp(cipher, "EXP"))) {
					strength |= SSL_EXPORT40|SSL_EXPORT56;
				} else if (!strcmp(cipher, "EXPORT40")) {
					strength |= SSL_EXPORT40;
				} else if (!strcmp(cipher, "EXPORT56")) {
					strength |= SSL_EXPORT56;
				}
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
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
				if (c)
					cipher = c;

			} /* while */

			/* If we have a mask, apply it. If not then perhaps they provided
			 * a specific cipher to enable.
			 */
			if (mask || strength || protocol) {
				for (i=0; i<ciphernum; i++) {
					if (((ciphers_def[i].attr & mask) ||
						 (ciphers_def[i].strength & strength) ||
						 (ciphers_def[i].version & protocol)) &&
						(cipher_list[i] != -1)) {
						/* Enable the NULL ciphers only if explicity
						 * requested */
						if (ciphers_def[i].attr & SSL_eNULL) {
							if (mask & SSL_eNULL)
								cipher_list[i] = action;
						} else
							cipher_list[i] = action;
					}
				}
			} else {
				for (i=0; i<ciphernum; i++) {
					if (!strcmp(ciphers_def[i].ossl_name, cipher) &&
						cipher_list[1] != -1)
						cipher_list[i] = action;
				}
			}
		}

		if (ciphers)
			cipher = ciphers;
	}

	/* See if any ciphers were enabled */
	rv = 0;
	for (i=0; i<ciphernum; i++) {
		if (cipher_list[i] == 1)
			rv = 1;
	}

	free(ciphertip);

	return rv;
}

static int
tlsm_parse_ciphers(tlsm_ctx *ctx, const char *str)
{
	int cipher_state[ciphernum];
	int rv, i;

	if (!ctx)
		return 0;

	rv = nss_parse_ciphers(str, cipher_state);

	if (rv) {
		/* First disable everything */
		for (i = 0; i < SSL_NumImplementedCiphers; i++)
			SSL_CipherPrefSet(ctx->tc_model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);

		/* Now enable what was requested */
		for (i=0; i<ciphernum; i++) {
			SSLCipherSuiteInfo suite;
			PRBool enabled;

			if (SSL_GetCipherSuiteInfo(ciphers_def[i].num, &suite, sizeof suite)
				== SECSuccess) {
				enabled = cipher_state[i] < 0 ? 0 : cipher_state[i];
				if (enabled == SSL_ALLOWED) {
					if (PK11_IsFIPS() && !suite.isFIPS)    
						enabled = SSL_NOT_ALLOWED;
				}
				SSL_CipherPrefSet(ctx->tc_model, ciphers_def[i].num, enabled);
			}
		}
	}

	return rv == 1 ? 0 : -1;
}

static SECStatus
tlsm_bad_cert_handler(void *arg, PRFileDesc *ssl)
{
	SECStatus success = SECSuccess;
	PRErrorCode err;
	tlsm_ctx *ctx = (tlsm_ctx *)arg;

	if (!ssl || !ctx) {
		return SECFailure;
	}

	err = PORT_GetError();

	switch (err) {
	case SEC_ERROR_UNTRUSTED_ISSUER:
	case SEC_ERROR_UNKNOWN_ISSUER:
	case SEC_ERROR_EXPIRED_CERTIFICATE:
		if (ctx->tc_verify_cert) {
			success = SECFailure;
		}
		break;
Howard Chu's avatar
Howard Chu committed
656
657
658
	/* we bypass NSS's hostname checks and do our own */
	case SSL_ERROR_BAD_CERT_DOMAIN:
		break;
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
	default:
		success = SECFailure;
		break;
	}

	return success;
}

static const char *
tlsm_dump_security_status(PRFileDesc *fd)
{
	char * cp;	/* bulk cipher name */
	char * ip;	/* cert issuer DN */
	char * sp;	/* cert subject DN */
	int    op;	/* High, Low, Off */
	int    kp0;	/* total key bits */
	int    kp1;	/* secret key bits */
	SSL3Statistics * ssl3stats = SSL_GetStatistics();

	SSL_SecurityStatus( fd, &op, &cp, &kp0, &kp1, &ip, &sp );
	Debug( LDAP_DEBUG_TRACE,
		   "TLS certificate verification: subject: %s, issuer: %s, cipher: %s, ",
		   sp ? sp : "-unknown-", ip ? ip : "-unknown-", cp ? cp : "-unknown-" );
	PR_Free(cp);
	PR_Free(ip);
	PR_Free(sp);
	Debug( LDAP_DEBUG_TRACE,
		   "security level: %s, secret key bits: %d, total key bits: %d, ",
		   ((op == SSL_SECURITY_STATUS_ON_HIGH) ? "high" :
			((op == SSL_SECURITY_STATUS_ON_LOW) ? "low" : "off")),
		   kp1, kp0 );

	Debug( LDAP_DEBUG_TRACE,
		   "cache hits: %ld, cache misses: %ld, cache not reusable: %ld\n",
		   ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
		   ssl3stats->hch_sid_cache_not_ok );

	return "";
}

#ifdef READ_PASSWORD_FROM_FILE
static char *
tlsm_get_pin_from_file(const char *token_name, tlsm_ctx *ctx)
{
	char *pwdstr = NULL;
	char *contents = NULL;
	char *lasts = NULL;
	char *line = NULL;
	char *candidate = NULL;
	PRFileInfo file_info;
	PRFileDesc *pwd_fileptr = PR_Open( ctx->tc_pin_file, PR_RDONLY, 00400 );

	/* open the password file */
	if ( !pwd_fileptr ) {
		PRErrorCode errcode = PR_GetError();
		Debug( LDAP_DEBUG_ANY,
		       "TLS: could not open security pin file %s - error %d:%s.\n",
		       ctx->tc_pin_file, errcode,
		       PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
		goto done;
	}

	/* get the file size */
	if ( PR_SUCCESS != PR_GetFileInfo( ctx->tc_pin_file, &file_info ) ) {
		PRErrorCode errcode = PR_GetError();
		Debug( LDAP_DEBUG_ANY,
		       "TLS: could not get file info from pin file %s - error %d:%s.\n",
		       ctx->tc_pin_file, errcode,
		       PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
		goto done;
	}

	/* create a buffer to hold the file contents */
	if ( !( contents = PR_MALLOC( file_info.size + 1 ) ) ) {
		PRErrorCode errcode = PR_GetError();
		Debug( LDAP_DEBUG_ANY,
		       "TLS: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
		       ctx->tc_pin_file, errcode,
		       PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
		goto done;
	}

	/* read file into the buffer */
	if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
		PRErrorCode errcode = PR_GetError();
		Debug( LDAP_DEBUG_ANY,
		       "TLS: could not read the file contents from pin file %s - error %d:%s.\n",
		       ctx->tc_pin_file, errcode,
		       PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
		goto done;
	}

	/* format is [tokenname:]password EOL [tokenname:]password EOL ... */
	/* if you want to use a password containing a colon character, use
	   the special tokenname "default" */
	for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
	      line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
		char *colon;

		if ( !*line ) {
			continue; /* skip blank lines */
		}
		colon = PL_strchr( line, ':' );
		if ( colon ) {
			if ( *(colon + 1) && token_name &&
			     !PL_strncmp( token_name, line, colon-line ) ) {
				candidate = colon + 1; /* found a definite match */
				break;
			} else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
				candidate = colon + 1; /* found possible match */
			}
		} else { /* no token name */
			candidate = line;
		}
	}
done:
	if ( pwd_fileptr ) {
		PR_Close( pwd_fileptr );
	}
	if ( candidate ) {
		pwdstr = PL_strdup( candidate );
	}
	PL_strfree( contents );

	return pwdstr;
}
#endif /* READ_PASSWORD_FROM_FILE */

#ifdef READ_PASSWORD_FROM_STDIN
/*
 * Turn the echoing off on a tty.
 */
static void
echoOff(int fd)
{
	if ( isatty( fd ) ) {
		struct termios tio;
		tcgetattr( fd, &tio );
		tio.c_lflag &= ~ECHO;
		tcsetattr( fd, TCSAFLUSH, &tio );
	}
}

/*
 * Turn the echoing on on a tty.
 */
static void
echoOn(int fd)
{
	if ( isatty( fd ) ) {
		struct termios tio;
		tcgetattr( fd, &tio );
		tio.c_lflag |= ECHO;
		tcsetattr( fd, TCSAFLUSH, &tio );
		tcsetattr( fd, TCSAFLUSH, &tio );
	}
}
#endif /* READ_PASSWORD_FROM_STDIN */

/*
 * This does the actual work of reading the pin/password/pass phrase
 */
static char *
tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
{
	char *token_name = NULL;
	char *pwdstr = NULL;

	token_name = PK11_GetTokenName( slot );
#ifdef READ_PASSWORD_FROM_FILE
	/* Try to get the passwords from the password file if it exists.
	 * THIS IS UNSAFE and is provided for convenience only. Without this
	 * capability the server would have to be started in foreground mode
	 * if using an encrypted key.
	 */
	if ( ctx->tc_pin_file ) {
		pwdstr = tlsm_get_pin_from_file( token_name, ctx );
	}
#endif /* RETRIEVE_PASSWORD_FROM_FILE */
#ifdef READ_PASSWORD_FROM_STDIN
	if ( !pwdstr ) {
		int infd = PR_FileDesc2NativeHandle( PR_STDIN );
		int isTTY = isatty( infd );
		unsigned char phrase[200];
		/* Prompt for password */
		if ( isTTY ) {
			fprintf( stdout,
				 "Please enter pin, password, or pass phrase for security token '%s': ",
				 token_name ? token_name : DEFAULT_TOKEN_NAME );
			echoOff( infd );
		}
		fgets( (char*)phrase, sizeof(phrase), stdin );
		if ( isTTY ) {
			fprintf( stdout, "\n" );
			echoOn( infd );
		}
		/* stomp on newline */
		phrase[strlen((char*)phrase)-1] = 0;

		pwdstr = PL_strdup( (char*)phrase );
	}

#endif /* READ_PASSWORD_FROM_STDIN */
	return pwdstr;
}

/*
 * PKCS11 devices (including the internal softokn cert/key database)
 * may be protected by a pin or password or even pass phrase
 * MozNSS needs a way for the user to provide that
 */
static char *
tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
{
	tlsm_ctx *ctx = (tlsm_ctx *)arg;

	return tlsm_get_pin( slot, retry, ctx );
}

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
static SECStatus
tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
                       PRBool checksig, PRBool isServer)
{
	SECStatus ret = SSL_AuthCertificate(arg, fd, checksig, isServer);

	tlsm_dump_security_status( fd );
	Debug( LDAP_DEBUG_TRACE,
		   "TLS certificate verification: %s\n",
		   ret == SECSuccess ? "ok" : "bad", 0, 0 );

	if ( ret != SECSuccess ) {
		PRErrorCode errcode = PORT_GetError();
		Debug( LDAP_DEBUG_ANY,
			   "TLS certificate verification: Error, %d: %s\n",
			   errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 ) ;
	}

	return ret;
}

static int
tlsm_authenticate_to_slot( tlsm_ctx *ctx, PK11SlotInfo *slot )
{
	int rc = -1;

	if ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) {
		char *token_name = PK11_GetTokenName( slot );
		PRErrorCode errcode = PR_GetError();
		Debug( LDAP_DEBUG_ANY,
			   "TLS: could not authenticate to the security token %s - error %d:%s.\n",
			   token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
	} else {
		rc = 0; /* success */
	}

	return rc;
}

static int
tlsm_init_tokens( tlsm_ctx *ctx )
{
	PK11SlotList *slotList;
	PK11SlotListElement *listEntry;
	int rc = 0;

	slotList = PK11_GetAllTokens( CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, NULL );

	for ( listEntry = PK11_GetFirstSafe( slotList ); !rc && listEntry;
		  listEntry = listEntry->next) {
		PK11SlotInfo *slot = listEntry->slot;
		rc = tlsm_authenticate_to_slot( ctx, slot );
		PK11_FreeSlot(slot);
	}

	return rc;
}

static int
tlsm_init_pem_module( void )
{
	int rc = 0;
	char *fullname = NULL;
	char *configstring = NULL;

	/* get the system dependent library name */
	fullname = PR_GetLibraryName( NULL, pem_library );
	/* Load our PKCS#11 module */
	configstring = PR_smprintf( "library=%s name=PEM parameters=\"\"", fullname );
	PR_smprintf_free( fullname );

	pemMod = SECMOD_LoadUserModule( configstring, NULL, PR_FALSE );
	PR_smprintf_free( configstring );

	if ( !pemMod || !pemMod->loaded ) {
		if ( pemMod ) {
			SECMOD_DestroyModule( pemMod );
			pemMod = NULL;
		}
		rc = -1;
	}

	return rc;
}

static int
tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca )
{
	CK_SLOT_ID slotID;
	PK11SlotInfo *slot = NULL;
	PK11GenericObject *rv;
	CK_ATTRIBUTE *attrs;
	CK_ATTRIBUTE theTemplate[20];
	CK_BBOOL cktrue = CK_TRUE;
	CK_BBOOL ckfalse = CK_FALSE;
	CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
	char tmpslotname[64];
	char *slotname = NULL;
	const char *ptr = NULL;
	char sep = PR_GetDirectorySeparator();

	attrs = theTemplate;

	if ( isca ) {
		slotID = 0; /* CA and trust objects use slot 0 */
		PR_snprintf( tmpslotname, sizeof(tmpslotname), TLSM_PEM_TOKEN_FMT, slotID );
		slotname = tmpslotname;
	} else {
		if ( ctx->tc_slotname == NULL ) { /* need new slot */
			slotID = ++tlsm_slot_count;
			ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
		}
		slotname = ctx->tc_slotname;

		if ( ( ptr = PL_strrchr( filename, sep ) ) ) {
			PL_strfree( ctx->tc_certname );
			++ptr;
			ctx->tc_certname = PR_smprintf( "%s:%s", slotname, ptr );
		}
	}

	slot = PK11_FindSlotByName( slotname );
For faster browsing, not all history is shown. View entire blame