spki.c 25.1 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
3
4
5
6
7
8
/* spki.c
 *
 * An implementation of SPKI certificate checking
 *
 * $Id$ */

/* lsh, an implementation of the ssh protocol
 *
9
 * Copyright (C) 1999 Balzs Scheidler, Niels Mller
Niels Möller's avatar
Niels Möller committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *
 * 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.
 *
 * 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; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "spki.h"

28
#include "atoms.h"
29
#include "crypto.h"
30
#include "format.h"
Niels Möller's avatar
Niels Möller committed
31
#include "io.h"
32
#include "interact.h"
33
#include "list.h"
Niels Möller's avatar
Niels Möller committed
34
35
#include "parse.h"
#include "publickey_crypto.h"
36
#include "randomness.h"
Niels Möller's avatar
Niels Möller committed
37
38
39
#include "sexp.h"
#include "werror.h"
#include "xalloc.h"
Balázs Scheidler's avatar
Balázs Scheidler committed
40
#include "alist.h"
Niels Möller's avatar
Niels Möller committed
41

42
#include <assert.h>
43
#include <string.h>
44
45
46
47
48

#define GABA_DEFINE
#include "spki.h.x"
#undef GABA_DEFINE

Balázs Scheidler's avatar
Balázs Scheidler committed
49
50
#include "spki.c.x"

Niels Möller's avatar
Niels Möller committed
51
52
53
54
55
56
57
58
59
60
61
62
#define SA(x) sexp_a(ATOM_##x)

struct exception *
make_spki_exception(UINT32 type, const char *msg, struct sexp *expr)
{
  NEW(spki_exception, self);
  assert(type & EXC_SPKI);

  self->super.type = type;
  self->super.msg = msg;
  self->expr = expr;

63
  return &self->super;
Niels Möller's avatar
Niels Möller committed
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
/* FIXME: This should create different tags for hostnames that are not
 * dns fqdn:s. */

struct sexp *
make_ssh_hostkey_tag(struct address_info *host)
{
  UINT32 left = host->ip->length;
  UINT8 *s = host->ip->data;
  
  struct lsh_string *reversed = lsh_string_alloc(left);

  /* First, transform "foo.lysator.liu.se" into "se.liu.lysator.foo" */
  while (left)
    {
      UINT8 *p = memchr(s, '.', left);
      if (!p)
	{
	  memcpy(reversed->data, s, left);
	  break;
	}
      else
	{
	  UINT32 segment = p - s;
	  left -= segment;

	  memcpy(reversed->data + left, s, segment);
	  reversed->data[--left] = '.';
	  s = p+1;
	}
    }

  return sexp_l(2, sexp_z("ssh-hostkey"),
98
		sexp_s(NULL, reversed),
99
100
		-1);
}      
101
102
103
104
105
106
107
108
109
110
111
112
113
114


struct verifier *
spki_make_verifier(struct alist *algorithms,
		   struct sexp *e)
{
  /* Syntax: (<algorithm> <s-expr>*) */
  struct signature_algorithm *algorithm;
  struct verifier *v;
  int algorithm_name;
  struct sexp_iterator *i;

  algorithm_name = spki_get_type(e, &i);

115
116
117
118
119
120
  {
    CAST_SUBTYPE(signature_algorithm, a, 
		 ALIST_GET(algorithms, algorithm_name));
    algorithm = a;
  }
  
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
  if (!algorithm)
    {
      werror("spki_make_verifier: Unsupported algorithm %a.\n", algorithm_name);
      return NULL;
    }

  v = MAKE_VERIFIER(algorithm, i);
  KILL(i);
  
  if (!v)
    {
      werror("spki_make_verifier: Invalid public-key data.\n");
      return NULL;
    }
  
  return v;
}

