This repository has been archived by the owner on Oct 22, 2020. It is now read-only.
/
ssl.c
5680 lines (4946 loc) · 145 KB
/
ssl.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
/*
* OpenVPN -- An application to securely tunnel IP networks
* over a single TCP/UDP port, with support for SSL/TLS-based
* session authentication and key exchange,
* packet encryption, packet authentication, and
* packet compression.
*
* Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
* Copyright (C) 2010 Fox Crypto B.V. <openvpn@fox-it.com>
*
* Additions for eurephia plugin done by:
* David Sommerseth <dazo@users.sourceforge.net> Copyright (C) 2008-2009
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program 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 (see the file COPYING included with this
* distribution); if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* @file Control Channel SSL/Data channel negotiation Module
*/
/*
* The routines in this file deal with dynamically negotiating
* the data channel HMAC and cipher keys through a TLS session.
*
* Both the TLS session and the data channel are multiplexed
* over the same TCP/UDP port.
*/
#include "syshead.h"
#if defined(USE_CRYPTO) && defined(USE_SSL)
#include "error.h"
#include "common.h"
#include "integer.h"
#include "socket.h"
#include "misc.h"
#include "fdmisc.h"
#include "interval.h"
#include "perf.h"
#include "status.h"
#include "gremlin.h"
#include "pkcs11.h"
#include "list.h"
#include "base64.h"
#include "ssl.h"
#include "ssl_verify.h"
#include "ssl_backend.h"
#ifdef WIN32
#include "cryptoapi.h"
#endif
#include "memdbg.h"
#ifndef ENABLE_OCC
static const char ssl_default_options_string[] = "V0 UNDEF";
#endif
static inline const char *
local_options_string (const struct tls_session *session)
{
#ifdef ENABLE_OCC
return session->opt->local_options;
#else
return ssl_default_options_string;
#endif
}
#ifdef MEASURE_TLS_HANDSHAKE_STATS
static int tls_handshake_success; /* GLOBAL */
static int tls_handshake_error; /* GLOBAL */
static int tls_packets_generated; /* GLOBAL */
static int tls_packets_sent; /* GLOBAL */
#define INCR_SENT ++tls_packets_sent
#define INCR_GENERATED ++tls_packets_generated
#define INCR_SUCCESS ++tls_handshake_success
#define INCR_ERROR ++tls_handshake_error
void
show_tls_performance_stats(void)
{
msg (D_TLS_DEBUG_LOW, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
(double) tls_handshake_success / (tls_handshake_success + tls_handshake_error) * 100.0,
tls_handshake_success, tls_handshake_error,
(double) (tls_packets_sent - tls_packets_generated) / tls_packets_generated * 100.0);
}
#else
#define INCR_SENT
#define INCR_GENERATED
#define INCR_SUCCESS
#define INCR_ERROR
#endif
#ifdef BIO_DEBUG
#warning BIO_DEBUG defined
static FILE *biofp; /* GLOBAL */
static bool biofp_toggle; /* GLOBAL */
static time_t biofp_last_open; /* GLOBAL */
static const int biofp_reopen_interval = 600; /* GLOBAL */
static void
close_biofp()
{
if (biofp)
{
ASSERT (!fclose (biofp));
biofp = NULL;
}
}
static void
open_biofp()
{
const time_t current = time (NULL);
const pid_t pid = getpid ();
if (biofp_last_open + biofp_reopen_interval < current)
close_biofp();
if (!biofp)
{
char fn[256];
openvpn_snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
biofp = fopen (fn, "w");
ASSERT (biofp);
biofp_last_open = time (NULL);
biofp_toggle ^= 1;
}
}
static void
bio_debug_data (const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
{
struct gc_arena gc = gc_new ();
if (len > 0)
{
open_biofp();
fprintf(biofp, "BIO_%s %s time=" time_format " bio=" ptr_format " len=%d data=%s\n",
mode, desc, time (NULL), (ptr_type)bio, len, format_hex (buf, len, 0, &gc));
fflush (biofp);
}
gc_free (&gc);
}
static void
bio_debug_oc (const char *mode, BIO *bio)
{
open_biofp();
fprintf(biofp, "BIO %s time=" time_format " bio=" ptr_format "\n",
mode, time (NULL), (ptr_type)bio);
fflush (biofp);
}
#endif
/*
* Max number of bytes we will add
* for data structures common to both
* data and control channel packets.
* (opcode only).
*/
void
tls_adjust_frame_parameters(struct frame *frame)
{
frame_add_to_extra_frame (frame, 1); /* space for opcode */
}
/*
* Max number of bytes we will add
* to control channel packet.
*/
static void
tls_init_control_channel_frame_parameters(const struct frame *data_channel_frame,
struct frame *frame)
{
/*
* frame->extra_frame is already initialized with tls_auth buffer requirements,
* if --tls-auth is enabled.
*/
/* inherit link MTU and extra_link from data channel */
frame->link_mtu = data_channel_frame->link_mtu;
frame->extra_link = data_channel_frame->extra_link;
/* set extra_frame */
tls_adjust_frame_parameters (frame);
reliable_ack_adjust_frame_parameters (frame, CONTROL_SEND_ACK_MAX);
frame_add_to_extra_frame (frame, SID_SIZE + sizeof (packet_id_type));
/* set dynamic link MTU to minimum value */
frame_set_mtu_dynamic (frame, 0, SET_MTU_TUN);
}
void
init_ssl_lib ()
{
tls_init_lib ();
crypto_init_lib ();
}
void
free_ssl_lib ()
{
crypto_uninit_lib ();
tls_free_lib();
}
/*
* OpenSSL library calls pem_password_callback if the
* private key is protected by a password.
*/
static struct user_pass passbuf; /* GLOBAL */
void
pem_password_setup (const char *auth_file)
{
if (!strlen (passbuf.password))
get_user_pass (&passbuf, auth_file, UP_TYPE_PRIVATE_KEY, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE|GET_USER_PASS_PASSWORD_ONLY);
}
int
pem_password_callback (char *buf, int size, int rwflag, void *u)
{
if (buf)
{
/* prompt for password even if --askpass wasn't specified */
pem_password_setup (NULL);
strncpynt (buf, passbuf.password, size);
purge_user_pass (&passbuf, false);
return strlen (buf);
}
return 0;
}
/*
* Auth username/password handling
*/
static bool auth_user_pass_enabled; /* GLOBAL */
static struct user_pass auth_user_pass; /* GLOBAL */
#ifdef ENABLE_CLIENT_CR
static char *auth_challenge; /* GLOBAL */
#endif
void
auth_user_pass_setup (const char *auth_file)
{
auth_user_pass_enabled = true;
if (!auth_user_pass.defined)
{
#if AUTO_USERID
get_user_pass_auto_userid (&auth_user_pass, auth_file);
#elif defined(ENABLE_CLIENT_CR)
get_user_pass_cr (&auth_user_pass, auth_file, UP_TYPE_AUTH, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE, auth_challenge);
#else
get_user_pass (&auth_user_pass, auth_file, UP_TYPE_AUTH, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE);
#endif
}
}
/*
* Disable password caching
*/
void
ssl_set_auth_nocache (void)
{
passbuf.nocache = true;
auth_user_pass.nocache = true;
}
/*
* Set an authentication token
*/
void
ssl_set_auth_token (const char *token)
{
set_auth_token (&auth_user_pass, token);
}
/*
* Forget private key password AND auth-user-pass username/password.
*/
void
ssl_purge_auth (const bool auth_user_pass_only)
{
if (!auth_user_pass_only)
{
#ifdef USE_PKCS11
pkcs11_logout ();
#endif
purge_user_pass (&passbuf, true);
}
purge_user_pass (&auth_user_pass, true);
#ifdef ENABLE_CLIENT_CR
ssl_purge_auth_challenge();
#endif
}
#ifdef ENABLE_CLIENT_CR
void
ssl_purge_auth_challenge (void)
{
free (auth_challenge);
auth_challenge = NULL;
}
void
ssl_put_auth_challenge (const char *cr_str)
{
ssl_purge_auth_challenge();
auth_challenge = string_alloc(cr_str, NULL);
}
#endif
/*
* Cert hash functions
*/
static void
cert_hash_remember (struct tls_session *session, const int error_depth, const unsigned char *sha1_hash)
{
if (error_depth >= 0 && error_depth < MAX_CERT_DEPTH)
{
if (!session->cert_hash_set)
ALLOC_OBJ_CLEAR (session->cert_hash_set, struct cert_hash_set);
if (!session->cert_hash_set->ch[error_depth])
ALLOC_OBJ (session->cert_hash_set->ch[error_depth], struct cert_hash);
{
struct cert_hash *ch = session->cert_hash_set->ch[error_depth];
memcpy (ch->sha1_hash, sha1_hash, SHA_DIGEST_LENGTH);
}
}
}
#if 0
static void
cert_hash_print (const struct cert_hash_set *chs, int msglevel)
{
struct gc_arena gc = gc_new ();
msg (msglevel, "CERT_HASH");
if (chs)
{
int i;
for (i = 0; i < MAX_CERT_DEPTH; ++i)
{
const struct cert_hash *ch = chs->ch[i];
if (ch)
msg (msglevel, "%d:%s", i, format_hex(ch->sha1_hash, SHA_DIGEST_LENGTH, 0, &gc));
}
}
gc_free (&gc);
}
#endif
static void
cert_hash_free (struct cert_hash_set *chs)
{
if (chs)
{
int i;
for (i = 0; i < MAX_CERT_DEPTH; ++i)
free (chs->ch[i]);
free (chs);
}
}
static bool
cert_hash_compare (const struct cert_hash_set *chs1, const struct cert_hash_set *chs2)
{
if (chs1 && chs2)
{
int i;
for (i = 0; i < MAX_CERT_DEPTH; ++i)
{
const struct cert_hash *ch1 = chs1->ch[i];
const struct cert_hash *ch2 = chs2->ch[i];
if (!ch1 && !ch2)
continue;
else if (ch1 && ch2 && !memcmp (ch1->sha1_hash, ch2->sha1_hash, SHA_DIGEST_LENGTH))
continue;
else
return false;
}
return true;
}
else if (!chs1 && !chs2)
return true;
else
return false;
}
static struct cert_hash_set *
cert_hash_copy (const struct cert_hash_set *chs)
{
struct cert_hash_set *dest = NULL;
if (chs)
{
int i;
ALLOC_OBJ_CLEAR (dest, struct cert_hash_set);
for (i = 0; i < MAX_CERT_DEPTH; ++i)
{
const struct cert_hash *ch = chs->ch[i];
if (ch)
{
ALLOC_OBJ (dest->ch[i], struct cert_hash);
memcpy (dest->ch[i]->sha1_hash, ch->sha1_hash, SHA_DIGEST_LENGTH);
}
}
}
return dest;
}
/*
* Extract a field from an X509 subject name.
*
* Example:
*
* /C=US/ST=CO/L=Denver/O=ORG/CN=First-CN/CN=Test-CA/Email=jim@yonan.net
*
* The common name is 'Test-CA'
*
* Return true on success, false on error (insufficient buffer size in 'out'
* to contain result is grounds for error).
*/
static bool
extract_x509_field_ssl (X509_NAME *x509, const char *field_name, char *out, int size)
{
int lastpos = -1;
int tmp = -1;
X509_NAME_ENTRY *x509ne = 0;
ASN1_STRING *asn1 = 0;
unsigned char *buf = (unsigned char *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
int nid = OBJ_txt2nid((char *)field_name);
ASSERT (size > 0);
*out = '\0';
do {
lastpos = tmp;
tmp = X509_NAME_get_index_by_NID(x509, nid, lastpos);
} while (tmp > -1);
/* Nothing found */
if (lastpos == -1)
return false;
x509ne = X509_NAME_get_entry(x509, lastpos);
if (!x509ne)
return false;
asn1 = X509_NAME_ENTRY_get_data(x509ne);
if (!asn1)
return false;
tmp = ASN1_STRING_to_UTF8(&buf, asn1);
if (tmp <= 0)
return false;
strncpynt(out, (char *)buf, size);
{
const bool ret = (strlen ((char *)buf) < size);
OPENSSL_free (buf);
return ret;
}
}
#ifdef ENABLE_X509ALTUSERNAME
static
bool extract_x509_extension(X509 *cert, char *fieldname, char *out, int size)
{
bool retval = false;
X509_EXTENSION *pExt;
char *buf = 0;
int length = 0;
GENERAL_NAMES *extensions;
int nid = OBJ_txt2nid(fieldname);
extensions = (GENERAL_NAMES *)X509_get_ext_d2i(cert, nid, NULL, NULL);
if ( extensions )
{
int numalts;
int i;
/* get amount of alternatives,
* RFC2459 claims there MUST be at least
* one, but we don't depend on it...
*/
numalts = sk_GENERAL_NAME_num(extensions);
/* loop through all alternatives */
for (i=0; i<numalts; i++)
{
/* get a handle to alternative name number i */
const GENERAL_NAME *name = sk_GENERAL_NAME_value (extensions, i );
switch (name->type)
{
case GEN_EMAIL:
ASN1_STRING_to_UTF8((unsigned char**)&buf, name->d.ia5);
if ( strlen (buf) != name->d.ia5->length )
{
msg (D_TLS_ERRORS, "ASN1 ERROR: string contained terminating zero");
OPENSSL_free (buf);
} else {
strncpynt(out, buf, size);
OPENSSL_free(buf);
retval = true;
}
break;
default:
msg (D_TLS_ERRORS, "ASN1 ERROR: can not handle field type %i",
name->type);
break;
}
}
sk_GENERAL_NAME_free (extensions);
}
return retval;
}
#endif /* ENABLE_X509ALTUSERNAME */
#ifdef ENABLE_X509_TRACK
/*
* setenv_x509_track function -- save X509 fields to environment,
* using the naming convention:
*
* X509_{cert_depth}_{name}={value}
*
* This function differs from setenv_x509 below in the following ways:
*
* (1) Only explicitly named attributes in xt are saved, per usage
* of --x509-track program options.
* (2) Only the level 0 cert info is saved unless the XT_FULL_CHAIN
* flag is set in xt->flags (corresponds with prepending a '+'
* to the name when specified by --x509-track program option).
* (3) This function supports both X509 subject name fields as
* well as X509 V3 extensions.
*/
/* worker method for setenv_x509_track */
static void
do_setenv_x509 (struct env_set *es, const char *name, char *value, int depth)
{
char *name_expand;
size_t name_expand_size;
string_mod (value, CC_ANY, CC_CRLF, '?');
msg (D_X509_ATTR, "X509 ATTRIBUTE name='%s' value='%s' depth=%d", name, value, depth);
name_expand_size = 64 + strlen (name);
name_expand = (char *) malloc (name_expand_size);
check_malloc_return (name_expand);
openvpn_snprintf (name_expand, name_expand_size, "X509_%d_%s", depth, name);
setenv_str (es, name_expand, value);
free (name_expand);
}
static void
setenv_x509_track (const struct x509_track *xt, struct env_set *es, const int depth, X509 *x509)
{
X509_NAME *x509_name = X509_get_subject_name (x509);
const char nullc = '\0';
int i;
while (xt)
{
if (depth == 0 || (xt->flags & XT_FULL_CHAIN))
{
i = X509_NAME_get_index_by_NID(x509_name, xt->nid, -1);
if (i >= 0)
{
X509_NAME_ENTRY *ent = X509_NAME_get_entry(x509_name, i);
if (ent)
{
ASN1_STRING *val = X509_NAME_ENTRY_get_data (ent);
unsigned char *buf;
buf = (unsigned char *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
if (ASN1_STRING_to_UTF8 (&buf, val) > 0)
{
do_setenv_x509(es, xt->name, (char *)buf, depth);
OPENSSL_free (buf);
}
}
}
else
{
i = X509_get_ext_by_NID(x509, xt->nid, -1);
if (i >= 0)
{
X509_EXTENSION *ext = X509_get_ext(x509, i);
if (ext)
{
BIO *bio = BIO_new(BIO_s_mem());
if (bio)
{
if (X509V3_EXT_print(bio, ext, 0, 0))
{
if (BIO_write(bio, &nullc, 1) == 1)
{
char *str;
BIO_get_mem_data(bio, &str);
do_setenv_x509(es, xt->name, str, depth);
}
}
BIO_free(bio);
}
}
}
}
}
xt = xt->next;
}
}
#endif
/*
* Save X509 fields to environment, using the naming convention:
*
* X509_{cert_depth}_{name}={value}
*/
static void
setenv_x509 (struct env_set *es, const int error_depth, X509_NAME *x509)
{
int i, n;
int fn_nid;
ASN1_OBJECT *fn;
ASN1_STRING *val;
X509_NAME_ENTRY *ent;
const char *objbuf;
unsigned char *buf;
char *name_expand;
size_t name_expand_size;
n = X509_NAME_entry_count (x509);
for (i = 0; i < n; ++i)
{
ent = X509_NAME_get_entry (x509, i);
if (!ent)
continue;
fn = X509_NAME_ENTRY_get_object (ent);
if (!fn)
continue;
val = X509_NAME_ENTRY_get_data (ent);
if (!val)
continue;
fn_nid = OBJ_obj2nid (fn);
if (fn_nid == NID_undef)
continue;
objbuf = OBJ_nid2sn (fn_nid);
if (!objbuf)
continue;
buf = (unsigned char *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
if (ASN1_STRING_to_UTF8 (&buf, val) <= 0)
continue;
name_expand_size = 64 + strlen (objbuf);
name_expand = (char *) malloc (name_expand_size);
check_malloc_return (name_expand);
openvpn_snprintf (name_expand, name_expand_size, "X509_%d_%s", error_depth, objbuf);
string_mod (name_expand, CC_PRINT, CC_CRLF, '_');
string_mod ((char*)buf, CC_PRINT, CC_CRLF, '_');
setenv_str (es, name_expand, (char*)buf);
free (name_expand);
OPENSSL_free (buf);
}
}
static void
setenv_untrusted (struct tls_session *session)
{
setenv_link_socket_actual (session->opt->es, "untrusted", &session->untrusted_addr, SA_IP_PORT);
}
static void
set_common_name (struct tls_session *session, const char *common_name)
{
if (session->common_name)
{
free (session->common_name);
session->common_name = NULL;
#ifdef ENABLE_PF
session->common_name_hashval = 0;
#endif
}
if (common_name)
{
session->common_name = string_alloc (common_name, NULL);
#ifdef ENABLE_PF
{
const uint32_t len = (uint32_t) strlen (common_name);
if (len)
session->common_name_hashval = hash_func ((const uint8_t*)common_name, len+1, 0);
else
session->common_name_hashval = 0;
}
#endif
}
}
#if OPENSSL_VERSION_NUMBER >= 0x00907000L
bool verify_cert_eku (X509 *x509, const char * const expected_oid) {
EXTENDED_KEY_USAGE *eku = NULL;
bool fFound = false;
if ((eku = (EXTENDED_KEY_USAGE *)X509_get_ext_d2i (x509, NID_ext_key_usage, NULL, NULL)) == NULL) {
msg (D_HANDSHAKE, "Certificate does not have extended key usage extension");
}
else {
int i;
msg (D_HANDSHAKE, "Validating certificate extended key usage");
for(i = 0; !fFound && i < sk_ASN1_OBJECT_num (eku); i++) {
ASN1_OBJECT *oid = sk_ASN1_OBJECT_value (eku, i);
char szOid[1024];
if (!fFound && OBJ_obj2txt (szOid, sizeof (szOid), oid, 0) != -1) {
msg (D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects %s", szOid, expected_oid);
if (!strcmp (expected_oid, szOid)) {
fFound = true;
}
}
if (!fFound && OBJ_obj2txt (szOid, sizeof (szOid), oid, 1) != -1) {
msg (D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects %s", szOid, expected_oid);
if (!strcmp (expected_oid, szOid)) {
fFound = true;
}
}
}
}
if (eku != NULL) {
sk_ASN1_OBJECT_pop_free (eku, ASN1_OBJECT_free);
}
return fFound;
}
bool verify_cert_ku (X509 *x509, const unsigned * const expected_ku, int expected_len) {
ASN1_BIT_STRING *ku = NULL;
bool fFound = false;
if ((ku = (ASN1_BIT_STRING *)X509_get_ext_d2i (x509, NID_key_usage, NULL, NULL)) == NULL) {
msg (D_HANDSHAKE, "Certificate does not have key usage extension");
}
else {
unsigned nku = 0;
int i;
for (i=0;i<8;i++) {
if (ASN1_BIT_STRING_get_bit (ku, i)) {
nku |= 1<<(7-i);
}
}
/*
* Fixup if no LSB bits
*/
if ((nku & 0xff) == 0) {
nku >>= 8;
}
msg (D_HANDSHAKE, "Validating certificate key usage");
for (i=0;!fFound && i<expected_len;i++) {
if (expected_ku[i] != 0) {
msg (D_HANDSHAKE, "++ Certificate has key usage %04x, expects %04x", nku, expected_ku[i]);
if (nku == expected_ku[i]) {
fFound = true;
}
}
}
}
if (ku != NULL) {
ASN1_BIT_STRING_free (ku);
}
return fFound;
}
#endif /* OPENSSL_VERSION_NUMBER */
/*
* nsCertType checking
*/
#define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
static const char *
print_nsCertType (int type)
{
switch (type)
{
case NS_SSL_SERVER:
return "SERVER";
case NS_SSL_CLIENT:
return "CLIENT";
default:
return "?";
}
}
static void
string_mod_sslname (char *str, const unsigned int restrictive_flags, const unsigned int ssl_flags)
{
if (ssl_flags & SSLF_NO_NAME_REMAPPING)
string_mod (str, CC_PRINT, CC_CRLF, '_');
else
string_mod (str, restrictive_flags, 0, '_');
}
/* Get peer cert and store it in pem format in a temporary file
* in tmp_dir
*/
const char *
get_peer_cert(X509_STORE_CTX *ctx, const char *tmp_dir, struct gc_arena *gc)
{
X509 *peercert;
FILE *peercert_file;
const char *peercert_filename="";
if(!tmp_dir)
return NULL;
/* get peer cert */
peercert = X509_STORE_CTX_get_current_cert(ctx);
if(!peercert)
{
msg (M_ERR, "Unable to get peer certificate from current context");
return NULL;
}
/* create tmp file to store peer cert */
peercert_filename = create_temp_file (tmp_dir, "pcf", gc);
/* write peer-cert in tmp-file */
peercert_file = fopen(peercert_filename, "w+");
if(!peercert_file)
{
msg (M_ERR, "Failed to open temporary file : %s", peercert_filename);
return NULL;
}
if(PEM_write_X509(peercert_file,peercert)<0)
{
msg (M_ERR, "Failed to write peer certificate in PEM format");
fclose(peercert_file);
return NULL;
}
fclose(peercert_file);
return peercert_filename;
}
char * x509_username_field; /* GLOBAL */
int
verify_callback (int preverify_ok, X509_STORE_CTX * ctx)
{
char *subject = NULL;
char envname[64];
char common_name[TLS_USERNAME_LEN];
SSL *ssl;
struct tls_session *session;
const struct tls_options *opt;
const int max_depth = MAX_CERT_DEPTH;
struct argv argv = argv_new ();
char *serial = NULL;
/* get the tls_session pointer */
ssl = X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
ASSERT (ssl);
session = (struct tls_session *) SSL_get_ex_data (ssl, mydata_index);
ASSERT (session);
opt = session->opt;
ASSERT (opt);
session->verified = false;
/* get the X509 name */
subject = X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), NULL, 0);
if (!subject)
{
msg (D_TLS_ERRORS, "VERIFY ERROR: depth=%d, could not extract X509 subject string from certificate", ctx->error_depth);
goto err;
}
/* Save X509 fields in environment */
#ifdef ENABLE_X509_TRACK
if (opt->x509_track)
setenv_x509_track (opt->x509_track, opt->es, ctx->error_depth, ctx->current_cert);
else
#endif
setenv_x509 (opt->es, ctx->error_depth, X509_get_subject_name (ctx->current_cert));
/* enforce character class restrictions in X509 name */
string_mod_sslname (subject, X509_NAME_CHAR_CLASS, opt->ssl_flags);
string_replace_leading (subject, '-', '_');
/* extract the username (default is CN) */
#ifdef ENABLE_X509ALTUSERNAME
if (strncmp("ext:",x509_username_field,4) == 0)
{
if (!extract_x509_extension (ctx->current_cert, x509_username_field+4, common_name, sizeof(common_name)))
{
msg (D_TLS_ERRORS, "VERIFY ERROR: could not extract %s extension from X509 subject string ('%s') "
"-- note that the username length is limited to %d characters",
x509_username_field+4,
subject,
TLS_USERNAME_LEN);
goto err;
}
} else
#endif
if (!extract_x509_field_ssl (X509_get_subject_name (ctx->current_cert), x509_username_field, common_name, sizeof(common_name)))
{
if (!ctx->error_depth)
{
msg (D_TLS_ERRORS, "VERIFY ERROR: could not extract %s from X509 subject string ('%s') -- note that the username length is limited to %d characters",
x509_username_field,
subject,
TLS_USERNAME_LEN);
goto err;
}
}
string_mod_sslname (common_name, COMMON_NAME_CHAR_CLASS, opt->ssl_flags);
cert_hash_remember (session, ctx->error_depth, ctx->current_cert->sha1_hash);
#if 0 /* print some debugging info */
{
struct gc_arena gc = gc_new ();
msg (M_INFO, "LOCAL OPT[%d]: %s", ctx->error_depth, opt->local_options);
msg (M_INFO, "X509[%d]: %s", ctx->error_depth, subject);
msg (M_INFO, "SHA1[%d]: %s", ctx->error_depth, format_hex(ctx->current_cert->sha1_hash, SHA_DIGEST_LENGTH, 0, &gc));
gc_free (&gc);
}
#endif
/* did peer present cert which was signed our root cert? */
if (!preverify_ok)
{
/* Remote site specified a certificate, but it's not correct */
msg (D_TLS_ERRORS, "VERIFY ERROR: depth=%d, error=%s: %s",
ctx->error_depth, X509_verify_cert_error_string (ctx->error), subject);
goto err; /* Reject connection */
}
/* warn if cert chain is too deep */
if (ctx->error_depth >= max_depth)
{
msg (D_TLS_ERRORS, "TLS Error: Convoluted certificate chain detected with depth [%d] greater than %d", ctx->error_depth, max_depth);
goto err; /* Reject connection */
}
/* verify level 1 cert, i.e. the CA that signed our leaf cert */
if (ctx->error_depth == 1 && opt->verify_hash)
{
if (memcmp (ctx->current_cert->sha1_hash, opt->verify_hash, SHA_DIGEST_LENGTH))
{
msg (D_TLS_ERRORS, "TLS Error: level-1 certificate hash verification failed");
goto err;
}
}
/* save common name in session object */
if (ctx->error_depth == 0)
set_common_name (session, common_name);
/* export subject name string as environmental variable */
session->verify_maxlevel = max_int (session->verify_maxlevel, ctx->error_depth);
openvpn_snprintf (envname, sizeof(envname), "tls_id_%d", ctx->error_depth);