Coverage Report

Created: 2024-02-27 06:14

/src/plan9port/src/libsec/port/x509.c
Line
Count
Source (jump to first uncovered line)
1
#include <u.h>
2
#include <libc.h>
3
#include <mp.h>
4
#include <libsec.h>
5
6
typedef DigestState*(*DigestFun)(uchar*,ulong,uchar*,DigestState*);
7
8
/* ANSI offsetof, backwards. */
9
11.8k
#define OFFSETOF(a, b)  offsetof(b, a)
10
11
/*=============================================================*/
12
/*  general ASN1 declarations and parsing
13
 *
14
 *  For now, this is used only for extracting the key from an
15
 *  X509 certificate, so the entire collection is hidden.  But
16
 *  someday we should probably make the functions visible and
17
 *  give them their own man page.
18
 */
19
typedef struct Elem Elem;
20
typedef struct Tag Tag;
21
typedef struct Value Value;
22
typedef struct Bytes Bytes;
23
typedef struct Ints Ints;
24
typedef struct Bits Bits;
25
typedef struct Elist Elist;
26
27
/* tag classes */
28
150k
#define Universal 0
29
0
#define Context 0x80
30
31
/* universal tags */
32
1.03k
#define BOOLEAN 1
33
2.09k
#define INTEGER 2
34
897
#define BIT_STRING 3
35
8.86k
#define OCTET_STRING 4
36
251
#define NULLTAG 5
37
1.32k
#define OBJECT_ID 6
38
6.03k
#define ObjectDescriptor 7
39
260
#define EXTERNAL 8
40
398
#define REAL 9
41
2.03k
#define ENUMERATED 10
42
1.08k
#define EMBEDDED_PDV 11
43
3.58k
#define SEQUENCE 16    /* also SEQUENCE OF */
44
2.38k
#define SETOF 17        /* also SETOF OF */
45
958
#define NumericString 18
46
2.94k
#define PrintableString 19
47
3.74k
#define TeletexString 20
48
39.6k
#define VideotexString 21
49
45.3k
#define IA5String 22
50
47.1k
#define UTCTime 23
51
54.3k
#define GeneralizedTime 24
52
61.9k
#define GraphicString 25
53
70.9k
#define VisibleString 26
54
108k
#define GeneralString 27
55
120k
#define UniversalString 28
56
125k
#define BMPString 30
57
58
struct Bytes {
59
  int len;
60
  uchar data[1];
61
};
62
63
struct Ints {
64
  int len;
65
  int data[1];
66
};
67
68
struct Bits {
69
  int len;    /* number of bytes */
70
  int unusedbits; /* unused bits in last byte */
71
  uchar data[1];  /* most-significant bit first */
72
};
73
74
struct Tag {
75
  int class;
76
  int num;
77
};
78
79
enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
80
  VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
81
struct Value {
82
  int tag;    /* VBool, etc. */
83
  union {
84
    int boolval;
85
    int intval;
86
    Bytes*  octetsval;
87
    Bytes*  bigintval;
88
    Bytes*  realval;  /* undecoded; hardly ever used */
89
    Bytes*  otherval;
90
    Bits* bitstringval;
91
    Ints* objidval;
92
    char* stringval;
93
    Elist*  seqval;
94
    Elist*  setval;
95
  } u;  /* (Don't use anonymous unions, for ease of porting) */
96
};
97
98
struct Elem {
99
  Tag tag;
100
  Value val;
101
};
102
103
struct Elist {
104
  Elist*  tl;
105
  Elem  hd;
106
};
107
108
/* decoding errors */
109
enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
110
    ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
111
112
113
/* here are the functions to consider making extern someday */
114
static Bytes* newbytes(int len);
115
static Bytes* makebytes(uchar* buf, int len);
116
static void freebytes(Bytes* b);
117
static Bytes* catbytes(Bytes* b1, Bytes* b2);
118
static Ints*  newints(int len);
119
static Ints*  makeints(int* buf, int len);
120
static void freeints(Ints* b);
121
static Bits*  newbits(int len);
122
static Bits*  makebits(uchar* buf, int len, int unusedbits);
123
static void freebits(Bits* b);
124
static Elist* mkel(Elem e, Elist* tail);
125
static void freeelist(Elist* el);
126
static int  elistlen(Elist* el);
127
static int  is_seq(Elem* pe, Elist** pseq);
128
static int  is_set(Elem* pe, Elist** pset);
129
static int  is_int(Elem* pe, int* pint);
130
static int  is_bigint(Elem* pe, Bytes** pbigint);
131
static int  is_bitstring(Elem* pe, Bits** pbits);
132
static int  is_octetstring(Elem* pe, Bytes** poctets);
133
static int  is_oid(Elem* pe, Ints** poid);
134
static int  is_string(Elem* pe, char** pstring);
135
static int  is_time(Elem* pe, char** ptime);
136
static int  decode(uchar* a, int alen, Elem* pelem);
137
/*
138
static int  decode_seq(uchar* a, int alen, Elist** pelist);
139
static int  decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval);
140
*/
141
static int  encode(Elem e, Bytes** pbytes);
142
static int  oid_lookup(Ints* o, Ints** tab);
143
static void freevalfields(Value* v);
144
static mpint  *asn1mpint(Elem *e);
145
146
147
148
285k
#define TAG_MASK 0x1F
149
142k
#define CONSTR_MASK 0x20
150
142k
#define CLASS_MASK 0xC0
151
2.66k
#define MAXOBJIDLEN 20
152
153
static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
154
static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
155
static int length_decode(uchar** pp, uchar* pend, int* plength);
156
static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
157
static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
158
static int uint7_decode(uchar** pp, uchar* pend, int* pint);
159
static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
160
static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
161
static int enc(uchar** pp, Elem e, int lenonly);
162
static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
163
static void uint7_enc(uchar** pp, int num, int lenonly);
164
static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
165
166
static void *
167
emalloc(int n)
168
23.5k
{
169
23.5k
  void *p;
170
23.5k
  if(n==0)
171
0
    n=1;
172
23.5k
  p = malloc(n);
173
23.5k
  if(p == nil){
174
0
    exits("out of memory");
175
0
  }
176
23.5k
  memset(p, 0, n);
177
23.5k
  return p;
178
23.5k
}
179
180
static char*
181
estrdup(char *s)
182
0
{
183
0
  char *d, *d0;
184
185
0
  if(!s)
186
0
    return 0;
187
0
  d = d0 = emalloc(strlen(s)+1);
188
0
  while(*d++ = *s++)
189
0
    ;
190
0
  return d0;
191
0
}
192
193
194
/*
195
 * Decode a[0..len] as a BER encoding of an ASN1 type.
196
 * The return value is one of ASN_OK, etc.
197
 * Depending on the error, the returned elem may or may not
198
 * be nil.
199
 */
200
static int
201
decode(uchar* a, int alen, Elem* pelem)
202
1.55k
{
203
1.55k
  uchar* p = a;
204
205
1.55k
  return  ber_decode(&p, &a[alen], pelem);
206
1.55k
}
207
208
/*
209
 * Like decode, but continue decoding after first element
210
 * of array ends.
211
 *
212
static int
213
decode_seq(uchar* a, int alen, Elist** pelist)
214
{
215
  uchar* p = a;
216
217
  return seq_decode(&p, &a[alen], -1, 1, pelist);
218
}
219
*/
220
221
/*
222
 * Decode the whole array as a BER encoding of an ASN1 value,
223
 * (i.e., the part after the tag and length).
224
 * Assume the value is encoded as universal tag "kind".
225
 * The constr arg is 1 if the value is constructed, 0 if primitive.
226
 * If there's an error, the return string will contain the error.
227
 * Depending on the error, the returned value may or may not
228
 * be nil.
229
 *
230
static int
231
decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
232
{
233
  uchar* p = a;
234
235
  return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
236
}
237
*/
238
239
/*
240
 * All of the following decoding routines take arguments:
241
 *  uchar **pp;
242
 *  uchar *pend;
243
 * Where parsing is supposed to start at **pp, and when parsing
244
 * is done, *pp is updated to point at next char to be parsed.
245
 * The pend pointer is just past end of string; an error should
246
 * be returned parsing hasn't finished by then.
247
 *
248
 * The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
249
 * The remaining argument(s) are pointers to where parsed entity goes.
250
 */
