/
secrets.c
1833 lines (1642 loc) · 50.2 KB
/
secrets.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
/*
* mechanisms for preshared keys (public, private, and preshared secrets)
*
* this is the library for reading (and later, writing!) the ipsec.secrets
* files.
*
* Copyright (C) 1998-2004 D. Hugh Redelmeier.
* Copyright (C) 2005 Michael Richardson <mcr@xelerance.com>
* Copyright (C) 2009-2012 Avesh Agarwal <avagarwa@redhat.com>
* Copyright (C) 2012-2015 Paul Wouters <paul@libreswan.org>
* Copyright (C) 2016-2019 Andrew Cagney <cagney@gnu.org>
* Copyright (C) 2017 Vukasin Karadzic <vukasin.karadzic@gmail.com>
* Copyright (C) 2018 Sahana Prasad <sahana.prasad07@gmail.com>
* Copyright (C) 2019 Paul Wouters <pwouters@redhat.com>
* Copyright (C) 2019 D. Hugh Redelmeier <hugh@mimosa.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <https://www.gnu.org/licenses/gpl2.txt>.
*
* 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.
*/
#include <pthread.h> /* pthread.h must be first include file */
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
#include <pk11pub.h>
#include <prerror.h>
#include <cert.h>
#include <cryptohi.h>
#include <keyhi.h>
#include <secport.h>
#include <prinit.h>
#include <prmem.h>
#include <keythi.h>
#include <seccomon.h>
#include <secerr.h>
#include "lswglob.h"
#include "sysdep.h"
#include "lswlog.h"
#include "constants.h"
#include "lswalloc.h"
#include "id.h"
#include "x509.h"
#include "secrets.h"
#include "certs.h"
#include "lex.h"
#include "lswconf.h"
#include "lswnss.h"
#include "ip_info.h"
#include "nss_cert_load.h"
#include "ike_alg.h"
#include "ike_alg_hash.h"
#include "certs.h"
/*
* Build up a diagnostic in a static buffer -- NOT RE-ENTRANT.
*
* Although this would be a generally useful function, it is very
* hard to come up with a discipline that prevents different uses
* from interfering. It is intended that by limiting it to building
* diagnostics, we will avoid this problem.
* Juggling is performed to allow an argument to be a previous
* result: the new string may safely depend on the old one. This
* restriction is not checked in any way: violators will produce
* confusing results (without crashing!).
*
* @param fmt String format
* @param ... strings
* @return err_t
*/
ECPointEncoding pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey);
ECPointEncoding
pk11_ECGetPubkeyEncoding(const SECKEYPublicKey *pubKey)
{
SECItem oid;
SECStatus rv;
PORTCheapArenaPool tmpArena;
ECPointEncoding encoding = ECPoint_Undefined;
PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE);
/* decode the OID tag */
rv = SEC_QuickDERDecodeItem(&tmpArena.arena, &oid,
SEC_ASN1_GET(SEC_ObjectIDTemplate),
&pubKey->u.ec.DEREncodedParams);
if (rv == SECSuccess) {
SECOidTag tag = SECOID_FindOIDTag(&oid);
switch (tag) {
case SEC_OID_CURVE25519:
encoding = ECPoint_XOnly;
break;
case SEC_OID_SECG_EC_SECP256R1:
case SEC_OID_SECG_EC_SECP384R1:
case SEC_OID_SECG_EC_SECP521R1:
default:
/* unknown curve, default to uncompressed */
encoding = ECPoint_Uncompressed;
}
}
PORT_DestroyCheapArena(&tmpArena);
return encoding;
}
static err_t builddiag(const char *fmt, ...) PRINTF_LIKE(1); /* NOT RE-ENTRANT */
static err_t builddiag(const char *fmt, ...)
{
/* longer messages will be truncated */
static char mydiag_space[LOG_WIDTH];
char t[sizeof(mydiag_space)]; /* build result here first */
va_list args;
va_start(args, fmt);
t[0] = '\0'; /* in case nothing terminates string */
vsnprintf(t, sizeof(t), fmt, args);
va_end(args);
strcpy(mydiag_space, t);
return mydiag_space;
}
/* this does not belong here, but leave it here for now */
const struct id empty_id; /* ID_NONE */
struct fld {
const char *name;
ssize_t offset;
};
static void process_secrets_file(struct file_lex_position *flp,
struct secret **psecrets, const char *file_pat);
struct secret {
struct secret *next;
struct id_list *ids;
struct private_key_stuff pks;
};
struct private_key_stuff *lsw_get_pks(struct secret *s)
{
return &s->pks;
}
struct id_list *lsw_get_idlist(const struct secret *s)
{
return s->ids;
}
/*
* forms the keyid from the public exponent e and modulus n
*/
void form_keyid(chunk_t e, chunk_t n, keyid_t *keyid, size_t *keysize)
{
/* eliminate leading zero byte in modulus from ASN.1 coding */
if (*n.ptr == 0x00) {
/*
* The "adjusted" length of modulus n in octets:
* [RSA_MIN_OCTETS, RSA_MAX_OCTETS].
*
* According to form_keyid() this is the modulus length
* less any leading byte added by DER encoding.
*
* The adjusted length is used in sign_hash() as the
* signature length - wouldn't PK11_SignatureLen be
* better?
*
* The adjusted length is used in
* same_RSA_public_key() as part of comparing two keys
* - but wouldn't that be redundant? The direct n==n
* test would pick up the difference.
*/
DBGF(DBG_CRYPT, "XXX: adjusted modulus length %zu->%zu",
n.len, n.len - 1);
n.ptr++;
n.len--;
}
/* form the Libreswan keyid */
err_t err = splitkey_to_keyid(e.ptr, e.len, n.ptr, n.len, keyid);
passert(err == NULL);
/* return the RSA modulus size in octets */
*keysize = n.len;
}
static err_t RSA_unpack_pubkey_content(union pubkey_content *u,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
chunk_t pubkey)
{
return unpack_RSA_public_key(&u->rsa, keyid, ckaid, size, &pubkey);
}
static void RSA_free_public_content(struct RSA_public_key *rsa)
{
free_chunk_content(&rsa->n);
free_chunk_content(&rsa->e);
}
static void RSA_free_pubkey_content(union pubkey_content *u)
{
RSA_free_public_content(&u->rsa);
}
static void RSA_extract_public_key(struct RSA_public_key *pub,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
SECKEYPublicKey *pubk,
SECItem *cert_ckaid)
{
pub->e = clone_bytes_as_chunk(pubk->u.rsa.publicExponent.data,
pubk->u.rsa.publicExponent.len, "e");
pub->n = clone_bytes_as_chunk(pubk->u.rsa.modulus.data,
pubk->u.rsa.modulus.len, "n");
*ckaid = ckaid_from_secitem(cert_ckaid);
form_keyid(pub->e, pub->n, keyid, size);
}
static void RSA_extract_pubkey_content(union pubkey_content *pkc,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
SECKEYPublicKey *pubkey_nss,
SECItem *ckaid_nss)
{
RSA_extract_public_key(&pkc->rsa, keyid, ckaid, size, pubkey_nss, ckaid_nss);
}
static void RSA_extract_private_key_pubkey_content(struct private_key_stuff *pks,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
SECKEYPublicKey *pubkey_nss,
SECItem *ckaid_nss)
{
struct RSA_private_key *rsak = &pks->u.RSA_private_key;
RSA_extract_public_key(&rsak->pub, keyid, ckaid, size,
pubkey_nss, ckaid_nss);
}
static void RSA_free_secret_content(struct private_key_stuff *pks)
{
SECKEY_DestroyPrivateKey(pks->private_key);
struct RSA_private_key *rsak = &pks->u.RSA_private_key;
RSA_free_public_content(&rsak->pub);
}
static err_t RSA_secret_sane(struct private_key_stuff *pks)
{
/*
* PKCS#1 1.5 section 6 requires modulus to have at least 12 octets.
*
* We actually require more (for security).
*/
if (pks->size < RSA_MIN_OCTETS)
return RSA_MIN_OCTETS_UGH;
/* we picked a max modulus size to simplify buffer allocation */
if (pks->size > RSA_MAX_OCTETS)
return RSA_MAX_OCTETS_UGH;
return NULL;
}
/* returns the length of the result on success; 0 on failure */
static struct hash_signature RSA_sign_hash(const struct private_key_stuff *pks,
const uint8_t *hash_val, size_t hash_len,
const struct hash_desc *hash_algo,
struct logger *logger)
{
dbg("RSA_sign_hash: Started using NSS");
if (!pexpect(pks->private_key != NULL)) {
dbg("no private key!");
return (struct hash_signature) { .len = 0, };
}
SECItem data = {
.type = siBuffer,
.len = hash_len,
.data = DISCARD_CONST(uint8_t *, hash_val),
};
struct hash_signature sig = { .len = PK11_SignatureLen(pks->private_key), };
passert(sig.len <= sizeof(sig.ptr/*array*/));
SECItem signature = {
.type = siBuffer,
.len = sig.len,
.data = sig.ptr,
};
if (hash_algo == NULL /* ikev1*/ ||
hash_algo == &ike_alg_hash_sha1 /* old style rsa with SHA1*/) {
SECStatus s = PK11_Sign(pks->private_key, &signature, &data);
if (s != SECSuccess) {
/* PR_GetError() returns the thread-local error */
llog_nss_error(RC_LOG_SERIOUS, logger,
"RSA sign function failed");
return (struct hash_signature) { .len = 0, };
}
} else { /* Digital signature scheme with rsa-pss*/
const CK_RSA_PKCS_PSS_PARAMS *mech = hash_algo->nss.rsa_pkcs_pss_params;
if (mech == NULL) {
llog(RC_LOG_SERIOUS, logger,
"digital signature scheme not supported for hash algorithm %s",
hash_algo->common.fqn);
return (struct hash_signature) { .len = 0, };
}
SECItem mech_item = {
.type = siBuffer,
.data = (void*)mech, /* strip const */
.len = sizeof(*mech),
};
SECStatus s = PK11_SignWithMechanism(pks->private_key, CKM_RSA_PKCS_PSS,
&mech_item, &signature, &data);
if (s != SECSuccess) {
/* PR_GetError() returns the thread-local error */
llog_nss_error(RC_LOG_SERIOUS, logger,
"RSA DSS sign function failed");
return (struct hash_signature) { .len = 0, };
}
}
dbg("RSA_sign_hash: Ended using NSS");
return sig;
}
const struct pubkey_type pubkey_type_rsa = {
.alg = PUBKEY_ALG_RSA,
.name = "RSA",
.private_key_kind = PKK_RSA,
.free_pubkey_content = RSA_free_pubkey_content,
.unpack_pubkey_content = RSA_unpack_pubkey_content,
.extract_pubkey_content = RSA_extract_pubkey_content,
.extract_private_key_pubkey_content = RSA_extract_private_key_pubkey_content,
.free_secret_content = RSA_free_secret_content,
.secret_sane = RSA_secret_sane,
.sign_hash = RSA_sign_hash,
};
static err_t EC_unpack_pubkey_content(union pubkey_content *u,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
chunk_t pubkey)
{
return unpack_EC_public_key(&u->ecPub, keyid, ckaid, size, &pubkey);
}
static void EC_free_public_content(struct EC_public_key *ecKey)
{
free_chunk_content(&ecKey->pub);
free_chunk_content(&ecKey->ecParams);
/* ckaid is an embedded struct (no pointer) */
/*
* ??? what about ecdsa->pub.{version,ckaid}?
*
* CKAID's been changed to an embedded struct (so no pointer).
* VERSION was dropped?
*/
}
static void EC_free_pubkey_content(union pubkey_content *u)
{
EC_free_public_content(&u->ecPub);
}
static void EC_extract_public_key(struct EC_public_key *pub,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
SECKEYPublicKey *pubkey_nss,
SECItem *ckaid_nss)
{
pub->pub = clone_secitem_as_chunk(pubkey_nss->u.ec.publicValue, "EC pub");
pub->ecParams = clone_secitem_as_chunk(pubkey_nss->u.ec.DEREncodedParams, "EC ecParams");
*size = pubkey_nss->u.ec.publicValue.len;
*ckaid = ckaid_from_secitem(ckaid_nss);
/* keyid */
err_t e = keyblob_to_keyid(pubkey_nss->u.ec.publicValue.data,
pubkey_nss->u.ec.publicValue.len, keyid);
passert(e == NULL);
if (DBGP(DBG_CRYPT)) {
DBG_log("keyid *%s", str_keyid(*keyid));
DBG_log(" size: %zu", *size);
DBG_dump_hunk("pub", pub->pub);
DBG_dump_hunk("ecParams", pub->ecParams);
}
}
static void EC_extract_pubkey_content(union pubkey_content *pkc,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
SECKEYPublicKey *pubkey_nss,
SECItem *ckaid_nss)
{
EC_extract_public_key(&pkc->ecPub, keyid, ckaid, size, pubkey_nss, ckaid_nss);
}
static void EC_extract_private_key_pubkey_content(struct private_key_stuff *pks,
keyid_t *keyid, ckaid_t *ckaid, size_t *size,
SECKEYPublicKey *pubkey_nss,
SECItem *ckaid_nss)
{
struct EC_private_key *ecKey = &pks->u.EC_private_key;
EC_extract_public_key(&ecKey->pub, keyid, ckaid, size,
pubkey_nss, ckaid_nss);
}
static void EC_free_secret_content(struct private_key_stuff *pks)
{
SECKEY_DestroyPrivateKey(pks->private_key);
struct EC_private_key *ecKey = &pks->u.EC_private_key;
EC_free_public_content(&ecKey->pub);
}
/*
* The only unsafe (according to FIPS) curve is p192, and NSS does not
* implement this, so there is no ECDSA curve that libreswan needs to
* disallow for security reasons
*/
static err_t EC_secret_sane(struct private_key_stuff *pks_unused UNUSED)
{
dbg("EC Algorithms are assumed to be sane");
return NULL;
}
static struct hash_signature EC_sign_hash(const struct private_key_stuff *pks,
const uint8_t *hash_val, size_t hash_len,
const struct hash_desc *hash_algo_unused UNUSED,
struct logger *logger)
{
if (!pexpect(pks->private_key != NULL)) {
dbg("no private key!");
return (struct hash_signature) { .len = 0, };
}
DBGF(DBG_CRYPT, "ECDSA_sign_hash: Started using NSS");
/* point HASH to sign at HASH_VAL */
SECItem hash_to_sign = {
.type = siBuffer,
.len = hash_len,
.data = DISCARD_CONST(uint8_t *, hash_val),
};
/* point signature at the SIG_VAL buffer */
uint8_t raw_signature_data[sizeof(struct hash_signature)];
SECItem raw_signature = {
.type = siBuffer,
.len = PK11_SignatureLen(pks->private_key),
.data = raw_signature_data,
};
passert(raw_signature.len <= sizeof(raw_signature_data));
dbg("ECDSA signature.len %d", raw_signature.len);
/* create the raw signature */
SECStatus s = PK11_Sign(pks->private_key, &raw_signature, &hash_to_sign);
if (DBGP(DBG_CRYPT)) {
DBG_dump("sig_from_nss", raw_signature.data, raw_signature.len);
}
if (s != SECSuccess) {
/* PR_GetError() returns the thread-local error */
llog_nss_error(RC_LOG_SERIOUS, logger,
"ECDSA sign function failed");
return (struct hash_signature) { .len = 0, };
}
SECItem encoded_signature;
if (DSAU_EncodeDerSigWithLen(&encoded_signature, &raw_signature,
raw_signature.len) != SECSuccess) {
/* PR_GetError() returns the thread-local error */
llog_nss_error(RC_LOG, logger,
"NSS: constructing DER encoded ECDSA signature using DSAU_EncodeDerSigWithLen() failed:");
return (struct hash_signature) { .len = 0, };
}
struct hash_signature signature = {
.len = encoded_signature.len,
};
passert(encoded_signature.len <= sizeof(signature.ptr/*an-array*/));
memcpy(signature.ptr, encoded_signature.data, encoded_signature.len);
SECITEM_FreeItem(&encoded_signature, PR_FALSE);
DBGF(DBG_CRYPT, "ECDSA_sign_hash: Ended using NSS");
return signature;
}
const struct pubkey_type pubkey_type_ecdsa = {
.alg = PUBKEY_ALG_ECDSA,
.name = "ECDSA",
.private_key_kind = PKK_EC,
.unpack_pubkey_content = EC_unpack_pubkey_content,
.free_pubkey_content = EC_free_pubkey_content,
.extract_private_key_pubkey_content = EC_extract_private_key_pubkey_content,
.free_secret_content = EC_free_secret_content,
.secret_sane = EC_secret_sane,
.sign_hash = EC_sign_hash,
.extract_pubkey_content = EC_extract_pubkey_content,
};
#ifdef NSS_EDDSA
const struct pubkey_type pubkey_type_eddsa = {
.alg = PUBKEY_ALG_EDDSA,
.name = "EDDSA",
.private_key_kind = PKK_EC,
.unpack_pubkey_content = EC_unpack_pubkey_content,
.free_pubkey_content = EC_free_pubkey_content,
.extract_private_key_pubkey_content = EC_extract_private_key_pubkey_content,
.free_secret_content = EC_free_secret_content,
.secret_sane = EC_secret_sane,
.sign_hash = EC_sign_hash,
.extract_pubkey_content = EC_extract_pubkey_content,
};
#endif
const struct pubkey_type *pubkey_alg_type(enum pubkey_alg alg)
{
static const struct pubkey_type *pubkey_types[] = {
[PUBKEY_ALG_RSA] = &pubkey_type_rsa,
[PUBKEY_ALG_ECDSA] = &pubkey_type_ecdsa,
#ifdef NSS_EDDSA
[PUBKEY_ALG_EDDSA] = &pubkey_type_eddsa,
#endif
};
passert(alg < elemsof(pubkey_types));
const struct pubkey_type *type = pubkey_types[alg];
pexpect(type != NULL);
return type;
}
/*
* XXX: Go for a simplicity - a switch is easier than adding to
* pubkey_type - especially when the fields could end up moving to
* struct pubkey proper (we can but dream).
*/
const keyid_t *pubkey_keyid(const struct pubkey *pk)
{
switch (pk->type->alg) {
case PUBKEY_ALG_RSA:
case PUBKEY_ALG_ECDSA:
#ifdef NSS_EDDSA
case PUBKEY_ALG_EDDSA:
#endif
return &pk->keyid;
default:
bad_case(pk->type->alg);
}
}
const ckaid_t *pubkey_ckaid(const struct pubkey *pk)
{
return &pk->ckaid;
}
const ckaid_t *secret_ckaid(const struct secret *secret)
{
if (secret->pks.pubkey_type != NULL) {
return &secret->pks.ckaid;
} else {
return NULL;
}
}
const keyid_t *secret_keyid(const struct secret *secret)
{
if (secret->pks.pubkey_type != NULL) {
switch (secret->pks.pubkey_type->alg) {
case PUBKEY_ALG_RSA:
case PUBKEY_ALG_ECDSA:
#ifdef NSS_EDDSA
case PUBKEY_ALG_EDDSA:
#endif
return &secret->pks.keyid;
default:
bad_case(secret->pks.pubkey_type->alg);
}
} else {
return NULL;
}
}
unsigned pubkey_size(const struct pubkey *pk)
{
switch (pk->type->alg) {
case PUBKEY_ALG_RSA:
case PUBKEY_ALG_ECDSA:
#ifdef NSS_EDDSA
case PUBKEY_ALG_EDDSA:
#endif
return pk->size;
default:
bad_case(pk->type->alg);
}
}
struct secret *lsw_foreach_secret(struct secret *secrets,
secret_eval func, void *uservoid)
{
for (struct secret *s = secrets; s != NULL; s = s->next) {
struct private_key_stuff *pks = &s->pks;
int result = (*func)(s, pks, uservoid);
if (result == 0)
return s;
if (result == -1)
break;
}
return NULL;
}
static struct secret *find_secret_by_pubkey_ckaid_1(struct secret *secrets,
const struct pubkey_type *type,
const SECItem *pubkey_ckaid)
{
for (struct secret *s = secrets; s != NULL; s = s->next) {
const struct private_key_stuff *pks = &s->pks;
dbg("trying secret %s:%s",
enum_name(&pkk_names, pks->kind),
str_keyid(pks->keyid));
if (type == NULL/*wildcard*/ ||
s->pks.pubkey_type == type) {
/* only public/private key pairs have a CKAID */
const ckaid_t *sckaid = secret_ckaid(s);
if (sckaid != NULL &&
ckaid_eq_nss(sckaid, pubkey_ckaid)) {
dbg("matched");
return s;
}
}
}
return NULL;
}
struct secret *lsw_find_secret_by_id(struct secret *secrets,
enum PrivateKeyKind kind,
const struct id *local_id,
const struct id *remote_id,
bool asym)
{
enum {
match_none = 000,
/* bits */
match_default = 001,
match_any = 002,
match_remote = 004,
match_local = 010
};
unsigned int best_match = match_none;
struct secret *best = NULL;
for (struct secret *s = secrets; s != NULL; s = s->next) {
if (DBGP(DBG_BASE)) {
id_buf idl;
DBG_log("line %d: key type %s(%s) to type %s",
s->pks.line,
enum_name(&pkk_names, kind),
str_id(local_id, &idl),
enum_name(&pkk_names, s->pks.kind));
}
if (s->pks.kind == kind) {
unsigned int match = match_none;
if (s->ids == NULL) {
/*
* a default (signified by lack of ids):
* accept if no more specific match found
*/
match = match_default;
} else {
/* check if both ends match ids */
struct id_list *i;
int idnum = 0;
for (i = s->ids; i != NULL; i = i->next) {
idnum++;
if (any_id(&i->id)) {
/*
* match any will
* automatically match
* local and remote so
* treat it as its own
* match type so that
* specific matches
* get a higher
* "match" value and
* are used in
* preference to "any"
* matches.
*/
match |= match_any;
} else {
if (same_id(&i->id, local_id)) {
match |= match_local;
}
if (remote_id != NULL &&
same_id(&i->id, remote_id)) {
match |= match_remote;
}
}
if (DBGP(DBG_BASE)) {
id_buf idi;
id_buf idl;
id_buf idr;
DBG_log("%d: compared key %s to %s / %s -> 0%02o",
idnum,
str_id(&i->id, &idi),
str_id(local_id, &idl),
(remote_id == NULL ? "" : str_id(remote_id, &idr)),
match);
}
}
/*
* If our end matched the only id in the list,
* default to matching any peer.
* A more specific match will trump this.
*/
if (match == match_local &&
s->ids->next == NULL)
match |= match_default;
}
dbg("line %d: match=0%02o", s->pks.line, match);
switch (match) {
case match_local:
/*
* if this is an asymmetric
* (eg. public key) system, allow
* this-side-only match to count, even
* if there are other ids in the list.
*/
if (!asym)
break;
/* FALLTHROUGH */
case match_default: /* default all */
case match_any: /* a wildcard */
case match_local | match_default: /* default peer */
case match_local | match_any: /* %any/0.0.0.0 and local */
case match_remote | match_any: /* %any/0.0.0.0 and remote */
case match_local | match_remote: /* explicit */
if (match == best_match) {
/*
* two good matches are equally good:
* do they agree?
*/
bool same = FALSE;
switch (kind) {
case PKK_NULL:
same = TRUE;
break;
case PKK_PSK:
same = hunk_eq(s->pks.u.preshared_secret,
best->pks.u.preshared_secret);
break;
case PKK_RSA:
/*
* Dirty trick: since we have
* code to compare RSA public
* keys, but not private keys,
* we make the assumption that
* equal public keys mean equal
* private keys. This ought to
* work.
*/
same = same_RSA_public_key(
&s->pks.u.RSA_private_key.pub,
&best->pks.u.RSA_private_key.pub);
break;
case PKK_EC:
/* there are no ECDSA kind of secrets */
/* ??? this seems not to be the case */
break;
case PKK_XAUTH:
/*
* We don't support this yet,
* but no need to die
*/
break;
case PKK_PPK:
same = hunk_eq(s->pks.ppk,
best->pks.ppk);
break;
default:
bad_case(kind);
}
if (!same) {
dbg("multiple ipsec.secrets entries with distinct secrets match endpoints: first secret used");
/*
* list is backwards:
* take latest in list
*/
best = s;
}
} else if (match > best_match) {
dbg("match 0%02o beats previous best_match 0%02o match=%p (line=%d)",
match,
best_match,
s, s->pks.line);
/* this is the best match so far */
best_match = match;
best = s;
} else {
dbg("match 0%02o loses to best_match 0%02o",
match, best_match);
}
}
}
}
dbg("concluding with best_match=0%02o best=%p (lineno=%d)",
best_match, best,
best == NULL ? -1 : best->pks.line);
return best;
}
/*
* digest a secrets file
*
* The file is a sequence of records. A record is a maximal sequence of
* tokens such that the first, and only the first, is in the first column
* of a line.
*
* Tokens are generally separated by whitespace and are key words, ids,
* strings, or data suitable for ttodata(3). As a nod to convention,
* a trailing ":" on what would otherwise be a token is taken as a
* separate token. If preceded by whitespace, a "#" is taken as starting
* a comment: it and the rest of the line are ignored.
*
* One kind of record is an include directive. It starts with "include".
* The filename is the only other token in the record.
* If the filename does not start with /, it is taken to
* be relative to the directory containing the current file.
*
* The other kind of record describes a key. It starts with a
* sequence of ids and ends with key information. Each id
* is an IP address, a Fully Qualified Domain Name (which will immediately
* be resolved), or @FQDN which will be left as a name.
*
* The form starts the key part with a ":".
*
* For Preshared Key, use the "PSK" keyword, and follow it by a string
* or a data token suitable for ttodata(3).
*
* For raw RSA Keys in NSS, use the "RSA" keyword, followed by a
* brace-enclosed list of key field keywords and data values.
* The data values are large integers to be decoded by ttodata(3).
* The fields are a subset of those used by BIND 8.2 and have the
* same names.
*
* For XAUTH passwords, use @username followed by ":XAUTH" followed by the password
*
* For Post-Quantum Preshared Keys, use the "PPKS" keyword if the PPK is static.
*
* PIN for smartcard is no longer supported - use NSS with smartcards
*/
/* parse PSK from file */
static err_t process_psk_secret(struct file_lex_position *flp, chunk_t *psk)
{
err_t ugh = NULL;
if (flp->tok[0] == '"' || flp->tok[0] == '\'') {
size_t len = flp->cur - flp->tok - 2;
if (len < 8) {
llog(RC_LOG_SERIOUS, flp->logger,
"WARNING: using a weak secret (PSK)");
}
*psk = clone_bytes_as_chunk(flp->tok + 1, len, "PSK");
shift(flp);
} else {
char buf[RSA_MAX_ENCODING_BYTES]; /*
* limit on size of
* binary
* representation
* of key
*/
size_t sz;
char diag_space[TTODATAV_BUF];
ugh = ttodatav(flp->tok, flp->cur - flp->tok, 0, buf,
sizeof(buf), &sz,
diag_space, sizeof(diag_space),
TTODATAV_SPACECOUNTS);
if (ugh != NULL) {
/* ttodata didn't like PSK data */
ugh = builddiag("PSK data malformed (%s): %s", ugh,
flp->tok);
} else {
*psk = clone_bytes_as_chunk(buf, sz, "PSK");
shift(flp);
}
}
dbg("processing PSK at line %d: %s",
flp->lino, ugh == NULL ? "passed" : ugh);
return ugh;
}
/* parse XAUTH secret from file */
static err_t process_xauth_secret(struct file_lex_position *flp, chunk_t *xauth)
{
err_t ugh = NULL;
if (flp->tok[0] == '"' || flp->tok[0] == '\'') {
*xauth = clone_bytes_as_chunk(flp->tok + 1, flp->cur - flp->tok - 2,
"XAUTH");
shift(flp);
} else {
char buf[RSA_MAX_ENCODING_BYTES]; /*
* limit on size of
* binary
* representation
* of key
*/
size_t sz;
char diag_space[TTODATAV_BUF];
ugh = ttodatav(flp->tok, flp->cur - flp->tok, 0, buf,
sizeof(buf), &sz,
diag_space, sizeof(diag_space),
TTODATAV_SPACECOUNTS);
if (ugh != NULL) {
/* ttodata didn't like PSK data */
ugh = builddiag("PSK data malformed (%s): %s", ugh,
flp->tok);
} else {
*xauth = clone_bytes_as_chunk(buf, sz, "XAUTH");
shift(flp);
}
}
dbg("processing XAUTH at line %d: %s",
flp->lino, ugh == NULL ? "passed" : ugh);
return ugh;
}
/* parse static PPK */
static err_t process_ppk_static_secret(struct file_lex_position *flp,
chunk_t *ppk, chunk_t *ppk_id)
{
err_t ugh = NULL;
if (flp->tok[0] == '"' || flp->tok[0] == '\'') {
size_t len = flp->cur - flp->tok - 2;
*ppk_id = clone_bytes_as_chunk(flp->tok + 1, len, "PPK ID");
} else {
ugh = "No quotation marks found. PPK ID should be in quotation marks";
return ugh;
}
if (!shift(flp)) {
ugh = "No PPK found. PPK should be specified after PPK ID";
free_chunk_content(ppk_id);
return ugh;
}
if (*flp->tok == '"' || *flp->tok == '\'') {
size_t len = flp->cur - flp->tok - 2;
*ppk = clone_bytes_as_chunk(flp->tok + 1, len, "PPK");
shift(flp);
} else {
char buf[RSA_MAX_ENCODING_BYTES]; /*
* limit on size of
* binary
* representation
* of key
*/
size_t sz;
char diag_space[TTODATAV_BUF];
ugh = ttodatav(flp->tok, flp->cur - flp->tok, 0, buf,
sizeof(buf), &sz,
diag_space, sizeof(diag_space),
TTODATAV_SPACECOUNTS);
if (ugh != NULL) {
/* ttodata didn't like PPK data */
ugh = builddiag("PPK data malformed (%s): %s", ugh,
flp->tok);