summaryrefslogtreecommitdiff
path: root/src/ber-help.c
blob: 1b72bf050f201b2f0c6f8f171912e9d91b7c4ec4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/* ber-help.c - BER herlper functions
 *      Copyright (C) 2001, 2012 g10 Code GmbH
 *
 * This file is part of KSBA.
 *
 * KSBA is free software; you can redistribute it and/or modify
 * it under the terms of either
 *
 *   - the GNU Lesser General Public License as published by the Free
 *     Software Foundation; either version 3 of the License, or (at
 *     your option) any later version.
 *
 * or
 *
 *   - 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.
 *
 * or both in parallel, as here.
 *
 * KSBA 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 copies of the GNU General Public License
 * and the GNU Lesser General Public License along with this program;
 * if not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "util.h"

#include "asn1-func.h" /* need some constants */
#include "convert.h"
#include "ber-help.h"

/* Fixme: The parser functions should check that primitive types don't
   have the constructed bit set (which is not allowed).  This saves us
   some work when using these parsers */

static int
read_byte (ksba_reader_t reader)
{
  unsigned char buf;
  size_t nread;
  int rc;

  do
    rc = ksba_reader_read (reader, &buf, 1, &nread);
  while (!rc && !nread);
  return rc? -1: buf;
}


static int
premature_eof (struct tag_info *ti)
{
  /* Note: We do an strcmp on this string at other places. */
  ti->err_string = "premature EOF";
  return gpg_error (GPG_ERR_BAD_BER);
}



static gpg_error_t
eof_or_error (ksba_reader_t reader, struct tag_info *ti, int premature)
{
  gpg_error_t err;

  err = ksba_reader_error (reader);
  if (err)
    {
      ti->err_string = "read error";
      return err;
    }
  if (premature)
    return premature_eof (ti);

  return gpg_error (GPG_ERR_EOF);
}



/*
   Read the tag and the length part from the TLV triplet.
 */
gpg_error_t
_ksba_ber_read_tl (ksba_reader_t reader, struct tag_info *ti)
{
  int c;
  unsigned long tag;

  ti->length = 0;
  ti->ndef = 0;
  ti->nhdr = 0;
  ti->err_string = NULL;
  ti->non_der = 0;

  /* Get the tag */
  c = read_byte (reader);
  if (c==-1)
    return eof_or_error (reader, ti, 0);

  ti->buf[ti->nhdr++] = c;
  ti->class = (c & 0xc0) >> 6;
  ti->is_constructed = !!(c & 0x20);
  tag = c & 0x1f;

  if (tag == 0x1f)
    {
      tag = 0;
      do
        {
          /* We silently ignore an overflow in the tag value.  It is
             not worth checking for it. */
          tag <<= 7;
          c = read_byte (reader);
          if (c == -1)
            return eof_or_error (reader, ti, 1);
          if (ti->nhdr >= DIM (ti->buf))
            {
              ti->err_string = "tag+length header too large";
              return gpg_error (GPG_ERR_BAD_BER);
            }
          ti->buf[ti->nhdr++] = c;
          tag |= c & 0x7f;
        }
      while (c & 0x80);
    }
  ti->tag = tag;

  /* Get the length */
  c = read_byte (reader);
  if (c == -1)
    return eof_or_error (reader, ti, 1);
  if (ti->nhdr >= DIM (ti->buf))
    {
      ti->err_string = "tag+length header too large";
      return gpg_error (GPG_ERR_BAD_BER);
    }
  ti->buf[ti->nhdr++] = c;

  if ( !(c & 0x80) )
    ti->length = c;
  else if (c == 0x80)
    {
      ti->ndef = 1;
      ti->non_der = 1;
    }
  else if (c == 0xff)
    {
      ti->err_string = "forbidden length value";
      return gpg_error (GPG_ERR_BAD_BER);
    }
  else
    {
      unsigned long len = 0;
      int count = c & 0x7f;

      if (count > sizeof (len) || count > sizeof (size_t))
        return gpg_error (GPG_ERR_BAD_BER);

      for (; count; count--)
        {
          len <<= 8;
          c = read_byte (reader);
          if (c == -1)
            return eof_or_error (reader, ti, 1);
          if (ti->nhdr >= DIM (ti->buf))
            {
              ti->err_string = "tag+length header too large";
              return gpg_error (GPG_ERR_BAD_BER);
            }
          ti->buf[ti->nhdr++] = c;
          len |= c & 0xff;
        }
      ti->length = len;
    }

  /* Without this kludge some example certs can't be parsed */
  if (ti->class == CLASS_UNIVERSAL && !ti->tag)
    ti->length = 0;

  return 0;
}