251
252
/* Decode an ASN1 'Elem' (tag, length, value) */
253
static int
254
ber_decode(uchar** pp, uchar* pend, Elem* pelem)
255
143k
{
256
143k
  int err;
257
143k
  int isconstr;
258
143k
  int length;
259
143k
  Tag tag;
260
143k
  Value val;
261
262
143k
  err = tag_decode(pp, pend, &tag, &isconstr);
263
143k
  if(err == ASN_OK) {
264
142k
    err = length_decode(pp, pend, &length);
265
142k
    if(err == ASN_OK) {
266
142k
      if(tag.class == Universal)
267
139k
        err = value_decode(pp, pend, length, tag.num, isconstr, &val);
268
3.70k
      else
269
3.70k
        err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
270
142k
      if(err == ASN_OK) {
271
14.8k
        pelem->tag = tag;
272
14.8k
        pelem->val = val;
273
14.8k
      }
274
142k
    }
275
142k
  }
276
143k
  return err;
277
143k
}
278
279
/* Decode a tag field */
280
static int
281
tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
282
143k
{
283
143k
  int err;
284
143k
  int v;
285
143k
  uchar* p;
286
287
143k
  err = ASN_OK;
288
143k
  p = *pp;
289
143k
  if(pend-p >= 2) {
290
142k
    v = *p++;
291
142k
    ptag->class = v&CLASS_MASK;
292
142k
    if(v&CONSTR_MASK)
293
133k
      *pisconstr = 1;
294
9.69k
    else
295
9.69k
      *pisconstr = 0;
296
142k
    v &= TAG_MASK;
297
142k
    if(v == TAG_MASK)
298
464
      err = uint7_decode(&p, pend, &v);
299
142k
    ptag->num = v;
300
142k
  }
301
42
  else
302
42
    err = ASN_ESHORT;
303
143k
  *pp = p;
304
143k
  return err;
305
143k
}
306
307
/* Decode a length field */
308
static int
309
length_decode(uchar** pp, uchar* pend, int* plength)
310
142k
{
311
142k
  int err;
312
142k
  int num;
313
142k
  int v;
314
142k
  uchar* p;
315
316
142k
  err = ASN_OK;
317
142k
  num = 0;
318
142k
  p = *pp;
319
142k
  if(p < pend) {
320
142k
    v = *p++;
321
142k
    if(v&0x80)
322
3.38k
      err = int_decode(&p, pend, v&0x7F, 1, &num);
323
139k
    else
324
139k
      num = v;
325
142k
  }
326
0
  else
327
0
    err = ASN_ESHORT;
328
142k
  *pp = p;
329
142k
  *plength = num;
330
142k
  return err;
331
142k
}
332
333
/* Decode a value field  */
334
static int
335
value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
336
142k
{
337
142k
  int err;
338
142k
  Bytes* va;
339
142k
  int num;
340
142k
  int bitsunused;
341
142k
  int subids[MAXOBJIDLEN];
342
142k
  int isubid;
343
142k
  Elist*  vl;
344
142k
  uchar* p;
345
142k
  uchar* pe;
346
347
142k
  err = ASN_OK;
348
142k
  p = *pp;
349
142k
  if(length == -1) { /* "indefinite" length spec */
350
0
    if(!isconstr)
351
0
      err = ASN_EINVAL;
352
0
  }
353
142k
  else if(p + length > pend)
354
112
    err = ASN_EVALLEN;
355
142k
  if(err != ASN_OK)
356
112
    return err;
357
358
142k
  switch(kind) {
359
841
  case 0:
360
    /* marker for end of indefinite constructions */
361
841
    if(length == 0)
362
823
      pval->tag = VNull;
363
18
    else
364
18
      err = ASN_EINVAL;
365
841
    break;
366
367
612
  case BOOLEAN:
368
612
    if(isconstr)
369
1
      err = ASN_ECONSTR;
370
611
    else if(length != 1)
371
18
      err = ASN_EVALLEN;
372
593
    else {
373
593
      pval->tag = VBool;
374
593
      pval->u.boolval = (*p++ != 0);
375
593
    }
376
612
    break;
377
378
1.46k
  case INTEGER:
379
1.93k
  case ENUMERATED:
380
1.93k
    if(isconstr)
381
1
      err = ASN_ECONSTR;
382
1.93k
    else if(length <= 4) {
383
1.62k
      err = int_decode(&p, pend, length, 0, &num);
384
1.62k
      if(err == ASN_OK) {
385
1.62k
        pval->tag = VInt;
386
1.62k
        pval->u.intval = num;
387
1.62k
      }
388
1.62k
    }
389
304
    else {
390
304
      pval->tag = VBigInt;
391
304
      pval->u.bigintval = makebytes(p, length);
392
304
      p += length;
393
304
    }
394
1.93k
    break;
395
396
642
  case BIT_STRING:
397
642
    pval->tag = VBitString;
398
642
    if(isconstr) {
399
6
      if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
400
0
        pval->u.bitstringval = makebits(0, 0, 0);
401
0
        p += 2;
402
0
      }
403
6
      else
404
        /* TODO: recurse and concat results */
405
6
        err = ASN_EUNIMPL;
406
6
    }
407
636
    else {
408
636
      if(length < 2) {
409
372
        if(length == 1 && *p == 0) {
410
363
          pval->u.bitstringval = makebits(0, 0, 0);
411
363
          p++;
412
363
        }
413
9
        else
414
9
          err = ASN_EINVAL;
415
372
      }
416
264
      else {
417
264
        bitsunused = *p;
418
264
        if(bitsunused > 7)
419
17
          err = ASN_EINVAL;
420
247
        else if(length > 0x0FFFFFFF)
421
0
          err = ASN_ETOOBIG;
422
247
        else {
423
247
          pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
424
247
          p += length;
425
247
        }
426
264
      }
427
636
    }
428
642
    break;
429
430
4.95k
  case OCTET_STRING:
431
6.03k
  case ObjectDescriptor:
432
6.03k
    err = octet_decode(&p, pend, length, isconstr, &va);
433
6.03k
    if(err == ASN_OK) {
434
4.69k
      pval->tag = VOctets;
435
4.69k
      pval->u.octetsval = va;
436
4.69k
    }
437
6.03k
    break;
438
439
227
  case NULLTAG:
440
227
    if(isconstr)
441
1
      err = ASN_ECONSTR;
442
226
    else if(length != 0)
443
20
      err = ASN_EVALLEN;
444
206
    else
445
206
      pval->tag = VNull;
446
227
    break;
447
448
788
  case OBJECT_ID:
449
788
    if(isconstr)
450
1
      err = ASN_ECONSTR;
451
787
    else if(length == 0)
452
1
      err = ASN_EVALLEN;
453
786
    else {
454
786
      isubid = 0;
455
786
      pe = p+length;
456
3.40k
      while(p < pe && isubid < MAXOBJIDLEN) {
457
2.65k
        err = uint7_decode(&p, pend, &num);
458
2.65k
        if(err != ASN_OK)
459
38
          break;
460
2.62k
        if(isubid == 0) {
461
779
          subids[isubid++] = num / 40;
462
779
          subids[isubid++] = num % 40;
463
779
        }
464
1.84k
        else
465
1.84k
          subids[isubid++] = num;
466
2.62k
      }
467
786
      if(err == ASN_OK) {
468
748
        if(p != pe)
469
6
          err = ASN_EVALLEN;
470
742
        else {
471
742
          pval->tag = VObjId;
472
742
          pval->u.objidval = makeints(subids, isubid);
473
742
        }
474
748
      }
475
786
    }
476
788
    break;
477
478
222
  case EXTERNAL:
479
739
  case EMBEDDED_PDV:
480
    /* TODO: parse this internally */
481
739
    if(p+length > pend)
482
0
      err = ASN_EVALLEN;
483
739
    else {
484
739
      pval->tag = VOther;
485
739
      pval->u.otherval = makebytes(p, length);
486
739
      p += length;
487
739
    }
488
739
    break;
489
490
289
  case REAL:
491
    /* Let the application decode */
492
289
    if(isconstr)
493
2
      err = ASN_ECONSTR;
494
287
    else if(p+length > pend)
495
0
      err = ASN_EVALLEN;
496
287
    else {
497
287
      pval->tag = VReal;
498
287
      pval->u.realval = makebytes(p, length);
499
287
      p += length;
500
287
    }
501
289
    break;
502
503
2.47k
  case SEQUENCE:
504
2.47k
    err = seq_decode(&p, pend, length, isconstr, &vl);
505
2.47k
    if(err == ASN_OK) {
506
1.41k
      pval->tag = VSeq ;
507
1.41k
      pval->u.seqval = vl;
508
1.41k
    }
509
2.47k
    break;
510
511
1.71k
  case SETOF:
512
1.71k
    err = seq_decode(&p, pend, length, isconstr, &vl);
513
1.71k
    if(err == ASN_OK) {
514
822
      pval->tag = VSet;
515
822
      pval->u.setval = vl;
516
822
    }
517
1.71k
    break;
518
519
909
  case NumericString:
520
2.88k
  case PrintableString:
521
3.71k
  case TeletexString:
522
39.6k
  case VideotexString:
523
45.3k
  case IA5String:
524
46.9k
  case UTCTime:
525
54.3k
  case GeneralizedTime:
526
61.8k
  case GraphicString:
527
70.9k
  case VisibleString:
528
108k
  case GeneralString:
529
120k
  case UniversalString:
530
125k
  case BMPString:
531
    /* TODO: figure out when character set conversion is necessary */
532
125k
    err = octet_decode(&p, pend, length, isconstr, &va);
533
125k
    if(err == ASN_OK) {
534
1.25k
      pval->tag = VString;
535
1.25k
      pval->u.stringval = (char*)emalloc(va->len+1);
536
1.25k
      memmove(pval->u.stringval, va->data, va->len);
537
1.25k
      pval->u.stringval[va->len] = 0;
538
1.25k
      free(va);
539
1.25k
    }
540
125k
    break;
541
542
700
  default:
543
700
    if(p+length > pend)
544
0
      err = ASN_EVALLEN;
545
700
    else {
546
700
      pval->tag = VOther;
547
700
      pval->u.otherval = makebytes(p, length);
548
700
      p += length;
549
700
    }
550
700
    break;
551
142k
  }
552
142k
  *pp = p;
553
142k
  return err;
554
142k
}
555
556
/*
557
 * Decode an int in format where count bytes are
558
 * concatenated to form value.
559
 * Although ASN1 allows any size integer, we return
560
 * an error if the result doesn't fit in a 32-bit int.
561
 * If unsgned is not set, make sure to propagate sign bit.
562
 */
563
static int
564
int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
565
5.01k
{
566
5.01k
  int err;
567
5.01k
  int num;
568
5.01k
  uchar* p;
569
570
5.01k
  p = *pp;
571
5.01k
  err = ASN_OK;
572
5.01k
  num = 0;
573
5.01k
  if(p+count <= pend) {
574
5.01k
    if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
575
26
      err = ASN_ETOOBIG;
576
4.98k
    else {
577
4.98k
      if(!unsgned && count > 0 && count < 4 && (*p&0x80))
578
247
        num = -1;   /* set all bits, initially */
579
9.20k
      while(count--)
580
4.21k
        num = (num << 8)|(*p++);
581
4.98k
    }
582
5.01k
  }
583
3
  else
584
3
    err = ASN_ESHORT;
585
5.01k
  *pint = num;
586
5.01k
  *pp = p;
587
5.01k
  return err;
588
5.01k
}
589
590
/*
591
 * Decode an unsigned int in format where each
592
 * byte except last has high bit set, and remaining
593
 * seven bits of each byte are concatenated to form value.
594
 * Although ASN1 allows any size integer, we return
595
 * an error if the result doesn't fit in a 32 bit int.
596
 */
597
static int
598
uint7_decode(uchar** pp, uchar* pend, int* pint)
599
3.12k
{
600
3.12k
  int err;
601
3.12k
  int num;
602
3.12k
  int more;
603
3.12k
  int v;
604
3.12k
  uchar* p;
605
606
3.12k
  p = *pp;
607
3.12k
  err = ASN_OK;
608
3.12k
  num = 0;
609
3.12k
  more = 1;
610
7.15k
  while(more && p < pend) {
611
4.05k
    v = *p++;
612
4.05k
    if(num&0x7F000000) {
613
15
      err = ASN_ETOOBIG;
614
15
      break;
615
15
    }
616
4.03k
    num <<= 7;
617
4.03k
    more = v&0x80;
618
4.03k
    num |= (v&0x7F);
619
4.03k
  }
620
3.12k
  if(p == pend)
621
50
    err = ASN_ESHORT;
622
3.12k
  *pint = num;
623
3.12k
  *pp = p;
624
3.12k
  return err;
625
3.12k
}
626
627
/*
628
 * Decode an octet string, recursively if isconstr.
629
 * We've already checked that length==-1 implies isconstr==1,
630
 * and otherwise that specified length fits within (*pp..pend)
631
 */
632
static int
633
octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
634
131k
{
635
131k
  int err;
636
131k
  uchar* p;
637
131k
  Bytes* ans;
638
131k
  Bytes* newans;
639
131k
  uchar* pstart;
640
131k
  uchar* pold;
641
131k
  Elem  elem;
642
643
131k
  err = ASN_OK;
644
131k
  p = *pp;
645
131k
  ans = nil;
646
131k
  if(length >= 0 && !isconstr) {
647
5.12k
    ans = makebytes(p, length);
648
5.12k
    p += length;
649
5.12k
  }
650
126k
  else {
651
    /* constructed, either definite or indefinite length */
652
126k
    pstart = p;
653
130k
    for(;;) {
654
130k
      if(length >= 0 && p >= pstart + length) {
655
907
        if(p != pstart + length)
656
77
          err = ASN_EVALLEN;
657
907
        break;
658
907
      }
659
129k
      pold = p;
660
129k
      err = ber_decode(&p, pend, &elem);
661
129k
      if(err != ASN_OK)
662
125k
        break;
663
3.50k
      switch(elem.val.tag) {
664
3.33k
      case VOctets:
665
3.33k
        newans = catbytes(ans, elem.val.u.octetsval);
666
3.33k
        freebytes(ans);
667
3.33k
        ans = newans;
668
3.33k
        break;
669
670
0
      case VEOC:
671
0
        if(length != -1) {
672
0
          p = pold;
673
0
          err = ASN_EINVAL;
674
0
        }
675
0
        goto cloop_done;
676
677
167
      default:
678
167
        p = pold;
679
167
        err = ASN_EINVAL;
680
167
        goto cloop_done;
681
3.50k
      }
682
3.50k
    }
683
126k
cloop_done:
684
126k
    ;
685
126k
  }
686
131k
  *pp = p;
687
131k
  *pbytes = ans;
688
131k
  return err;
689
131k
}
690
691
/*
692
 * Decode a sequence or set.
693
 * We've already checked that length==-1 implies isconstr==1,
694
 * and otherwise that specified length fits within (*p..pend)
695
 */