139
/* FIXME: Merge spki_make_signer and spki_sexp_to_signer? */
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/* Returns the algorithm type, or zero on error. */
struct signer *
spki_make_signer(struct alist *algorithms,
		 struct sexp *e,
		 int *type)
{
  /* Syntax: (<algorithm> <s-expr>*) */
  struct signature_algorithm *algorithm;
  struct signer *s;
  int algorithm_name;
  struct sexp_iterator *i;

  algorithm_name = spki_get_type(e, &i);

  if (!algorithm_name)
    return NULL;
  
157
158
159
160
161
  {
    CAST_SUBTYPE(signature_algorithm, a, 
		 ALIST_GET(algorithms, algorithm_name));
    algorithm = a;
  }
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

  if (!algorithm)
    {
      werror("spki_make_signer: Unsupported algorithm %a.\n", algorithm_name);
      return NULL;
    }

  s = MAKE_SIGNER(algorithm, i);
  KILL(i);
  
  if (!s)
    {
      werror("spki_make_signer: Invalid public-key data.\n");
      return NULL;
    }

  if (type)
    *type = algorithm_name;

  return s;
}

184
185
186
187
/* Reading keys */

struct signer *
spki_sexp_to_signer(struct alist *algorithms,
188
189
                    struct sexp *key,
                    int *algorithm_name)
190
191
192
193
194
195
196
197
198
199
200
201
202
203
{
  struct sexp_iterator *i;
  
  if ((i = sexp_check_type(key, ATOM_PRIVATE_KEY)))
    {
      struct sexp *expr = SEXP_GET(i);
      struct signer *s;
      
      if (!expr)
        {
          werror("sexp_to_signer: Invalid key\n");
          return NULL;
        }
      
204
      s = spki_make_signer(algorithms, expr, algorithm_name);
205
206
207
208
209
210
211
212
213
214
215
216
217
      
      if (s)
	/* Test key here? */
	;
      else
	werror("sexp_to_signer: Invalid key.", expr);

      return s;
    }
  werror("sexp_to_signer: Expected private-key expression.");
  return NULL;
}

218
struct sexp *
219
spki_make_public_key(struct verifier *verifier)
220
221
{
  return sexp_l(2, SA(PUBLIC_KEY),
222
		PUBLIC_SPKI_KEY(verifier), -1);
223
224
}

Niels Möller's avatar
Niels Möller committed
225
/* Returns 0 or an atom */
226
227
int
spki_get_type(struct sexp *e, struct sexp_iterator **res)
Niels Möller's avatar
Niels Möller committed
228
229
{
  struct sexp_iterator *i;
230
  int type;
Niels Möller's avatar
Niels Möller committed
231
232
233
234
235
236
237
238
  
  if (sexp_atomp(e) || sexp_nullp(e))
    return 0;

  i = SEXP_ITER(e);

  type = sexp2atom(SEXP_GET(i));
  if (type && res)
239
240
241
242
    {
      SEXP_NEXT(i);
      *res = i;
    }
Niels Möller's avatar
Niels Möller committed
243
244
245
246
247
248
  else
    KILL(i);

  return type;
}

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
struct sexp *
spki_hash_data(struct hash_algorithm *algorithm,
	       int algorithm_name,
	       UINT32 length, UINT8 *data)
{
  struct hash_instance *hash = MAKE_HASH(algorithm);
  struct lsh_string *out = lsh_string_alloc(hash->hash_size);

  HASH_UPDATE(hash, length, data);
  HASH_DIGEST(hash, out->data);

  return sexp_l(3,
		SA(HASH),
		sexp_a(algorithm_name),
		sexp_s(NULL, out), -1);
}  

266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/* Create an SPKI hash from an s-expression. */

struct sexp *
spki_hash_sexp(struct hash_algorithm *algorithm,
	       int name,
	       struct sexp *expr)
{
  struct lsh_string *s = hash_string(algorithm,
				     sexp_format(expr, SEXP_CANONICAL, 0),
				     1);
  struct sexp *hash = spki_hash_data(algorithm, name, 
				     s->length, s->data);
  lsh_string_free(s);

  return hash;
}

283

284
285
/* 5-tuples */

286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
struct spki_subject *
make_spki_subject(struct sexp *key,
		  struct verifier *verifier,
		  struct lsh_string *sha1,
		  struct lsh_string *md5)
{
  NEW(spki_subject, self);
  self->key = key;
  self->verifier = verifier;
  self->sha1 = sha1;
  self->md5 = md5;

  return self;
}