/* Parse the buffer at the address BUFFER which of SIZE and return the
 * tag and the length part from the TLV triplet.  Update BUFFER and
 * SIZE on success.  Note that this function will never return
 * GPG_ERR_INV_OBJ so that this error code can be used by the parse_foo
 * functions below to return an error for unexpected tags and the
 * caller is able to backoff in that case.  */
gpg_error_t
_ksba_ber_parse_tl (unsigned char const **buffer, size_t *size,
                    struct tag_info *ti)
{
  int c;
  unsigned long tag;
  const unsigned char *buf = *buffer;
  size_t length = *size;

  ti->length = 0;
  ti->ndef = 0;
  ti->nhdr = 0;
  ti->err_string = NULL;
  ti->non_der = 0;

  /* Get the tag */
  if (!length)
    return premature_eof (ti);
  c = *buf++; length--;

  ti->buf[ti->nhdr++] = c;
  ti->class = (c & 0xc0) >> 6;
  ti->is_constructed = !!(c & 0x20);
  tag = c & 0x1f;

  if (tag == 0x1f)
    {
      tag = 0;
      do
        {
          /* We silently ignore an overflow in the tag value.  It is
             not worth checking for it. */
          tag <<= 7;
          if (!length)
            return premature_eof (ti);
          c = *buf++; length--;
          if (ti->nhdr >= DIM (ti->buf))
            {
              ti->err_string = "tag+length header too large";
              return gpg_error (GPG_ERR_BAD_BER);
            }
          ti->buf[ti->nhdr++] = c;
          tag |= c & 0x7f;
        }
      while (c & 0x80);
    }
  ti->tag = tag;

  /* Get the length */
  if (!length)
    return premature_eof (ti);
  c = *buf++; length--;
  if (ti->nhdr >= DIM (ti->buf))
    {
      ti->err_string = "tag+length header too large";
      return gpg_error (GPG_ERR_BAD_BER);
    }
  ti->buf[ti->nhdr++] = c;

  if ( !(c & 0x80) )
    ti->length = c;
  else if (c == 0x80)
    {
      ti->ndef = 1;
      ti->non_der = 1;
    }
  else if (c == 0xff)
    {
      ti->err_string = "forbidden length value";
      return gpg_error (GPG_ERR_BAD_BER);
    }
  else
    {
      unsigned long len = 0;
      int count = c & 0x7f;

      if (count > sizeof (len) || count > sizeof (size_t))
        return gpg_error (GPG_ERR_BAD_BER);

      for (; count; count--)
        {
          len <<= 8;
          if (!length)
            return premature_eof (ti);
          c = *buf++; length--;
          if (ti->nhdr >= DIM (ti->buf))
            {
              ti->err_string = "tag+length header too large";
              return gpg_error (GPG_ERR_BAD_BER);
            }
          ti->buf[ti->nhdr++] = c;
          len |= c & 0xff;
        }
      /* Sanity check for the length: This is done so that we can take
       * the value for malloc plus some additional bytes without
       * risking an overflow.  */
      if (len > (1 << 30))
        return gpg_error (GPG_ERR_BAD_BER);
      ti->length = len;
    }


  /* Without this kludge some example certs can't be parsed */
  if (ti->class == CLASS_UNIVERSAL && !ti->tag)
    ti->length = 0;

  *buffer = buf;
  *size = length;
  return 0;
}


/* Write TAG of CLASS to WRITER.  constructed is a flag telling
   whether the value is a constructed one.  length gives the length of
   the value, if it is 0 undefinite length is assumed.  length is
   ignored for the NULL tag. */
gpg_error_t
_ksba_ber_write_tl (ksba_writer_t writer,
                    unsigned long tag,
                    enum tag_class class,
                    int constructed,
                    unsigned long length)
{
  unsigned char buf[50];
  int buflen = 0;

  if (tag < 0x1f)
    {
      *buf = (class << 6) | tag;
      if (constructed)
        *buf |= 0x20;
      buflen++;
    }
  else
    {
      return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
    }

  if (!tag && !class)
    buf[buflen++] = 0; /* end tag */
  else if (tag == TYPE_NULL && !class)
    buf[buflen++] = 0; /* NULL tag */
  else if (!length)
    buf[buflen++] = 0x80; /* indefinite length */
  else if (length < 128)
    buf[buflen++] = length;
  else
    {
      int i;

      /* fixme: if we know the sizeof an ulong we could support larger
         objects - however this is pretty ridiculous */
      i = (length <= 0xff ? 1:
           length <= 0xffff ? 2:
           length <= 0xffffff ? 3: 4);

      buf[buflen++] = (0x80 | i);
      if (i > 3)
        buf[buflen++] = length >> 24;
      if (i > 2)
        buf[buflen++] = length >> 16;
      if (i > 1)
        buf[buflen++] = length >> 8;
      buf[buflen++] = length;
    }

  return ksba_writer_write (writer, buf, buflen);
}