696
static int
697
seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
698
4.19k
{
699
4.19k
  int err;
700
4.19k
  uchar* p;
701
4.19k
  uchar* pstart;
702
4.19k
  uchar* pold;
703
4.19k
  Elist* ans;
704
4.19k
  Elem elem;
705
4.19k
  Elist* lve;
706
4.19k
  Elist* lveold;
707
708
4.19k
  err = ASN_OK;
709
4.19k
  ans = nil;
710
4.19k
  p = *pp;
711
4.19k
  if(!isconstr)
712
16
    err = ASN_EPRIM;
713
4.17k
  else {
714
    /* constructed, either definite or indefinite length */
715
4.17k
    lve = nil;
716
4.17k
    pstart = p;
717
14.6k
    for(;;) {
718
14.6k
      if(length >= 0 && p >= pstart + length) {
719
2.30k
        if(p != pstart + length)
720
77
          err = ASN_EVALLEN;
721
2.30k
        break;
722
2.30k
      }
723
12.3k
      pold = p;
724
12.3k
      err = ber_decode(&p, pend, &elem);
725
12.3k
      if(err != ASN_OK)
726
1.86k
        break;
727
10.4k
      if(elem.val.tag == VEOC) {
728
0
        if(length != -1) {
729
0
          p = pold;
730
0
          err = ASN_EINVAL;
731
0
        }
732
0
        break;
733
0
      }
734
10.4k
      else
735
10.4k
        lve = mkel(elem, lve);
736
10.4k
    }
737
4.17k
    if(err == ASN_OK) {
738
      /* reverse back to original order */
739
9.25k
      while(lve != nil) {
740
7.01k
        lveold = lve;
741
7.01k
        lve = lve->tl;
742
7.01k
        lveold->tl = ans;
743
7.01k
        ans = lveold;
744
7.01k
      }
745
2.23k
    }
746
4.17k
  }
747
4.19k
  *pp = p;
748
4.19k
  *pelist = ans;
749
4.19k
  return err;
750
4.19k
}
751
752
/*
753
 * Encode e by BER rules, putting answer in *pbytes.
754
 * This is done by first calling enc with lenonly==1
755
 * to get the length of the needed buffer,
756
 * then allocating the buffer and using enc again to fill it up.
757
 */
758
static int
759
encode(Elem e, Bytes** pbytes)
760
0
{
761
0
  uchar* p;
762
0
  Bytes* ans;
763
0
  int err;
764
0
  uchar uc;
765
766
0
  p = &uc;
767
0
  err = enc(&p, e, 1);
768
0
  if(err == ASN_OK) {
769
0
    ans = newbytes(p-&uc);
770
0
    p = ans->data;
771
0
    err = enc(&p, e, 0);
772
0
    *pbytes = ans;
773
0
  }
774
0
  return err;
775
0
}
776
777
/*
778
 * The various enc functions take a pointer to a pointer
779
 * into a buffer, and encode their entity starting there,
780
 * updating the pointer afterwards.
781
 * If lenonly is 1, only the pointer update is done,
782
 * allowing enc to be called first to calculate the needed
783
 * buffer length.
784
 * If lenonly is 0, it is assumed that the answer will fit.
785
 */
786
787
static int
788
enc(uchar** pp, Elem e, int lenonly)
789
0
{
790
0
  int err;
791
0
  int vlen;
792
0
  int constr;
793
0
  Tag tag;
794
0
  int v;
795
0
  int ilen;
796
0
  uchar* p;
797
0
  uchar* psave;
798
799
0
  p = *pp;
800
0
  err = val_enc(&p, e, &constr, 1);
801
0
  if(err != ASN_OK)
802
0
    return err;
803
0
  vlen = p - *pp;
804
0
  p = *pp;
805
0
  tag = e.tag;
806
0
  v = tag.class|constr;
807
0
  if(tag.num < 31) {
808
0
    if(!lenonly)
809
0
      *p = (v|tag.num);
810
0
    p++;
811
0
  }
812
0
  else {
813
0
    if(!lenonly)
814
0
      *p = (v|31);
815
0
    p++;
816
0
    if(tag.num < 0)
817
0
      return ASN_EINVAL;
818
0
    uint7_enc(&p, tag.num, lenonly);
819
0
  }
820
0
  if(vlen < 0x80) {
821
0
    if(!lenonly)
822
0
      *p = vlen;
823
0
    p++;
824
0
  }
825
0
  else {
826
0
    psave = p;
827
0
    int_enc(&p, vlen, 1, 1);
828
0
    ilen = p-psave;
829
0
    p = psave;
830
0
    if(!lenonly) {
831
0
      *p++ = (0x80 | ilen);
832
0
      int_enc(&p, vlen, 1, 0);
833
0
    }
834
0
    else
835
0
      p += 1 + ilen;
836
0
  }
837
0
  if(!lenonly)
838
0
    val_enc(&p, e, &constr, 0);
839
0
  else
840
0
    p += vlen;
841
0
  *pp = p;
842
0
  return err;
843
0
}
844
845
static int
846
val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
847
0
{
848
0
  int err;
849
0
  uchar* p;
850
0
  int kind;
851
0
  int cl;
852
0
  int v;
853
0
  Bytes* bb = nil;
854
0
  Bits* bits;
855
0
  Ints* oid;
856
0
  int k;
857
0
  Elist* el;
858
0
  char* s;
859
860
0
  p = *pp;
861
0
  err = ASN_OK;
862
0
  kind = e.tag.num;
863
0
  cl = e.tag.class;
864
0
  *pconstr = 0;
865
0
  if(cl != Universal) {
866
0
    switch(e.val.tag) {
867
0
    case VBool:
868
0
      kind = BOOLEAN;
869
0
      break;
870
0
    case VInt:
871
0
      kind = INTEGER;
872
0
      break;
873
0
    case VBigInt:
874
0
      kind = INTEGER;
875
0
      break;
876
0
    case VOctets:
877
0
      kind = OCTET_STRING;
878
0
      break;
879
0
    case VReal:
880
0
      kind = REAL;
881
0
      break;
882
0
    case VOther:
883
0
      kind = OCTET_STRING;
884
0
      break;
885
0
    case VBitString:
886
0
      kind = BIT_STRING;
887
0
      break;
888
0
    case VNull:
889
0
      kind = NULLTAG;
890
0
      break;
891
0
    case VObjId:
892
0
      kind = OBJECT_ID;
893
0
      break;
894
0
    case VString:
895
0
      kind = UniversalString;
896
0
      break;
897
0
    case VSeq:
898
0
      kind = SEQUENCE;
899
0
      break;
900
0
    case VSet:
901
0
      kind = SETOF;
902
0
      break;
903
0
    }
904
0
  }
905
0
  switch(kind) {
906
0
  case BOOLEAN:
907
0
    if(is_int(&e, &v)) {
908
0
      if(v != 0)
909
0
        v = 255;
910
0
       int_enc(&p, v, 1, lenonly);
911
0
    }
912
0
    else
913
0
      err = ASN_EINVAL;
914
0
    break;
915
916
0
  case INTEGER:
917
0
  case ENUMERATED:
918
0
    if(is_int(&e, &v))
919
0
      int_enc(&p, v, 0, lenonly);
920
0
    else {
921
0
      if(is_bigint(&e, &bb)) {
922
0
        if(!lenonly)
923
0
          memmove(p, bb->data, bb->len);
924
0
        p += bb->len;
925
0
      }
926
0
      else
927
0
        err = ASN_EINVAL;
928
0
    }
929
0
    break;
930
931
0
  case BIT_STRING:
932
0
    if(is_bitstring(&e, &bits)) {
933
0
      if(bits->len == 0) {
934
0
        if(!lenonly)
935
0
          *p = 0;
936
0
        p++;
937
0
      }
938
0
      else {
939
0
        v = bits->unusedbits;
940
0
        if(v < 0 || v > 7)
941
0
          err = ASN_EINVAL;
942
0
        else {
943
0
          if(!lenonly) {
944
0
            *p = v;
945
0
            memmove(p+1, bits->data, bits->len);
946
0
          }
947
0
          p += 1 + bits->len;
948
0
        }
949
0
      }
950
0
    }
951
0
    else
952
0
      err = ASN_EINVAL;
953
0
    break;
954
955
0
  case OCTET_STRING:
956
0
  case ObjectDescriptor:
957
0
  case EXTERNAL:
958
0
  case REAL:
959
0
  case EMBEDDED_PDV:
960
0
    bb = nil;
961
0
    switch(e.val.tag) {
962
0
    case VOctets:
963
0
      bb = e.val.u.octetsval;
964
0
      break;
965
0
    case VReal:
966
0
      bb = e.val.u.realval;
967
0
      break;
968
0
    case VOther:
969
0
      bb = e.val.u.otherval;
970
0
      break;
971
0
    }
972
0
    if(bb != nil) {
973
0
      if(!lenonly)
974
0
        memmove(p, bb->data, bb->len);
975
0
      p += bb->len;
976
0
    }
977
0
      else
978
0
        err = ASN_EINVAL;
979
0
    break;
980
981
0
  case NULLTAG:
982
0
    break;
983
984
0
  case OBJECT_ID:
985
0
    if(is_oid(&e, &oid)) {
986
0
      for(k = 0; k < oid->len; k++) {
987
0
        v = oid->data[k];
988
0
        if(k == 0) {
989
0
          v *= 40;
990
0
          if(oid->len > 1)
991
0
            v += oid->data[++k];
992
0
        }
993
0
        uint7_enc(&p, v, lenonly);
994
0
      }
995
0
    }
996
0
    else
997
0
      err = ASN_EINVAL;
998
0
    break;
999
1000
0
  case SEQUENCE:
1001
0
  case SETOF:
1002
0
    el = nil;
1003
0
    if(e.val.tag == VSeq)
1004
0
      el = e.val.u.seqval;
1005
0
    else if(e.val.tag == VSet)
1006
0
      el = e.val.u.setval;
1007
0
    else
1008
0
      err = ASN_EINVAL;
1009
0
    if(el != nil) {
1010
0
      *pconstr = CONSTR_MASK;
1011
0
      for(; el != nil; el = el->tl) {
1012
0
        err = enc(&p, el->hd, lenonly);
1013
0
        if(err != ASN_OK)
1014
0
          break;
1015
0
      }
1016
0
    }
1017
0
    break;
1018
1019
0
  case NumericString:
1020
0
  case PrintableString:
1021
0
  case TeletexString:
1022
0
  case VideotexString:
1023
0
  case IA5String:
1024
0
  case UTCTime:
1025
0
  case GeneralizedTime:
1026
0
  case GraphicString:
1027
0
  case VisibleString:
1028
0
  case GeneralString:
1029
0
  case UniversalString:
1030
0
  case BMPString:
1031
0
    if(e.val.tag == VString) {
1032
0
      s = e.val.u.stringval;
1033
0
      if(s != nil) {
1034
0
        v = strlen(s);
1035
0
        if(!lenonly)
1036
0
          memmove(p, s, v);
1037
0
        p += v;
1038
0
      }
1039
0
    }
1040
0
    else
1041
0
      err = ASN_EINVAL;
1042
0
    break;
1043
1044
0
  default:
1045
0
    err = ASN_EINVAL;
1046
0
  }
1047
0
  *pp = p;
1048
0
  return err;
1049
0
}
1050
1051
/*
1052
 * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1053
 * except last, only putting in bytes if !lenonly.
1054
 */