static int
subject_match_hash(struct spki_subject *self,
		   int method,
304
		   const struct lsh_string *h1)
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
{
  struct lsh_string *h2;

  switch (method)
    {
    case ATOM_SHA1:
      if (self->sha1)
	h2 = self->sha1;
#if 0
      else if (self->key)
	h2 = self->sha1
	  = hash_string(&sha1_algorithm,
			sexp_format(self->key, SEXP_CANONICAL, 0), 1);
#endif
      else
	return 0;
      break;

    case ATOM_MD5:
      if (self->md5)
	h2 = self->md5;
#if 0
      else if (self->key)
	h2 = self->md5
	  = hash_string(&md5_algorithm,
			sexp_format(self->key, SEXP_CANONICAL, 0), 1);
#endif
      else
	return 0;
      break;

    default:
      return 0;
    }
  return lsh_string_eq(h1, h2);
}

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
struct spki_5_tuple *
make_spki_5_tuple(struct spki_subject *issuer,
		  struct spki_subject *subject,
		  int propagate,
		  struct spki_tag *authorization,
		  int before_limit, time_t not_before,
		  int after_limit, time_t not_after)
{
  NEW(spki_5_tuple, self);
  self->issuer = issuer;
  self->subject = subject;
  self->propagate = propagate;
  self->authorization = authorization;
  self->validity.before_limit = before_limit;
  self->validity.not_before = not_before;
  self->validity.after_limit = after_limit;
  self->validity.not_after = not_after;

  return self;
}


364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/* Sets of authorizations, representing the (tag ...) expressions in
 * acl:s and certificates. */

/* An authorization represented as a string (optionally with display
 * type). */

/* GABA:
   (class
     (name spki_tag_atom)
     (super spki_tag)
     (vars
       (resource object sexp)))
*/

static int
do_spki_tag_atom_match(struct spki_tag *s,
380
		       struct sexp *e)
381
382
383
384
385
386
{
  CAST(spki_tag_atom, self, s);

  assert(sexp_atomp(self->resource));
  
  return sexp_atomp(e)
387
    && sexp_atoms_eq(self->resource, e);
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
}

static struct spki_tag *
make_spki_tag_atom(struct sexp *resource)
{
  NEW(spki_tag_atom, self);

  assert(sexp_atomp(resource));
  
  self->super.type = SPKI_TAG_ATOM;
  self->super.match = do_spki_tag_atom_match;

  self->resource = resource;

  return &self->super;
}


/* An authorization represented as a list. Includes all authorizations
 * that for which a prefix matches the list. */

/* GABA:
   (class
     (name spki_tag_list)
     (super spki_tag)
     (vars
       (list object object_list)))
*/

static int
do_spki_tag_list_match(struct spki_tag *s,
		       struct sexp *e)
{
421
  CAST(spki_tag_list, self, s);
422
423
424
425
426
427
428
  unsigned i;
  struct sexp_iterator *j;
  
  if (sexp_atomp(e))
    return 0;

  for (i = 0, j = SEXP_ITER(e);
429
       i<LIST_LENGTH(self->list);
430
431
       i++, SEXP_NEXT(j))
    {
432
      CAST_SUBTYPE(spki_tag, tag, LIST(self->list)[i]);
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
      struct sexp *o = SEXP_GET(j);

      if (! (o && SPKI_TAG_MATCH(tag, o)))
	return 0;
    }
  
  return 1;
}

static struct spki_tag *
make_spki_tag_list(struct object_list *list)
{
  NEW(spki_tag_list, self);

  self->super.type = SPKI_TAG_LIST;
  self->super.match = do_spki_tag_list_match;

  self->list = list;

  return &self->super;
}

/* A (* set ...) construction */

/* GABA:
   (class
     (name spki_tag_set)
     (super spki_tag)
     (vars
       (set object object_list)))
*/

static int
do_spki_tag_set_match(struct spki_tag *s,
		      struct sexp *e)
{
  CAST(spki_tag_set, self, s);
  unsigned i;

  for (i = 0; i<LIST_LENGTH(self->set); i++)
    {
      CAST_SUBTYPE(spki_tag, tag, LIST(self->set)[i]);
      if (SPKI_TAG_MATCH(tag, e))
	return 1;
    }

