forked from SWI-Prolog/packages-ssl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssl4pl.c
More file actions
1903 lines (1618 loc) · 51.4 KB
/
ssl4pl.c
File metadata and controls
1903 lines (1618 loc) · 51.4 KB
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 and Matt Lilley
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (C): 1985-2015, SWI-Prolog Foundation
VU University Amsterdam
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <SWI-Stream.h>
#include <SWI-Prolog.h>
#include <assert.h>
#include <string.h>
#include "ssllib.h"
#ifdef _REENTRANT
#include <pthread.h>
#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_port;
static atom_t ATOM_cert;
static atom_t ATOM_peer_cert;
static atom_t ATOM_cacert_file;
static atom_t ATOM_require_crl;
static atom_t ATOM_crl;
static atom_t ATOM_certificate_file;
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_disable_ssl_methods;
static atom_t ATOM_root_certificates;
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_minus; /* "-" */
static atom_t ATOM_text;
static atom_t ATOM_octet;
static atom_t ATOM_utf8;
static functor_t FUNCTOR_unsupported_hash_algorithm1;
static functor_t FUNCTOR_system1;
functor_t FUNCTOR_error2; /* also used in ssllib.c */
functor_t FUNCTOR_ssl_error4; /* also used in ssllib.c */
static functor_t FUNCTOR_permission_error3;
static functor_t FUNCTOR_ip4;
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_key1;
static functor_t FUNCTOR_hash1;
static functor_t FUNCTOR_next_update1;
static functor_t FUNCTOR_signature1;
static functor_t FUNCTOR_equals2;
static functor_t FUNCTOR_crl1;
static functor_t FUNCTOR_revocations1;
static functor_t FUNCTOR_revoked2;
static functor_t FUNCTOR_session_key1;
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 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
get_char_arg(int a, term_t t, char **s)
{ term_t t2 = PL_new_term_ref();
_PL_get_arg(a, t, t2);
if ( !PL_get_chars(t2, s, CVT_ATOM|CVT_STRING|CVT_EXCEPTION) )
return FALSE;
return TRUE;
}
static int
get_int_arg(int a, term_t t, int *i)
{ term_t t2 = PL_new_term_ref();
_PL_get_arg(a, t, t2);
if ( !PL_get_integer_ex(t2, i) )
return FALSE;
return TRUE;
}
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);
if ( !PL_get_bool_ex(t2, i) )
return FALSE;
return TRUE;
}
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);
if ( !PL_get_file_name(t2, f, PL_FILE_EXIST) )
return FALSE;
return TRUE;
}
static int
get_predicate_arg(int a, module_t m, term_t t, int arity, predicate_t *pred)
{ term_t t2 = PL_new_term_ref();
atom_t name;
_PL_get_arg(a, t, t2);
if ( !PL_strip_module(t2, &m, t2) ||
!PL_get_atom_ex(t2, &name) )
return FALSE;
*pred = PL_pred(PL_new_functor(name, arity), m);
return TRUE;
}
static int
get_bn_arg(int a, term_t t, BIGNUM **bn)
{ term_t arg;
char *hex;
if ( (arg=PL_new_term_ref()) &&
PL_get_arg(a, t, arg) &&
PL_get_chars(arg, &hex,
CVT_ATOM|CVT_STRING|REP_ISO_LATIN_1|CVT_EXCEPTION) )
{ if ( strcmp(hex, "-") == 0 )
*bn = NULL;
else
BN_hex2bn(bn, hex);
return TRUE;
}
return FALSE;
}
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;
if ( bn )
{ char *hex = BN_bn2hex(bn);
rc = PL_unify_chars(arg, PL_STRING|REP_ISO_LATIN_1, (size_t)-1, hex);
OPENSSL_free(hex);
} else
rc = PL_unify_atom(arg, ATOM_minus);
PL_reset_term_refs(arg);
return rc;
}
return FALSE;
}
static int
recover_rsa(term_t t, RSA** rsap)
{ RSA *rsa = RSA_new();
if ( get_bn_arg(1, t, &rsa->n) &&
get_bn_arg(2, t, &rsa->e) &&
get_bn_arg(3, t, &rsa->d) &&
get_bn_arg(4, t, &rsa->p) &&
get_bn_arg(5, t, &rsa->q) &&
get_bn_arg(6, t, &rsa->dmp1) &&
get_bn_arg(7, t, &rsa->dmq1) &&
get_bn_arg(8, t, &rsa->iqmp)
)
{ *rsap = rsa;
return TRUE;
}
RSA_free(rsa);
return FALSE;
}
static int
recover_private_key(term_t t, RSA** rsap)
{ if ( PL_is_functor(t, FUNCTOR_private_key1) )
{ term_t arg;
if ( (arg = PL_new_term_ref()) &&
PL_get_arg(1, t, arg) )
return recover_rsa(arg, rsap);
return FALSE;
}
return PL_type_error("private_key", t);
}
static int
recover_public_key(term_t t, RSA** rsap)
{ if ( PL_is_functor(t, FUNCTOR_public_key1) )
{ term_t arg;
if ( (arg = PL_new_term_ref()) &&
PL_get_arg(1, t, arg) )
return recover_rsa(arg, rsap);
return FALSE;
}
return PL_type_error("public_key", t);
}
static int
unify_rsa(term_t item, RSA* rsa)
{ 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)
);
}
static int
unify_bytes_hex(term_t t, size_t len, const unsigned char *data)
{ char tmp[512];
char *out, *o;
static const char *tohex = "0123456789ABCDEF";
const unsigned char *end = data+len;
int rc;
if ( len*2 <= sizeof(tmp) )
out = tmp;
else if ( !(out = malloc(len*2)) )
return PL_resource_error("memory");
for(o=out ; data < end; data++)
{ *o++ = tohex[(*data >> 4) & 0xf];
*o++ = tohex[(*data >> 0) & 0xf];
}
rc = PL_unify_chars(t, PL_STRING|REP_ISO_LATIN_1, len*2, out);
if ( out != tmp )
free(out);
return rc;
}
/* 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, 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)
{ result += lSecondsFromUTC; /* Add in the UTC offset of the original value */
result -= timezone; /* Adjust for localtime */
} else
{ ssl_deb(2, "mktime() failed");
return FALSE;
}
#endif
return PL_unify_int64(term, result);
}
static int
unify_hash(term_t hash, ASN1_OBJECT* algorithm, int (*i2d)(void*, unsigned char**), void * data)
{ const EVP_MD *type;
EVP_MD_CTX ctx;
int digestible_length;
unsigned char* digest_buffer;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_length;
unsigned char* p;
int nid = 0;
/* Generate hash */
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
*/
if (nid == NID_ecdsa_with_SHA1)
{ type = EVP_sha1();
} else if (nid == NID_ecdsa_with_SHA256)
{ type = EVP_sha256();
} else if (nid == NID_ecdsa_with_SHA384)
{ type = EVP_sha384();
#ifdef HAVE_OPENSSL_MD2_H
} else if (nid == NID_md2WithRSAEncryption)
{ type = EVP_md2();
#endif
} else
{ type = EVP_get_digestbynid(nid);
if (type == NULL)
return PL_unify_term(hash,
PL_FUNCTOR, FUNCTOR_unsupported_hash_algorithm1,
PL_INTEGER, nid);
}
EVP_MD_CTX_init(&ctx);
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_cleanup(&ctx);
PL_free(digest_buffer);
return raise_ssl_error(ERR_get_error());
}
if (!EVP_DigestUpdate(&ctx, digest_buffer, digestible_length))
{ EVP_MD_CTX_cleanup(&ctx);
PL_free(digest_buffer);
return raise_ssl_error(ERR_get_error());
}
if (!EVP_DigestFinal(&ctx, digest, &digest_length))
{ EVP_MD_CTX_cleanup(&ctx);
PL_free(digest_buffer);
return raise_ssl_error(ERR_get_error());
}
EVP_MD_CTX_cleanup(&ctx);
PL_free(digest_buffer);
return unify_bytes_hex(hash, digest_length, digest);
}
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(e->object)),
PL_UTF8_CHARS, utf8_data)
);
OPENSSL_free(utf8_data);
if ( !rc )
return FALSE;
}
return PL_unify_nil(list);
}
static int
unify_crl(term_t term, X509_CRL* crl)
{ X509_CRL_INFO* info = crl->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");
i2a_ASN1_INTEGER(mem, crl->signature);
if (!(unify_name(issuer, X509_CRL_get_issuer(crl)) &&
unify_hash(hash, crl->sig_alg->algorithm, i2d_X509_CRL_INFO_wrapper, crl->crl) &&
unify_asn1_time(next_update, X509_CRL_get_nextUpdate(crl)) &&
unify_bytes_hex(signature, crl->signature->length, crl->signature->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(info->revoked); i++)
{
X509_REVOKED* revoked = sk_X509_REVOKED_value(info->revoked, i);
(void)BIO_reset(mem);
i2a_ASN1_INTEGER(mem, revoked->serialNumber);
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, revoked->revocationDate) &&
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_key(EVP_PKEY* key, functor_t type, term_t item)
{ if ( !PL_unify_functor(item, type) ||
!PL_get_arg(1, item, item) )
return FALSE;
/* EVP_PKEY_get1_* returns a copy of the existing key */
switch (EVP_PKEY_type(key->type))
{ int rc;
#ifndef OPENSSL_NO_RSA
case EVP_PKEY_RSA:
{ RSA* rsa = EVP_PKEY_get1_RSA(key);
rc = unify_rsa(item, rsa);
RSA_free(rsa);
return rc;
}
#endif
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC:
{ EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key);
rc = PL_unify_atom_chars(item, "ec_key");
EC_KEY_free(ec);
return rc;
}
#endif
#ifndef OPENSSL_NO_DH
case EVP_PKEY_DH:
{ DH* dh = EVP_PKEY_get1_DH(key);
rc = PL_unify_atom_chars(item, "dh_key");
DH_free(dh);
return rc;
}
#endif
#ifndef OPENSSL_NO_DSA
case EVP_PKEY_DSA:
{ DSA* dsa = EVP_PKEY_get1_DSA(key);
rc = PL_unify_atom_chars(item, "dsa_key");
DSA_free(dsa);
return rc;
}
#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);
}
static int
unify_certificate(term_t cert, X509* data)
{ term_t list = PL_copy_term_ref(cert);
term_t item = PL_new_term_ref();
BIO * mem = NULL;
long n;
EVP_PKEY *key;
term_t issuername;
term_t subject;
term_t hash;
term_t not_before;
term_t not_after;
term_t signature;
unsigned int crl_ext_id;
unsigned char *p;
X509_EXTENSION * crl_ext = NULL;
if (!(PL_unify_list(list, item, list) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_version1,
PL_LONG, X509_get_version(data))
))
return FALSE;
if (!(PL_unify_list(list, item, list) &&
(not_before = PL_new_term_ref()) &&
unify_asn1_time(not_before, X509_get_notBefore(data)) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_notbefore1,
PL_TERM, not_before)))
return FALSE;
if (!(PL_unify_list(list, item, list) &&
(not_after = PL_new_term_ref()) &&
unify_asn1_time(not_after, X509_get_notAfter(data)) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_notafter1,
PL_TERM, not_after)))
return FALSE;
if ((mem = BIO_new(BIO_s_mem())) != NULL)
{ i2a_ASN1_INTEGER(mem, X509_get_serialNumber(data));
if ((n = BIO_get_mem_data(mem, &p)) > 0)
{ if (!(PL_unify_list(list, item, list) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_serial1,
PL_NCHARS, (size_t)n, p)
))
{ BIO_vfree(mem);
return FALSE;
}
} else
Sdprintf("Failed to print serial - continuing without serial\n");
} else
Sdprintf("Failed to allocate BIO for printing - continuing without serial\n");
BIO_vfree(mem);
if (!(PL_unify_list(list, item, list) &&
(subject = PL_new_term_ref()) &&
unify_name(subject, X509_get_subject_name(data)) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_subject1,
PL_TERM, subject))
)
return FALSE;
if (!((hash = PL_new_term_ref()) &&
unify_hash(hash, data->sig_alg->algorithm, i2d_X509_CINF_wrapper, data->cert_info) &&
PL_unify_list(list, item, list) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_hash1,
PL_TERM, hash)))
return FALSE;
if (!((signature = PL_new_term_ref()) &&
unify_bytes_hex(signature,
data->signature->length, data->signature->data) &&
PL_unify_list(list, item, list) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_signature1,
PL_TERM, signature)
))
return FALSE;
if (!(PL_unify_list(list, item, list) &&
(issuername = PL_new_term_ref()) &&
unify_name(issuername, X509_get_issuer_name(data)) &&
PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_issuername1,
PL_TERM, issuername))
)
return FALSE;
if (!PL_unify_list(list, item, list))
return FALSE;
/* X509_extract_key returns a copy of the existing key */
key = X509_extract_key(data);
if ( !PL_unify_functor(item, FUNCTOR_key1) ||
!PL_get_arg(1, item, item) ||
!unify_public_key(key, item) )
return FALSE;
EVP_PKEY_free(key);
/* If the cert has a CRL distribution point, return that. If it does not,
it is not an error
*/
crl_ext_id = X509_get_ext_by_NID(data, NID_crl_distribution_points, -1);
crl_ext = X509_get_ext(data, crl_ext_id);
if (crl_ext != NULL)
{ STACK_OF(DIST_POINT) * distpoints;
int i, j;
term_t crl;
term_t crl_list;
term_t crl_item;
if (!PL_unify_list(list, item, list))
return FALSE;
distpoints = X509_get_ext_d2i(data, NID_crl_distribution_points, NULL, NULL);
/* Loop through the CRL points, putting them into a list */
crl = PL_new_term_ref();
crl_list = PL_copy_term_ref(crl);
crl_item = PL_new_term_ref();
for (i = 0; i < sk_DIST_POINT_num(distpoints); i++)
{ DIST_POINT *point;
GENERAL_NAME *name;
point = sk_DIST_POINT_value(distpoints, i);
if (point->distpoint != NULL)
{ /* Each point may have several names? May as well put them all in */
for (j = 0; j < sk_GENERAL_NAME_num(point->distpoint->name.fullname); j++)
{ name = sk_GENERAL_NAME_value(point->distpoint->name.fullname, j);
if (name != NULL && name->type == GEN_URI)
{ if (!(PL_unify_list(crl_list, crl_item, crl_list) &&
PL_unify_atom_chars(crl_item, (const char *)name->d.ia5->data)))
{
CRL_DIST_POINTS_free(distpoints);
return FALSE;
}
}
}
}
}
CRL_DIST_POINTS_free(distpoints);
if (!PL_unify_nil(crl_list))
return FALSE;
if (!PL_unify_term(item,
PL_FUNCTOR, FUNCTOR_crl1,
PL_TERM, crl))
return FALSE;
}
return PL_unify_nil(list);
}
static int
unify_certificates(term_t certs, term_t tail, STACK_OF(X509)* stack)
{ term_t item = PL_new_term_ref();
term_t list = PL_copy_term_ref(certs);
X509* cert = sk_X509_pop(stack);
int retval = 1;
while (cert != NULL && retval == 1)
{ retval &= PL_unify_list(list, item, list);
retval &= unify_certificate(item, cert);
X509_free(cert);
cert = sk_X509_pop(stack);
if (cert == NULL)
return PL_unify(tail, item) && PL_unify_nil(list);
}
return retval && PL_unify_nil(list);
}
static foreign_t
pl_load_public_key(term_t source, term_t key_t)
{ EVP_PKEY* key;
BIO* bio;
IOSTREAM* stream;
int c;
if ( !PL_get_stream_handle(source, &stream) )
return FALSE;
bio = BIO_new(&bio_read_functions);
BIO_set_ex_data(bio, 0, stream);
/* Determine format */
c = Speekcode(stream);
if (c == 0x30) /* ASN.1 sequence, so assume DER */
key = d2i_PUBKEY_bio(bio, NULL);
else
key = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL);
BIO_free(bio);
PL_release_stream(stream);
if (key == NULL)
return PL_permission_error("read", "key", source);
if (!unify_public_key(key, key_t))
{ EVP_PKEY_free(key);
PL_fail;
}
EVP_PKEY_free(key);
PL_succeed;
}
static int
private_password_callback(char *buf, int bufsiz, int verify, void* pw)
{ char *password = (char*)pw;
size_t res = strlen(password);
if ( res > (size_t)bufsiz )
res = bufsiz;
memcpy(buf, password, res);
return res;
}
static foreign_t
pl_load_private_key(term_t source, term_t password, term_t key_t)
{ EVP_PKEY* key;
BIO* bio;
IOSTREAM* stream;
char* password_chars;
int c, rc;
if ( !PL_get_chars(password, &password_chars,
CVT_ATOM|CVT_STRING|CVT_LIST|CVT_EXCEPTION) )
return FALSE;
if ( !PL_get_stream_handle(source, &stream) )
return FALSE;
bio = BIO_new(&bio_read_functions);
BIO_set_ex_data(bio, 0, stream);
/* Determine format */
c = Speekcode(stream);
if (c == 0x30) /* ASN.1 sequence, so assume DER */
key = d2i_PrivateKey_bio(bio, NULL); /* TBD: Password! */
else
key = PEM_read_bio_PrivateKey(bio, NULL,
&private_password_callback,
(void*)password_chars);
BIO_free(bio);
PL_release_stream(stream);
if ( key == NULL )
return PL_permission_error("read", "key", source);
rc = (unify_private_key(key, key_t) != 0);
EVP_PKEY_free(key);
return rc;
}
static foreign_t
pl_load_crl(term_t source, term_t list)
{ X509_CRL* crl;
BIO* bio;
IOSTREAM* stream;
int result;
int c;
if ( !PL_get_stream_handle(source, &stream) )
return FALSE;
bio = BIO_new(&bio_read_functions);
BIO_set_ex_data(bio, 0, stream);
/* Determine the format of the CRL */
c = Speekcode(stream);
if (c == 0x30) /* ASN.1 sequence, so assume DER */
crl = d2i_X509_CRL_bio(bio, NULL);
else
crl = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL);
BIO_free(bio);
PL_release_stream(stream);
if (crl == NULL)
{ ssl_deb(2, "Failed to load CRL");
PL_fail;
}
result = unify_crl(list, crl);
X509_CRL_free(crl);
return result;
}
static foreign_t
pl_load_certificate(term_t source, term_t cert)
{ X509* x509;
BIO* bio;
IOSTREAM* stream;
int c = 0;
if ( !PL_get_stream_handle(source, &stream) )
return FALSE;
bio = BIO_new(&bio_read_functions);
BIO_set_ex_data(bio, 0, stream);
/* Determine format */
c = Speekcode(stream);
if (c == 0x30) /* ASN.1 sequence, so assume DER */
x509 = d2i_X509_bio(bio, NULL);
else
x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
BIO_free(bio);
PL_release_stream(stream);
if (x509 == NULL)
return raise_ssl_error(ERR_get_error());
if (unify_certificate(cert, x509))
{ X509_free(x509);
PL_succeed;
} else
{ X509_free(x509);
PL_fail;
}
}
static void
acquire_ssl(atom_t atom)
{ ssl_deb(4, "Acquire on atom %d\n", atom);
}
static int
release_ssl(atom_t atom)
{ PL_SSL* conf;
size_t size;
conf = PL_blob_data(atom, &size, NULL);
ssl_deb(4, "Releasing PL_SSL %p\n", conf);
ssl_exit(conf); /* conf is freed by an internal call from OpenSSL
via ssl_config_free() */
return TRUE;
}
static int
compare_ssl(atom_t a, atom_t b)
{ PL_SSL* *ssla = PL_blob_data(a, NULL, NULL);
PL_SSL* *sslb = PL_blob_data(b, NULL, NULL);
return ( ssla > sslb ? 1 :
ssla < sslb ? -1 : 0
);
}
static int
write_ssl(IOSTREAM *s, atom_t symbol, int flags)
{ PL_SSL *ssl = PL_blob_data(symbol, NULL, NULL);
Sfprintf(s, "<ssl_context>(%p)", ssl);
return TRUE;
}
static PL_blob_t ssl_context_type =
{ PL_BLOB_MAGIC,
PL_BLOB_NOCOPY,
"ssl_context",
release_ssl,
compare_ssl,
write_ssl,
acquire_ssl
};
static int
put_conf(term_t config, PL_SSL *conf)
{ return PL_unify_atom(config, conf->atom);
}
static int
register_conf(term_t config, PL_SSL *conf)
{ term_t blob = PL_new_term_ref();
int rc;