1055
static void
1056
uint7_enc(uchar** pp, int num, int lenonly)
1057
0
{
1058
0
  int n;
1059
0
  int v;
1060
0
  int k;
1061
0
  uchar* p;
1062
1063
0
  p = *pp;
1064
0
  n = 1;
1065
0
  v = num >> 7;
1066
0
  while(v > 0) {
1067
0
    v >>= 7;
1068
0
    n++;
1069
0
  }
1070
0
  if(lenonly)
1071
0
    p += n;
1072
0
  else {
1073
0
    for(k = (n - 1)*7; k > 0; k -= 7)
1074
0
      *p++= ((num >> k)|0x80);
1075
0
    *p++ = (num&0x7F);
1076
0
  }
1077
0
  *pp = p;
1078
0
}
1079
1080
/*
1081
 * Encode num as unsigned or signed integer,
1082
 * only putting in bytes if !lenonly.
1083
 * Encoding is length followed by bytes to concatenate.
1084
 */
1085
static void
1086
int_enc(uchar** pp, int num, int unsgned, int lenonly)
1087
0
{
1088
0
  int v;
1089
0
  int n;
1090
0
  int prevv;
1091
0
  int k;
1092
0
  uchar* p;
1093
1094
0
  p = *pp;
1095
0
  v = num;
1096
0
  if(v < 0)
1097
0
    v = -(v + 1);
1098
0
  n = 1;
1099
0
  prevv = v;
1100
0
  v >>= 8;
1101
0
  while(v > 0) {
1102
0
    prevv = v;
1103
0
    v >>= 8;
1104
0
    n++;
1105
0
  }
1106
0
  if(!unsgned && (prevv&0x80))
1107
0
    n++;
1108
0
  if(lenonly)
1109
0
    p += n;
1110
0
  else {
1111
0
    for(k = (n - 1)*8; k >= 0; k -= 8)
1112
0
      *p++ = (num >> k);
1113
0
  }
1114
0
  *pp = p;
1115
0
}
1116
1117
static int
1118
ints_eq(Ints* a, Ints* b)
1119
0
{
1120
0
  int alen;
1121
0
  int i;
1122
1123
0
  alen = a->len;
1124
0
  if(alen != b->len)
1125
0
    return 0;
1126
0
  for(i = 0; i < alen; i++)
1127
0
    if(a->data[i] != b->data[i])
1128
0
      return 0;
1129
0
  return 1;
1130
0
}
1131
1132
/*
1133
 * Look up o in tab (which must have nil entry to terminate).
1134
 * Return index of matching entry, or -1 if none.
1135
 */
1136
static int
1137
oid_lookup(Ints* o, Ints** tab)
1138
0
{
1139
0
  int i;
1140
1141
0
  for(i = 0; tab[i] != nil; i++)
1142
0
    if(ints_eq(o, tab[i]))
1143
0
      return  i;
1144
0
  return -1;
1145
0
}
1146
1147
/*
1148
 * Return true if *pe is a SEQUENCE, and set *pseq to
1149
 * the value of the sequence if so.
1150
 */
1151
static int
1152
is_seq(Elem* pe, Elist** pseq)
1153
0
{
1154
0
  if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1155
0
    *pseq = pe->val.u.seqval;
1156
0
    return 1;
1157
0
  }
1158
0
  return 0;
1159
0
}
1160
1161
static int
1162
is_set(Elem* pe, Elist** pset)
1163
0
{
1164
0
  if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1165
0
    *pset = pe->val.u.setval;
1166
0
    return 1;
1167
0
  }
1168
0
  return 0;
1169
0
}
1170
1171
static int
1172
is_int(Elem* pe, int* pint)
1173
0
{
1174
0
  if(pe->tag.class == Universal) {
1175
0
    if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1176
0
      *pint = pe->val.u.intval;
1177
0
      return 1;
1178
0
    }
1179
0
    else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1180
0
      *pint = pe->val.u.boolval;
1181
0
      return 1;
1182
0
    }
1183
0
  }
1184
0
  return 0;
1185
0
}
1186
1187
/*
1188
 * for convience, all VInt's are readable via this routine,
1189
 * as well as all VBigInt's
1190
 */
1191
static int
1192
is_bigint(Elem* pe, Bytes** pbigint)
1193
0
{
1194
0
  int v, n, i;
1195
1196
0
  if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
1197
0
    if(pe->val.tag == VBigInt)
1198
0
      *pbigint = pe->val.u.bigintval;
1199
0
    else if(pe->val.tag == VInt){
1200
0
      v = pe->val.u.intval;
1201
0
      for(n = 1; n < 4; n++)
1202
0
        if((1 << (8 * n)) > v)
1203
0
          break;
1204
0
      *pbigint = newbytes(n);
1205
0
      for(i = 0; i < n; i++)
1206
0
        (*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
1207
0
    }else
1208
0
      return 0;
1209
0
    return 1;
1210
0
  }
1211
0
  return 0;
1212
0
}
1213
1214
static int
1215
is_bitstring(Elem* pe, Bits** pbits)
1216
0
{
1217
0
  if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1218
0
    *pbits = pe->val.u.bitstringval;
1219
0
    return 1;
1220
0
  }
1221
0
  return 0;
1222
0
}
1223
1224
static int
1225
is_octetstring(Elem* pe, Bytes** poctets)
1226
0
{
1227
0
  if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1228
0
    *poctets = pe->val.u.octetsval;
1229
0
    return 1;
1230
0
  }
1231
0
  return 0;
1232
0
}
1233
1234
static int
1235
is_oid(Elem* pe, Ints** poid)
1236
0
{
1237
0
  if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1238
0
    *poid = pe->val.u.objidval;
1239
0
    return 1;
1240
0
  }
1241
0
  return 0;
1242
0
}
1243
1244
static int
1245
is_string(Elem* pe, char** pstring)
1246
0
{
1247
0
  if(pe->tag.class == Universal) {
1248
0
    switch(pe->tag.num) {
1249
0
    case NumericString:
1250
0
    case PrintableString:
1251
0
    case TeletexString:
1252
0
    case VideotexString:
1253
0
    case IA5String:
1254
0
    case GraphicString:
1255
0
    case VisibleString:
1256
0
    case GeneralString:
1257
0
    case UniversalString:
1258
0
    case BMPString:
1259
0
      if(pe->val.tag == VString) {
1260
0
        *pstring = pe->val.u.stringval;
1261
0
        return 1;
1262
0
      }
1263
0
    }
1264
0
  }
1265
0
  return 0;
1266
0
}
1267
1268
static int
1269
is_time(Elem* pe, char** ptime)
1270
0
{
1271
0
  if(pe->tag.class == Universal
1272
0
     && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
1273
0
     && pe->val.tag == VString) {
1274
0
    *ptime = pe->val.u.stringval;
1275
0
    return 1;
1276
0
  }
1277
0
  return 0;
1278
0
}
1279
1280
1281
/*
1282
 * malloc and return a new Bytes structure capable of
1283
 * holding len bytes. (len >= 0)
1284
 */
1285
static Bytes*
1286
newbytes(int len)
1287
10.4k
{
1288
10.4k
  Bytes* ans;
1289
1290
10.4k
  ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
1291
10.4k
  ans->len = len;
1292
10.4k
  return ans;
1293
10.4k
}
1294
1295
/*
1296
 * newbytes(len), with data initialized from buf
1297
 */
1298
static Bytes*
1299
makebytes(uchar* buf, int len)
1300
7.84k
{
1301
7.84k
  Bytes* ans;
1302
1303
7.84k
  ans = newbytes(len);
1304
7.84k
  memmove(ans->data, buf, len);
1305
7.84k
  return ans;
1306
7.84k
}
1307
1308
static void
1309
freebytes(Bytes* b)
1310
3.33k
{
1311
3.33k
  if(b != nil)
1312
2.78k
    free(b);
1313
3.33k
}
1314
1315
/*
1316
 * Make a new Bytes, containing bytes of b1 followed by those of b2.
1317
 * Either b1 or b2 or both can be nil.
1318
 */