  return 0;
}

static struct spki_tag *
make_spki_tag_set(struct object_list *set)
{
  NEW(spki_tag_set, self);

  self->super.type = SPKI_TAG_SET;
  self->super.match = do_spki_tag_set_match;

  self->set = set;

  return &self->super;
}

/* Authorizations represented as a string prefix. If display types are
 * present, they must be equal. */

/* GABA:
   (class
     (name spki_tag_prefix)
     (super spki_tag)
     (vars
       (prefix object sexp)))
*/

static int
do_spki_tag_prefix_match(struct spki_tag *s,
			 struct sexp *e)
{
  CAST(spki_tag_prefix, self, s);
511
512
  const struct lsh_string *ed;
  const struct lsh_string *pd;
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

  assert(sexp_atomp(self->prefix));
  
  if (!sexp_atomp(e))
    return 0;

  ed = sexp_display(e);
  pd = sexp_display(self->prefix);
  
  return (ed ? (pd && lsh_string_eq(ed, pd)) : !pd)
    && lsh_string_prefixp(sexp_contents(self->prefix),
			  sexp_contents(e));
}

static struct spki_tag *
make_spki_tag_prefix(struct sexp *prefix)
{
  NEW(spki_tag_prefix, self);

  self->super.type = SPKI_TAG_PREFIX;
  self->super.match = do_spki_tag_prefix_match;

  self->prefix = prefix;

  return &self->super;
}


static int
do_spki_tag_any_match(struct spki_tag *self UNUSED,
			 struct sexp *e UNUSED)
{
  return 1;
}

/* FIXME: Make this const */
struct spki_tag spki_tag_any =
{ STATIC_HEADER, SPKI_TAG_ANY, do_spki_tag_any_match };


static struct object_list *
spki_sexp_to_tag_list(struct sexp_iterator *i, unsigned limit)
{
  unsigned left;
  struct object_list *l;
  unsigned j;

  left = SEXP_LEFT(i);

  if (!left)
    {
      werror("spki_sexp_to_tag_list: Empty list.\n");
      return NULL;
    }
  
  l = alloc_object_list(left);
  
570
  for (j = 0; j<left; j++)
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
    {
      struct spki_tag *tag = spki_sexp_to_tag(SEXP_GET(i), limit);
      if (!tag)
	{
	  /* FIXME: We could explicitly kill the elements of the list
	   * as well. */
	  KILL(l);
	  return NULL;
	}
      LIST(l)[j] = &tag->super;
      SEXP_NEXT(i);
    }
  assert(!SEXP_GET(i));

  return l;
}

struct spki_tag *
spki_sexp_to_tag(struct sexp *e,
		 /* Some limit on the recursion */
		 unsigned limit)
{
  if (sexp_atomp(e))
    return make_spki_tag_atom(e);
  else
    {
      struct sexp_iterator *i;
      if (!limit)
	{
	  werror("spki_sexp_to_tag: Nesting too deep.\n");
	  return NULL;
	}
      
604
      if ((i = sexp_check_type(e, ATOM_STAR)))
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
	{
	  struct sexp *magic = SEXP_GET(i);
	  
	  if (!magic)
	    return &spki_tag_any;

	  SEXP_NEXT(i);
	  
	  switch(sexp2atom(magic))
	    {
	    case ATOM_SET:
	      {
		struct object_list *l = spki_sexp_to_tag_list(i, limit - 1);

		return l ? make_spki_tag_set(l) : NULL;
	      }
	    case ATOM_PREFIX:
	      {
		struct sexp *prefix = SEXP_GET(i);

		return (prefix && sexp_atomp(prefix))
		  ? make_spki_tag_prefix(prefix)
		  : NULL;
	      }
	    default:
	      werror("spki_sexp_to_tag: Invalid (* ...) tag.\n");
	      return NULL;
	    }
	}
      else
	{
	  struct object_list *l = spki_sexp_to_tag_list(SEXP_ITER(e), limit - 1);

	  return l ? make_spki_tag_list(l) : NULL;
	}
    }
}

#define SPKI_NESTING_LIMIT 17