/* Encode TAG of CLASS in BUFFER.  CONSTRUCTED is a flag telling
   whether the value is a constructed one.  LENGTH gives the length of
   the value, if it is 0 undefinite length is assumed.  LENGTH is
   ignored for the NULL tag. It is assumed that the provide buffer is
   large enough for storing the result - this is usually achieved by
   using _ksba_ber_count_tl() in advance.  Returns 0 in case of an
   error or the length of the encoding.*/
size_t
_ksba_ber_encode_tl (unsigned char *buffer,
                     unsigned long tag,
                     enum tag_class class,
                     int constructed,
                     unsigned long length)
{
  unsigned char *buf = buffer;

  if (tag < 0x1f)
    {
      *buf = (class << 6) | tag;
      if (constructed)
        *buf |= 0x20;
      buf++;
    }
  else
    {
      return 0; /*Not implemented*/
    }

  if (!tag && !class)
    *buf++ = 0; /* end tag */
  else if (tag == TYPE_NULL && !class)
    *buf++ = 0; /* NULL tag */
  else if (!length)
    *buf++ = 0x80; /* indefinite length */
  else if (length < 128)
    *buf++ = length;
  else
    {
      int i;

      /* fixme: if we know the sizeof an ulong we could support larger
         objetcs - however this is pretty ridiculous */
      i = (length <= 0xff ? 1:
           length <= 0xffff ? 2:
           length <= 0xffffff ? 3: 4);

      *buf++ = (0x80 | i);
      if (i > 3)
        *buf++ = length >> 24;
      if (i > 2)
        *buf++ = length >> 16;
      if (i > 1)
        *buf++ = length >> 8;
      *buf++ = length;
    }

  return buf - buffer;
}


/* Calculate the length of the TL needed to encode a TAG of CLASS.
   CONSTRUCTED is a flag telling whether the value is a constructed
   one.  LENGTH gives the length of the value; if it is 0 an
   indefinite length is assumed.  LENGTH is ignored for the NULL
   tag. */
size_t
_ksba_ber_count_tl (unsigned long tag,
                    enum tag_class class,
                    int constructed,
                    unsigned long length)
{
  int buflen = 0;

  (void)constructed;  /* Not used, but passed for uniformity of such calls.  */

  if (tag < 0x1f)
    {
      buflen++;
    }
  else
    {
      buflen++; /* assume one and let the actual write function bail out */
    }

  if (!tag && !class)
    buflen++; /* end tag */
  else if (tag == TYPE_NULL && !class)
    buflen++; /* NULL tag */
  else if (!length)
    buflen++; /* indefinite length */
  else if (length < 128)
    buflen++;
  else
    {
      int i;

      /* fixme: if we know the sizeof an ulong we could support larger
         objetcs - however this is pretty ridiculous */
      i = (length <= 0xff ? 1:
           length <= 0xffff ? 2:
           length <= 0xffffff ? 3: 4);

      buflen++;
      if (i > 3)
        buflen++;
      if (i > 2)
        buflen++;
      if (i > 1)
        buflen++;
      buflen++;
    }

  return buflen;
}


gpg_error_t
_ksba_parse_sequence (unsigned char const **buf, size_t *len,
                      struct tag_info *ti)
{
  gpg_error_t err;

  err = _ksba_ber_parse_tl (buf, len, ti);
  if (err)
    ;
  else if (!(ti->class == CLASS_UNIVERSAL && ti->tag == TYPE_SEQUENCE
             && ti->is_constructed) )
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (ti->length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);
  return err;
}


/* Note that this function returns GPG_ERR_FALSE if the TLV is valid
 * but the tag does not match.  The caller may thus check for this
 * error code and compare against other tag values.  */
gpg_error_t
_ksba_parse_context_tag (unsigned char const **buf, size_t *len,
                         struct tag_info *ti, int tag)
{
  gpg_error_t err;

  err = _ksba_ber_parse_tl (buf, len, ti);
  if (err)
    ;
  else if (!(ti->class == CLASS_CONTEXT && ti->is_constructed))
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (ti->length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);
  else if (ti->tag != tag)
    err = gpg_error (GPG_ERR_FALSE);

  return err;
}


gpg_error_t
_ksba_parse_enumerated (unsigned char const **buf, size_t *len,
                        struct tag_info *ti, size_t maxlen)
{
  gpg_error_t err;

  err = _ksba_ber_parse_tl (buf, len, ti);
  if (err)
     ;
  else if (!(ti->class == CLASS_UNIVERSAL && ti->tag == TYPE_ENUMERATED
             && !ti->is_constructed) )
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (!ti->length)
    err = gpg_error (GPG_ERR_TOO_SHORT);
  else if (maxlen && ti->length > maxlen)
    err = gpg_error (GPG_ERR_TOO_LARGE);
  else if (ti->length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);