1319
static Bytes*
1320
catbytes(Bytes* b1, Bytes* b2)
1321
3.33k
{
1322
3.33k
  Bytes* ans;
1323
3.33k
  int n;
1324
1325
3.33k
  if(b1 == nil) {
1326
550
    if(b2 == nil)
1327
252
      ans = newbytes(0);
1328
298
    else
1329
298
      ans = makebytes(b2->data, b2->len);
1330
550
  }
1331
2.78k
  else if(b2 == nil) {
1332
399
    ans = makebytes(b1->data, b1->len);
1333
399
  }
1334
2.38k
  else {
1335
2.38k
    n = b1->len + b2->len;
1336
2.38k
    ans = newbytes(n);
1337
2.38k
    ans->len = n;
1338
2.38k
    memmove(ans->data, b1->data, b1->len);
1339
2.38k
    memmove(ans->data+b1->len, b2->data, b2->len);
1340
2.38k
  }
1341
3.33k
  return ans;
1342
3.33k
}
1343
1344
/* len is number of ints */
1345
static Ints*
1346
newints(int len)
1347
742
{
1348
742
  Ints* ans;
1349
1350
742
  ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
1351
742
  ans->len = len;
1352
742
  return ans;
1353
742
}
1354
1355
static Ints*
1356
makeints(int* buf, int len)
1357
742
{
1358
742
  Ints* ans;
1359
1360
742
  ans = newints(len);
1361
742
  if(len > 0)
1362
742
    memmove(ans->data, buf, len*sizeof(int));
1363
742
  return ans;
1364
742
}
1365
1366
static void
1367
freeints(Ints* b)
1368
0
{
1369
0
  if(b != nil)
1370
0
    free(b);
1371
0
}
1372
1373
/* len is number of bytes */
1374
static Bits*
1375
newbits(int len)
1376
610
{
1377
610
  Bits* ans;
1378
1379
610
  ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
1380
610
  ans->len = len;
1381
610
  ans->unusedbits = 0;
1382
610
  return ans;
1383
610
}
1384
1385
static Bits*
1386
makebits(uchar* buf, int len, int unusedbits)
1387
610
{
1388
610
  Bits* ans;
1389
1390
610
  ans = newbits(len);
1391
610
  memmove(ans->data, buf, len);
1392
610
  ans->unusedbits = unusedbits;
1393
610
  return ans;
1394
610
}
1395
1396
static void
1397
freebits(Bits* b)
1398
0
{
1399
0
  if(b != nil)
1400
0
    free(b);
1401
0
}
1402
1403
static Elist*
1404
mkel(Elem e, Elist* tail)
1405
10.4k
{
1406
10.4k
  Elist* el;
1407
1408
10.4k
  el = (Elist*)emalloc(sizeof(Elist));
1409
10.4k
  el->hd = e;
1410
10.4k
  el->tl = tail;
1411
10.4k
  return el;
1412
10.4k
}
1413
1414
static int
1415
elistlen(Elist* el)
1416
0
{
1417
0
  int ans = 0;
1418
0
  while(el != nil) {
1419
0
    ans++;
1420
0
    el = el->tl;
1421
0
  }
1422
0
  return ans;
1423
0
}
1424
1425
/* Frees elist, but not fields inside values of constituent elems */
1426
static void
1427
freeelist(Elist* el)
1428
0
{
1429
0
  Elist* next;
1430
1431
0
  while(el != nil) {
1432
0
    next = el->tl;
1433
0
    free(el);
1434
0
    el = next;
1435
0
  }
1436
0
}
1437
1438
/* free any allocated structures inside v (recursively freeing Elists) */
1439
static void
1440
freevalfields(Value* v)
1441
0
{
1442
0
  Elist* el;
1443
0
  Elist* l;
1444
0
  if(v == nil)
1445
0
    return;
1446
0
  switch(v->tag) {
1447
0
  case VOctets:
1448
0
    freebytes(v->u.octetsval);
1449
0
    break;
1450
0
  case VBigInt:
1451
0
    freebytes(v->u.bigintval);
1452
0
    break;
1453
0
  case VReal:
1454
0
    freebytes(v->u.realval);
1455
0
    break;
1456
0
  case VOther:
1457
0
    freebytes(v->u.otherval);
1458
0
    break;
1459
0
  case VBitString:
1460
0
    freebits(v->u.bitstringval);
1461
0
    break;
1462
0
  case VObjId:
1463
0
    freeints(v->u.objidval);
1464
0
    break;
1465
0
  case VString:
1466
0
    if (v->u.stringval)
1467
0
      free(v->u.stringval);
1468
0
    break;
1469
0
  case VSeq:
1470
0
    el = v->u.seqval;
1471
0
    for(l = el; l != nil; l = l->tl)
1472
0
      freevalfields(&l->hd.val);
1473
0
    if (el)
1474
0
      freeelist(el);
1475
0
    break;
1476
0
  case VSet:
1477
0
    el = v->u.setval;
1478
0
    for(l = el; l != nil; l = l->tl)
1479
0
      freevalfields(&l->hd.val);
1480
0
    if (el)
1481
0
      freeelist(el);
1482
0
    break;
1483
0
  }
1484
0
}
1485
1486
/* end of general ASN1 functions */
1487
1488
1489
1490
1491
1492
/*=============================================================*/
1493
/*
1494
 * Decode and parse an X.509 Certificate, defined by this ASN1:
1495
 *  Certificate ::= SEQUENCE {
1496
 *    certificateInfo CertificateInfo,
1497
 *    signatureAlgorithm AlgorithmIdentifier,
1498
 *    signature BIT STRING }
1499
 *
1500
 *  CertificateInfo ::= SEQUENCE {
1501
 *    version [0] INTEGER DEFAULT v1 (0),
1502
 *    serialNumber INTEGER,
1503
 *    signature AlgorithmIdentifier,
1504
 *    issuer Name,
1505
 *    validity Validity,
1506
 *    subject Name,
1507
 *    subjectPublicKeyInfo SubjectPublicKeyInfo }
1508
 *  (version v2 has two more fields, optional unique identifiers for
1509
 *  issuer and subject; since we ignore these anyway, we won't parse them)
1510
 *
1511
 *  Validity ::= SEQUENCE {
1512
 *    notBefore UTCTime,
1513
 *    notAfter UTCTime }
1514
 *
1515
 *  SubjectPublicKeyInfo ::= SEQUENCE {
1516
 *    algorithm AlgorithmIdentifier,
1517
 *    subjectPublicKey BIT STRING }
1518
 *
1519
 *  AlgorithmIdentifier ::= SEQUENCE {
1520
 *    algorithm OBJECT IDENTIFER,
1521
 *    parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1522
 *
1523
 *  Name ::= SEQUENCE OF RelativeDistinguishedName
1524
 *
1525
 *  RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
1526
 *
1527
 *  AttributeTypeAndValue ::= SEQUENCE {
1528
 *    type OBJECT IDENTIFER,
1529
 *    value DirectoryString }
1530
 *  (selected attributes have these Object Ids:
1531
 *    commonName {2 5 4 3}
1532
 *    countryName {2 5 4 6}
1533
 *    localityName {2 5 4 7}
1534
 *    stateOrProvinceName {2 5 4 8}
1535
 *    organizationName {2 5 4 10}
1536
 *    organizationalUnitName {2 5 4 11}
1537
 *  )
1538
 *
1539
 *  DirectoryString ::= CHOICE {
1540
 *    teletexString TeletexString,
1541
 *    printableString PrintableString,
1542
 *    universalString UniversalString }
1543
 *
1544
 *  See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1545
 *
1546
 *  Not yet implemented:
1547
 *   CertificateRevocationList ::= SIGNED SEQUENCE{
1548
 *           signature       AlgorithmIdentifier,
1549
 *           issuer          Name,
1550
 *           lastUpdate      UTCTime,
1551
 *           nextUpdate      UTCTime,
1552
 *           revokedCertificates
1553
 *                           SEQUENCE OF CRLEntry OPTIONAL}
1554
 *   CRLEntry ::= SEQUENCE{
1555
 *           userCertificate SerialNumber,
1556
 *           revocationDate UTCTime}
1557
 */
1558
1559
typedef struct CertX509 {
1560
  int serial;
1561
  char* issuer;
1562
  char* validity_start;
1563
  char* validity_end;
1564
  char* subject;
1565
  int publickey_alg;
1566
  Bytes*  publickey;
1567
  int signature_alg;
1568
  Bytes*  signature;
1569
} CertX509;
1570
1571
/* Algorithm object-ids */
1572
enum {
1573
  ALG_rsaEncryption,
1574
  ALG_md2WithRSAEncryption,
1575
  ALG_md4WithRSAEncryption,
1576
  ALG_md5WithRSAEncryption,
1577
  ALG_sha1WithRSAEncryption,
1578
  ALG_md5,
1579
  NUMALGS
1580
};
1581
typedef struct Ints7 {
1582
  int   len;
1583
  int   data[7];
1584
} Ints7;
1585
static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1586
static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1587
static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1588
static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1589
static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1590
static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
1591
static Ints *alg_oid_tab[NUMALGS+1] = {
1592
  (Ints*)(void*)&oid_rsaEncryption,
1593
  (Ints*)(void*)&oid_md2WithRSAEncryption,
1594
  (Ints*)(void*)&oid_md4WithRSAEncryption,
1595
  (Ints*)(void*)&oid_md5WithRSAEncryption,
1596
  (Ints*)(void*)&oid_sha1WithRSAEncryption,
1597
  (Ints*)(void*)&oid_md5,
1598
  nil
1599
};
1600
static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, 0 };
1601
1602
static void
1603
freecert(CertX509* c)
1604
0
{
1605
0
  if (!c) return;
1606
0
  if(c->issuer != nil)
1607
0
    free(c->issuer);
1608
0
  if(c->validity_start != nil)
1609
0
    free(c->validity_start);
1610
0
  if(c->validity_end != nil)
1611
0
    free(c->validity_end);
1612
0
  if(c->subject != nil)
1613
0
    free(c->subject);
1614
0
  freebytes(c->publickey);
1615
0
  freebytes(c->signature);
1616
0
}
1617
1618
/*
1619
 * Parse the Name ASN1 type.
1620
 * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1621
 * from most general to most specific.  Each element of the path can be
1622
 * one or more (but usually just one) attribute-value pair, such as
1623
 * countryName="US".
1624
 * We'll just form a "postal-style" address string by concatenating the elements
1625
 * from most specific to least specific, separated by commas.
1626
 * Return name-as-string (which must be freed by caller).
1627
 */
1628
static char*
1629
parse_name(Elem* e)
1630
0
{
1631
0
  Elist* el;
1632
0
  Elem* es;
1633
0
  Elist* esetl;
1634
0
  Elem* eat;
1635
0
  Elist* eatl;
1636
0
  char* s;
1637
0
  enum { MAXPARTS = 100 };
1638
0
  char* parts[MAXPARTS];
1639
0
  int i;
1640
0
  int plen;
1641
0
  char* ans = nil;
1642
1643
0
  if(!is_seq(e, &el))
1644
0
    goto errret;
1645
0
  i = 0;
1646
0
  plen = 0;
1647
0
  while(el != nil) {
1648
0
    es = &el->hd;
1649
0
    if(!is_set(es, &esetl))
1650
0
      goto errret;
1651
0
    while(esetl != nil) {
1652
0
      eat = &esetl->hd;
1653
0
      if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1654
0
        goto errret;
1655
0
      if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1656
0
        goto errret;
1657
0
      parts[i++] = s;
1658
0
      plen += strlen(s) + 2;    /* room for ", " after */
1659
0
      esetl = esetl->tl;
1660
0
    }
1661
0
    el = el->tl;
1662
0
  }
1663
0
  if(i > 0) {
1664
0
    ans = (char*)emalloc(plen);
1665
0
    *ans = '\0';
1666
0
    while(--i >= 0) {
1667
0
      s = parts[i];
1668
0
      strcat(ans, s);
1669
0
      if(i > 0)
1670
0
        strcat(ans, ", ");
1671
0
    }
1672
0
  }
1673
1674
0
errret:
1675
0
  return ans;
1676
0
}
1677
1678
/*
1679
 * Parse an AlgorithmIdentifer ASN1 type.
1680
 * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1681
 * or -1 if not found.
1682
 * For now, ignore parameters, since none of our algorithms need them.
1683
 */