645
646
647
648
649
/* The iterator should point at the element after the tag of an expression
 *
 *   (entry (public-key|hash|name ...) (propagate)? (tag ...) (valid ...)? )
 */

650
struct spki_5_tuple *
651
652
spki_acl_entry_to_5_tuple(struct spki_context *ctx,
			  struct sexp_iterator *i)
653
{
654
655
656
657
658
659
660
661
662
  struct spki_subject *subject;
  struct sexp_iterator *j;
  struct spki_tag *authorization;
  
  int propagate = 0;
  
  struct sexp *e = SEXP_GET(i);
  
  if (!e)
663
    {
664
665
666
      werror("spki_acl_entry_to_5_tuple: Invalid entry.\n");
      return NULL;
    }
667

668
  subject = SPKI_LOOKUP(ctx, e, NULL);
669
670
671
672
673
674
675
  if (!subject)
    return NULL;

  SEXP_NEXT(i);
  e = SEXP_GET(i);
  if (!e)
    return NULL;
676

677
  if ((j = sexp_check_type(e, ATOM_PROPAGATE)))
678
679
680
681
682
683
684
    {
      if (SEXP_GET(j))
	{
	  werror("spki_acl_entry_to_5_tuple: Invalid propagate-expression.\n");
	  return NULL;
	}
      propagate = 1;
685
      SEXP_NEXT(i);
686
687
688
      e = SEXP_GET(i);
    }

689
  if ((j = sexp_check_type(e, ATOM_TAG)))
690
691
692
693
    {
      struct sexp *tag = SEXP_GET(j);
      SEXP_NEXT(j);
      if (SEXP_GET(j))
694
	{
695
	  werror("spki_acl_entry_to_5_tuple: Invalid tag-expression.\n");
696
	  return NULL;
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
	}
      
      authorization = spki_sexp_to_tag(tag, SPKI_NESTING_LIMIT);
      if (!authorization)
	return NULL;
    }
  else
    {
      werror("spki_acl_entry_to_5_tuple: Invalid entry.\n");
      return NULL;
    }
    
  SEXP_NEXT(i);
  if (SEXP_GET(i))
    {
      werror("spki_acl_entry_to_5_tuple: Garbage at end of entry.\n");
      return NULL;
    }

  /* Create a 5-tuple with a NULL (i.e. self) issuer */
  return make_spki_5_tuple(NULL, subject, propagate,
			   authorization, 0, 0, 0, 0);
}

721
722
/* Takes an spki_context and an ACL s-expression, and adds
 * corresponding 5-tuples to the context. Returns 1 if all entries
723
 * were correct, 0 on any error. However, it tries to go on if some
724
 * sub-expression is invalid. */
725

726
727
728
int
spki_add_acl(struct spki_context *ctx,
	     struct sexp *e)
729
730
{
  struct sexp_iterator *i;
731
  int res = 1;
732
  
733
  if (!(i = sexp_check_type(e, ATOM_ACL)))
734
735
    {
      werror("spki_read_acls: Invalid acl\n");
736
      return 0;
737
    }
738

739
  /* FIXME: Accept at least (version "0") */
740
#if 0
741
  if (sexp_check_type(SEXP_GET(i), ATOM_VERSION, NULL))
742
743
    {
      werror("spki_read_acls: Unsupported acl version\n");
744
      return 0;
745
    }
746
#endif
747
  
748
749
750
  for (; (e = SEXP_GET(i)); SEXP_NEXT(i))
    {
      struct sexp_iterator *j;
751
      if ((j = sexp_check_type(e, ATOM_ENTRY)))
752
753
754
	{
	  struct spki_5_tuple *acl = spki_acl_entry_to_5_tuple(ctx, j);
	  if (acl)
755
756
	    SPKI_ADD_TUPLE(ctx, acl);
	  else res = 0;
757
758
	}
      else
759
760
761
762
	{
	  werror("spki_read_acls: Invalid entry, ignoring\n");
	  res = 0;
	}
763
764
    }

765
  return res;
766
}
767

768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

/* SPKI context */