  return err;
}


gpg_error_t
_ksba_parse_integer (unsigned char const **buf, size_t *len,
                     struct tag_info *ti)
{
  gpg_error_t err;

  err = _ksba_ber_parse_tl (buf, len, ti);
  if (err)
     ;
  else if (!(ti->class == CLASS_UNIVERSAL && ti->tag == TYPE_INTEGER
             && !ti->is_constructed) )
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (!ti->length)
    err = gpg_error (GPG_ERR_TOO_SHORT);
  else if (ti->length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);

  return err;
}


gpg_error_t
_ksba_parse_octet_string (unsigned char const **buf, size_t *len,
                          struct tag_info *ti)
{
  gpg_error_t err;

  err= _ksba_ber_parse_tl (buf, len, ti);
  if (err)
    ;
  else if (!(ti->class == CLASS_UNIVERSAL && ti->tag == TYPE_OCTET_STRING
             && !ti->is_constructed) )
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (!ti->length)
    err = gpg_error (GPG_ERR_TOO_SHORT);
  else if (ti->length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);

  return err;
}


/* Note that R_BOOL will only be set if a value has been given. Thus
   the caller should set it to the default value prior to calling this
   function.  Obviously no call to parse_skip is required after
   calling this function. */
gpg_error_t
_ksba_parse_optional_boolean (unsigned char const **buf, size_t *len,
                              int *r_bool)
{
  gpg_error_t err;
  struct tag_info ti;

  err = _ksba_ber_parse_tl (buf, len, &ti);
  if (err)
    ;
  else if (!ti.length)
    err = gpg_error (GPG_ERR_TOO_SHORT);
  else if (ti.length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);
  else if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_BOOLEAN
           && !ti.is_constructed)
    {
      if (ti.length != 1)
        err = gpg_error (GPG_ERR_BAD_BER);
      *r_bool = !!**buf;
      parse_skip (buf, len, &ti);
    }
  else
    { /* Undo the read. */
      *buf -= ti.nhdr;
      *len += ti.nhdr;
    }

  return err;
}


/* Parse an optional Null tag.  Ir R_SEEN is not NULL it is set to
 * true if a NULL tag was encountered.  */
gpg_error_t
_ksba_parse_optional_null (unsigned char const **buf, size_t *len,
                           int *r_seen)
{
  gpg_error_t err;
  struct tag_info ti;

  if (r_seen)
    *r_seen = 0;
  err = _ksba_ber_parse_tl (buf, len, &ti);
  if (err)
    ;
  else if (ti.length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);
  else if (ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_NULL
           && !ti.is_constructed)
    {
      if (ti.length)
        err = gpg_error (GPG_ERR_BAD_BER);
      if (r_seen)
        *r_seen = 1;
      parse_skip (buf, len, &ti);
    }
  else
    { /* Undo the read. */
      *buf -= ti.nhdr;
      *len += ti.nhdr;
    }

  return err;
}



gpg_error_t
_ksba_parse_object_id_into_str (unsigned char const **buf, size_t *len,
                                char **oid)
{
  struct tag_info ti;
  gpg_error_t err;

  *oid = NULL;
  err = _ksba_ber_parse_tl (buf, len, &ti);
  if (err)
    ;
  else if (!(ti.class == CLASS_UNIVERSAL && ti.tag == TYPE_OBJECT_ID
                && !ti.is_constructed) )
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (!ti.length)
    err = gpg_error (GPG_ERR_TOO_SHORT);
  else if (ti.length > *len)
    err = gpg_error (GPG_ERR_BAD_BER);
  else if (!(*oid = ksba_oid_to_str (*buf, ti.length)))
    err = gpg_error_from_syserror ();
  else
    {
      *buf += ti.length;
      *len -= ti.length;
    }
  return err;
}


gpg_error_t
_ksba_parse_asntime_into_isotime (unsigned char const **buf, size_t *len,
                                  ksba_isotime_t isotime)
{
  struct tag_info ti;
  gpg_error_t err;

  err = _ksba_ber_parse_tl (buf, len, &ti);
  if (err)
    ;
  else if ( !(ti.class == CLASS_UNIVERSAL
              && (ti.tag == TYPE_UTC_TIME || ti.tag == TYPE_GENERALIZED_TIME)
              && !ti.is_constructed) )
    err = gpg_error (GPG_ERR_INV_OBJ);
  else if (ti.length > *len)
    err = gpg_error (GPG_ERR_INV_BER);
  else if (!(err = _ksba_asntime_to_iso (*buf, ti.length,
                                         ti.tag == TYPE_UTC_TIME, isotime)))
    parse_skip (buf, len, &ti);

  return err;
}