1684
static int
1685
parse_alg(Elem* e)
1686
0
{
1687
0
  Elist* el;
1688
0
  Ints* oid;
1689
1690
0
  if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1691
0
    return -1;
1692
0
  return oid_lookup(oid, alg_oid_tab);
1693
0
}
1694
1695
static CertX509*
1696
decode_cert(Bytes* a)
1697
0
{
1698
0
  int ok = 0;
1699
0
  int n;
1700
0
  CertX509* c = nil;
1701
0
  Elem  ecert;
1702
0
  Elem* ecertinfo;
1703
0
  Elem* esigalg;
1704
0
  Elem* esig;
1705
0
  Elem* eserial;
1706
0
  Elem* eissuer;
1707
0
  Elem* evalidity;
1708
0
  Elem* esubj;
1709
0
  Elem* epubkey;
1710
0
  Elist* el;
1711
0
  Elist* elcert = nil;
1712
0
  Elist* elcertinfo = nil;
1713
0
  Elist* elvalidity = nil;
1714
0
  Elist* elpubkey = nil;
1715
0
  Bits* bits = nil;
1716
0
  Bytes* b;
1717
0
  Elem* e;
1718
1719
0
  if(decode(a->data, a->len, &ecert) != ASN_OK)
1720
0
    goto errret;
1721
1722
0
  c = (CertX509*)emalloc(sizeof(CertX509));
1723
0
  c->serial = -1;
1724
0
  c->issuer = nil;
1725
0
  c->validity_start = nil;
1726
0
  c->validity_end = nil;
1727
0
  c->subject = nil;
1728
0
  c->publickey_alg = -1;
1729
0
  c->publickey = nil;
1730
0
  c->signature_alg = -1;
1731
0
  c->signature = nil;
1732
1733
  /* Certificate */
1734
0
  if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1735
0
    goto errret;
1736
0
  ecertinfo = &elcert->hd;
1737
0
  el = elcert->tl;
1738
0
  esigalg = &el->hd;
1739
0
  c->signature_alg = parse_alg(esigalg);
1740
0
  el = el->tl;
1741
0
  esig = &el->hd;
1742
1743
  /* Certificate Info */
1744
0
  if(!is_seq(ecertinfo, &elcertinfo))
1745
0
    goto errret;
1746
0
  n = elistlen(elcertinfo);
1747
0
    if(n < 6)
1748
0
    goto errret;
1749
0
  eserial =&elcertinfo->hd;
1750
0
  el = elcertinfo->tl;
1751
  /* check for optional version, marked by explicit context tag 0 */
1752
0
  if(eserial->tag.class == Context && eserial->tag.num == 0) {
1753
0
    eserial = &el->hd;
1754
0
    if(n < 7)
1755
0
      goto errret;
1756
0
    el = el->tl;
1757
0
  }
1758
1759
0
  if(parse_alg(&el->hd) != c->signature_alg)
1760
0
    goto errret;
1761
0
  el = el->tl;
1762
0
  eissuer = &el->hd;
1763
0
  el = el->tl;
1764
0
  evalidity = &el->hd;
1765
0
  el = el->tl;
1766
0
  esubj = &el->hd;
1767
0
  el = el->tl;
1768
0
  epubkey = &el->hd;
1769
0
  if(!is_int(eserial, &c->serial)) {
1770
0
    if(!is_bigint(eserial, &b))
1771
0
      goto errret;
1772
0
    c->serial = -1; /* else we have to change cert struct */
1773
0
    }
1774
0
  c->issuer = parse_name(eissuer);
1775
0
  if(c->issuer == nil)
1776
0
    goto errret;
1777
  /* Validity */
1778
0
    if(!is_seq(evalidity, &elvalidity))
1779
0
    goto errret;
1780
0
  if(elistlen(elvalidity) != 2)
1781
0
    goto errret;
1782
0
  e = &elvalidity->hd;
1783
0
  if(!is_time(e, &c->validity_start))
1784
0
    goto errret;
1785
0
  e->val.u.stringval = nil; /* string ownership transfer */
1786
0
  e = &elvalidity->tl->hd;
1787
0
  if(!is_time(e, &c->validity_end))
1788
0
    goto errret;
1789
0
  e->val.u.stringval = nil; /* string ownership transfer */
1790
1791
  /* resume CertificateInfo */
1792
0
  c->subject = parse_name(esubj);
1793
0
  if(c->subject == nil)
1794
0
    goto errret;
1795
1796
  /* SubjectPublicKeyInfo */
1797
0
  if(!is_seq(epubkey, &elpubkey))
1798
0
    goto errret;
1799
0
  if(elistlen(elpubkey) != 2)
1800
0
    goto errret;
1801
1802
0
  c->publickey_alg = parse_alg(&elpubkey->hd);
1803
0
  if(c->publickey_alg < 0)
1804
0
    goto errret;
1805
0
    if(!is_bitstring(&elpubkey->tl->hd, &bits))
1806
0
    goto errret;
1807
0
  if(bits->unusedbits != 0)
1808
0
    goto errret;
1809
0
  c->publickey = makebytes(bits->data, bits->len);
1810
1811
  /*resume Certificate */
1812
0
  if(c->signature_alg < 0)
1813
0
    goto errret;
1814
0
  if(!is_bitstring(esig, &bits))
1815
0
    goto errret;
1816
0
  c->signature = makebytes(bits->data, bits->len);
1817
0
  ok = 1;
1818
1819
0
errret:
1820
0
  freevalfields(&ecert.val);  /* recurses through lists, too */
1821
0
  if(!ok){
1822
0
    freecert(c);
1823
0
    c = nil;
1824
0
  }
1825
0
  return c;
1826
0
}
1827
1828
/*
1829
 *  RSAPublickKey :: SEQUENCE {
1830
 *    modulus INTEGER,
1831
 *    publicExponent INTEGER
1832
 *  }
1833
 */
1834
static RSApub*
1835
decode_rsapubkey(Bytes* a)
1836
0
{
1837
0
  Elem e;
1838
0
  Elist *el;
1839
0
  mpint *mp;
1840
0
  RSApub* key;
1841
1842
0
  key = rsapuballoc();
1843
0
  if(decode(a->data, a->len, &e) != ASN_OK)
1844
0
    goto errret;
1845
0
  if(!is_seq(&e, &el) || elistlen(el) != 2)
1846
0
    goto errret;
1847
1848
0
  key->n = mp = asn1mpint(&el->hd);
1849
0
  if(mp == nil)
1850
0
    goto errret;
1851
1852
0
  el = el->tl;
1853
0
  key->ek = mp = asn1mpint(&el->hd);
1854
0
  if(mp == nil)
1855
0
    goto errret;
1856
0
  return key;
1857
0
errret:
1858
0
  rsapubfree(key);
1859
0
  return nil;
1860
0
}
1861
1862
/*
1863
 *  RSAPrivateKey ::= SEQUENCE {
1864
 *    version Version,
1865
 *    modulus INTEGER, -- n
1866
 *    publicExponent INTEGER, -- e
1867
 *    privateExponent INTEGER, -- d
1868
 *    prime1 INTEGER, -- p
1869
 *    prime2 INTEGER, -- q
1870
 *    exponent1 INTEGER, -- d mod (p-1)
1871
 *    exponent2 INTEGER, -- d mod (q-1)
1872
 *    coefficient INTEGER -- (inverse of q) mod p }
1873
 */
1874
static RSApriv*
1875
decode_rsaprivkey(Bytes* a)
1876
0
{
1877
0
  int version;
1878
0
  Elem e;
1879
0
  Elist *el;
1880
0
  mpint *mp;
1881
0
  RSApriv* key;
1882
1883
0
  key = rsaprivalloc();
1884
0
  if(decode(a->data, a->len, &e) != ASN_OK)
1885
0
    goto errret;
1886
0
  if(!is_seq(&e, &el) || elistlen(el) != 9)
1887
0
    goto errret;
1888
0
  if(!is_int(&el->hd, &version) || version != 0)
1889
0
    goto errret;
1890
1891
0
  el = el->tl;
1892
0
  key->pub.n = mp = asn1mpint(&el->hd);
1893
0
  if(mp == nil)
1894
0
    goto errret;
1895
1896
0
  el = el->tl;
1897
0
  key->pub.ek = mp = asn1mpint(&el->hd);
1898
0
  if(mp == nil)
1899
0
    goto errret;
1900
1901
0
  el = el->tl;
1902
0
  key->dk = mp = asn1mpint(&el->hd);
1903
0
  if(mp == nil)
1904
0
    goto errret;
1905
1906
0
  el = el->tl;
1907
0
  key->q = mp = asn1mpint(&el->hd);
1908
0
  if(mp == nil)
1909
0
    goto errret;
1910
1911
0
  el = el->tl;
1912
0
  key->p = mp = asn1mpint(&el->hd);
1913
0
  if(mp == nil)
1914
0
    goto errret;
1915
1916
0
  el = el->tl;
1917
0
  key->kq = mp = asn1mpint(&el->hd);
1918
0
  if(mp == nil)
1919
0
    goto errret;
1920
1921
0
  el = el->tl;
1922
0
  key->kp = mp = asn1mpint(&el->hd);
1923
0
  if(mp == nil)
1924
0
    goto errret;
1925
1926
0
  el = el->tl;
1927
0
  key->c2 = mp = asn1mpint(&el->hd);
1928
0
  if(mp == nil)
1929
0
    goto errret;
1930
1931
0
  return key;
1932
0
errret:
1933
0
  rsaprivfree(key);
1934
0
  return nil;
1935
0
}
1936
1937
/*
1938
 *  DSAPrivateKey ::= SEQUENCE{
1939
 *    version Version,
1940
 *    p INTEGER,
1941
 *    q INTEGER,
1942
 *    g INTEGER, -- alpha
1943
 *    pub_key INTEGER, -- key
1944
 *    priv_key INTEGER, -- secret
1945
 *  }
1946
 */
1947
static DSApriv*
1948
decode_dsaprivkey(Bytes* a)
1949
0
{
1950
0
  int version;
1951
0
  Elem e;
1952
0
  Elist *el;
1953
0
  mpint *mp;
1954
0
  DSApriv* key;
1955
1956
0
  key = dsaprivalloc();
1957
0
  if(decode(a->data, a->len, &e) != ASN_OK)
1958
0
    goto errret;
1959
0
  if(!is_seq(&e, &el) || elistlen(el) != 6)
1960
0
    goto errret;
1961
0
version=-1;
1962
0
  if(!is_int(&el->hd, &version) || version != 0)
1963
0
{
1964
0
fprint(2, "version %d\n", version);
1965
0
    goto errret;
1966
0
  }
1967
1968
0
  el = el->tl;
1969
0
  key->pub.p = mp = asn1mpint(&el->hd);
1970
0
  if(mp == nil)
1971
0
    goto errret;
1972
1973
0
  el = el->tl;
1974
0
  key->pub.q = mp = asn1mpint(&el->hd);
1975
0
  if(mp == nil)
1976
0
    goto errret;
1977
1978
0
  el = el->tl;
1979
0
  key->pub.alpha = mp = asn1mpint(&el->hd);
1980
0
  if(mp == nil)
1981
0
    goto errret;
1982
1983
0
  el = el->tl;
1984
0
  key->pub.key = mp = asn1mpint(&el->hd);
1985
0
  if(mp == nil)
1986
0
    goto errret;
1987
1988
0
  el = el->tl;
1989
0
  key->secret = mp = asn1mpint(&el->hd);
1990
0
  if(mp == nil)
1991
0
    goto errret;
1992
1993
0
  return key;
1994
0
errret:
1995
0
  dsaprivfree(key);
1996
0
  return nil;
1997
0
}
1998
1999
static mpint*
2000
asn1mpint(Elem *e)
2001
0
{
2002
0
  Bytes *b;
2003
0
  mpint *mp;
2004
0
  int v;
2005
2006
0
  if(is_int(e, &v))
2007
0
    return itomp(v, nil);
2008
0
  if(is_bigint(e, &b)) {
2009
0
    mp = betomp(b->data, b->len, nil);
2010
0
    freebytes(b);
2011
0
    return mp;
2012
0
  }
2013
0
  return nil;
2014
0
}
2015
2016
static mpint*
2017
pkcs1pad(Bytes *b, mpint *modulus)
2018
0
{
2019
0
  int n = (mpsignif(modulus)+7)/8;
2020
0
  int pm1, i;
2021
0
  uchar *p;
2022
0
  mpint *mp;
2023
2024
0
  pm1 = n - 1 - b->len;
2025
0
  p = (uchar*)emalloc(n);
2026
0
  p[0] = 0;
2027
0
  p[1] = 1;
2028
0
  for(i = 2; i < pm1; i++)
2029
0
    p[i] = 0xFF;
2030
0
  p[pm1] = 0;
2031
0
  memcpy(&p[pm1+1], b->data, b->len);
2032
0
  mp = betomp(p, n, nil);
2033
0
  free(p);
2034
0
  return mp;
2035
0
}
2036
2037
RSApriv*
2038
asn1toRSApriv(uchar *kd, int kn)
2039
0
{
2040
0
  Bytes *b;
2041
0
  RSApriv *key;
2042
2043
0
  b = makebytes(kd, kn);
2044
0
  key = decode_rsaprivkey(b);
2045
0
  freebytes(b);
2046
0
  return key;
2047
0
}
2048
2049
DSApriv*
2050
asn1toDSApriv(uchar *kd, int kn)
2051
0
{
2052
0
  Bytes *b;
2053
0
  DSApriv *key;
2054
2055
0
  b = makebytes(kd, kn);
2056
0
  key = decode_dsaprivkey(b);
2057
0
  freebytes(b);
2058
0
  return key;
2059
0
}
2060
2061
/*
2062
 * digest(CertificateInfo)
2063
 * Our ASN.1 library doesn't return pointers into the original
2064
 * data array, so we need to do a little hand decoding.
2065
 */