/* GABA:
   (class
     (name spki_state)
     (super spki_context)
     (vars
       ; Signature algorithms
       (algorithms object alist)
       ;; FIXME: Could have a alist of hash algorithms as well.
       
       ; We could use some kind of hash table instead
       (keys struct object_queue)

       ; Five tuples. 
       (db struct object_queue)))
*/

static struct spki_subject *
spki_subject_by_hash(struct spki_state *self,
789
790
		     int algorithm,
		     const struct lsh_string *hash)
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
{
  FOR_OBJECT_QUEUE(&self->keys, n)
    {
      CAST(spki_subject, subject, n);
	    
      if (subject_match_hash(subject, algorithm, hash))
	return subject;
    }
  return NULL;
}

static struct spki_subject *
do_spki_lookup(struct spki_context *s,
	       struct sexp *e,
	       struct verifier *v)

{
  CAST(spki_state, self, s);
  struct sexp_iterator *i;

  switch (spki_get_type(e, &i))
    {
    case ATOM_HASH:
      {
815
	/* Syntax: (hash <hash-alg-name> <hash-value> <uris>) */
816
	struct spki_subject *subject;
817
	const struct lsh_string *hash;
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

	int method = sexp2atom(SEXP_GET(i));
	if (!method)
	  return NULL;

	SEXP_NEXT(i);
	hash = sexp2string(SEXP_GET(i));

	if (!hash)
	  return NULL;

	SEXP_NEXT(i);
	if (SEXP_GET(i))
	  return NULL;
	
	subject = spki_subject_by_hash(self, method, hash);
	
	if (!subject)
	  {
	    switch (method)
	      {
	      case ATOM_SHA1:
		subject = make_spki_subject(NULL, NULL, lsh_string_dup(hash), NULL);
		break;
	      case ATOM_MD5:
		subject = make_spki_subject(NULL, NULL, NULL, lsh_string_dup(hash));
		break;
	      default:
		return NULL;
	      }

	    object_queue_add_tail(&self->keys, &subject->super);
	  }

	if (!subject->verifier && v)
	  subject->verifier = v;

	return subject;
      }
    case ATOM_PUBLIC_KEY:
      {
859
	/* Syntax: (public-key (<pub-sig-alg-id> <s-expr>*) <uris>) */
860
861
862
	struct spki_subject *subject;
	struct lsh_string *sha1;
	struct lsh_string *md5;
863
864
865
866
867
868
869
	struct sexp *key = SEXP_GET(i);

	if (!key)
	  {
	    werror("do_spki_lookup: Invalid (public-key ...) expression.\n");
	    return NULL;
	  }
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887

	/* We first se if we can find the key by hash */
	{
	  struct lsh_string *canonical = sexp_format(e, SEXP_CANONICAL, 0);
	  sha1 = hash_string(&sha1_algorithm, canonical, 0);
	  md5 = hash_string(&md5_algorithm, canonical, 1);
	}

	if ( ((subject = spki_subject_by_hash(self, ATOM_SHA1, sha1)))
	     || ((subject = spki_subject_by_hash(self, ATOM_MD5, md5))) )
	  {
	    lsh_string_free(md5);
	    lsh_string_free(sha1);

	    if (!subject->key)
	      {
		assert(!subject->verifier);
		subject->key = e;
888

889
		subject->verifier
890
		  = v ? v : spki_make_verifier(self->algorithms, key);
891
892
893
894
895
896
	      }
	  }
	else
	  {
	    /* New subject */
	    subject = make_spki_subject(e,
897
					v ? v : spki_make_verifier(self->algorithms, key),
898
899
900
901
902
903
904
					sha1, md5);
	    
	    object_queue_add_head(&self->keys, &subject->super);
	  }
	
	return subject;
      }
Niels Möller's avatar
Niels Möller committed
905
906
907
908
    case ATOM_SEQUENCE:
      werror("do_spki_lookup: spki sequences not yet supported.\n");
      return NULL;
      
909
910
911
912
913
914
915
916
917
    case ATOM_NAME:
      werror("do_spki_lookup: names not yet supported.\n");
      return NULL;
    default:
      werror("do_spki_lookup: Invalid expression.\n");
      return NULL;
    }
}

918
919
920
921
922
923
924
925
926
static void
do_spki_add_tuple(struct spki_context *s,
		  struct spki_5_tuple *tuple)
{
  CAST(spki_state, self, s);

