forked from ldmud/ldmud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpkg-gnutls.c
1460 lines (1221 loc) · 43.1 KB
/
pkg-gnutls.c
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
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
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
/*------------------------------------------------------------------
* Wrapper for the GnuTLS module.
*
*------------------------------------------------------------------
*/
#include "driver.h"
#include "machine.h"
#if defined(USE_TLS) && defined(HAS_GNUTLS)
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include "pkg-tls.h"
#include "actions.h"
#include "array.h"
#include "comm.h"
#include "gcollect.h"
#include "interpret.h"
#include "main.h"
#include "mstrings.h"
#include "object.h"
#include "sha1.h"
#include "svalue.h"
#include "xalloc.h"
#include "../mudlib/sys/tls.h"
/*-------------------------------------------------------------------------*/
/* Structs */
/* Maximum number of certificates in a certificate chain.
* If there are more certificates in the chain, the chain will not be loaded
* and an error is logged.
*/
#define MAX_CHAIN_LENGTH 10
/* One server key and corresponding certicate chain. */
struct tls_key_s
{
unsigned char fingerprint[20]; /* SHA1 */
gnutls_x509_crt_t cert[MAX_CHAIN_LENGTH];
gnutls_x509_privkey_t key;
unsigned int num_certs;
};
/*-------------------------------------------------------------------------*/
/* Constants */
static const char *dh_pkcs3 =
"-----BEGIN DH PARAMETERS-----\n"
"MIIBCAKCAQEAnE/wdy2KvsDtoGcoeth2e1CceYOoiEoLTwTumYD3L2kmavYtCM5l\n"
"Z9dUHoOZXKOvBtHUh4N5yld1AuEC6tE3a+Hr4TIkSCaRXUJhNh5kyebkxWM6zlJx\n"
"hGTxDd6WJk1eeWwKa8KFgoEh2WHqNwuBWeSdoAHmw0iVSjbj2lpb/XIVJJQSX8HT\n"
"mWUPIuRaKQmExS4F25dALeFXXYz0bX72FnPgab/fjBNVBbZksV++Plui7NLzn5q+\n"
"gSJfIqbdAdQr7v25rrFowz/ClEMRH0IXM10h8shzr3Cx4e552Z2saV9SRPOgrlcD\n"
"VxyEwepMIUNDCOCPNP2nwwBXav10bGmZ0wIBBQ==\n"
"-----END DH PARAMETERS-----\n";
/* The statically provided Diffie-Hellmann parameters (2048 bits), used as
* default if the administrator does not provide parameters. */
/*-------------------------------------------------------------------------*/
/* Variables */
static Bool tls_is_available = MY_FALSE;
/* Set to TRUE when the TLS layer has been initialised successfully.
*/
static gnutls_certificate_server_credentials x509_cred;
/* The x509 credentials. */
static gnutls_dh_params_t* dh_params = NULL;
/* Pointer to the Diffie-Hellmann parameters, permanently allocated */
static gnutls_priority_t* priority_cache = NULL;
/* Pointer to the priority cache, permanently allocated */
static struct tls_key_s* keys;
/* Our certificate-key-pairs. */
static int num_keys;
/* Number of elements in <keys>. */
static int current_key;
/* Index into <keys>. */
/*-------------------------------------------------------------------------*/
int
tls_import_dh_params (const char* const buffer, size_t length)
/* GnuTLS: Import Diffie Hellman parameters. They are for use with DHE kx
* algorithms. By default, sets the statically provided parameters in the
* source.
* Depending on security requirements, they may be provided by the
* administrator or even re-newed from time to time.
* If successful, the global <dh_params> points to the new parameters,
* otherwise, <dh_params> still points to the old parameters. The memory block
* for the parameters is allocated by pxalloc().
* Unless the very first import fails, <x509_cred> will always point to valid
* parameters.
*
* returns 1 on success, 0 otherwise.
*
* The global <x509_cred> must be initialized.
*/
{
gnutls_dh_params_t* newparam = NULL;
gnutls_dh_params_t* oldparam = dh_params; // pointer auf alte params sichern
unsigned char* pemstr;
int err;
if (buffer == NULL || !length)
{
// use built-in defaults
pemstr = (unsigned char*)dh_pkcs3;
length = strlen(dh_pkcs3);
printf("%s TLS: Importing built-in default DH parameters.\n"
, time_stamp());
debug_message("%s TLS: Importing built-in default DH parameters.\n"
, time_stamp());
}
else
{
pemstr = (unsigned char*)buffer;
printf("%s TLS: Importing user-supplied DH parameters.\n"
, time_stamp());
debug_message("%s TLS: Importing user-supplied DH parameters.\n"
, time_stamp());
}
const gnutls_datum_t p3 = { pemstr, length };
// neue struktur initialisieren
newparam = pxalloc(sizeof(*newparam));
if (!newparam)
{
printf("%s TLS: Error importing Diffie-Hellman parameters: Out of memory.\n"
, time_stamp());
debug_message("%s Error importing Diffie-Hellman parameters: Out ofmemory.\n"
, time_stamp());
return 0;
}
err = gnutls_dh_params_init(newparam);
if (err != GNUTLS_E_SUCCESS)
{
printf("%s TLS: Error importing Diffie-Hellman parameters: %s\n"
, time_stamp(), gnutls_strerror(err) );
debug_message("%s Error importing Diffie-Hellman parameters: %s\n"
, time_stamp(), gnutls_strerror(err));
pfree(newparam);
return 0;
}
// importieren
err = gnutls_dh_params_import_pkcs3(*newparam, &p3, GNUTLS_X509_FMT_PEM);
if (err != GNUTLS_E_SUCCESS)
{
printf("%s TLS: Error importing Diffie-Hellman parameters: %s\n"
, time_stamp(), gnutls_strerror(err) );
debug_message("%s Error importing Diffie-Hellman parameters: %s\n"
, time_stamp(), gnutls_strerror(err));
gnutls_dh_params_deinit(*newparam);
return 0;
}
// update pointers (never fails)
dh_params = newparam;
gnutls_certificate_set_dh_params(x509_cred, *dh_params);
// alte struktur freigeben
if (oldparam)
{
gnutls_dh_params_deinit(*oldparam);
pfree(oldparam);
}
return 1;
} /* tls_import_dh_params() */
/*-------------------------------------------------------------------------*/
int
tls_set_ciphers (const char* buffer)
/* GnuTLS: sets priorities to use.
* These are stored in the global gnutls_priority_t * <priority_cache>.
* If the priority string <buffer> is NULL, the default priorities will be set.
* In case of error, the old priorities will be retained (possibly NULL, which
* defaults to GnuTLS defaults).
*
* returns 1 on success, 0 otherwise.
*
*/
{
gnutls_priority_t* newp = NULL;
gnutls_priority_t* oldp = priority_cache; // pointer auf alte params sichern
const char* pstr;
const char *errstr;
int err;
if (buffer == NULL)
{
// use built-in defaults. We favor stronger ciphers with PFS and disallow SSLv3, MD5, RC4, DES
pstr = "PFS:+SECURE128:-VERS-SSL3.0:-DHE-DSS:-ARCFOUR-128:-MD5:-DES-CBC:%SERVER_PRECEDENCE";
printf("%s TLS: Setting built-in default priorities: %s.\n"
, time_stamp(), pstr);
debug_message("%s TLS: Setting built-in default priorities: %s.\n"
, time_stamp(), pstr);
}
else
{
pstr = buffer;
printf("%s TLS: Setting user-supplied priorities: %s.\n"
, time_stamp(), pstr);
debug_message("%s TLS: Setting user-supplied priorities: %s.\n"
, time_stamp(), pstr);
}
// neue struktur initialisieren
newp = pxalloc(sizeof(*newp));
if (!newp)
{
printf("%s TLS: Error setting priorities.: Out of memory.\n"
, time_stamp());
debug_message("%s Error setting priorities.: Out of memory.\n"
, time_stamp());
return 0;
}
err = gnutls_priority_init(newp, pstr, &errstr);
if (err != GNUTLS_E_SUCCESS)
{
printf("%s TLS: Error parsing priority string: %s at %s.\n"
, time_stamp(), gnutls_strerror(err), errstr );
debug_message("%s Error parsing priority string: %s at %s.\n"
, time_stamp(), gnutls_strerror(err), errstr);
pfree(newp);
return 0;
}
// update pointers
priority_cache = newp;
// alte struktur freigeben
if (oldp)
{
gnutls_priority_deinit(*oldp);
pfree(oldp);
}
return 1;
} // tls_set_ciphers
/*-------------------------------------------------------------------------*/
static void
initialize_tls_session (gnutls_session_t *session, Bool outgoing) __attribute__((nonnull));
static void
initialize_tls_session (gnutls_session_t *session, Bool outgoing)
/* GnuTLS: Initialise a TLS <session>.
* tls_is_available must be TRUE.
*/
{
unsigned int flags;
flags = outgoing ? GNUTLS_CLIENT : GNUTLS_SERVER;
// don't receive signals during send (SIGPIPE)
#ifdef GNUTLS_NOSIGNAL
flags |= GNUTLS_NOSIGNAL;
#endif
gnutls_init(session, flags);
// if we have priorities in the cache, set them.
if (priority_cache)
gnutls_priority_set(*session, *priority_cache);
else
gnutls_priority_set_direct(*session, "NORMAL", NULL); // last fallback
gnutls_credentials_set( *session, GNUTLS_CRD_CERTIFICATE, x509_cred);
gnutls_certificate_server_set_request( *session, GNUTLS_CERT_REQUEST);
gnutls_dh_set_prime_bits( *session, DH_BITS);
gnutls_session_set_ptr( *session, (void*)(intptr_t) current_key);
} /* initialize_tls_session() */
#if defined(ALLOCATOR_WRAPPERS) && GNUTLS_VERSION_NUMBER < 0x030300
/*-------------------------------------------------------------------------*/
static void *
tls_xalloc (size_t size)
/* Wrapper function so that (gnu)tls will use the driver's allocator.
* The wrapper is required as 'pxalloc' itself is a macro.
*/
{
return pxalloc(size);
} /* tls_xalloc() */
/*-------------------------------------------------------------------------*/
static void *
tls_rexalloc (void *old, size_t size) __attribute__((nonnull));
static void *
tls_rexalloc (void *old, size_t size)
/* Wrapper function so that (gnu)tls will use the driver's allocator.
* The wrapper is required as 'prexalloc' itself is a macro.
*/
{
return prexalloc(old, size);
} /* tls_rexalloc() */
/*-------------------------------------------------------------------------*/
static void
tls_xfree (void *p) __attribute__((nonnull));
static void
tls_xfree (void *p)
/* Wrapper function so that (gnu)tls will use the driver's allocator.
* The wrapper is not exactly required for pfree(), but it keeps things
* consistent.
*/
{
return pfree(p);
} /* tls_xfree() */
#endif /* ALLOCATOR_WRAPPERS && GNUTLS_VERSION_NUMBER */
/*-------------------------------------------------------------------------*/
static gnutls_datum_t
tls_read_file (const char * fname, const char * desc)
/* Reads a file fully into memory.
*
* On error returns .data = NULL and logs the error
* (with <desc> as the description of the file type).
*
* Otherwise .data contains the file's content in an xalloced memory block
* (of .size bytes). It's the caller's responsibility to xfree it afterwards.
*/
{
gnutls_datum_t result = { NULL, 0 };
FILE * file;
long fpos;
file = fopen(fname, "rt");
if (!file)
return result;
fseek(file, 0, SEEK_END);
fpos = ftell(file);
if (fpos < 0)
{
fclose(file);
if (desc)
{
printf("%s TLS: Can't read %s: %s.\n"
, time_stamp(), desc, strerror(errno));
debug_message("%s TLS: Can't read %s: %s\n"
, time_stamp(), desc, strerror(errno));
}
return result;
}
result.size = fpos;
result.data = xalloc(result.size);
if (result.data == NULL)
{
fclose(file);
if (desc)
{
printf("%s TLS: Can't read %s: Out of memory.\n"
, time_stamp(), desc);
debug_message("%s TLS: Can't read %s: Out of memory.\n"
, time_stamp(), desc);
}
return result;
}
fseek(file, 0, SEEK_SET);
if (fread(result.data, 1, result.size, file) < result.size)
{
fclose(file);
xfree(result.data);
result.data = NULL;
if (desc)
{
printf("%s TLS: Can't read %s: %s.\n"
, time_stamp(), desc, strerror(errno));
debug_message("%s TLS: Can't read %s: %s\n"
, time_stamp(), desc, strerror(errno));
}
return result;
}
fclose(file);
return result;
}
/*-------------------------------------------------------------------------*/
static Bool
tls_read_cert (int pos, const char * key, const char * cert, const char * password)
/* Reads a key and certificate from the given files into keys[pos].
* <key> and <cert> should be absolute filenames
* (or relative to current i.e. mudlib directory).
* cert may be NULL, then it will be read from the key file.
*
* Returns MY_TRUE on success.
*/
{
int err;
size_t fpsize;
gnutls_datum_t data;
/* Load the key. */
data = tls_read_file(key, cert ? "key" : "key and certificate");
if (data.data == NULL)
return MY_FALSE;
gnutls_x509_privkey_init(&keys[pos].key);
err = gnutls_x509_privkey_import2(keys[pos].key, &data, GNUTLS_X509_FMT_PEM, password, 0);
if (err < 0)
{
printf("%s TLS: Error loading x509 key from '%s': %s\n"
, time_stamp(), key, gnutls_strerror(err));
debug_message("%s TLS: Error loading x509 key from '%s': %s\n"
, time_stamp(), key, gnutls_strerror(err));
gnutls_x509_privkey_deinit(keys[pos].key);
xfree(data.data);
return MY_FALSE;
}
/* Load the ceriticate chain. */
if (cert)
{
/* The certificate has its own file. */
xfree(data.data);
data = tls_read_file(cert, "certificate");
if (data.data == NULL)
{
gnutls_x509_privkey_deinit(keys[pos].key);
return MY_FALSE;
}
}
keys[pos].num_certs = MAX_CHAIN_LENGTH;
err = gnutls_x509_crt_list_import(keys[pos].cert, &keys[pos].num_certs, &data, GNUTLS_X509_FMT_PEM,
#if GNUTLS_VERSION_MAJOR >= 3
GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED | GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED
#else
GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED
#endif
);
if (err < 0 || keys[pos].num_certs == 0)
{
printf("%s TLS: Error loading x509 certificate from '%s': %s\n"
, time_stamp(), cert ? cert : key, gnutls_strerror(err));
debug_message("%s TLS: Error loading x509 certificate from '%s': %s\n"
, time_stamp(), cert ? cert : key, gnutls_strerror(err));
gnutls_x509_privkey_deinit(keys[pos].key);
xfree(data.data);
return MY_FALSE;
}
xfree(data.data);
/* Generate and log its fingerprint. */
fpsize = sizeof(keys[pos].fingerprint);
err = gnutls_x509_crt_get_fingerprint(keys[pos].cert[0], GNUTLS_DIG_SHA1, keys[pos].fingerprint, &fpsize);
if (err < 0)
{
printf("%s TLS: Error calculating fingerprint from '%s': %s\n"
, time_stamp(), cert ? cert : key, gnutls_strerror(err));
debug_message("%s TLS: Error calculating fingerprint from '%s': %s\n"
, time_stamp(), cert ? cert : key, gnutls_strerror(err));
gnutls_x509_privkey_deinit(keys[pos].key);
for (int i = 0; i < keys[pos].num_certs; ++i)
gnutls_x509_crt_deinit(keys[pos].cert[i]);
return MY_FALSE;
}
assert(fpsize == sizeof(keys[pos].fingerprint));
printf("%s TLS: (GnuTLS) X509 certificate from '%s': "
, time_stamp(), cert ? cert : key);
debug_message("%s TLS: (GnuTLS) X509 certificate from '%s': "
, time_stamp(), cert ? cert : key);
for (int i = 0; i < sizeof(keys[pos].fingerprint); ++i)
{
printf( i ? ":%02X" : "%02X", (unsigned char) keys[pos].fingerprint[i] );
debug_message( i ? ":%02X" : "%02X", (unsigned char) keys[pos].fingerprint[i] );
}
printf("\n");
debug_message("\n");
return MY_TRUE;
}
/*-------------------------------------------------------------------------*/
static void
tls_free_keys (void)
/* Free all keys and certificates held in <keys>.
*/
{
if (keys)
{
for (int i = 0; i < num_keys; ++i)
{
gnutls_x509_privkey_deinit(keys[i].key);
for (int j = 0; j < keys[i].num_certs; ++j)
gnutls_x509_crt_deinit(keys[i].cert[j]);
}
xfree(keys);
}
}
/*-------------------------------------------------------------------------*/
void
tls_verify_init (void)
/* Initialize or reinitialize tls certificate storage and revocation lists.
*
* If there are no keys and certificates to be loaded, then this function
* will keep the current keys, because there should be at least one key
* to keep TLS working. We might still end up with no keys, if all files
* are unreadable or contain no valid keys and certificates.
* CAs and CRLs are cleared and reloaded in any case.
*/
{
struct tls_dir_s dir;
const char* fname;
char oldfingerprint[sizeof(keys[0].fingerprint)];
Bool havefingerprint = MY_FALSE;
int num = 0;
/* Remember the current key. */
if (keys)
{
memcpy(oldfingerprint, keys[current_key].fingerprint, sizeof(oldfingerprint));
havefingerprint = MY_TRUE;
}
current_key = 0;
if (tls_opendir(tls_keydirectory, "key and certificate", &dir))
{
/* First get the number of pairs */
while (tls_readdir(&dir) != NULL)
num++;
}
if (tls_keyfile)
num++;
if (num)
{
tls_free_keys();
num_keys = 0;
keys = xalloc(sizeof(struct tls_key_s) * num);
if (!keys)
{
printf("%s TLS: Error loading %d keys: Out of memory.\n"
, time_stamp(), num);
debug_message("%s TLS: Error loading %d keys: Out of memory.\n"
, time_stamp(), num);
}
}
if (num && keys)
{
char password[1024];
size_t pwdlen = tls_get_password(password, sizeof(password));
if (tls_keyfile)
{
if (tls_read_cert(0, tls_keyfile, tls_certfile, pwdlen < 0 ? NULL : password))
num_keys++;
}
if (num_keys < num)
{
tls_opendir(tls_keydirectory, NULL, &dir);
while ((fname = tls_readdir(&dir)) != NULL)
{
/* Some files mysteriously appeared,
* but we have to finish the tls_readdir loop.
*/
if (num_keys >= num)
continue;
if (tls_read_cert(num_keys, fname, NULL, pwdlen < 0 ? NULL : password))
num_keys++;
}
}
/* Restore the old current key, if it's there.
* Otherwise fail silently (then the first
* found key will be the new current key).
*
* We do this silently because it's the usual
* case with just a key file and no key directory.
* In the other case the mudlib will hopefully
* select the right key before the next TLS session starts.
*/
if (havefingerprint)
tls_set_certificate(oldfingerprint, sizeof(oldfingerprint));
}
/* CAs are reloaded in any case, even if there are no certificates there. */
gnutls_certificate_free_cas(x509_cred);
if (tls_trustfile != NULL)
{
int err;
printf("%s TLS: (GnuTLS) trusted x509 certificates from '%s'.\n"
, time_stamp(), tls_trustfile);
debug_message("%s TLS: (GnuTLS) trusted x509 certificates from '%s'.\n"
, time_stamp(), tls_trustfile);
err = gnutls_certificate_set_x509_trust_file(x509_cred, tls_trustfile, GNUTLS_X509_FMT_PEM);
if (err < 0)
{
printf("%s TLS: Error setting x509 verification certificates: %s\n"
, time_stamp(), gnutls_strerror(err));
debug_message("%s TLS: Error setting x509 verification certificates: %s\n"
, time_stamp(), gnutls_strerror(err));
}
}
else if(tls_trustdirectory == NULL)
{
printf("%s TLS: (GnuTLS) Trusted x509 certificates locations not specified.\n"
, time_stamp());
debug_message("%s TLS: (GnuTLS) trusted x509 certificates locations not specified.\n"
, time_stamp());
}
tls_opendir(tls_trustdirectory, "trusted x509 certificates", &dir);
while ((fname = tls_readdir(&dir)) != NULL)
{
int err;
err = gnutls_certificate_set_x509_trust_file(x509_cred, fname, GNUTLS_X509_FMT_PEM);
if (err < 0)
{
printf("%s TLS: Error setting x509 verification certificates from '%s': %s\n"
, time_stamp(), fname, gnutls_strerror(err));
debug_message("%s TLS: Error setting x509 verification certificates from '%s': %s\n"
, time_stamp(), fname, gnutls_strerror(err));
}
}
/* CRLs are also reloaded in any case, even if it's empty. */
gnutls_certificate_free_crls(x509_cred);
if (tls_crlfile != NULL)
{
int err;
printf("%s TLS: (GnuTLS) CRLs from '%s'.\n"
, time_stamp(), tls_crlfile);
debug_message("%s TLS: (GnuTLS) CRLs from '%s'.\n"
, time_stamp(), tls_crlfile);
err = gnutls_certificate_set_x509_crl_file(x509_cred, tls_crlfile, GNUTLS_X509_FMT_PEM);
if (err < 0)
{
printf("%s TLS: Error loading CRLs: %s\n"
, time_stamp(), gnutls_strerror(err));
debug_message("%s TLS: Error loading CRLs: %s\n"
, time_stamp(), gnutls_strerror(err));
}
}
else if(!tls_crldirectory)
{
printf("%s TLS: (GnuTLS) CRL checking disabled.\n"
, time_stamp());
debug_message("%s TLS: (GnuTLS) CRL checking disabled.\n"
, time_stamp());
}
tls_opendir(tls_crldirectory, "CRLs", &dir);
while ((fname = tls_readdir(&dir)) != NULL)
{
int err;
err = gnutls_certificate_set_x509_crl_file(x509_cred, fname, GNUTLS_X509_FMT_PEM);
if (err < 0)
{
printf("%s TLS: Error loading CRL from '%s': %s\n"
, time_stamp(), fname, gnutls_strerror(err));
debug_message("%s TLS: Error loading CRL from '%s': %s\n"
, time_stamp(), fname, gnutls_strerror(err));
}
}
}
/*-------------------------------------------------------------------------*/
#if GNUTLS_VERSION_MAJOR >= 3 || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR >= 11)
static int
tls_select_certificate (gnutls_session_t session
, const gnutls_datum_t *requested_dns
, int num_requested_dns
, const gnutls_pk_algorithm_t *available_algos
, int num_available_algos
, gnutls_retr2_st * st)
/* Called from GnuTLS to select a certificate and key to use.
*
* We store the index into our key list as the GnuTLS session
* pointer (pointer for private use in a session object).
* Note that it's really not a pointer, just the plain index.
*/
{
int keyidx = (intptr_t) gnutls_session_get_ptr( session );
if (!keys)
{
st->ncerts = 0;
return 0;
}
/* There was a tls_refresh_certs() during handshake? */
if (keyidx >= num_keys)
keyidx = current_key;
st->ncerts = keys[keyidx].num_certs;
st->cert.x509 = keys[keyidx].cert;
st->key.x509 = keys[keyidx].key;
st->cert_type = GNUTLS_CRT_X509;
st->key_type = GNUTLS_PRIVKEY_X509;
st->deinit_all = 0;
return 0;
}
#else
static int
tls_select_server_certificate (gnutls_session_t session
, gnutls_retr_st * st)
/* Called from GnuTLS to select a certificate and key to use.
*/
{
int keyidx = (intptr_t) gnutls_session_get_ptr( session );
if (!keys)
{
st->ncerts = 0;
return 0;
}
/* There was a tls_refresh_certs() during handshake? */
if (keyidx >= num_keys)
keyidx = current_key;
st->ncerts = keys[keyidx].num_certs;
st->cert.x509 = keys[keyidx].cert;
st->key.x509 = keys[keyidx].key;
st->type = GNUTLS_CRT_X509;
st->deinit_all = 0;
return 0;
}
static int
tls_select_client_certificate (gnutls_session_t session
, const gnutls_datum_t *requested_dns
, int num_requested_dns
, const gnutls_pk_algorithm_t *available_algos
, int num_available_algos
, gnutls_retr_st * st)
{
return tls_select_server_certificate(session, st);
}
#endif
/*-------------------------------------------------------------------------*/
Bool
tls_set_certificate (char *fingerprint, int len)
/* Sets the certificate used for the next sessions.
* <fingerprint> contains the certificate's fingerprint as
* <len> raw bytes. As long as we're using SHA1 <len>
* should by 20.
*/
{
if (len != sizeof(keys[0].fingerprint))
return MY_FALSE;
if (!keys)
return MY_FALSE;
for (int i = 0; i < num_keys; ++i)
if (!memcmp(fingerprint, keys[i].fingerprint, len))
{
current_key = i;
return MY_TRUE;
}
return MY_FALSE;
}
/*-------------------------------------------------------------------------*/
const unsigned char *
tls_get_certificate_fingerprint (int *len)
/* Returns the current certificate's fingerprint or NULL if there is
* no current certificate.
* If <len> is given, then the length of the fingerprint will be
* stored there. The function returns a pointer to the fingerprint
* as <*len> raw bytes. The returned buffer MUST NOT be freed.
*/
{
if (!keys)
return NULL;
if (len)
*len = sizeof(keys[current_key].fingerprint);
return keys[current_key].fingerprint;
} /* tls_get_certificate_fingerprint() */
/*-------------------------------------------------------------------------*/
void
tls_global_init (void)
/* Initialise the TLS package; to be called once at program startup.
*/
{
if (tls_keyfile == NULL && tls_keydirectory == NULL)
{
printf("%s TLS deactivated.\n", time_stamp());
return;
}
keys = NULL;
current_key = 0;
#if defined(ALLOCATOR_WRAPPERS) && GNUTLS_VERSION_NUMBER < 0x030300
/* In order to be able to identify gnutls allocations as such, we redirect
* all allocations through the driver's allocator. The wrapper functions
* make sure that the allocations are annotated properly with this source
* file.
*/
gnutls_global_set_mem_functions(tls_xalloc,
tls_xalloc,
NULL,
tls_rexalloc,
tls_xfree);
gnutls_global_init();
#elif GNUTLS_VERSION_NUMBER < 0x030300
gnutls_global_init();
#endif
if (strcmp(gnutls_check_version(NULL), GNUTLS_VERSION) != 0)
{
printf("%s TLS: The currently used version of GnuTLS (%s) "
"differs from the one during compilation (%s). This "
"might lead to problems.\n"
, time_stamp(), gnutls_check_version(NULL), GNUTLS_VERSION );
debug_message("%s TLS: The currently used version of OpenSSL (%s) "
"differs from the one during compilation (%s). This "
"might lead to problems.\n"
, time_stamp(), gnutls_check_version(NULL), GNUTLS_VERSION );
}
// Check for decently recent version of gnutls (3.3.8 is currently in
// Debian stable (2016-01-14)). Issue a warning only, we will still work
// with old versions.
if (!gnutls_check_version("3.3.8"))
{
printf("%s TLS: Detected outdated version of GnuTLS (%s). Please "
"consider upgrading.\n"
, time_stamp(), gnutls_check_version(NULL));
debug_message("%s Detected outdated version of GnuTLS (%s). Please "
"consider upgrading."
, time_stamp(), gnutls_check_version(NULL));
}
gnutls_certificate_allocate_credentials(&x509_cred);
#if GNUTLS_VERSION_MAJOR >= 3 || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR >= 11)
gnutls_certificate_set_retrieve_function(x509_cred, &tls_select_certificate);
#else
gnutls_certificate_client_set_retrieve_function(x509_cred, &tls_select_client_certificate);
gnutls_certificate_server_set_retrieve_function(x509_cred, &tls_select_server_certificate);
#endif
tls_verify_init();
tls_import_dh_params(NULL, 0);
// Set default priorities
tls_set_ciphers(NULL);
tls_is_available = MY_TRUE;
} /* tls_global_init() */
/*-------------------------------------------------------------------------*/
void
tls_global_deinit (void)
/* Clean up the TLS package on program termination.
*/
{
if (tls_is_available)
{
gnutls_certificate_free_credentials(x509_cred);
gnutls_dh_params_deinit(*dh_params);
tls_free_keys();
}
#if GNUTLS_VERSION_NUMBER < 0x030300
gnutls_global_deinit();
#endif
tls_is_available = MY_FALSE;
} /* tls_global_deinit() */
/*-------------------------------------------------------------------------*/
int
tls_read (interactive_t *ip, char *buffer, int length) __attribute__((nonnull));
int
tls_read (interactive_t *ip, char *buffer, int length)
/* Read up to <length> bytes data for the TLS connection of <ip>
* and store it in <buffer>.
* Return then number of bytes read, or a negative number if an error
* occurred.
*/
{
int ret;
int retries = 5;
do {
ret = gnutls_record_recv(ip->tls_session, buffer, length);
} while ( ret < 0
&& (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN)
&& (--retries) );
if (ret <= 0)
{
/* Let comm.c handle EINTR and EWOULDBLOCK.
* We are then called again later with the
* same content.
*/
if (ret == GNUTLS_E_INTERRUPTED)
{
errno = EINTR;
return -1;
}
else if (ret == GNUTLS_E_AGAIN)
{
errno = EWOULDBLOCK;
return -1;
}
// all other errors are fatal.
debug_message("%s GnuTLS: Error in receiving data (%s). "
"Closing the connection.\n"
, time_stamp(), gnutls_strerror(ret));
tls_deinit_connection(ip);
/* get_message() expects an errno value.
* ESHUTDOWN will close the connection.
*/
errno = ESHUTDOWN;
}
return (ret < 0 ? -1 : ret);
} /* tls_read() */