2066
static void
2067
digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
2068
0
{
2069
0
  uchar *info, *p, *pend;
2070
0
  ulong infolen;
2071
0
  int isconstr, length;
2072
0
  Tag tag;
2073
0
  Elem elem;
2074
2075
0
  p = cert->data;
2076
0
  pend = cert->data + cert->len;
2077
0
  if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2078
0
     tag.class != Universal || tag.num != SEQUENCE ||
2079
0
     length_decode(&p, pend, &length) != ASN_OK ||
2080
0
     length > pend - p)
2081
0
    return;
2082
0
  info = p;
2083
0
  if(ber_decode(&p, pend, &elem) != ASN_OK || elem.tag.num != SEQUENCE)
2084
0
    return;
2085
0
  infolen = p - info;
2086
0
  (*digestfun)(info, infolen, digest, nil);
2087
0
}
2088
2089
static char*
2090
verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
2091
0
{
2092
0
  Elem e;
2093
0
  Elist *el;
2094
0
  Bytes *digest;
2095
0
  uchar *pkcs1buf, *buf;
2096
0
  int buflen;
2097
0
  mpint *pkcs1;
2098
0
  int nlen;
2099
2100
  /* one less than the byte length of the modulus */
2101
0
  nlen = (mpsignif(pk->n)-1)/8;
2102
2103
  /* see 9.2.1 of rfc2437 */
2104
0
  pkcs1 = betomp(signature->data, signature->len, nil);
2105
0
  mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2106
0
  pkcs1buf = nil;
2107
0
  buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
2108
0
  buf = pkcs1buf;
2109
0
  if(buflen != nlen || buf[0] != 1)
2110
0
    return "expected 1";
2111
0
  buf++;
2112
0
  while(buf[0] == 0xff)
2113
0
    buf++;
2114
0
  if(buf[0] != 0)
2115
0
    return "expected 0";
2116
0
  buf++;
2117
0
  buflen -= buf-pkcs1buf;
2118
0
  if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
2119
0
      !is_octetstring(&el->tl->hd, &digest))
2120
0
    return "signature parse error";
2121
0
  *psigalg = &el->hd;
2122
0
  if(memcmp(digest->data, edigest, digest->len) == 0)
2123
0
    return nil;
2124
0
  return "digests did not match";