  object_queue_add_tail(&self->db, &tuple->super);
}

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
static int
do_spki_authorize(struct spki_context *s,
		  struct spki_subject *user,
		  struct sexp *access)
{
  CAST(spki_state, self, s);

  FOR_OBJECT_QUEUE(&self->db, n)
    {
      CAST(spki_5_tuple, tuple, n);

      /* FIXME: Handles ACL:s only. I.e. issuer == NULL. */
      if ( (user == tuple->subject)
	   && !tuple->issuer
	   && SPKI_TAG_MATCH(tuple->authorization, access))
	return 1;
    }
  return 0;
}

struct spki_context *
make_spki_context(struct alist *algorithms)
{
  NEW(spki_state, self);
  self->super.lookup = do_spki_lookup;
952
  self->super.add_tuple = do_spki_add_tuple;
953
954
955
956
957
958
959
960
  self->super.authorize = do_spki_authorize;
  
  self->algorithms = algorithms;
  object_queue_init(&self->keys);
  object_queue_init(&self->db);

  return &self->super;
}
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036


/* PKCS-5 handling */

/* Encryption of private data.
 * For PKCS#5 (version 2) key derivation, we use
 *
 * (password-encrypted LABEL
 *   (Xpkcs5v2 hmac-sha1 (salt #...#)
 *                       (iterations #...#))
 *   ("3des-cbc" (iv #...#) (data #...#)))
 *
 * where the X:s will be removed when the format is more stable.
 *
 */

struct sexp *
spki_pkcs5_encrypt(struct randomness *r,
                   struct lsh_string *label,
		   UINT32 prf_name,
		   struct mac_algorithm *prf,
		   int crypto_name,
		   struct crypto_algorithm *crypto,
		   UINT32 salt_length,
		   struct lsh_string *password,
		   UINT32 iterations,
                   struct lsh_string *data)
{
  struct lsh_string *key;
  struct lsh_string *salt;
  struct lsh_string *iv;
  struct sexp *method;
  
  assert(crypto);
  assert(prf);

  salt = lsh_string_alloc(salt_length);
  RANDOM(r, salt->length, salt->data);
    
  key = lsh_string_alloc(crypto->key_size);

  pkcs5_derive_key(prf,
		   password->length, password->data,
		   salt->length, salt->data,
		   iterations,
		   key->length, key->data);

  method = sexp_l(4, SA(XPKCS5V2), sexp_a(prf_name),
                  sexp_l(2, SA(ITERATIONS), sexp_uint32(iterations), -1),
                  sexp_l(2, SA(SALT), sexp_s(NULL, salt), -1), -1);

  if (crypto->iv_size)
    {
      iv = lsh_string_alloc(crypto->iv_size);
      RANDOM(r, iv->length, iv->data);
    }
  else
    iv = NULL;

  return sexp_l(4,
                SA(PASSWORD_ENCRYPTED),
                sexp_s(NULL, lsh_string_dup(label)),
                method,
                sexp_l(3,
                       sexp_a(crypto_name),
                       sexp_l(2, SA(IV), sexp_s(NULL, iv), -1),
                       sexp_l(2, SA(DATA),
                              sexp_s(NULL, crypt_string_pad
                                     (MAKE_ENCRYPT(crypto,
                                                   key->data,
                                                   iv ? iv->data : NULL),
                                      data, 0)),
                              -1),
                       -1),
                -1);
}
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227

struct sexp *
spki_pkcs5_decrypt(struct alist *mac_algorithms,
                   struct alist *crypto_algorithms,
                   struct interact *interact,
                   struct sexp *expr)
{
  struct sexp_iterator *i;
  
  if (!(i = sexp_check_type(expr, ATOM_PASSWORD_ENCRYPTED)))
    return expr;

