-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathssl4pl.c
4585 lines (3882 loc) · 127 KB
/
ssl4pl.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
/* Part of SWI-Prolog
Author: Jan van der Steen, Jan Wielemaker, Matt Lilley,
Markus Triska and James Cash
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2004-2024, SWI-Prolog Foundation
VU University Amsterdam
CWI, Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include <config.h>
#include <SWI-Stream.h>
#include <SWI-Prolog.h>
#include <assert.h>
#include <string.h>
#include <openssl/rand.h>
#ifdef O_PLMT
#include <pthread.h>
#endif
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include <openssl/bn.h>
#include <openssl/dh.h>
#define NEED_BIO 1
#define NEED_SSL_ERR 1
#define NEED_SSL_STRDUP 1
#include "cryptolib.c"
#ifdef HAVE_OPENSSL_CORE_NAMES_H
#include <openssl/core_names.h>
#endif
#include "common.h"
#include "ssl_applink.h"
#if defined(__WINDOWS__) || defined (__CYGWIN__)
#define timezone _timezone
#endif
#define SSL_CONFIG_MAGIC 0x539dbe3a
#ifndef SYSTEM_CACERT_FILENAME
#define SYSTEM_CACERT_FILENAME "/etc/ssl/certs/ca-certificates.crt"
#endif
#define SSL_MAX_CERT_KEY_PAIRS 12
typedef int BOOL;
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
static atom_t ATOM_server;
static atom_t ATOM_client;
static atom_t ATOM_password;
static atom_t ATOM_host;
static atom_t ATOM_peer_cert;
static atom_t ATOM_cacerts;
static atom_t ATOM_require_crl;
static atom_t ATOM_crl;
static atom_t ATOM_certificate_file;
static atom_t ATOM_certificate_key_pairs;
static atom_t ATOM_key_file;
static atom_t ATOM_pem_password_hook;
static atom_t ATOM_cert_verify_hook;
static atom_t ATOM_close_parent;
static atom_t ATOM_close_notify;
static atom_t ATOM_disable_ssl_methods;
static atom_t ATOM_min_protocol_version;
static atom_t ATOM_max_protocol_version;
static atom_t ATOM_cipher_list;
static atom_t ATOM_ecdh_curve;
static atom_t ATOM_root_certificates;
static atom_t ATOM_sni_hook;
static atom_t ATOM_alpn_protocols;
static atom_t ATOM_alpn_protocol_hook;
static atom_t ATOM_sslv2;
static atom_t ATOM_sslv23;
static atom_t ATOM_sslv3;
static atom_t ATOM_tlsv1;
static atom_t ATOM_tlsv1_1;
static atom_t ATOM_tlsv1_2;
static atom_t ATOM_tlsv1_3;
static atom_t ATOM_minus; /* "-" */
static functor_t FUNCTOR_unsupported_hash_algorithm1;
static functor_t FUNCTOR_system1;
static functor_t FUNCTOR_error2;
static functor_t FUNCTOR_ssl_error4;
static functor_t FUNCTOR_permission_error3;
static functor_t FUNCTOR_version1;
static functor_t FUNCTOR_notbefore1;
static functor_t FUNCTOR_notafter1;
static functor_t FUNCTOR_subject1;
static functor_t FUNCTOR_issuername1;
static functor_t FUNCTOR_serial1;
static functor_t FUNCTOR_public_key1;
static functor_t FUNCTOR_private_key1;
static functor_t FUNCTOR_rsa8;
static functor_t FUNCTOR_ec3;
static functor_t FUNCTOR_key1;
static functor_t FUNCTOR_hash1;
static functor_t FUNCTOR_next_update1;
static functor_t FUNCTOR_signature1;
static functor_t FUNCTOR_signature_algorithm1;
static functor_t FUNCTOR_to_be_signed1;
static functor_t FUNCTOR_equals2;
static functor_t FUNCTOR_crl1;
static functor_t FUNCTOR_revocations1;
static functor_t FUNCTOR_revoked2;
#ifndef OPENSSL_NO_SSL2
static functor_t FUNCTOR_session_key1;
#endif
static functor_t FUNCTOR_cipher1;
static functor_t FUNCTOR_master_key1;
static functor_t FUNCTOR_session_id1;
static functor_t FUNCTOR_client_random1;
static functor_t FUNCTOR_server_random1;
static functor_t FUNCTOR_system1;
static functor_t FUNCTOR_unknown1;
static functor_t FUNCTOR_alpn_protocol1;
static functor_t FUNCTOR_file1;
static functor_t FUNCTOR_certificate1;
#ifdef USE_EVP_API
#define RSAKEY EVP_PKEY
#define ECKEY EVP_PKEY
#define DHKEY EVP_PKEY
#else
#define RSAKEY RSA
#define ECKEY EC_KEY
#define DHKEY DH
#endif
typedef enum
{ PL_SSL_NONE,
PL_SSL_SERVER,
PL_SSL_CLIENT
} PL_SSL_ROLE;
typedef enum
{ SSL_PL_OK,
SSL_PL_RETRY,
SSL_PL_ERROR
} SSL_PL_STATUS;
#define SSL_CERT_VERIFY_MORE 0
static STACK_OF(X509) *system_root_store = NULL;
static int system_root_store_fetched = FALSE;
#ifdef O_PLMT
static pthread_mutex_t root_store_lock = PTHREAD_MUTEX_INITIALIZER;
#endif
/*
* Index of our config data in the SSL data
*/
static int ssl_idx;
static int ctx_idx;
typedef struct pl_cert_key_pair
{ X509 *certificate_X509;
char *key;
char *certificate;
} PL_CERT_KEY_PAIR;
typedef struct pl_ssl_callback
{ record_t goal;
module_t module;
} PL_SSL_CALLBACK;
typedef struct pl_ssl_protocol
{ BOOL is_set;
int version;
} PL_SSL_PROTOCOL;
typedef struct
{ int references;
STACK_OF(X509) *cacerts;
} cacert_stack;
typedef struct pl_ssl
{ long magic;
/*
* Are we server or client
*/
PL_SSL_ROLE role;
int close_parent;
atom_t atom;
BOOL close_notify;
/*
* Context, Certificate, SSL info
*/
SSL_CTX *ctx;
int idx;
X509 *peer_cert;
/*
* In case of the client the host we're connecting to.
*/
char *host;
/*
* Various parameters affecting the SSL layer
*/
cacert_stack *cacerts;
char *certificate_file;
char *key_file;
PL_CERT_KEY_PAIR cert_key_pairs[SSL_MAX_CERT_KEY_PAIRS];
int num_cert_key_pairs;
char *cipher_list;
char *ecdh_curve;
STACK_OF(X509_CRL) *crl_list;
char *password;
BOOL crl_required;
BOOL peer_cert_required;
PL_SSL_PROTOCOL min_protocol;
PL_SSL_PROTOCOL max_protocol;
/*
* Application defined handlers
*/
PL_SSL_CALLBACK cb_cert_verify;
PL_SSL_CALLBACK cb_pem_passwd;
PL_SSL_CALLBACK cb_sni;
PL_SSL_CALLBACK cb_alpn_proto;
#ifndef HAVE_X509_CHECK_HOST
int hostname_check_status;
#endif
unsigned char *alpn_protos;
size_t alpn_protos_len;
} PL_SSL;
typedef struct ssl_instance
{ PL_SSL *config;
SSL *ssl;
IOSTREAM *sread; /* wire streams */
IOSTREAM *swrite;
IOSTREAM *dread; /* data streams */
IOSTREAM *dwrite;
int close_needed;
BOOL fatal_alert;
} PL_SSL_INSTANCE;
typedef enum
{ RSA_MODE, EVP_MODE
} crypt_mode_t;
/*******************************
* ATOMIC *
*******************************/
#if O_PLMT
#ifdef _MSC_VER
#define ATOMIC_INC(ptr) _Generic((*ptr), \
int: _InterlockedIncrement((long*)ptr), \
unsigned int: _InterlockedIncrement((long*)ptr), \
size_t: _InterlockedIncrement64((__int64*)ptr), \
__int64: _InterlockedIncrement64((__int64*)ptr))
#define ATOMIC_DEC(ptr) _Generic((*ptr), \
int: _InterlockedDecrement((long*)ptr), \
unsigned int: _InterlockedDecrement((long*)ptr), \
size_t: _InterlockedDecrement64((__int64*)ptr), \
__int64: _InterlockedDecrement64((__int64*)ptr))
#else
#define ATOMIC_ADD(ptr, v) __atomic_add_fetch(ptr, v, __ATOMIC_SEQ_CST)
#define ATOMIC_SUB(ptr, v) __atomic_sub_fetch(ptr, v, __ATOMIC_SEQ_CST)
#define ATOMIC_INC(ptr) ATOMIC_ADD(ptr, 1) /* ++(*ptr) */
#define ATOMIC_DEC(ptr) ATOMIC_SUB(ptr, 1) /* --(*ptr) */
#define __COMPARE_AND_SWAP(at, from, to) \
__atomic_compare_exchange_n(at, &(from), to, FALSE, \
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)
#endif
static inline int
COMPARE_AND_SWAP_PTR(void *at, void *from, void *to)
{
#ifdef _MSC_VER
# if SIZEOF_VOIDP == 4
return _InterlockedCompareExchange(at, (long)to, (long)from) == (long)from;
# else
return _InterlockedCompareExchange64(at, (int64_t)to, (int64_t)from) == (int64_t)from;
#endif
#else
void **ptr = at;
return __COMPARE_AND_SWAP(ptr, from, to);
#endif
}
#else
#define ATOMIC_INC(ptr) (++(*ptr))
#define ATOMIC_DEC(ptr) (--(*ptr))
#define COMPARE_AND_SWAP(ptr,o,n) (*ptr == o ? (*ptr = n), 1 : 0)
#define COMPARE_AND_SWAP_PTR(ptr,o,n) COMPARE_AND_SWAP(ptr,o,n)
#endif
/*******************************
* MANAGE STRUCT VALUES *
*******************************/
#define set_string(obj, field, str) \
attr_set_string(&((obj)->field), str)
static void
attr_set_string(char **where, const char *str)
{ if ( *where )
free(*where);
if ( str )
*where = ssl_strdup(str);
}
static cacert_stack *
new_cacert_stack(void)
{ cacert_stack *s = malloc(sizeof(*s));
if ( s )
{ s->references = 1;
if ( !(s->cacerts=sk_X509_new_null()) )
{ free(s);
s = NULL;
}
}
return s;
}
static cacert_stack *
dup_cacert_stack(cacert_stack *s)
{ if ( s )
ATOMIC_INC(&s->references);
return s;
}
static void
free_cacert_stack(cacert_stack *s)
{ if ( s && ATOMIC_DEC(&s->references) == 0 )
{ sk_X509_pop_free(s->cacerts, X509_free);
free(s);
}
}
/*******************************
* GET TYPED TERM ARGUMENTS *
*******************************/
static int
get_char_arg(int a, term_t t, char **s)
{ term_t t2 = PL_new_term_ref();
_PL_get_arg(a, t, t2);
return PL_get_chars(t2, s, CVT_ATOM|CVT_STRING|CVT_EXCEPTION);
}
static int
get_bool_arg(int a, term_t t, int *i)
{ term_t t2 = PL_new_term_ref();
_PL_get_arg(a, t, t2);
return PL_get_bool_ex(t2, i);
}
static int
get_file_arg(int a, term_t t, char **f)
{ term_t t2 = PL_new_term_ref();
_PL_get_arg(a, t, t2);
return PL_get_file_name(t2, f, PL_FILE_EXIST);
}
static int
unify_bignum(term_t t, const BIGNUM *bn)
{ int rc;
if ( bn )
{ char *hex = BN_bn2hex(bn);
rc = PL_unify_chars(t, PL_STRING|REP_ISO_LATIN_1, (size_t)-1, hex);
OPENSSL_free(hex);
} else
{ rc = PL_unify_atom(t, ATOM_minus);
}
return rc;
}
static int
unify_bignum_arg(int a, term_t t, const BIGNUM *bn)
{ term_t arg;
if ( (arg = PL_new_term_ref()) &&
PL_get_arg(a, t, arg) )
{ int rc = unify_bignum(arg, bn);
PL_reset_term_refs(arg);
return rc;
}
return FALSE;
}
/* Note that while this might seem incredibly hacky, it is
essentially the same algorithm used by X509_cmp_time to
parse the date. Some
Fractional seconds are ignored. This is also largely untested - there
may be a lot of edge cases that dont work!
*/
static int
unify_asn1_time(term_t term, const ASN1_TIME *time)
{ time_t result = 0;
char buffer[24];
char* pbuffer = buffer;
size_t length = time->length;
char * source = (char *)time->data;
struct tm time_tm;
time_t lSecondsFromUTC;
if (time->type == V_ASN1_UTCTIME)
{ if ((length < 11) || (length > 17))
{ ssl_deb(2, "Unable to parse time - expected either 11 or 17 chars,"
" not %d", length);
return FALSE;
}
/* Otherwise just get the first 10 chars - ignore seconds */
memcpy(pbuffer, source, 10);
pbuffer += 10;
source += 10;
length -= 10;
} else
{ if (length < 13)
{ ssl_deb(2, "Unable to parse time - expected at least 13 chars,"
" not %d", length);
return FALSE;
}
/* Otherwise just get the first 12 chars - ignore seconds */
memcpy(pbuffer, source, 12);
pbuffer += 12;
source += 12;
length -= 12;
}
/* Next find end of string */
if ((*source == 'Z') || (*source == '-') || (*source == '+'))
{ *(pbuffer++) = '0';
*(pbuffer++) = '0';
} else
{ *(pbuffer++) = *(source++);
*(pbuffer++) = *(source++);
if (*source == '.')
{ source++;
while ((*source >= '0') && (*source <= '9'))
source++;
}
}
*(pbuffer++) = 'Z';
*(pbuffer++) = '\0';
/* If not UTC, calculate offset */
if (*source == 'Z')
{ lSecondsFromUTC = 0;
} else
{ if ( length < 6 || (*source != '+' && source[5] != '-') )
{ ssl_deb(2, "Unable to parse time. Missing UTC offset");
return FALSE;
}
lSecondsFromUTC = ((source[1]-'0') * 10 + (source[2]-'0')) * 60;
lSecondsFromUTC += (source[3]-'0') * 10 + (source[4]-'0');
if (*source == '-')
lSecondsFromUTC = -lSecondsFromUTC;
}
/* Parse date */
time_tm.tm_sec = ((buffer[10] - '0') * 10) + (buffer[11] - '0');
time_tm.tm_min = ((buffer[8] - '0') * 10) + (buffer[9] - '0');
time_tm.tm_hour = ((buffer[6] - '0') * 10) + (buffer[7] - '0');
time_tm.tm_mday = ((buffer[4] - '0') * 10) + (buffer[5] - '0');
time_tm.tm_mon = (((buffer[2] - '0') * 10) + (buffer[3] - '0')) - 1;
time_tm.tm_year = ((buffer[0] - '0') * 10) + (buffer[1] - '0');
if (time_tm.tm_year < 50)
time_tm.tm_year += 100; /* according to RFC 2459 */
time_tm.tm_wday = 0;
time_tm.tm_yday = 0;
time_tm.tm_isdst = 0; /* No DST adjustment requested, though */
/* mktime might do it anyway */
#ifdef HAVE_TIMEGM
result = timegm(&time_tm);
if ((time_t)-1 != result)
{ result += lSecondsFromUTC;
} else
{ ssl_deb(2, "timegm() failed");
return FALSE;
}
#else
result = mktime(&time_tm);
/* mktime assumes that the time_tm contains information for localtime. */
/* Convert back to UTC: */
if ((time_t)-1 != result)
{ long tz;
#ifdef _MSC_VER
_get_timezone(&tz);
#else
tz = timezone;
#endif
result += lSecondsFromUTC; /* Add in the UTC offset of the original value */
result -= tz; /* Adjust for localtime */
} else
{ ssl_deb(2, "mktime() failed");
return FALSE;
}
#endif
return PL_unify_int64(term, result);
}
static const EVP_MD *
algorithm_to_type(const ASN1_OBJECT* algorithm, int *nid)
{ *nid = OBJ_obj2nid(algorithm);
/* Annoyingly, EVP_get_digestbynid doesnt work for some of these
algorithms. Instead check for them explicitly and set the digest manually
*/
switch (*nid)
{ case NID_ecdsa_with_SHA1:
return EVP_sha1();
case NID_ecdsa_with_SHA256:
return EVP_sha256();
case NID_ecdsa_with_SHA384:
return EVP_sha384();
#ifdef HAVE_OPENSSL_MD2_H
case NID_md2WithRSAEncryption:
return EVP_md2();
#endif
}
return EVP_get_digestbynid(*nid);
}
#if defined(HAVE_X509_DIGEST) && defined(HAVE_X509_CRL_DIGEST)
static int
hash_X509_digest_wrapper(const void *data, const EVP_MD *type,
unsigned char* md, unsigned int *l)
{ return X509_digest((X509 *) data, type, md, l);
}
static int
hash_X509_crl_digest_wrapper(const void *data, const EVP_MD *type,
unsigned char* md, unsigned int *l)
{ return X509_CRL_digest((X509_CRL *) data, type, md, l);
}
static int
unify_hash(term_t hash, const ASN1_OBJECT* algorithm,
int (*data_to_digest)(const void*, const EVP_MD *,
unsigned char*, unsigned int*),
void *data)
{ int nid;
const EVP_MD *type = algorithm_to_type(algorithm, &nid);
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_length;
if ( type == NULL )
return PL_unify_term(hash,
PL_FUNCTOR, FUNCTOR_unsupported_hash_algorithm1,
PL_INT, nid);
if ( !data_to_digest(data, type, digest, &digest_length) )
return FALSE;
return unify_bytes_hex(hash, digest_length, digest);
}
#else
static int
i2d_X509_CRL_INFO_wrapper(void* i, unsigned char** d)
{ return i2d_X509_CRL_INFO(i, d);
}
static int
i2d_X509_CINF_wrapper(void* i, unsigned char** d)
{ return i2d_X509_CINF(i, d);
}
static int
unify_hash(term_t hash, const ASN1_OBJECT* algorithm,
int (*i2d)(void*, unsigned char**), void * data)
{ int nid;
const EVP_MD *type = algorithm_to_type(algorithm, &nid);
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
int digestible_length;
unsigned char* digest_buffer;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_length;
unsigned char* p;
/* Generate hash */
if ( type == NULL )
return PL_unify_term(hash,
PL_FUNCTOR, FUNCTOR_unsupported_hash_algorithm1,
PL_INT, nid);
digestible_length=i2d(data,NULL);
digest_buffer = PL_malloc(digestible_length);
if ( digest_buffer == NULL )
return PL_resource_error("memory");
/* i2d_X509_CINF will change the value of p. We need to pass in a copy */
p = digest_buffer;
i2d(data,&p);
if (!EVP_DigestInit(ctx, type))
{ EVP_MD_CTX_free(ctx);
PL_free(digest_buffer);
return raise_ssl_error(ERR_get_error());
}
if (!EVP_DigestUpdate(ctx, digest_buffer, digestible_length))
{ EVP_MD_CTX_free(ctx);
PL_free(digest_buffer);
return raise_ssl_error(ERR_get_error());
}
if (!EVP_DigestFinal(ctx, digest, &digest_length))
{ EVP_MD_CTX_free(ctx);
PL_free(digest_buffer);
return raise_ssl_error(ERR_get_error());
}
EVP_MD_CTX_free(ctx);
PL_free(digest_buffer);
return unify_bytes_hex(hash, digest_length, digest);
}
#endif
static int
unify_name(term_t term, X509_NAME* name)
{ int ni;
term_t list = PL_copy_term_ref(term);
term_t item = PL_new_term_ref();
if ( name == NULL )
return PL_unify_term(term, PL_CHARS, "<null>");
for (ni = 0; ni < X509_NAME_entry_count(name); ni++)
{ X509_NAME_ENTRY* e = X509_NAME_get_entry(name, ni);
ASN1_STRING* entry_data = X509_NAME_ENTRY_get_data(e);
unsigned char *utf8_data;
int rc;
if ( ASN1_STRING_to_UTF8(&utf8_data, entry_data) < 0 )
return PL_resource_error("memory");
rc = ( PL_unify_list(list, item, list) &&
PL_unify_term(
item,
PL_FUNCTOR, FUNCTOR_equals2,
PL_CHARS, OBJ_nid2sn(OBJ_obj2nid(X509_NAME_ENTRY_get_object(e))),
PL_UTF8_CHARS, utf8_data)
);
OPENSSL_free(utf8_data);
if ( !rc )
return FALSE;
}
return PL_unify_nil(list);
}
#if SSL_API_0
#define X509_REVOKED_get0_serialNumber(R) ((R)->serialNumber)
#define X509_REVOKED_get0_revocationDate(R) ((R)->revocationDate)
#define EVP_PKEY_base_id(key) ((key)->type)
#define X509_CRL_get0_nextUpdate(C) X509_CRL_get_nextUpdate(C)
#ifndef HAVE_X509_CRL_GET0_SIGNATURE
/* Avoid conflict if the prototype is there, but the function is not */
#define X509_CRL_get0_signature my_X509_CRL_get0_signature
static void
X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
const X509_ALGOR **palg)
{ *psig = crl->signature;
*palg = crl->sig_alg;
}
#endif
#ifndef HAVE_X509_GET0_SIGNATURE
/* Avoid conflict if the prototype is there, but the function is not */
#define X509_get0_signature my_X509_get0_signature
static void
X509_get0_signature(const ASN1_BIT_STRING **psig, const X509_ALGOR **palg,
const X509 *data)
{
*psig = data->signature;
*palg = data->sig_alg;
}
#endif
#endif
static int
unify_crl(term_t term, X509_CRL* crl)
{ const ASN1_BIT_STRING *psig;
const X509_ALGOR *palg;
STACK_OF(X509_REVOKED) *revoked = X509_CRL_get_REVOKED(crl);
int i;
term_t item = PL_new_term_ref();
term_t hash = PL_new_term_ref();
term_t issuer = PL_new_term_ref();
term_t revocations = PL_new_term_ref();
term_t list = PL_copy_term_ref(revocations);
term_t next_update = PL_new_term_ref();
term_t signature = PL_new_term_ref();
int result = 1;
long n;
unsigned char* p;
term_t revocation_date;
BIO* mem;
mem = BIO_new(BIO_s_mem());
if (mem == NULL)
return PL_resource_error("memory");
X509_CRL_get0_signature(crl, &psig, &palg);
i2a_ASN1_INTEGER(mem, (ASN1_BIT_STRING *) psig);
if (!(unify_name(issuer, X509_CRL_get_issuer(crl)) &&
#ifdef HAVE_X509_CRL_DIGEST
unify_hash(hash, palg->algorithm, hash_X509_crl_digest_wrapper, crl) &&
#else
unify_hash(hash, palg->algorithm, i2d_X509_CRL_INFO_wrapper, crl->crl) &&
#endif
unify_asn1_time(next_update, X509_CRL_get0_nextUpdate(crl)) &&
unify_bytes_hex(signature, psig->length, psig->data) &&
PL_unify_term(term,
PL_LIST, 5,
PL_FUNCTOR, FUNCTOR_issuername1,
PL_TERM, issuer,
PL_FUNCTOR, FUNCTOR_signature1,
PL_TERM, signature,
PL_FUNCTOR, FUNCTOR_hash1,
PL_TERM, hash,
PL_FUNCTOR, FUNCTOR_next_update1,
PL_TERM, next_update,
PL_FUNCTOR, FUNCTOR_revocations1,
PL_TERM, revocations)))
{ return FALSE;
}
for (i = 0; i < sk_X509_REVOKED_num(revoked); i++)
{ X509_REVOKED *r = sk_X509_REVOKED_value(revoked, i);
(void)BIO_reset(mem);
i2a_ASN1_INTEGER(mem, X509_REVOKED_get0_serialNumber(r));
result &= (((n = BIO_get_mem_data(mem, &p)) > 0) &&
PL_unify_list(list, item, list) &&
(revocation_date = PL_new_term_ref()) &&
unify_asn1_time(revocation_date, X509_REVOKED_get0_revocationDate(r)) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_revoked2,
PL_NCHARS, (size_t)n, p,
PL_TERM, revocation_date));
if ( BIO_reset(mem) != 1 )
{ BIO_free(mem);
// The only reason I can imagine this would fail is out of memory
return PL_resource_error("memory");
}
}
BIO_free(mem);
return result && PL_unify_nil(list);
}
static int
unify_rsa(term_t item, RSAKEY* rsa)
{
#if SSL_API_0
return ( PL_unify_functor(item, FUNCTOR_rsa8) &&
unify_bignum_arg(1, item, rsa->n) &&
unify_bignum_arg(2, item, rsa->e) &&
unify_bignum_arg(3, item, rsa->d) &&
unify_bignum_arg(4, item, rsa->p) &&
unify_bignum_arg(5, item, rsa->q) &&
unify_bignum_arg(6, item, rsa->dmp1) &&
unify_bignum_arg(7, item, rsa->dmq1) &&
unify_bignum_arg(8, item, rsa->iqmp)
);
#else
#ifdef USE_EVP_API
BIGNUM *n = NULL, *e = NULL, *d = NULL,
*p = NULL, *q = NULL,
*dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_N, &n);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_E, &e);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_D, &d);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_FACTOR1, &p);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_FACTOR2, &q);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_EXPONENT1, &dmp1);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_EXPONENT2, &dmq1);
EVP_PKEY_get_bn_param(rsa, OSSL_PKEY_PARAM_RSA_COEFFICIENT1, &iqmp);
#else
const BIGNUM *n = NULL, *e = NULL, *d = NULL,
*p = NULL, *q = NULL,
*dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
RSA_get0_key(rsa, &n, &e, &d);
RSA_get0_factors(rsa, &p, &q);
RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
#endif
return ( PL_unify_functor(item, FUNCTOR_rsa8) &&
unify_bignum_arg(1, item, n) &&
unify_bignum_arg(2, item, e) &&
unify_bignum_arg(3, item, d) &&
unify_bignum_arg(4, item, p) &&
unify_bignum_arg(5, item, q) &&
unify_bignum_arg(6, item, dmp1) &&
unify_bignum_arg(7, item, dmq1) &&
unify_bignum_arg(8, item, iqmp)
);
#endif
}
#ifndef OPENSSL_NO_EC
static int
unify_ec(term_t item, ECKEY *key)
{ unsigned char *buf = NULL;
int rc;
term_t privkey, pubkey;
#ifdef USE_EVP_API
BIGNUM* priv_bn;
size_t publen;
size_t grouplen;
unsigned char* group;
EVP_PKEY_get_octet_string_param(key, "pub", NULL, 0, &publen);
buf = OPENSSL_malloc(publen);
EVP_PKEY_get_octet_string_param(key, "pub", buf, publen, NULL);
EVP_PKEY_get_bn_param(key, "priv", &priv_bn);
EVP_PKEY_get_octet_string_param(key, "group", NULL, 0, &grouplen);
group = PL_malloc(grouplen);
EVP_PKEY_get_octet_string_param(key, "group", group, grouplen, NULL);
#else
int publen = i2o_ECPublicKey(key, &buf);
const BIGNUM* priv_bn = EC_KEY_get0_private_key(key);
const char* group = OBJ_nid2sn(EC_GROUP_get_curve_name(EC_KEY_get0_group(key)));
#endif
if ( publen < 0 )
return raise_ssl_error(ERR_get_error());
rc = ( (pubkey = PL_new_term_ref()) &&
(privkey = PL_new_term_ref()) &&
unify_bignum(privkey, priv_bn) &&
unify_bytes_hex(pubkey, publen, buf) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_ec3,
PL_TERM, privkey,
PL_TERM, pubkey,
PL_CHARS, group));
OPENSSL_free(buf);
#ifdef USE_EVP_API
PL_free(group);
#endif
return rc;
}
#endif
static int
unify_key(EVP_PKEY* key, functor_t type, term_t item)
{ if ( type )
{ term_t arg;
if ( !(arg=PL_new_term_ref()) ||
!PL_unify_functor(item, type) ||
!PL_get_arg(1, item, arg) )
return FALSE;
item = arg;
}
/* EVP_PKEY_get1_* returns a copy of the existing key */
/* We can just call unify_rsa or unify_ec directly if we are using OpenSSL 3.0+ since
those functions just take a EVP_PKEY in
*/
switch (EVP_PKEY_base_id(key))
{
#ifndef USE_EVP_API
int rc;
#endif
#ifndef OPENSSL_NO_RSA
case EVP_PKEY_RSA:
#ifdef USE_EVP_API
return unify_rsa(item, key);
#else
{ RSAKEY* rsa = EVP_PKEY_get1_RSA(key);
rc = unify_rsa(item, rsa);
RSA_free(rsa);
return rc;
}
#endif
#endif
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
#ifdef USE_EVP_API
return unify_ec(item, key);
#else
{ EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
rc = unify_ec(item, ec);
EC_KEY_free(ec);
return rc;
}
#endif
#endif
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
#ifdef USE_EVP_API
return PL_unify_atom_chars(item, "dh_key");
#else
{ DH* dh = EVP_PKEY_get1_DH(key);
rc = PL_unify_atom_chars(item, "dh_key");
DH_free(dh);
return rc;
}
#endif
#endif
#ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
#ifdef USE_EVP_API
return PL_unify_atom_chars(item, "dsa_key");
#else
{ DSA* dsa = EVP_PKEY_get1_DSA(key);
rc = PL_unify_atom_chars(item, "dsa_key");
DSA_free(dsa);
return rc;
}
#endif
#endif
default:
/* Unknown key type */
return PL_representation_error("ssl_key");
}
return TRUE;
}
static int
unify_public_key(EVP_PKEY* key, term_t item)
{ return unify_key(key, FUNCTOR_public_key1, item);
}
static int
unify_private_key(EVP_PKEY* key, term_t item)
{ return unify_key(key, FUNCTOR_private_key1, item);
}
#ifndef HAVE_X509_GET0_NOTBEFORE
#define X509_get0_notBefore(C) X509_get_notBefore(C)
#endif
#ifndef HAVE_X509_GET0_NOTAFTER