2125
0
}
2126
2127
RSApub*
2128
X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2129
0
{
2130
0
  char *e;
2131
0
  Bytes *b;
2132
0
  CertX509 *c;
2133
0
  RSApub *pk;
2134
2135
0
  b = makebytes(cert, ncert);
2136
0
  c = decode_cert(b);
2137
0
  freebytes(b);
2138
0
  if(c == nil)
2139
0
    return nil;
2140
0
  if(name != nil && c->subject != nil){
2141
0
    e = strchr(c->subject, ',');
2142
0
    if(e != nil)
2143
0
      *e = 0;  /* take just CN part of Distinguished Name */
2144
0
    strncpy(name, c->subject, nname);
2145
0
  }
2146
0
  pk = decode_rsapubkey(c->publickey);
2147
0
  freecert(c);
2148
0
  return pk;
2149
0
}
2150
2151
char*
2152
X509verify(uchar *cert, int ncert, RSApub *pk)
2153
0
{
2154
0
  char *e;
2155
0
  Bytes *b;
2156
0
  CertX509 *c;
2157
0
  uchar digest[SHA1dlen];
2158
0
  Elem *sigalg;
2159
2160
0
  b = makebytes(cert, ncert);
2161
0
  c = decode_cert(b);
2162
0
  if(c != nil)
2163
0
    digest_certinfo(b, digestalg[c->signature_alg], digest);
2164
0
  freebytes(b);
2165
0
  if(c == nil)
2166
0
    return "cannot decode cert";
2167
0
  e = verify_signature(c->signature, pk, digest, &sigalg);
2168
0
  freecert(c);
2169
0
  return e;
2170
0
}
2171
2172
/* ------- Elem constructors ---------- */
2173
static Elem
2174
Null(void)
2175
0
{
2176
0
  Elem e;
2177
2178
0
  e.tag.class = Universal;
2179
0
  e.tag.num = NULLTAG;
2180
0
  e.val.tag = VNull;
2181
0
  return e;
2182
0
}
2183
2184
static Elem
2185
mkint(int j)
2186
0
{
2187
0
  Elem e;
2188
2189
0
  e.tag.class = Universal;
2190
0
  e.tag.num = INTEGER;
2191
0
  e.val.tag = VInt;
2192
0
  e.val.u.intval = j;
2193
0
  return e;
2194
0
}
2195
2196
static Elem
2197
mkbigint(mpint *p)
2198
0
{
2199
0
  Elem e;
2200
0
  uchar *buf;
2201
0
  int buflen;
2202
2203
0
  e.tag.class = Universal;
2204
0
  e.tag.num = INTEGER;
2205
0
  e.val.tag = VBigInt;
2206
0
  buflen = mptobe(p, nil, 0, &buf);
2207
0
  e.val.u.bigintval = makebytes(buf, buflen);
2208
0
  free(buf);
2209
0
  return e;
2210
0
}
2211
2212
static Elem
2213
mkstring(char *s)
2214
0
{
2215
0
  Elem e;
2216
2217
0
  e.tag.class = Universal;
2218
0
  e.tag.num = IA5String;
2219
0
  e.val.tag = VString;
2220
0
  e.val.u.stringval = estrdup(s);
2221
0
  return e;
2222
0
}
2223
2224
static Elem
2225
mkoctet(uchar *buf, int buflen)
2226
0
{
2227
0
  Elem e;
2228
2229
0
  e.tag.class = Universal;
2230
0
  e.tag.num = OCTET_STRING;
2231
0
  e.val.tag = VOctets;
2232
0
  e.val.u.octetsval = makebytes(buf, buflen);
2233
0
  return e;
2234
0
}
2235
2236
static Elem
2237
mkbits(uchar *buf, int buflen)
2238
0
{
2239
0
  Elem e;
2240
2241
0
  e.tag.class = Universal;
2242
0
  e.tag.num = BIT_STRING;
2243
0
  e.val.tag = VBitString;
2244
0
  e.val.u.bitstringval = makebits(buf, buflen, 0);
2245
0
  return e;
2246
0
}
2247
2248
static Elem
2249
mkutc(long t)
2250
0
{
2251
0
  Elem e;
2252
0
  char utc[50];
2253
0
  Tm *tm = gmtime(t);
2254
2255
0
  e.tag.class = Universal;
2256
0
  e.tag.num = UTCTime;
2257
0
  e.val.tag = VString;
2258
0
  snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2259
0
    tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2260
0
  e.val.u.stringval = estrdup(utc);
2261
0
  return e;
2262
0
}
2263
2264
static Elem
2265
mkoid(Ints *oid)
2266
0
{
2267
0
  Elem e;
2268
2269
0
  e.tag.class = Universal;
2270
0
  e.tag.num = OBJECT_ID;
2271
0
  e.val.tag = VObjId;
2272
0
  e.val.u.objidval = makeints(oid->data, oid->len);
2273
0
  return e;
2274
0
}
2275
2276
static Elem
2277
mkseq(Elist *el)
2278
0
{
2279
0
  Elem e;
2280
2281
0
  e.tag.class = Universal;
2282
0
  e.tag.num = SEQUENCE;
2283
0
  e.val.tag = VSeq;
2284
0
  e.val.u.seqval = el;
2285
0
  return e;
2286
0
}
2287
2288
static Elem
2289
mkset(Elist *el)
2290
0
{
2291
0
  Elem e;
2292
2293
0
  e.tag.class = Universal;
2294
0
  e.tag.num = SETOF;
2295
0
  e.val.tag = VSet;
2296
0
  e.val.u.setval = el;
2297
0
  return e;
2298
0
}
2299
2300
static Elem
2301
mkalg(int alg)
2302
0
{
2303
0
  return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2304
0
}
2305
2306
typedef struct Ints7pref {
2307
  int   len;
2308
  int   data[7];
2309
  char  prefix[4];
2310
} Ints7pref;
2311
Ints7pref DN_oid[] = {
2312
  {4, 2, 5, 4, 6, 0, 0, 0,  "C="},
2313
  {4, 2, 5, 4, 8, 0, 0, 0,  "ST="},
2314
  {4, 2, 5, 4, 7, 0, 0, 0,  "L="},
2315
  {4, 2, 5, 4, 10, 0, 0, 0, "O="},
2316
  {4, 2, 5, 4, 11, 0, 0, 0, "OU="},
2317
  {4, 2, 5, 4, 3, 0, 0, 0,  "CN="},
2318
  {7, 1,2,840,113549,1,9,1, "E="},
2319
};
2320
2321
static Elem
2322
mkname(Ints7pref *oid, char *subj)
2323
0
{
2324
0
  return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2325
0
}
2326
2327
static Elem
2328
mkDN(char *dn)
2329
0
{
2330
0
  int i, j, nf;
2331
0
  char *f[20], *prefix, *d2 = estrdup(dn);
2332
0
  Elist* el = nil;
2333
2334
0
  nf = tokenize(d2, f, nelem(f));
2335
0
  for(i=nf-1; i>=0; i--){
2336
0
    for(j=0; j<nelem(DN_oid); j++){
2337
0
      prefix = DN_oid[j].prefix;
2338
0
      if(strncmp(f[i],prefix,strlen(prefix))==0){
2339
0
        el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2340
0
        break;
2341
0
      }
2342
0
    }
2343
0
  }
2344
0
  free(d2);
2345
0
  return mkseq(el);
2346
0
}
2347
2348
2349
uchar*
2350
X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2351
0
{
2352
0
  int serial = 0;
2353
0
  uchar *cert = nil;
2354
0
  RSApub *pk = rsaprivtopub(priv);
2355
0
  Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2356
0
  Elem e, certinfo, issuer, subject, pubkey, validity, sig;
2357
0
  uchar digest[MD5dlen], *buf;
2358
0
  int buflen;
2359
0
  mpint *pkcs1;
2360
2361
0
  e.val.tag = VInt;  /* so freevalfields at errret is no-op */
2362
0
  issuer = mkDN(subj);
2363
0
  subject = mkDN(subj);
2364
0
  pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2365
0
  if(encode(pubkey, &pkbytes) != ASN_OK)
2366
0
    goto errret;
2367
0
  freevalfields(&pubkey.val);
2368
0
  pubkey = mkseq(
2369
0
    mkel(mkalg(ALG_rsaEncryption),
2370
0
    mkel(mkbits(pkbytes->data, pkbytes->len),
2371
0
    nil)));
2372
0
  freebytes(pkbytes);
2373
0
  validity = mkseq(
2374
0
    mkel(mkutc(valid[0]),
2375
0
    mkel(mkutc(valid[1]),
2376
0
    nil)));
2377
0
  certinfo = mkseq(
2378
0
    mkel(mkint(serial),
2379
0
    mkel(mkalg(ALG_md5WithRSAEncryption),
2380
0
    mkel(issuer,
2381
0
    mkel(validity,
2382
0
    mkel(subject,
2383
0
    mkel(pubkey,
2384
0
    nil)))))));
2385
0
  if(encode(certinfo, &certinfobytes) != ASN_OK)
2386
0
    goto errret;
2387
0
  md5(certinfobytes->data, certinfobytes->len, digest, 0);
2388
0
  freebytes(certinfobytes);
2389
0
  sig = mkseq(
2390
0
    mkel(mkalg(ALG_md5),
2391
0
    mkel(mkoctet(digest, MD5dlen),
2392
0
    nil)));
2393
0
  if(encode(sig, &sigbytes) != ASN_OK)
2394
0
    goto errret;
2395
0
  pkcs1 = pkcs1pad(sigbytes, pk->n);
2396
0
  freebytes(sigbytes);
2397
0
  rsadecrypt(priv, pkcs1, pkcs1);
2398
0
  buflen = mptobe(pkcs1, nil, 0, &buf);
2399
0
  mpfree(pkcs1);
2400
0
  e = mkseq(
2401
0
    mkel(certinfo,
2402
0
    mkel(mkalg(ALG_md5WithRSAEncryption),
2403
0
    mkel(mkbits(buf, buflen),
2404
0
    nil))));
2405
0
  free(buf);
2406
0
  if(encode(e, &certbytes) != ASN_OK)
2407
0
    goto errret;
2408
0
  if(certlen)
2409
0
    *certlen = certbytes->len;
2410
0
  cert = certbytes->data;
2411
0
errret:
2412
0
  freevalfields(&e.val);
2413
0
  return cert;
2414
0
}
2415
2416
uchar*
2417
X509req(RSApriv *priv, char *subj, int *certlen)
2418
0
{
2419
  /* RFC 2314, PKCS #10 Certification Request Syntax */
2420
0
  int version = 0;
2421
0
  uchar *cert = nil;
2422
0
  RSApub *pk = rsaprivtopub(priv);
2423
0
  Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2424
0
  Elem e, certinfo, subject, pubkey, sig;
2425
0
  uchar digest[MD5dlen], *buf;
2426
0
  int buflen;
2427
0
  mpint *pkcs1;
2428
2429
0
  e.val.tag = VInt;  /* so freevalfields at errret is no-op */
2430
0
  subject = mkDN(subj);
2431
0
  pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2432
0
  if(encode(pubkey, &pkbytes) != ASN_OK)
2433
0
    goto errret;
2434
0
  freevalfields(&pubkey.val);
2435
0
  pubkey = mkseq(
2436
0
    mkel(mkalg(ALG_rsaEncryption),
2437
0
    mkel(mkbits(pkbytes->data, pkbytes->len),
2438
0
    nil)));
2439
0
  freebytes(pkbytes);
2440
0
  certinfo = mkseq(
2441
0
    mkel(mkint(version),
2442
0
    mkel(subject,
2443
0
    mkel(pubkey,
2444
0
    nil))));
2445
0
  if(encode(certinfo, &certinfobytes) != ASN_OK)
2446
0
    goto errret;
2447
0
  md5(certinfobytes->data, certinfobytes->len, digest, 0);
2448
0
  freebytes(certinfobytes);
2449
0
  sig = mkseq(
2450
0
    mkel(mkalg(ALG_md5),
2451
0
    mkel(mkoctet(digest, MD5dlen),
2452
0
    nil)));
2453
0
  if(encode(sig, &sigbytes) != ASN_OK)
2454
0
    goto errret;
2455
0
  pkcs1 = pkcs1pad(sigbytes, pk->n);
2456
0
  freebytes(sigbytes);
2457
0
  rsadecrypt(priv, pkcs1, pkcs1);
2458
0
  buflen = mptobe(pkcs1, nil, 0, &buf);
2459
0
  mpfree(pkcs1);
2460
0
  e = mkseq(
2461
0
    mkel(certinfo,
2462
0
    mkel(mkalg(ALG_md5),
2463
0
    mkel(mkbits(buf, buflen),
2464
0
    nil))));
2465
0
  free(buf);
2466
0
  if(encode(e, &certbytes) != ASN_OK)
2467
0
    goto errret;
2468
0
  if(certlen)
2469
0
    *certlen = certbytes->len;
2470
0
  cert = certbytes->data;
2471
0
errret:
2472
0
  freevalfields(&e.val);
2473
0
  return cert;
2474
0
}
2475
2476
static char*
2477
tagdump(Tag tag)
2478
7.26k
{
2479
7.26k
  if(tag.class != Universal)
2480
643
    return smprint("class%d,num%d", tag.class, tag.num);
2481
6.62k
  switch(tag.num){
2482
424
    case BOOLEAN: return "BOOLEAN"; break;
2483
630
    case INTEGER: return "INTEGER"; break;
2484
255
    case BIT_STRING: return "BIT STRING"; break;
2485
196
    case OCTET_STRING: return "OCTET STRING"; break;
2486
24
    case NULLTAG: return "NULLTAG"; break;
2487
533
    case OBJECT_ID: return "OID"; break;
2488
5
    case ObjectDescriptor: return "OBJECT_DES"; break;
2489
38
    case EXTERNAL: return "EXTERNAL"; break;
2490
109
    case REAL: return "REAL"; break;
2491
104
    case ENUMERATED: return "ENUMERATED"; break;
2492
345
    case EMBEDDED_PDV: return "EMBEDDED PDV"; break;
2493
1.11k
    case SEQUENCE: return "SEQUENCE"; break;
2494
666
    case SETOF: return "SETOF"; break;
2495
49
    case NumericString: return "NumericString"; break;
2496
57
    case PrintableString: return "PrintableString"; break;
2497
33
    case TeletexString: return "TeletexString"; break;
2498
42
    case VideotexString: return "VideotexString"; break;
2499
44
    case IA5String: return "IA5String"; break;
2500
210
    case UTCTime: return "UTCTime"; break;
2501
57
    case GeneralizedTime: return "GeneralizedTime"; break;
2502
85
    case GraphicString: return "GraphicString"; break;
2503
79
    case VisibleString: return "VisibleString"; break;
2504
61
    case GeneralString: return "GeneralString"; break;
2505
79
    case UniversalString: return "UniversalString"; break;
2506
127
    case BMPString: return "BMPString"; break;
2507
1.25k
    default:
2508
1.25k
      return smprint("Universal,num%d", tag.num);
2509
6.62k
  }
2510
6.62k
}
2511
2512
static void
2513
edump(Elem e)
2514
7.26k
{
2515
7.26k
  Value v;
2516
7.26k
  Elist *el;
2517
7.26k
  int i;
2518
2519
7.26k
  print("%s{", tagdump(e.tag));
2520
7.26k
  v = e.val;
2521
7.26k
  switch(v.tag){
2522
424
  case VBool: print("Bool %d",v.u.boolval); break;
2523
609
  case VInt: print("Int %d",v.u.intval); break;
2524
844
  case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2525
125
  case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2526
109
  case VReal: print("Real..."); break;
2527
913
  case VOther: print("Other..."); break;
2528
255
  case VBitString: print("BitString..."); break;
2529
752
  case VNull: print("Null"); break;
2530
0
  case VEOC: print("EOC..."); break;
2531
533
  case VObjId: print("ObjId");
2532
2.70k
    for(i = 0; i<v.u.objidval->len; i++)
2533
2.17k
      print(" %d", v.u.objidval->data[i]);
2534
533
    break;
2535
923
  case VString: print("String \"%s\"",v.u.stringval); break;
2536
1.11k
  case VSeq: print("Seq\n");
2537
4.63k
    for(el = v.u.seqval; el!=nil; el = el->tl)
2538
3.52k
      edump(el->hd);
2539
1.11k
    break;
2540
666
  case VSet: print("Set\n");
2541
3.54k
    for(el = v.u.setval; el!=nil; el = el->tl)
2542
2.87k
      edump(el->hd);
2543
666
    break;
2544
7.26k
  }
2545
7.26k
  print("}\n");
2546
7.26k
}
2547
2548
void
2549
asn1dump(uchar *der, int len)
2550
1.55k
{
2551
1.55k
  Elem e;
2552
2553
1.55k
  if(decode(der, len, &e) != ASN_OK){
2554
    //print("didn't parse\n");
2555
    //exits("didn't parse");
2556
684
    return;
2557
684
  }
2558
870
  edump(e);
2559
870
}
2560
2561
void
2562
X509dump(uchar *cert, int ncert)
2563
0
{
2564
0
  char *e;
2565
0
  Bytes *b;
2566
0
  CertX509 *c;
2567
0
  RSApub *pk;
2568
0
  uchar digest[SHA1dlen];
2569
0
  Elem *sigalg;
2570
2571
0
  print("begin X509dump\n");
2572
0
  b = makebytes(cert, ncert);
2573
0
  c = decode_cert(b);
2574
0
  if(c != nil)
2575
0
    digest_certinfo(b, digestalg[c->signature_alg], digest);
2576
0
  freebytes(b);
2577
0
  if(c == nil){
2578
0
    print("cannot decode cert");
2579
0
    return;
2580
0
  }
2581
2582
0
  print("serial %d\n", c->serial);
2583
0
  print("issuer %s\n", c->issuer);
2584
0
  print("validity %s %s\n", c->validity_start, c->validity_end);
2585
0
  print("subject %s\n", c->subject);
2586
0
  pk = decode_rsapubkey(c->publickey);
2587
0
  print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
2588
2589
0
  print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
2590
0
  e = verify_signature(c->signature, pk, digest, &sigalg);
2591
0
  if(e==nil){
2592
0
    e = "nil (meaning ok)";
2593
0
    print("sigalg=\n");
2594
0
    if(sigalg)
2595
0
      edump(*sigalg);
2596
0
  }
2597
0
  print("self-signed verify_signature returns: %s\n", e);
2598
2599
0
  rsapubfree(pk);
2600
0
  freecert(c);
2601
0
  print("end X509dump\n");
2602
0
}