  else
    {
      const struct lsh_string *label;
      struct sexp *key_info;
      struct sexp *payload;

      struct crypto_algorithm *crypto;
      struct mac_algorithm *mac;
      
      const struct lsh_string *salt;
      const struct lsh_string *iv;
      const struct lsh_string *data;
      UINT32 iterations;
      
      if (SEXP_LEFT(i) != 3)
	{
	  werror("Invalid (password-encrypted ...) expression.\n");
	  return NULL;
	}
	
      /* NOTE: This is a place where it might make sense to use a sexp
       * display type, but we don't support that for now. */
      label = sexp2string(SEXP_GET(i));

      if (!label)
	{
	  werror("Invalid label in (password-encrypted ...) expression.\n");
	  return NULL;
	}

      SEXP_NEXT(i);
      key_info = SEXP_GET(i);
      assert(key_info);

      SEXP_NEXT(i);
      payload = SEXP_GET(i);
      assert(payload);

      /* Examine the payload expression first, before asking for a
       * pass phrase. */

      {
	int algorithm_name = spki_get_type(payload, &i);
	CAST_SUBTYPE(crypto_algorithm, tmp,
		     ALIST_GET(crypto_algorithms, algorithm_name));
	crypto = tmp;
      }

      if (!crypto)
	{
          werror("Unknown encryption algorithm for pkcs5v2.\n");
	  return NULL;
	}

      iv = sexp2string(sexp_assq(i, ATOM_IV));

      if (crypto->iv_size)
	{
	  if (!iv || (iv->length != crypto->iv_size))
	    {
	      werror("Invalid IV for pkcs5v2.\n");
	      return NULL;
	    }
	}
      else if (iv)
	{
	  if (iv->length)
	    {
	      werror("Unexpected iv provided for pkcs5v2.\n");
	      return NULL;
	    }
	  iv = NULL;
	}
	
      data = sexp2string(sexp_assq(i, ATOM_DATA));

      if (!data)
	{
	  werror("Payload data missing for pkcs5v2.\n");
	  return NULL;
	}

      if (crypto->block_size && (data->length & crypto->block_size))
	{
	  werror("Payload data doesn't match block size for pkcs5v2.\n");
	  return NULL;
	}

      /* Get key */
      switch (spki_get_type(key_info, &i)) 
	{
	default:
	  werror("Unknown key derivation mechanism.\n");
	  return NULL;

	case ATOM_XPKCS5V2:
	  if (SEXP_LEFT(i) != 3)
	    {
	      werror("Invalid pkcs5v2 parameters.\n");
	      return NULL;
	    }
	  
	  {
	    int algorithm_name = sexp2atom(SEXP_GET(i));
	    
	    CAST_SUBTYPE(mac_algorithm, tmp,
			 ALIST_GET(mac_algorithms,
				   algorithm_name));

	    mac = tmp;
	  }

	  if (!mac)
	    {
	      werror("Unknown mac for pkcs5v2.\n");
	      return NULL;
	    }

	  SEXP_NEXT(i);
	  if (!sexp2uint32(sexp_assq(i, ATOM_ITERATIONS), &iterations)
	      || !iterations)
	    {
	      werror("Invalid iteration count for pkcs5v2.\n");
	      return NULL;
	    }
	    
	  salt = sexp2string(sexp_assq(i, ATOM_SALT));

	  if (!salt)
	    {
	      werror("Invalid salt for pkcs5v2.\n");
	      return NULL;
	    }

	  /* Do the work */

	  {
	    struct lsh_string *password
	      = INTERACT_READ_PASSWORD(interact, 500, label, 0);
	    struct lsh_string *clear;
	    struct sexp *res;
	    UINT8 *key;
	    
	    if (!password)
	      {
		werror("No password provided for pkcs5v2.");
		return NULL;
	      }

	    key = alloca(crypto->key_size);
	    pkcs5_derive_key(mac,
			     password->length, password->data,
			     salt->length, salt->data,
			     iterations,
			     crypto->key_size, key);

	    lsh_string_free(password);

	    clear = crypt_string_unpad(MAKE_DECRYPT(crypto,
						    key,
						    iv ? iv->data : NULL),
				       data, 0);

	    if (!clear)
	      {
		werror("Bad password for pkcs5v2.\n");
		return NULL;
	      }

	    res = string_to_sexp(SEXP_CANONICAL, clear, 1);

	    if (!res)
              werror("Bad password for pkcs5v2.\n");

            return res;
	  }
	}
    }
}