Ruby  2.0.0p648(2015-12-16revision53162)
ossl_asn1.c
Go to the documentation of this file.
1 /*
2  * $Id: ossl_asn1.c 46200 2014-05-28 04:22:15Z usa $
3  * 'OpenSSL for Ruby' team members
4  * Copyright (C) 2003
5  * All rights reserved.
6  */
7 /*
8  * This program is licenced under the same licence as Ruby.
9  * (See the file 'LICENCE'.)
10  */
11 #include "ossl.h"
12 
13 #if defined(HAVE_SYS_TIME_H)
14 # include <sys/time.h>
15 #elif !defined(NT) && !defined(_WIN32)
16 struct timeval {
17  long tv_sec; /* seconds */
18  long tv_usec; /* and microseconds */
19 };
20 #endif
21 
22 static VALUE join_der(VALUE enumerable);
23 static VALUE ossl_asn1_decode0(unsigned char **pp, long length, long *offset,
24  int depth, int yield, long *num_read);
25 static VALUE ossl_asn1_initialize(int argc, VALUE *argv, VALUE self);
27 
28 /*
29  * DATE conversion
30  */
31 VALUE
32 asn1time_to_time(ASN1_TIME *time)
33 {
34  struct tm tm;
35  VALUE argv[6];
36  int count;
37 
38  if (!time || !time->data) return Qnil;
39  memset(&tm, 0, sizeof(struct tm));
40 
41  switch (time->type) {
42  case V_ASN1_UTCTIME:
43  count = sscanf((const char *)time->data, "%2d%2d%2d%2d%2d%2dZ",
44  &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min,
45  &tm.tm_sec);
46 
47  if (count == 5) {
48  tm.tm_sec = 0;
49  } else if (count != 6) {
50  ossl_raise(rb_eTypeError, "bad UTCTIME format: \"%s\"",
51  time->data);
52  }
53  if (tm.tm_year < 69) {
54  tm.tm_year += 2000;
55  } else {
56  tm.tm_year += 1900;
57  }
58  break;
59  case V_ASN1_GENERALIZEDTIME:
60  if (sscanf((const char *)time->data, "%4d%2d%2d%2d%2d%2dZ", &tm.tm_year, &tm.tm_mon,
61  &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
62  ossl_raise(rb_eTypeError, "bad GENERALIZEDTIME format" );
63  }
64  break;
65  default:
66  rb_warning("unknown time format");
67  return Qnil;
68  }
69  argv[0] = INT2NUM(tm.tm_year);
70  argv[1] = INT2NUM(tm.tm_mon);
71  argv[2] = INT2NUM(tm.tm_mday);
72  argv[3] = INT2NUM(tm.tm_hour);
73  argv[4] = INT2NUM(tm.tm_min);
74  argv[5] = INT2NUM(tm.tm_sec);
75 
76  return rb_funcall2(rb_cTime, rb_intern("utc"), 6, argv);
77 }
78 
79 /*
80  * This function is not exported in Ruby's *.h
81  */
82 extern struct timeval rb_time_timeval(VALUE);
83 
84 time_t
86 {
87  return (time_t)NUM2LONG(rb_Integer(time));
88 }
89 
90 /*
91  * STRING conversion
92  */
93 VALUE
94 asn1str_to_str(ASN1_STRING *str)
95 {
96  return rb_str_new((const char *)str->data, str->length);
97 }
98 
99 /*
100  * ASN1_INTEGER conversions
101  * TODO: Make a decision what's the right way to do this.
102  */
103 #define DO_IT_VIA_RUBY 0
104 VALUE
105 asn1integer_to_num(ASN1_INTEGER *ai)
106 {
107  BIGNUM *bn;
108 #if DO_IT_VIA_RUBY
109  char *txt;
110 #endif
111  VALUE num;
112 
113  if (!ai) {
114  ossl_raise(rb_eTypeError, "ASN1_INTEGER is NULL!");
115  }
116  if (!(bn = ASN1_INTEGER_to_BN(ai, NULL))) {
118  }
119 #if DO_IT_VIA_RUBY
120  if (!(txt = BN_bn2dec(bn))) {
121  BN_free(bn);
123  }
124  num = rb_cstr_to_inum(txt, 10, Qtrue);
125  OPENSSL_free(txt);
126 #else
127  num = ossl_bn_new(bn);
128 #endif
129  BN_free(bn);
130 
131  return num;
132 }
133 
134 #if DO_IT_VIA_RUBY
135 ASN1_INTEGER *
136 num_to_asn1integer(VALUE obj, ASN1_INTEGER *ai)
137 {
138  BIGNUM *bn = NULL;
139 
140  if (RTEST(rb_obj_is_kind_of(obj, cBN))) {
141  bn = GetBNPtr(obj);
142  } else {
143  obj = rb_String(obj);
144  if (!BN_dec2bn(&bn, StringValuePtr(obj))) {
146  }
147  }
148  if (!(ai = BN_to_ASN1_INTEGER(bn, ai))) {
149  BN_free(bn);
151  }
152  BN_free(bn);
153  return ai;
154 }
155 #else
156 ASN1_INTEGER *
157 num_to_asn1integer(VALUE obj, ASN1_INTEGER *ai)
158 {
159  BIGNUM *bn;
160 
161  if (NIL_P(obj))
162  ossl_raise(rb_eTypeError, "Can't convert nil into Integer");
163 
164  bn = GetBNPtr(obj);
165 
166  if (!(ai = BN_to_ASN1_INTEGER(bn, ai)))
168 
169  return ai;
170 }
171 #endif
172 
173 /********/
174 /*
175  * ASN1 module
176  */
177 #define ossl_asn1_get_value(o) rb_attr_get((o),sivVALUE)
178 #define ossl_asn1_get_tag(o) rb_attr_get((o),sivTAG)
179 #define ossl_asn1_get_tagging(o) rb_attr_get((o),sivTAGGING)
180 #define ossl_asn1_get_tag_class(o) rb_attr_get((o),sivTAG_CLASS)
181 #define ossl_asn1_get_infinite_length(o) rb_attr_get((o),sivINFINITE_LENGTH)
182 
183 #define ossl_asn1_set_value(o,v) rb_ivar_set((o),sivVALUE,(v))
184 #define ossl_asn1_set_tag(o,v) rb_ivar_set((o),sivTAG,(v))
185 #define ossl_asn1_set_tagging(o,v) rb_ivar_set((o),sivTAGGING,(v))
186 #define ossl_asn1_set_tag_class(o,v) rb_ivar_set((o),sivTAG_CLASS,(v))
187 #define ossl_asn1_set_infinite_length(o,v) rb_ivar_set((o),sivINFINITE_LENGTH,(v))
188 
191 
195 
197 VALUE cASN1Boolean; /* BOOLEAN */
199 VALUE cASN1BitString; /* BIT STRING */
206 VALUE cASN1Null; /* NULL */
207 VALUE cASN1ObjectId; /* OBJECT IDENTIFIER */
209 VALUE cASN1Sequence, cASN1Set; /* CONSTRUCTIVE */
210 
214 
215 /*
216  * We need to implement these for backward compatibility
217  * reasons, behavior of ASN1_put_object and ASN1_object_size
218  * for infinite length values is different in OpenSSL <= 0.9.7
219  */
220 #if OPENSSL_VERSION_NUMBER < 0x00908000L
221 #define ossl_asn1_object_size(cons, len, tag) (cons) == 2 ? (len) + ASN1_object_size((cons), 0, (tag)) : ASN1_object_size((cons), (len), (tag))
222 #define ossl_asn1_put_object(pp, cons, len, tag, xc) (cons) == 2 ? ASN1_put_object((pp), (cons), 0, (tag), (xc)) : ASN1_put_object((pp), (cons), (len), (tag), (xc))
223 #else
224 #define ossl_asn1_object_size(cons, len, tag) ASN1_object_size((cons), (len), (tag))
225 #define ossl_asn1_put_object(pp, cons, len, tag, xc) ASN1_put_object((pp), (cons), (len), (tag), (xc))
226 #endif
227 
228 /*
229  * Ruby to ASN1 converters
230  */
231 static ASN1_BOOLEAN
233 {
234  if (NIL_P(obj))
235  ossl_raise(rb_eTypeError, "Can't convert nil into Boolean");
236 
237 #if OPENSSL_VERSION_NUMBER < 0x00907000L
238  return RTEST(obj) ? 0xff : 0x100;
239 #else
240  return RTEST(obj) ? 0xff : 0x0;
241 #endif
242 }
243 
244 static ASN1_INTEGER*
246 {
247  return num_to_asn1integer(obj, NULL);
248 }
249 
250 static ASN1_BIT_STRING*
251 obj_to_asn1bstr(VALUE obj, long unused_bits)
252 {
253  ASN1_BIT_STRING *bstr;
254 
255  if(unused_bits < 0) unused_bits = 0;
256  StringValue(obj);
257  if(!(bstr = ASN1_BIT_STRING_new()))
258  ossl_raise(eASN1Error, NULL);
259  ASN1_BIT_STRING_set(bstr, (unsigned char *)RSTRING_PTR(obj), RSTRING_LENINT(obj));
260  bstr->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07); /* clear */
261  bstr->flags |= ASN1_STRING_FLAG_BITS_LEFT|(unused_bits&0x07);
262 
263  return bstr;
264 }
265 
266 static ASN1_STRING*
268 {
269  ASN1_STRING *str;
270 
271  StringValue(obj);
272  if(!(str = ASN1_STRING_new()))
273  ossl_raise(eASN1Error, NULL);
274  ASN1_STRING_set(str, RSTRING_PTR(obj), RSTRING_LENINT(obj));
275 
276  return str;
277 }
278 
279 static ASN1_NULL*
281 {
282  ASN1_NULL *null;
283 
284  if(!NIL_P(obj))
285  ossl_raise(eASN1Error, "nil expected");
286  if(!(null = ASN1_NULL_new()))
287  ossl_raise(eASN1Error, NULL);
288 
289  return null;
290 }
291 
292 static ASN1_OBJECT*
294 {
295  ASN1_OBJECT *a1obj;
296 
297  StringValue(obj);
298  a1obj = OBJ_txt2obj(RSTRING_PTR(obj), 0);
299  if(!a1obj) a1obj = OBJ_txt2obj(RSTRING_PTR(obj), 1);
300  if(!a1obj) ossl_raise(eASN1Error, "invalid OBJECT ID");
301 
302  return a1obj;
303 }
304 
305 static ASN1_UTCTIME*
307 {
308  time_t sec;
309  ASN1_UTCTIME *t;
310 
311  sec = time_to_time_t(time);
312  if(!(t = ASN1_UTCTIME_set(NULL, sec)))
313  ossl_raise(eASN1Error, NULL);
314 
315  return t;
316 }
317 
318 static ASN1_GENERALIZEDTIME*
320 {
321  time_t sec;
322  ASN1_GENERALIZEDTIME *t;
323 
324  sec = time_to_time_t(time);
325  if(!(t =ASN1_GENERALIZEDTIME_set(NULL, sec)))
326  ossl_raise(eASN1Error, NULL);
327 
328  return t;
329 }
330 
331 static ASN1_STRING*
333 {
334  ASN1_STRING *a1str;
335  VALUE str;
336 
337  str = ossl_to_der(obj);
338  if(!(a1str = ASN1_STRING_new()))
339  ossl_raise(eASN1Error, NULL);
340  ASN1_STRING_set(a1str, RSTRING_PTR(str), RSTRING_LENINT(str));
341 
342  return a1str;
343 }
344 
345 /*
346  * DER to Ruby converters
347  */
348 static VALUE
349 decode_bool(unsigned char* der, long length)
350 {
351  int val;
352  const unsigned char *p;
353 
354  p = der;
355  if((val = d2i_ASN1_BOOLEAN(NULL, &p, length)) < 0)
356  ossl_raise(eASN1Error, NULL);
357 
358  return val ? Qtrue : Qfalse;
359 }
360 
361 static VALUE
362 decode_int(unsigned char* der, long length)
363 {
364  ASN1_INTEGER *ai;
365  const unsigned char *p;
366  VALUE ret;
367  int status = 0;
368 
369  p = der;
370  if(!(ai = d2i_ASN1_INTEGER(NULL, &p, length)))
371  ossl_raise(eASN1Error, NULL);
373  (VALUE)ai, &status);
374  ASN1_INTEGER_free(ai);
375  if(status) rb_jump_tag(status);
376 
377  return ret;
378 }
379 
380 static VALUE
381 decode_bstr(unsigned char* der, long length, long *unused_bits)
382 {
383  ASN1_BIT_STRING *bstr;
384  const unsigned char *p;
385  long len;
386  VALUE ret;
387 
388  p = der;
389  if(!(bstr = d2i_ASN1_BIT_STRING(NULL, &p, length)))
390  ossl_raise(eASN1Error, NULL);
391  len = bstr->length;
392  *unused_bits = 0;
393  if(bstr->flags & ASN1_STRING_FLAG_BITS_LEFT)
394  *unused_bits = bstr->flags & 0x07;
395  ret = rb_str_new((const char *)bstr->data, len);
396  ASN1_BIT_STRING_free(bstr);
397 
398  return ret;
399 }
400 
401 static VALUE
402 decode_enum(unsigned char* der, long length)
403 {
404  ASN1_ENUMERATED *ai;
405  const unsigned char *p;
406  VALUE ret;
407  int status = 0;
408 
409  p = der;
410  if(!(ai = d2i_ASN1_ENUMERATED(NULL, &p, length)))
411  ossl_raise(eASN1Error, NULL);
413  (VALUE)ai, &status);
414  ASN1_ENUMERATED_free(ai);
415  if(status) rb_jump_tag(status);
416 
417  return ret;
418 }
419 
420 static VALUE
421 decode_null(unsigned char* der, long length)
422 {
423  ASN1_NULL *null;
424  const unsigned char *p;
425 
426  p = der;
427  if(!(null = d2i_ASN1_NULL(NULL, &p, length)))
428  ossl_raise(eASN1Error, NULL);
429  ASN1_NULL_free(null);
430 
431  return Qnil;
432 }
433 
434 static VALUE
435 decode_obj(unsigned char* der, long length)
436 {
437  ASN1_OBJECT *obj;
438  const unsigned char *p;
439  VALUE ret;
440  int nid;
441  BIO *bio;
442 
443  p = der;
444  if(!(obj = d2i_ASN1_OBJECT(NULL, &p, length)))
445  ossl_raise(eASN1Error, NULL);
446  if((nid = OBJ_obj2nid(obj)) != NID_undef){
447  ASN1_OBJECT_free(obj);
448  ret = rb_str_new2(OBJ_nid2sn(nid));
449  }
450  else{
451  if(!(bio = BIO_new(BIO_s_mem()))){
452  ASN1_OBJECT_free(obj);
453  ossl_raise(eASN1Error, NULL);
454  }
455  i2a_ASN1_OBJECT(bio, obj);
456  ASN1_OBJECT_free(obj);
457  ret = ossl_membio2str(bio);
458  }
459 
460  return ret;
461 }
462 
463 static VALUE
464 decode_time(unsigned char* der, long length)
465 {
466  ASN1_TIME *time;
467  const unsigned char *p;
468  VALUE ret;
469  int status = 0;
470 
471  p = der;
472  if(!(time = d2i_ASN1_TIME(NULL, &p, length)))
473  ossl_raise(eASN1Error, NULL);
475  (VALUE)time, &status);
476  ASN1_TIME_free(time);
477  if(status) rb_jump_tag(status);
478 
479  return ret;
480 }
481 
482 static VALUE
483 decode_eoc(unsigned char *der, long length)
484 {
485  if (length != 2 || !(der[0] == 0x00 && der[1] == 0x00))
486  ossl_raise(eASN1Error, NULL);
487 
488  return rb_str_new("", 0);
489 }
490 
491 /********/
492 
493 typedef struct {
494  const char *name;
497 
499  { "EOC", &cASN1EndOfContent, }, /* 0 */
500  { "BOOLEAN", &cASN1Boolean, }, /* 1 */
501  { "INTEGER", &cASN1Integer, }, /* 2 */
502  { "BIT_STRING", &cASN1BitString, }, /* 3 */
503  { "OCTET_STRING", &cASN1OctetString, }, /* 4 */
504  { "NULL", &cASN1Null, }, /* 5 */
505  { "OBJECT", &cASN1ObjectId, }, /* 6 */
506  { "OBJECT_DESCRIPTOR", NULL, }, /* 7 */
507  { "EXTERNAL", NULL, }, /* 8 */
508  { "REAL", NULL, }, /* 9 */
509  { "ENUMERATED", &cASN1Enumerated, }, /* 10 */
510  { "EMBEDDED_PDV", NULL, }, /* 11 */
511  { "UTF8STRING", &cASN1UTF8String, }, /* 12 */
512  { "RELATIVE_OID", NULL, }, /* 13 */
513  { "[UNIVERSAL 14]", NULL, }, /* 14 */
514  { "[UNIVERSAL 15]", NULL, }, /* 15 */
515  { "SEQUENCE", &cASN1Sequence, }, /* 16 */
516  { "SET", &cASN1Set, }, /* 17 */
517  { "NUMERICSTRING", &cASN1NumericString, }, /* 18 */
518  { "PRINTABLESTRING", &cASN1PrintableString, }, /* 19 */
519  { "T61STRING", &cASN1T61String, }, /* 20 */
520  { "VIDEOTEXSTRING", &cASN1VideotexString, }, /* 21 */
521  { "IA5STRING", &cASN1IA5String, }, /* 22 */
522  { "UTCTIME", &cASN1UTCTime, }, /* 23 */
523  { "GENERALIZEDTIME", &cASN1GeneralizedTime, }, /* 24 */
524  { "GRAPHICSTRING", &cASN1GraphicString, }, /* 25 */
525  { "ISO64STRING", &cASN1ISO64String, }, /* 26 */
526  { "GENERALSTRING", &cASN1GeneralString, }, /* 27 */
527  { "UNIVERSALSTRING", &cASN1UniversalString, }, /* 28 */
528  { "CHARACTER_STRING", NULL, }, /* 29 */
529  { "BMPSTRING", &cASN1BMPString, }, /* 30 */
530 };
531 
532 int ossl_asn1_info_size = (sizeof(ossl_asn1_info)/sizeof(ossl_asn1_info[0]));
533 
535 
536 static int ossl_asn1_default_tag(VALUE obj);
537 
538 ASN1_TYPE*
540 {
541  ASN1_TYPE *ret;
542  VALUE value, rflag;
543  void *ptr;
544  void (*free_func)();
545  int tag, flag;
546 
547  tag = ossl_asn1_default_tag(obj);
548  value = ossl_asn1_get_value(obj);
549  switch(tag){
550  case V_ASN1_BOOLEAN:
551  ptr = (void*)(VALUE)obj_to_asn1bool(value);
552  free_func = NULL;
553  break;
554  case V_ASN1_INTEGER: /* FALLTHROUGH */
555  case V_ASN1_ENUMERATED:
556  ptr = obj_to_asn1int(value);
557  free_func = ASN1_INTEGER_free;
558  break;
559  case V_ASN1_BIT_STRING:
560  rflag = rb_attr_get(obj, sivUNUSED_BITS);
561  flag = NIL_P(rflag) ? -1 : NUM2INT(rflag);
562  ptr = obj_to_asn1bstr(value, flag);
563  free_func = ASN1_BIT_STRING_free;
564  break;
565  case V_ASN1_NULL:
566  ptr = obj_to_asn1null(value);
567  free_func = ASN1_NULL_free;
568  break;
569  case V_ASN1_OCTET_STRING: /* FALLTHROUGH */
570  case V_ASN1_UTF8STRING: /* FALLTHROUGH */
571  case V_ASN1_NUMERICSTRING: /* FALLTHROUGH */
572  case V_ASN1_PRINTABLESTRING: /* FALLTHROUGH */
573  case V_ASN1_T61STRING: /* FALLTHROUGH */
574  case V_ASN1_VIDEOTEXSTRING: /* FALLTHROUGH */
575  case V_ASN1_IA5STRING: /* FALLTHROUGH */
576  case V_ASN1_GRAPHICSTRING: /* FALLTHROUGH */
577  case V_ASN1_ISO64STRING: /* FALLTHROUGH */
578  case V_ASN1_GENERALSTRING: /* FALLTHROUGH */
579  case V_ASN1_UNIVERSALSTRING: /* FALLTHROUGH */
580  case V_ASN1_BMPSTRING:
581  ptr = obj_to_asn1str(value);
582  free_func = ASN1_STRING_free;
583  break;
584  case V_ASN1_OBJECT:
585  ptr = obj_to_asn1obj(value);
586  free_func = ASN1_OBJECT_free;
587  break;
588  case V_ASN1_UTCTIME:
589  ptr = obj_to_asn1utime(value);
590  free_func = ASN1_TIME_free;
591  break;
592  case V_ASN1_GENERALIZEDTIME:
593  ptr = obj_to_asn1gtime(value);
594  free_func = ASN1_TIME_free;
595  break;
596  case V_ASN1_SET: /* FALLTHROUGH */
597  case V_ASN1_SEQUENCE:
598  ptr = obj_to_asn1derstr(obj);
599  free_func = ASN1_STRING_free;
600  break;
601  default:
602  ossl_raise(eASN1Error, "unsupported ASN.1 type");
603  }
604  if(!(ret = OPENSSL_malloc(sizeof(ASN1_TYPE)))){
605  if(free_func) free_func(ptr);
606  ossl_raise(eASN1Error, "ASN1_TYPE alloc failure");
607  }
608  memset(ret, 0, sizeof(ASN1_TYPE));
609  ASN1_TYPE_set(ret, tag, ptr);
610 
611  return ret;
612 }
613 
614 static int
616 {
617  VALUE tmp_class, tag;
618 
619  tmp_class = CLASS_OF(obj);
620  while (tmp_class) {
621  tag = rb_hash_lookup(class_tag_map, tmp_class);
622  if (tag != Qnil) {
623  return NUM2INT(tag);
624  }
625  tmp_class = rb_class_superclass(tmp_class);
626  }
627  ossl_raise(eASN1Error, "universal tag for %"PRIsVALUE" not found",
628  rb_obj_class(obj));
629 
630  return -1; /* dummy */
631 }
632 
633 static int
635 {
636  VALUE tag;
637 
638  tag = ossl_asn1_get_tag(obj);
639  if(NIL_P(tag))
640  ossl_raise(eASN1Error, "tag number not specified");
641 
642  return NUM2INT(tag);
643 }
644 
645 static int
647 {
648  VALUE s;
649  int ret = -1;
650 
651  s = ossl_asn1_get_tagging(obj);
652  if(NIL_P(s)) return 0;
653  else if(SYMBOL_P(s)){
654  if (SYM2ID(s) == sIMPLICIT)
655  ret = 0;
656  else if (SYM2ID(s) == sEXPLICIT)
657  ret = 1;
658  }
659  if(ret < 0){
660  ossl_raise(eASN1Error, "invalid tag default");
661  }
662 
663  return ret;
664 }
665 
666 static int
668 {
669  VALUE s;
670  int ret = -1;
671 
672  s = ossl_asn1_get_tag_class(obj);
673  if(NIL_P(s)) ret = V_ASN1_UNIVERSAL;
674  else if(SYMBOL_P(s)){
675  if (SYM2ID(s) == sUNIVERSAL)
676  ret = V_ASN1_UNIVERSAL;
677  else if (SYM2ID(s) == sAPPLICATION)
678  ret = V_ASN1_APPLICATION;
679  else if (SYM2ID(s) == sCONTEXT_SPECIFIC)
680  ret = V_ASN1_CONTEXT_SPECIFIC;
681  else if (SYM2ID(s) == sPRIVATE)
682  ret = V_ASN1_PRIVATE;
683  }
684  if(ret < 0){
685  ossl_raise(eASN1Error, "invalid tag class");
686  }
687 
688  return ret;
689 }
690 
691 static VALUE
693 {
694  if((tc & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
695  return ID2SYM(sPRIVATE);
696  else if((tc & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
697  return ID2SYM(sCONTEXT_SPECIFIC);
698  else if((tc & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
699  return ID2SYM(sAPPLICATION);
700  else
701  return ID2SYM(sUNIVERSAL);
702 }
703 
704 /*
705  * call-seq:
706  * OpenSSL::ASN1::ASN1Data.new(value, tag, tag_class) => ASN1Data
707  *
708  * +value+: Please have a look at Constructive and Primitive to see how Ruby
709  * types are mapped to ASN.1 types and vice versa.
710  *
711  * +tag+: A +Number+ indicating the tag number.
712  *
713  * +tag_class+: A +Symbol+ indicating the tag class. Please cf. ASN1 for
714  * possible values.
715  *
716  * == Example
717  * asn1_int = OpenSSL::ASN1Data.new(42, 2, :UNIVERSAL) # => Same as OpenSSL::ASN1::Integer.new(42)
718  * tagged_int = OpenSSL::ASN1Data.new(42, 0, :CONTEXT_SPECIFIC) # implicitly 0-tagged INTEGER
719  */
720 static VALUE
721 ossl_asn1data_initialize(VALUE self, VALUE value, VALUE tag, VALUE tag_class)
722 {
723  if(!SYMBOL_P(tag_class))
724  ossl_raise(eASN1Error, "invalid tag class");
725  if((SYM2ID(tag_class) == sUNIVERSAL) && NUM2INT(tag) > 31)
726  ossl_raise(eASN1Error, "tag number for Universal too large");
727  ossl_asn1_set_tag(self, tag);
728  ossl_asn1_set_value(self, value);
729  ossl_asn1_set_tag_class(self, tag_class);
731 
732  return self;
733 }
734 
735 static VALUE
737 {
739  StringValue(i);
740  rb_str_append(str, i);
741  return Qnil;
742 }
743 
744 static VALUE
745 join_der(VALUE enumerable)
746 {
747  VALUE str = rb_str_new(0, 0);
748  rb_block_call(enumerable, rb_intern("each"), 0, 0, join_der_i, str);
749  return str;
750 }
751 
752 /*
753  * call-seq:
754  * asn1.to_der => DER-encoded String
755  *
756  * Encodes this ASN1Data into a DER-encoded String value. The result is
757  * DER-encoded except for the possibility of infinite length encodings.
758  * Infinite length encodings are not allowed in strict DER, so strictly
759  * speaking the result of such an encoding would be a BER-encoding.
760  */
761 static VALUE
763 {
764  VALUE value, der, inf_length;
765  int tag, tag_class, is_cons = 0;
766  long length;
767  unsigned char *p;
768 
769  value = ossl_asn1_get_value(self);
770  if(rb_obj_is_kind_of(value, rb_cArray)){
771  is_cons = 1;
772  value = join_der(value);
773  }
774  StringValue(value);
775 
776  tag = ossl_asn1_tag(self);
777  tag_class = ossl_asn1_tag_class(self);
778  inf_length = ossl_asn1_get_infinite_length(self);
779  if (inf_length == Qtrue) {
780  is_cons = 2;
781  }
782  if((length = ossl_asn1_object_size(is_cons, RSTRING_LENINT(value), tag)) <= 0)
783  ossl_raise(eASN1Error, NULL);
784  der = rb_str_new(0, length);
785  p = (unsigned char *)RSTRING_PTR(der);
786  ossl_asn1_put_object(&p, is_cons, RSTRING_LENINT(value), tag, tag_class);
787  memcpy(p, RSTRING_PTR(value), RSTRING_LEN(value));
788  p += RSTRING_LEN(value);
789  ossl_str_adjust(der, p);
790 
791  return der;
792 }
793 
794 static VALUE
795 int_ossl_asn1_decode0_prim(unsigned char **pp, long length, long hlen, int tag,
796  VALUE tc, long *num_read)
797 {
798  VALUE value, asn1data;
799  unsigned char *p;
800  long flag = 0;
801 
802  p = *pp;
803 
804  if(tc == sUNIVERSAL && tag < ossl_asn1_info_size) {
805  switch(tag){
806  case V_ASN1_EOC:
807  value = decode_eoc(p, hlen+length);
808  break;
809  case V_ASN1_BOOLEAN:
810  value = decode_bool(p, hlen+length);
811  break;
812  case V_ASN1_INTEGER:
813  value = decode_int(p, hlen+length);
814  break;
815  case V_ASN1_BIT_STRING:
816  value = decode_bstr(p, hlen+length, &flag);
817  break;
818  case V_ASN1_NULL:
819  value = decode_null(p, hlen+length);
820  break;
821  case V_ASN1_ENUMERATED:
822  value = decode_enum(p, hlen+length);
823  break;
824  case V_ASN1_OBJECT:
825  value = decode_obj(p, hlen+length);
826  break;
827  case V_ASN1_UTCTIME: /* FALLTHROUGH */
828  case V_ASN1_GENERALIZEDTIME:
829  value = decode_time(p, hlen+length);
830  break;
831  default:
832  /* use original value */
833  p += hlen;
834  value = rb_str_new((const char *)p, length);
835  break;
836  }
837  }
838  else {
839  p += hlen;
840  value = rb_str_new((const char *)p, length);
841  }
842 
843  *pp += hlen + length;
844  *num_read = hlen + length;
845 
846  if (tc == sUNIVERSAL && tag < ossl_asn1_info_size && ossl_asn1_info[tag].klass) {
847  VALUE klass = *ossl_asn1_info[tag].klass;
848  VALUE args[4];
849  args[0] = value;
850  args[1] = INT2NUM(tag);
851  args[2] = Qnil;
852  args[3] = ID2SYM(tc);
853  asn1data = rb_obj_alloc(klass);
854  ossl_asn1_initialize(4, args, asn1data);
855  if(tag == V_ASN1_BIT_STRING){
856  rb_ivar_set(asn1data, sivUNUSED_BITS, LONG2NUM(flag));
857  }
858  }
859  else {
860  asn1data = rb_obj_alloc(cASN1Data);
861  ossl_asn1data_initialize(asn1data, value, INT2NUM(tag), ID2SYM(tc));
862  }
863 
864  return asn1data;
865 }
866 
867 static VALUE
868 int_ossl_asn1_decode0_cons(unsigned char **pp, long max_len, long length,
869  long *offset, int depth, int yield, int j,
870  int tag, VALUE tc, long *num_read)
871 {
872  VALUE value, asn1data, ary;
873  int infinite;
874  long available_len, off = *offset;
875 
876  infinite = (j == 0x21);
877  ary = rb_ary_new();
878 
879  available_len = infinite ? max_len : length;
880  while (available_len > 0) {
881  long inner_read = 0;
882  value = ossl_asn1_decode0(pp, available_len, &off, depth + 1, yield, &inner_read);
883  *num_read += inner_read;
884  available_len -= inner_read;
885  rb_ary_push(ary, value);
886 
887  if (infinite &&
888  NUM2INT(ossl_asn1_get_tag(value)) == V_ASN1_EOC &&
889  SYM2ID(ossl_asn1_get_tag_class(value)) == sUNIVERSAL) {
890  break;
891  }
892  }
893 
894  if (tc == sUNIVERSAL) {
895  VALUE args[4];
896  int not_sequence_or_set;
897 
898  not_sequence_or_set = tag != V_ASN1_SEQUENCE && tag != V_ASN1_SET;
899 
900  if (not_sequence_or_set) {
901  if (infinite) {
902  asn1data = rb_obj_alloc(cASN1Constructive);
903  }
904  else {
905  ossl_raise(eASN1Error, "invalid non-infinite tag");
906  return Qnil;
907  }
908  }
909  else {
910  VALUE klass = *ossl_asn1_info[tag].klass;
911  asn1data = rb_obj_alloc(klass);
912  }
913  args[0] = ary;
914  args[1] = INT2NUM(tag);
915  args[2] = Qnil;
916  args[3] = ID2SYM(tc);
917  ossl_asn1_initialize(4, args, asn1data);
918  }
919  else {
920  asn1data = rb_obj_alloc(cASN1Data);
921  ossl_asn1data_initialize(asn1data, ary, INT2NUM(tag), ID2SYM(tc));
922  }
923 
924  if (infinite)
926  else
928 
929  *offset = off;
930  return asn1data;
931 }
932 
933 static VALUE
934 ossl_asn1_decode0(unsigned char **pp, long length, long *offset, int depth,
935  int yield, long *num_read)
936 {
937  unsigned char *start, *p;
938  const unsigned char *p0;
939  long len = 0, inner_read = 0, off = *offset, hlen;
940  int tag, tc, j;
941  VALUE asn1data, tag_class;
942 
943  p = *pp;
944  start = p;
945  p0 = p;
946  j = ASN1_get_object(&p0, &len, &tag, &tc, length);
947  p = (unsigned char *)p0;
948  if(j & 0x80) ossl_raise(eASN1Error, NULL);
949  if(len > length) ossl_raise(eASN1Error, "value is too short");
950  if((tc & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
951  tag_class = sPRIVATE;
952  else if((tc & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
953  tag_class = sCONTEXT_SPECIFIC;
954  else if((tc & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
955  tag_class = sAPPLICATION;
956  else
957  tag_class = sUNIVERSAL;
958 
959  hlen = p - start;
960 
961  if(yield) {
962  VALUE arg = rb_ary_new();
963  rb_ary_push(arg, LONG2NUM(depth));
964  rb_ary_push(arg, LONG2NUM(*offset));
965  rb_ary_push(arg, LONG2NUM(hlen));
966  rb_ary_push(arg, LONG2NUM(len));
967  rb_ary_push(arg, (j & V_ASN1_CONSTRUCTED) ? Qtrue : Qfalse);
969  rb_ary_push(arg, INT2NUM(tag));
970  rb_yield(arg);
971  }
972 
973  if(j & V_ASN1_CONSTRUCTED) {
974  *pp += hlen;
975  off += hlen;
976  asn1data = int_ossl_asn1_decode0_cons(pp, length - hlen, len, &off, depth, yield, j, tag, tag_class, &inner_read);
977  inner_read += hlen;
978  }
979  else {
980  if ((j & 0x01) && (len == 0)) ossl_raise(eASN1Error, "Infinite length for primitive value");
981  asn1data = int_ossl_asn1_decode0_prim(pp, len, hlen, tag, tag_class, &inner_read);
982  off += hlen + len;
983  }
984  if (num_read)
985  *num_read = inner_read;
986  if (len != 0 && inner_read != hlen + len) {
987  ossl_raise(eASN1Error,
988  "Type mismatch. Bytes read: %ld Bytes available: %ld",
989  inner_read, hlen + len);
990  }
991 
992  *offset = off;
993  return asn1data;
994 }
995 
996 static void
997 int_ossl_decode_sanity_check(long len, long read, long offset)
998 {
999  if (len != 0 && (read != len || offset != len)) {
1000  ossl_raise(eASN1Error,
1001  "Type mismatch. Total bytes read: %ld Bytes available: %ld Offset: %ld",
1002  read, len, offset);
1003  }
1004 }
1005 
1006 /*
1007  * call-seq:
1008  * OpenSSL::ASN1.traverse(asn1) -> nil
1009  *
1010  * If a block is given, it prints out each of the elements encountered.
1011  * Block parameters are (in that order):
1012  * * depth: The recursion depth, plus one with each constructed value being encountered (Number)
1013  * * offset: Current byte offset (Number)
1014  * * header length: Combined length in bytes of the Tag and Length headers. (Number)
1015  * * length: The overall remaining length of the entire data (Number)
1016  * * constructed: Whether this value is constructed or not (Boolean)
1017  * * tag_class: Current tag class (Symbol)
1018  * * tag: The current tag (Number)
1019  *
1020  * == Example
1021  * der = File.binread('asn1data.der')
1022  * OpenSSL::ASN1.traverse(der) do | depth, offset, header_len, length, constructed, tag_class, tag|
1023  * puts "Depth: #{depth} Offset: #{offset} Length: #{length}"
1024  * puts "Header length: #{header_len} Tag: #{tag} Tag class: #{tag_class} Constructed: #{constructed}"
1025  * end
1026  */
1027 static VALUE
1029 {
1030  unsigned char *p;
1031  volatile VALUE tmp;
1032  long len, read = 0, offset = 0;
1033 
1034  obj = ossl_to_der_if_possible(obj);
1035  tmp = rb_str_new4(StringValue(obj));
1036  p = (unsigned char *)RSTRING_PTR(tmp);
1037  len = RSTRING_LEN(tmp);
1038  ossl_asn1_decode0(&p, len, &offset, 0, 1, &read);
1039  int_ossl_decode_sanity_check(len, read, offset);
1040  return Qnil;
1041 }
1042 
1043 /*
1044  * call-seq:
1045  * OpenSSL::ASN1.decode(der) -> ASN1Data
1046  *
1047  * Decodes a BER- or DER-encoded value and creates an ASN1Data instance. +der+
1048  * may be a +String+ or any object that features a +#to_der+ method transforming
1049  * it into a BER-/DER-encoded +String+.
1050  *
1051  * == Example
1052  * der = File.binread('asn1data')
1053  * asn1 = OpenSSL::ASN1.decode(der)
1054  */
1055 static VALUE
1057 {
1058  VALUE ret;
1059  unsigned char *p;
1060  volatile VALUE tmp;
1061  long len, read = 0, offset = 0;
1062 
1063  obj = ossl_to_der_if_possible(obj);
1064  tmp = rb_str_new4(StringValue(obj));
1065  p = (unsigned char *)RSTRING_PTR(tmp);
1066  len = RSTRING_LEN(tmp);
1067  ret = ossl_asn1_decode0(&p, len, &offset, 0, 0, &read);
1068  int_ossl_decode_sanity_check(len, read, offset);
1069  return ret;
1070 }
1071 
1072 /*
1073  * call-seq:
1074  * OpenSSL::ASN1.decode_all(der) -> Array of ASN1Data
1075  *
1076  * Similar to +decode+ with the difference that +decode+ expects one
1077  * distinct value represented in +der+. +decode_all+ on the contrary
1078  * decodes a sequence of sequential BER/DER values lined up in +der+
1079  * and returns them as an array.
1080  *
1081  * == Example
1082  * ders = File.binread('asn1data_seq')
1083  * asn1_ary = OpenSSL::ASN1.decode_all(ders)
1084  */
1085 static VALUE
1087 {
1088  VALUE ary, val;
1089  unsigned char *p;
1090  long len, tmp_len = 0, read = 0, offset = 0;
1091  volatile VALUE tmp;
1092 
1093  obj = ossl_to_der_if_possible(obj);
1094  tmp = rb_str_new4(StringValue(obj));
1095  p = (unsigned char *)RSTRING_PTR(tmp);
1096  len = RSTRING_LEN(tmp);
1097  tmp_len = len;
1098  ary = rb_ary_new();
1099  while (tmp_len > 0) {
1100  long tmp_read = 0;
1101  val = ossl_asn1_decode0(&p, tmp_len, &offset, 0, 0, &tmp_read);
1102  rb_ary_push(ary, val);
1103  read += tmp_read;
1104  tmp_len -= tmp_read;
1105  }
1106  int_ossl_decode_sanity_check(len, read, offset);
1107  return ary;
1108 }
1109 
1110 /*
1111  * call-seq:
1112  * OpenSSL::ASN1::Primitive.new( value [, tag, tagging, tag_class ]) => Primitive
1113  *
1114  * +value+: is mandatory.
1115  *
1116  * +tag+: optional, may be specified for tagged values. If no +tag+ is
1117  * specified, the UNIVERSAL tag corresponding to the Primitive sub-class
1118  * is used by default.
1119  *
1120  * +tagging+: may be used as an encoding hint to encode a value either
1121  * explicitly or implicitly, see ASN1 for possible values.
1122  *
1123  * +tag_class+: if +tag+ and +tagging+ are +nil+ then this is set to
1124  * +:UNIVERSAL+ by default. If either +tag+ or +tagging+ are set then
1125  * +:CONTEXT_SPECIFIC+ is used as the default. For possible values please
1126  * cf. ASN1.
1127  *
1128  * == Example
1129  * int = OpenSSL::ASN1::Integer.new(42)
1130  * zero_tagged_int = OpenSSL::ASN1::Integer.new(42, 0, :IMPLICIT)
1131  * private_explicit_zero_tagged_int = OpenSSL::ASN1::Integer.new(42, 0, :EXPLICIT, :PRIVATE)
1132  */
1133 static VALUE
1135 {
1136  VALUE value, tag, tagging, tag_class;
1137 
1138  rb_scan_args(argc, argv, "13", &value, &tag, &tagging, &tag_class);
1139  if(argc > 1){
1140  if(NIL_P(tag))
1141  ossl_raise(eASN1Error, "must specify tag number");
1142  if(!NIL_P(tagging) && !SYMBOL_P(tagging))
1143  ossl_raise(eASN1Error, "invalid tagging method");
1144  if(NIL_P(tag_class)) {
1145  if (NIL_P(tagging))
1146  tag_class = ID2SYM(sUNIVERSAL);
1147  else
1148  tag_class = ID2SYM(sCONTEXT_SPECIFIC);
1149  }
1150  if(!SYMBOL_P(tag_class))
1151  ossl_raise(eASN1Error, "invalid tag class");
1152  if(!NIL_P(tagging) && SYM2ID(tagging) == sIMPLICIT && NUM2INT(tag) > 31)
1153  ossl_raise(eASN1Error, "tag number for Universal too large");
1154  }
1155  else{
1156  tag = INT2NUM(ossl_asn1_default_tag(self));
1157  tagging = Qnil;
1158  tag_class = ID2SYM(sUNIVERSAL);
1159  }
1160  ossl_asn1_set_tag(self, tag);
1161  ossl_asn1_set_value(self, value);
1162  ossl_asn1_set_tagging(self, tagging);
1163  ossl_asn1_set_tag_class(self, tag_class);
1165 
1166  return self;
1167 }
1168 
1169 static VALUE
1171  VALUE tag, tagging, tag_class, value;
1172  tag = INT2NUM(ossl_asn1_default_tag(self));
1173  tagging = Qnil;
1174  tag_class = ID2SYM(sUNIVERSAL);
1175  value = rb_str_new("", 0);
1176  ossl_asn1_set_tag(self, tag);
1177  ossl_asn1_set_value(self, value);
1178  ossl_asn1_set_tagging(self, tagging);
1179  ossl_asn1_set_tag_class(self, tag_class);
1181  return self;
1182 }
1183 
1184 static int
1185 ossl_i2d_ASN1_TYPE(ASN1_TYPE *a, unsigned char **pp)
1186 {
1187 #if OPENSSL_VERSION_NUMBER < 0x00907000L
1188  if(!a) return 0;
1189  if(a->type == V_ASN1_BOOLEAN)
1190  return i2d_ASN1_BOOLEAN(a->value.boolean, pp);
1191 #endif
1192  return i2d_ASN1_TYPE(a, pp);
1193 }
1194 
1195 static void
1196 ossl_ASN1_TYPE_free(ASN1_TYPE *a)
1197 {
1198 #if OPENSSL_VERSION_NUMBER < 0x00907000L
1199  if(!a) return;
1200  if(a->type == V_ASN1_BOOLEAN){
1201  OPENSSL_free(a);
1202  return;
1203  }
1204 #endif
1205  ASN1_TYPE_free(a);
1206 }
1207 
1208 /*
1209  * call-seq:
1210  * asn1.to_der => DER-encoded String
1211  *
1212  * See ASN1Data#to_der for details. *
1213  */
1214 static VALUE
1216 {
1217  ASN1_TYPE *asn1;
1218  int tn, tc, explicit;
1219  long len, reallen;
1220  unsigned char *buf, *p;
1221  VALUE str;
1222 
1223  tn = NUM2INT(ossl_asn1_get_tag(self));
1224  tc = ossl_asn1_tag_class(self);
1225  explicit = ossl_asn1_is_explicit(self);
1226  asn1 = ossl_asn1_get_asn1type(self);
1227 
1228  len = ossl_asn1_object_size(1, ossl_i2d_ASN1_TYPE(asn1, NULL), tn);
1229  if(!(buf = OPENSSL_malloc(len))){
1230  ossl_ASN1_TYPE_free(asn1);
1231  ossl_raise(eASN1Error, "cannot alloc buffer");
1232  }
1233  p = buf;
1234  if (tc == V_ASN1_UNIVERSAL) {
1235  ossl_i2d_ASN1_TYPE(asn1, &p);
1236  } else if (explicit) {
1237  ossl_asn1_put_object(&p, 1, ossl_i2d_ASN1_TYPE(asn1, NULL), tn, tc);
1238  ossl_i2d_ASN1_TYPE(asn1, &p);
1239  } else {
1240  ossl_i2d_ASN1_TYPE(asn1, &p);
1241  *buf = tc | tn | (*buf & V_ASN1_CONSTRUCTED);
1242  }
1243  ossl_ASN1_TYPE_free(asn1);
1244  reallen = p - buf;
1245  assert(reallen <= len);
1246  str = ossl_buf2str((char *)buf, rb_long2int(reallen)); /* buf will be free in ossl_buf2str */
1247 
1248  return str;
1249 }
1250 
1251 /*
1252  * call-seq:
1253  * asn1.to_der => DER-encoded String
1254  *
1255  * See ASN1Data#to_der for details.
1256  */
1257 static VALUE
1259 {
1260  int tag, tn, tc, explicit, constructed = 1;
1261  int found_prim = 0, seq_len;
1262  long length;
1263  unsigned char *p;
1264  VALUE value, str, inf_length;
1265 
1266  tn = NUM2INT(ossl_asn1_get_tag(self));
1267  tc = ossl_asn1_tag_class(self);
1268  inf_length = ossl_asn1_get_infinite_length(self);
1269  if (inf_length == Qtrue) {
1270  VALUE ary, example;
1271  constructed = 2;
1272  if (CLASS_OF(self) == cASN1Sequence ||
1273  CLASS_OF(self) == cASN1Set) {
1274  tag = ossl_asn1_default_tag(self);
1275  }
1276  else { /* must be a constructive encoding of a primitive value */
1277  ary = ossl_asn1_get_value(self);
1278  if (!rb_obj_is_kind_of(ary, rb_cArray))
1279  ossl_raise(eASN1Error, "Constructive value must be an Array");
1280  /* Recursively descend until a primitive value is found.
1281  The overall value of the entire constructed encoding
1282  is of the type of the first primitive encoding to be
1283  found. */
1284  while (!found_prim){
1285  example = rb_ary_entry(ary, 0);
1286  if (rb_obj_is_kind_of(example, cASN1Primitive)){
1287  found_prim = 1;
1288  }
1289  else {
1290  /* example is another ASN1Constructive */
1291  if (!rb_obj_is_kind_of(example, cASN1Constructive)){
1292  ossl_raise(eASN1Error, "invalid constructed encoding");
1293  return Qnil; /* dummy */
1294  }
1295  ary = ossl_asn1_get_value(example);
1296  }
1297  }
1298  tag = ossl_asn1_default_tag(example);
1299  }
1300  }
1301  else {
1302  if (CLASS_OF(self) == cASN1Constructive)
1303  ossl_raise(eASN1Error, "Constructive shall only be used with infinite length");
1304  tag = ossl_asn1_default_tag(self);
1305  }
1306  explicit = ossl_asn1_is_explicit(self);
1307  value = join_der(ossl_asn1_get_value(self));
1308 
1309  seq_len = ossl_asn1_object_size(constructed, RSTRING_LENINT(value), tag);
1310  length = ossl_asn1_object_size(constructed, seq_len, tn);
1311  str = rb_str_new(0, length);
1312  p = (unsigned char *)RSTRING_PTR(str);
1313  if(tc == V_ASN1_UNIVERSAL)
1314  ossl_asn1_put_object(&p, constructed, RSTRING_LENINT(value), tn, tc);
1315  else{
1316  if(explicit){
1317  ossl_asn1_put_object(&p, constructed, seq_len, tn, tc);
1318  ossl_asn1_put_object(&p, constructed, RSTRING_LENINT(value), tag, V_ASN1_UNIVERSAL);
1319  }
1320  else{
1321  ossl_asn1_put_object(&p, constructed, RSTRING_LENINT(value), tn, tc);
1322  }
1323  }
1324  memcpy(p, RSTRING_PTR(value), RSTRING_LEN(value));
1325  p += RSTRING_LEN(value);
1326 
1327  /* In this case we need an additional EOC (one for the explicit part and
1328  * one for the Constructive itself. The EOC for the Constructive is
1329  * supplied by the user, but that for the "explicit wrapper" must be
1330  * added here.
1331  */
1332  if (explicit && inf_length == Qtrue) {
1333  ASN1_put_eoc(&p);
1334  }
1335  ossl_str_adjust(str, p);
1336 
1337  return str;
1338 }
1339 
1340 /*
1341  * call-seq:
1342  * asn1_ary.each { |asn1| block } => asn1_ary
1343  *
1344  * Calls <i>block</i> once for each element in +self+, passing that element
1345  * as parameter +asn1+. If no block is given, an enumerator is returned
1346  * instead.
1347  *
1348  * == Example
1349  * asn1_ary.each do |asn1|
1350  * puts asn1
1351  * end
1352  */
1353 static VALUE
1355 {
1357  return self;
1358 }
1359 
1360 static VALUE
1362 {
1363  StringValue(oid);
1364  StringValue(sn);
1365  StringValue(ln);
1366 
1367  if(!OBJ_create(RSTRING_PTR(oid), RSTRING_PTR(sn), RSTRING_PTR(ln)))
1368  ossl_raise(eASN1Error, NULL);
1369 
1370  return Qtrue;
1371 }
1372 
1373 static VALUE
1375 {
1376  VALUE val, ret = Qnil;
1377  int nid;
1378 
1379  val = ossl_asn1_get_value(self);
1380  if ((nid = OBJ_txt2nid(StringValuePtr(val))) != NID_undef)
1381  ret = rb_str_new2(OBJ_nid2sn(nid));
1382 
1383  return ret;
1384 }
1385 
1386 static VALUE
1388 {
1389  VALUE val, ret = Qnil;
1390  int nid;
1391 
1392  val = ossl_asn1_get_value(self);
1393  if ((nid = OBJ_txt2nid(StringValuePtr(val))) != NID_undef)
1394  ret = rb_str_new2(OBJ_nid2ln(nid));
1395 
1396  return ret;
1397 }
1398 
1399 static VALUE
1401 {
1402  VALUE val;
1403  ASN1_OBJECT *a1obj;
1404  char buf[128];
1405 
1406  val = ossl_asn1_get_value(self);
1407  a1obj = obj_to_asn1obj(val);
1408  OBJ_obj2txt(buf, sizeof(buf), a1obj, 1);
1409  ASN1_OBJECT_free(a1obj);
1410 
1411  return rb_str_new2(buf);
1412 }
1413 
1414 #define OSSL_ASN1_IMPL_FACTORY_METHOD(klass) \
1415 static VALUE ossl_asn1_##klass(int argc, VALUE *argv, VALUE self)\
1416 { return rb_funcall3(cASN1##klass, rb_intern("new"), argc, argv); }
1417 
1422 OSSL_ASN1_IMPL_FACTORY_METHOD(OctetString)
1424 OSSL_ASN1_IMPL_FACTORY_METHOD(NumericString)
1425 OSSL_ASN1_IMPL_FACTORY_METHOD(PrintableString)
1427 OSSL_ASN1_IMPL_FACTORY_METHOD(VideotexString)
1429 OSSL_ASN1_IMPL_FACTORY_METHOD(GraphicString)
1430 OSSL_ASN1_IMPL_FACTORY_METHOD(ISO64String)
1431 OSSL_ASN1_IMPL_FACTORY_METHOD(GeneralString)
1432 OSSL_ASN1_IMPL_FACTORY_METHOD(UniversalString)
1437 OSSL_ASN1_IMPL_FACTORY_METHOD(GeneralizedTime)
1440 OSSL_ASN1_IMPL_FACTORY_METHOD(EndOfContent)
1441 
1442 void
1444 {
1445  VALUE ary;
1446  int i;
1447 
1448 #if 0
1449  mOSSL = rb_define_module("OpenSSL"); /* let rdoc know about mOSSL */
1450 #endif
1451 
1452  sUNIVERSAL = rb_intern("UNIVERSAL");
1453  sCONTEXT_SPECIFIC = rb_intern("CONTEXT_SPECIFIC");
1454  sAPPLICATION = rb_intern("APPLICATION");
1455  sPRIVATE = rb_intern("PRIVATE");
1456  sEXPLICIT = rb_intern("EXPLICIT");
1457  sIMPLICIT = rb_intern("IMPLICIT");
1458 
1459  sivVALUE = rb_intern("@value");
1460  sivTAG = rb_intern("@tag");
1461  sivTAGGING = rb_intern("@tagging");
1462  sivTAG_CLASS = rb_intern("@tag_class");
1463  sivINFINITE_LENGTH = rb_intern("@infinite_length");
1464  sivUNUSED_BITS = rb_intern("@unused_bits");
1465 
1466  /*
1467  * Document-module: OpenSSL::ASN1
1468  *
1469  * Abstract Syntax Notation One (or ASN.1) is a notation syntax to
1470  * describe data structures and is defined in ITU-T X.680. ASN.1 itself
1471  * does not mandate any encoding or parsing rules, but usually ASN.1 data
1472  * structures are encoded using the Distinguished Encoding Rules (DER) or
1473  * less often the Basic Encoding Rules (BER) described in ITU-T X.690. DER
1474  * and BER encodings are binary Tag-Length-Value (TLV) encodings that are
1475  * quite concise compared to other popular data description formats such
1476  * as XML, JSON etc.
1477  * ASN.1 data structures are very common in cryptographic applications,
1478  * e.g. X.509 public key certificates or certificate revocation lists
1479  * (CRLs) are all defined in ASN.1 and DER-encoded. ASN.1, DER and BER are
1480  * the building blocks of applied cryptography.
1481  * The ASN1 module provides the necessary classes that allow generation
1482  * of ASN.1 data structures and the methods to encode them using a DER
1483  * encoding. The decode method allows parsing arbitrary BER-/DER-encoded
1484  * data to a Ruby object that can then be modified and re-encoded at will.
1485  *
1486  * == ASN.1 class hierarchy
1487  *
1488  * The base class representing ASN.1 structures is ASN1Data. ASN1Data offers
1489  * attributes to read and set the +tag+, the +tag_class+ and finally the
1490  * +value+ of a particular ASN.1 item. Upon parsing, any tagged values
1491  * (implicit or explicit) will be represented by ASN1Data instances because
1492  * their "real type" can only be determined using out-of-band information
1493  * from the ASN.1 type declaration. Since this information is normally
1494  * known when encoding a type, all sub-classes of ASN1Data offer an
1495  * additional attribute +tagging+ that allows to encode a value implicitly
1496  * (+:IMPLICIT+) or explicitly (+:EXPLICIT+).
1497  *
1498  * === Constructive
1499  *
1500  * Constructive is, as its name implies, the base class for all
1501  * constructed encodings, i.e. those that consist of several values,
1502  * opposed to "primitive" encodings with just one single value.
1503  * Primitive values that are encoded with "infinite length" are typically
1504  * constructed (their values come in multiple chunks) and are therefore
1505  * represented by instances of Constructive. The value of an Constructive
1506  * is always an Array.
1507  *
1508  * ==== ASN1::Set and ASN1::Sequence
1509  *
1510  * The most common constructive encodings are SETs and SEQUENCEs, which is
1511  * why there are two sub-classes of Constructive representing each of
1512  * them.
1513  *
1514  * === Primitive
1515  *
1516  * This is the super class of all primitive values. Primitive
1517  * itself is not used when parsing ASN.1 data, all values are either
1518  * instances of a corresponding sub-class of Primitive or they are
1519  * instances of ASN1Data if the value was tagged implicitly or explicitly.
1520  * Please cf. Primitive documentation for details on sub-classes and
1521  * their respective mappings of ASN.1 data types to Ruby objects.
1522  *
1523  * == Possible values for +tagging+
1524  *
1525  * When constructing an ASN1Data object the ASN.1 type definition may
1526  * require certain elements to be either implicitly or explicitly tagged.
1527  * This can be achieved by setting the +tagging+ attribute manually for
1528  * sub-classes of ASN1Data. Use the symbol +:IMPLICIT+ for implicit
1529  * tagging and +:EXPLICIT+ if the element requires explicit tagging.
1530  *
1531  * == Possible values for +tag_class+
1532  *
1533  * It is possible to create arbitrary ASN1Data objects that also support
1534  * a PRIVATE or APPLICATION tag class. Possible values for the +tag_class+
1535  * attribute are:
1536  * * +:UNIVERSAL+ (the default for untagged values)
1537  * * +:CONTEXT_SPECIFIC+ (the default for tagged values)
1538  * * +:APPLICATION+
1539  * * +:PRIVATE+
1540  *
1541  * == Tag constants
1542  *
1543  * There is a constant defined for each universal tag:
1544  * * OpenSSL::ASN1::EOC (0)
1545  * * OpenSSL::ASN1::BOOLEAN (1)
1546  * * OpenSSL::ASN1::INTEGER (2)
1547  * * OpenSSL::ASN1::BIT_STRING (3)
1548  * * OpenSSL::ASN1::OCTET_STRING (4)
1549  * * OpenSSL::ASN1::NULL (5)
1550  * * OpenSSL::ASN1::OBJECT (6)
1551  * * OpenSSL::ASN1::ENUMERATED (10)
1552  * * OpenSSL::ASN1::UTF8STRING (12)
1553  * * OpenSSL::ASN1::SEQUENCE (16)
1554  * * OpenSSL::ASN1::SET (17)
1555  * * OpenSSL::ASN1::NUMERICSTRING (18)
1556  * * OpenSSL::ASN1::PRINTABLESTRING (19)
1557  * * OpenSSL::ASN1::T61STRING (20)
1558  * * OpenSSL::ASN1::VIDEOTEXSTRING (21)
1559  * * OpenSSL::ASN1::IA5STRING (22)
1560  * * OpenSSL::ASN1::UTCTIME (23)
1561  * * OpenSSL::ASN1::GENERALIZEDTIME (24)
1562  * * OpenSSL::ASN1::GRAPHICSTRING (25)
1563  * * OpenSSL::ASN1::ISO64STRING (26)
1564  * * OpenSSL::ASN1::GENERALSTRING (27)
1565  * * OpenSSL::ASN1::UNIVERSALSTRING (28)
1566  * * OpenSSL::ASN1::BMPSTRING (30)
1567  *
1568  * == UNIVERSAL_TAG_NAME constant
1569  *
1570  * An Array that stores the name of a given tag number. These names are
1571  * the same as the name of the tag constant that is additionally defined,
1572  * e.g. UNIVERSAL_TAG_NAME[2] = "INTEGER" and OpenSSL::ASN1::INTEGER = 2.
1573  *
1574  * == Example usage
1575  *
1576  * === Decoding and viewing a DER-encoded file
1577  * require 'openssl'
1578  * require 'pp'
1579  * der = File.binread('data.der')
1580  * asn1 = OpenSSL::ASN1.decode(der)
1581  * pp der
1582  *
1583  * === Creating an ASN.1 structure and DER-encoding it
1584  * require 'openssl'
1585  * version = OpenSSL::ASN1::Integer.new(1)
1586  * # Explicitly 0-tagged implies context-specific tag class
1587  * serial = OpenSSL::ASN1::Integer.new(12345, 0, :EXPLICIT, :CONTEXT_SPECIFIC)
1588  * name = OpenSSL::ASN1::PrintableString.new('Data 1')
1589  * sequence = OpenSSL::ASN1::Sequence.new( [ version, serial, name ] )
1590  * der = sequence.to_der
1591  */
1592  mASN1 = rb_define_module_under(mOSSL, "ASN1");
1593 
1594  /* Document-class: OpenSSL::ASN1::ASN1Error
1595  *
1596  * Generic error class for all errors raised in ASN1 and any of the
1597  * classes defined in it.
1598  */
1599  eASN1Error = rb_define_class_under(mASN1, "ASN1Error", eOSSLError);
1600  rb_define_module_function(mASN1, "traverse", ossl_asn1_traverse, 1);
1601  rb_define_module_function(mASN1, "decode", ossl_asn1_decode, 1);
1602  rb_define_module_function(mASN1, "decode_all", ossl_asn1_decode_all, 1);
1603  ary = rb_ary_new();
1604 
1605  /*
1606  * Array storing tag names at the tag's index.
1607  */
1608  rb_define_const(mASN1, "UNIVERSAL_TAG_NAME", ary);
1609  for(i = 0; i < ossl_asn1_info_size; i++){
1610  if(ossl_asn1_info[i].name[0] == '[') continue;
1611  rb_define_const(mASN1, ossl_asn1_info[i].name, INT2NUM(i));
1612  rb_ary_store(ary, i, rb_str_new2(ossl_asn1_info[i].name));
1613  }
1614 
1615  /* Document-class: OpenSSL::ASN1::ASN1Data
1616  *
1617  * The top-level class representing any ASN.1 object. When parsed by
1618  * ASN1.decode, tagged values are always represented by an instance
1619  * of ASN1Data.
1620  *
1621  * == The role of ASN1Data for parsing tagged values
1622  *
1623  * When encoding an ASN.1 type it is inherently clear what original
1624  * type (e.g. INTEGER, OCTET STRING etc.) this value has, regardless
1625  * of its tagging.
1626  * But opposed to the time an ASN.1 type is to be encoded, when parsing
1627  * them it is not possible to deduce the "real type" of tagged
1628  * values. This is why tagged values are generally parsed into ASN1Data
1629  * instances, but with a different outcome for implicit and explicit
1630  * tagging.
1631  *
1632  * === Example of a parsed implicitly tagged value
1633  *
1634  * An implicitly 1-tagged INTEGER value will be parsed as an
1635  * ASN1Data with
1636  * * +tag+ equal to 1
1637  * * +tag_class+ equal to +:CONTEXT_SPECIFIC+
1638  * * +value+ equal to a +String+ that carries the raw encoding
1639  * of the INTEGER.
1640  * This implies that a subsequent decoding step is required to
1641  * completely decode implicitly tagged values.
1642  *
1643  * === Example of a parsed explicitly tagged value
1644  *
1645  * An explicitly 1-tagged INTEGER value will be parsed as an
1646  * ASN1Data with
1647  * * +tag+ equal to 1
1648  * * +tag_class+ equal to +:CONTEXT_SPECIFIC+
1649  * * +value+ equal to an +Array+ with one single element, an
1650  * instance of OpenSSL::ASN1::Integer, i.e. the inner element
1651  * is the non-tagged primitive value, and the tagging is represented
1652  * in the outer ASN1Data
1653  *
1654  * == Example - Decoding an implicitly tagged INTEGER
1655  * int = OpenSSL::ASN1::Integer.new(1, 0, :IMPLICIT) # implicit 0-tagged
1656  * seq = OpenSSL::ASN1::Sequence.new( [int] )
1657  * der = seq.to_der
1658  * asn1 = OpenSSL::ASN1.decode(der)
1659  * # pp asn1 => #<OpenSSL::ASN1::Sequence:0x87326e0
1660  * # @infinite_length=false,
1661  * # @tag=16,
1662  * # @tag_class=:UNIVERSAL,
1663  * # @tagging=nil,
1664  * # @value=
1665  * # [#<OpenSSL::ASN1::ASN1Data:0x87326f4
1666  * # @infinite_length=false,
1667  * # @tag=0,
1668  * # @tag_class=:CONTEXT_SPECIFIC,
1669  * # @value="\x01">]>
1670  * raw_int = asn1.value[0]
1671  * # manually rewrite tag and tag class to make it an UNIVERSAL value
1672  * raw_int.tag = OpenSSL::ASN1::INTEGER
1673  * raw_int.tag_class = :UNIVERSAL
1674  * int2 = OpenSSL::ASN1.decode(raw_int)
1675  * puts int2.value # => 1
1676  *
1677  * == Example - Decoding an explicitly tagged INTEGER
1678  * int = OpenSSL::ASN1::Integer.new(1, 0, :EXPLICIT) # explicit 0-tagged
1679  * seq = OpenSSL::ASN1::Sequence.new( [int] )
1680  * der = seq.to_der
1681  * asn1 = OpenSSL::ASN1.decode(der)
1682  * # pp asn1 => #<OpenSSL::ASN1::Sequence:0x87326e0
1683  * # @infinite_length=false,
1684  * # @tag=16,
1685  * # @tag_class=:UNIVERSAL,
1686  * # @tagging=nil,
1687  * # @value=
1688  * # [#<OpenSSL::ASN1::ASN1Data:0x87326f4
1689  * # @infinite_length=false,
1690  * # @tag=0,
1691  * # @tag_class=:CONTEXT_SPECIFIC,
1692  * # @value=
1693  * # [#<OpenSSL::ASN1::Integer:0x85bf308
1694  * # @infinite_length=false,
1695  * # @tag=2,
1696  * # @tag_class=:UNIVERSAL
1697  * # @tagging=nil,
1698  * # @value=1>]>]>
1699  * int2 = asn1.value[0].value[0]
1700  * puts int2.value # => 1
1701  */
1702  cASN1Data = rb_define_class_under(mASN1, "ASN1Data", rb_cObject);
1703  /*
1704  * Carries the value of a ASN.1 type.
1705  * Please confer Constructive and Primitive for the mappings between
1706  * ASN.1 data types and Ruby classes.
1707  */
1708  rb_attr(cASN1Data, rb_intern("value"), 1, 1, 0);
1709  /*
1710  * A +Number+ representing the tag number of this ASN1Data. Never +nil+.
1711  */
1712  rb_attr(cASN1Data, rb_intern("tag"), 1, 1, 0);
1713  /*
1714  * A +Symbol+ representing the tag class of this ASN1Data. Never +nil+.
1715  * See ASN1Data for possible values.
1716  */
1717  rb_attr(cASN1Data, rb_intern("tag_class"), 1, 1, 0);
1718  /*
1719  * Never +nil+. A +Boolean+ indicating whether the encoding was infinite
1720  * length (in the case of parsing) or whether an infinite length encoding
1721  * shall be used (in the encoding case).
1722  * In DER, every value has a finite length associated with it. But in
1723  * scenarios where large amounts of data need to be transferred it
1724  * might be desirable to have some kind of streaming support available.
1725  * For example, huge OCTET STRINGs are preferably sent in smaller-sized
1726  * chunks, each at a time.
1727  * This is possible in BER by setting the length bytes of an encoding
1728  * to zero and by this indicating that the following value will be
1729  * sent in chunks. Infinite length encodings are always constructed.
1730  * The end of such a stream of chunks is indicated by sending a EOC
1731  * (End of Content) tag. SETs and SEQUENCEs may use an infinite length
1732  * encoding, but also primitive types such as e.g. OCTET STRINGS or
1733  * BIT STRINGS may leverage this functionality (cf. ITU-T X.690).
1734  */
1735  rb_attr(cASN1Data, rb_intern("infinite_length"), 1, 1, 0);
1736  rb_define_method(cASN1Data, "initialize", ossl_asn1data_initialize, 3);
1737  rb_define_method(cASN1Data, "to_der", ossl_asn1data_to_der, 0);
1738 
1739  /* Document-class: OpenSSL::ASN1::Primitive
1740  *
1741  * The parent class for all primitive encodings. Attributes are the same as
1742  * for ASN1Data, with the addition of +tagging+.
1743  * Primitive values can never be infinite length encodings, thus it is not
1744  * possible to set the +infinite_length+ attribute for Primitive and its
1745  * sub-classes.
1746  *
1747  * == Primitive sub-classes and their mapping to Ruby classes
1748  * * OpenSSL::ASN1::EndOfContent <=> +value+ is always +nil+
1749  * * OpenSSL::ASN1::Boolean <=> +value+ is a +Boolean+
1750  * * OpenSSL::ASN1::Integer <=> +value+ is a +Number+
1751  * * OpenSSL::ASN1::BitString <=> +value+ is a +String+
1752  * * OpenSSL::ASN1::OctetString <=> +value+ is a +String+
1753  * * OpenSSL::ASN1::Null <=> +value+ is always +nil+
1754  * * OpenSSL::ASN1::Object <=> +value+ is a +String+
1755  * * OpenSSL::ASN1::Enumerated <=> +value+ is a +Number+
1756  * * OpenSSL::ASN1::UTF8String <=> +value+ is a +String+
1757  * * OpenSSL::ASN1::NumericString <=> +value+ is a +String+
1758  * * OpenSSL::ASN1::PrintableString <=> +value+ is a +String+
1759  * * OpenSSL::ASN1::T61String <=> +value+ is a +String+
1760  * * OpenSSL::ASN1::VideotexString <=> +value+ is a +String+
1761  * * OpenSSL::ASN1::IA5String <=> +value+ is a +String+
1762  * * OpenSSL::ASN1::UTCTime <=> +value+ is a +Time+
1763  * * OpenSSL::ASN1::GeneralizedTime <=> +value+ is a +Time+
1764  * * OpenSSL::ASN1::GraphicString <=> +value+ is a +String+
1765  * * OpenSSL::ASN1::ISO64String <=> +value+ is a +String+
1766  * * OpenSSL::ASN1::GeneralString <=> +value+ is a +String+
1767  * * OpenSSL::ASN1::UniversalString <=> +value+ is a +String+
1768  * * OpenSSL::ASN1::BMPString <=> +value+ is a +String+
1769  *
1770  * == OpenSSL::ASN1::BitString
1771  *
1772  * === Additional attributes
1773  * +unused_bits+: if the underlying BIT STRING's
1774  * length is a multiple of 8 then +unused_bits+ is 0. Otherwise
1775  * +unused_bits+ indicates the number of bits that are to be ignored in
1776  * the final octet of the +BitString+'s +value+.
1777  *
1778  * == OpenSSL::ASN1::ObjectId
1779  *
1780  * === Additional attributes
1781  * * +sn+: the short name as defined in <openssl/objects.h>.
1782  * * +ln+: the long name as defined in <openssl/objects.h>.
1783  * * +oid+: the object identifier as a +String+, e.g. "1.2.3.4.5"
1784  * * +short_name+: alias for +sn+.
1785  * * +long_name+: alias for +ln+.
1786  *
1787  * == Examples
1788  * With the Exception of OpenSSL::ASN1::EndOfContent, each Primitive class
1789  * constructor takes at least one parameter, the +value+.
1790  *
1791  * === Creating EndOfContent
1792  * eoc = OpenSSL::ASN1::EndOfContent.new
1793  *
1794  * === Creating any other Primitive
1795  * prim = <class>.new(value) # <class> being one of the sub-classes except EndOfContent
1796  * prim_zero_tagged_implicit = <class>.new(value, 0, :IMPLICIT)
1797  * prim_zero_tagged_explicit = <class>.new(value, 0, :EXPLICIT)
1798  */
1799  cASN1Primitive = rb_define_class_under(mASN1, "Primitive", cASN1Data);
1800  /*
1801  * May be used as a hint for encoding a value either implicitly or
1802  * explicitly by setting it either to +:IMPLICIT+ or to +:EXPLICIT+.
1803  * +tagging+ is not set when a ASN.1 structure is parsed using
1804  * OpenSSL::ASN1.decode.
1805  */
1806  rb_attr(cASN1Primitive, rb_intern("tagging"), 1, 1, Qtrue);
1807  rb_undef_method(cASN1Primitive, "infinite_length=");
1808  rb_define_method(cASN1Primitive, "initialize", ossl_asn1_initialize, -1);
1809  rb_define_method(cASN1Primitive, "to_der", ossl_asn1prim_to_der, 0);
1810 
1811  /* Document-class: OpenSSL::ASN1::Constructive
1812  *
1813  * The parent class for all constructed encodings. The +value+ attribute
1814  * of a Constructive is always an +Array+. Attributes are the same as
1815  * for ASN1Data, with the addition of +tagging+.
1816  *
1817  * == SET and SEQUENCE
1818  *
1819  * Most constructed encodings come in the form of a SET or a SEQUENCE.
1820  * These encodings are represented by one of the two sub-classes of
1821  * Constructive:
1822  * * OpenSSL::ASN1::Set
1823  * * OpenSSL::ASN1::Sequence
1824  * Please note that tagged sequences and sets are still parsed as
1825  * instances of ASN1Data. Find further details on tagged values
1826  * there.
1827  *
1828  * === Example - constructing a SEQUENCE
1829  * int = OpenSSL::ASN1::Integer.new(1)
1830  * str = OpenSSL::ASN1::PrintableString.new('abc')
1831  * sequence = OpenSSL::ASN1::Sequence.new( [ int, str ] )
1832  *
1833  * === Example - constructing a SET
1834  * int = OpenSSL::ASN1::Integer.new(1)
1835  * str = OpenSSL::ASN1::PrintableString.new('abc')
1836  * set = OpenSSL::ASN1::Set.new( [ int, str ] )
1837  *
1838  * == Infinite length primitive values
1839  *
1840  * The only case where Constructive is used directly is for infinite
1841  * length encodings of primitive values. These encodings are always
1842  * constructed, with the contents of the +value+ +Array+ being either
1843  * UNIVERSAL non-infinite length partial encodings of the actual value
1844  * or again constructive encodings with infinite length (i.e. infinite
1845  * length primitive encodings may be constructed recursively with another
1846  * infinite length value within an already infinite length value). Each
1847  * partial encoding must be of the same UNIVERSAL type as the overall
1848  * encoding. The value of the overall encoding consists of the
1849  * concatenation of each partial encoding taken in sequence. The +value+
1850  * array of the outer infinite length value must end with a
1851  * OpenSSL::ASN1::EndOfContent instance.
1852  *
1853  * Please note that it is not possible to encode Constructive without
1854  * the +infinite_length+ attribute being set to +true+, use
1855  * OpenSSL::ASN1::Sequence or OpenSSL::ASN1::Set in these cases instead.
1856  *
1857  * === Example - Infinite length OCTET STRING
1858  * partial1 = OpenSSL::ASN1::OctetString.new("\x01")
1859  * partial2 = OpenSSL::ASN1::OctetString.new("\x02")
1860  * inf_octets = OpenSSL::ASN1::Constructive.new( [ partial1,
1861  * partial2,
1862  * OpenSSL::ASN1::EndOfContent.new ],
1863  * OpenSSL::ASN1::OCTET_STRING,
1864  * nil,
1865  * :UNIVERSAL )
1866  * # The real value of inf_octets is "\x01\x02", i.e. the concatenation
1867  * # of partial1 and partial2
1868  * inf_octets.infinite_length = true
1869  * der = inf_octets.to_der
1870  * asn1 = OpenSSL::ASN1.decode(der)
1871  * puts asn1.infinite_length # => true
1872  */
1873  cASN1Constructive = rb_define_class_under(mASN1,"Constructive", cASN1Data);
1874  rb_include_module(cASN1Constructive, rb_mEnumerable);
1875  /*
1876  * May be used as a hint for encoding a value either implicitly or
1877  * explicitly by setting it either to +:IMPLICIT+ or to +:EXPLICIT+.
1878  * +tagging+ is not set when a ASN.1 structure is parsed using
1879  * OpenSSL::ASN1.decode.
1880  */
1881  rb_attr(cASN1Constructive, rb_intern("tagging"), 1, 1, Qtrue);
1882  rb_define_method(cASN1Constructive, "initialize", ossl_asn1_initialize, -1);
1883  rb_define_method(cASN1Constructive, "to_der", ossl_asn1cons_to_der, 0);
1884  rb_define_method(cASN1Constructive, "each", ossl_asn1cons_each, 0);
1885 
1886 #define OSSL_ASN1_DEFINE_CLASS(name, super) \
1887 do{\
1888  cASN1##name = rb_define_class_under(mASN1, #name, cASN1##super);\
1889  rb_define_module_function(mASN1, #name, ossl_asn1_##name, -1);\
1890 }while(0)
1891 
1892  OSSL_ASN1_DEFINE_CLASS(Boolean, Primitive);
1893  OSSL_ASN1_DEFINE_CLASS(Integer, Primitive);
1894  OSSL_ASN1_DEFINE_CLASS(Enumerated, Primitive);
1895  OSSL_ASN1_DEFINE_CLASS(BitString, Primitive);
1896  OSSL_ASN1_DEFINE_CLASS(OctetString, Primitive);
1897  OSSL_ASN1_DEFINE_CLASS(UTF8String, Primitive);
1898  OSSL_ASN1_DEFINE_CLASS(NumericString, Primitive);
1899  OSSL_ASN1_DEFINE_CLASS(PrintableString, Primitive);
1900  OSSL_ASN1_DEFINE_CLASS(T61String, Primitive);
1901  OSSL_ASN1_DEFINE_CLASS(VideotexString, Primitive);
1902  OSSL_ASN1_DEFINE_CLASS(IA5String, Primitive);
1903  OSSL_ASN1_DEFINE_CLASS(GraphicString, Primitive);
1904  OSSL_ASN1_DEFINE_CLASS(ISO64String, Primitive);
1905  OSSL_ASN1_DEFINE_CLASS(GeneralString, Primitive);
1906  OSSL_ASN1_DEFINE_CLASS(UniversalString, Primitive);
1907  OSSL_ASN1_DEFINE_CLASS(BMPString, Primitive);
1908  OSSL_ASN1_DEFINE_CLASS(Null, Primitive);
1909  OSSL_ASN1_DEFINE_CLASS(ObjectId, Primitive);
1910  OSSL_ASN1_DEFINE_CLASS(UTCTime, Primitive);
1911  OSSL_ASN1_DEFINE_CLASS(GeneralizedTime, Primitive);
1912 
1913  OSSL_ASN1_DEFINE_CLASS(Sequence, Constructive);
1914  OSSL_ASN1_DEFINE_CLASS(Set, Constructive);
1915 
1916  OSSL_ASN1_DEFINE_CLASS(EndOfContent, Data);
1917 
1918 
1919 #if 0
1920  cASN1ObjectId = rb_define_class_under(mASN1, "ObjectId", cASN1Primitive); /* let rdoc know */
1921 #endif
1922  rb_define_singleton_method(cASN1ObjectId, "register", ossl_asn1obj_s_register, 3);
1923  rb_define_method(cASN1ObjectId, "sn", ossl_asn1obj_get_sn, 0);
1924  rb_define_method(cASN1ObjectId, "ln", ossl_asn1obj_get_ln, 0);
1925  rb_define_method(cASN1ObjectId, "oid", ossl_asn1obj_get_oid, 0);
1926  rb_define_alias(cASN1ObjectId, "short_name", "sn");
1927  rb_define_alias(cASN1ObjectId, "long_name", "ln");
1928  rb_attr(cASN1BitString, rb_intern("unused_bits"), 1, 1, 0);
1929 
1930  rb_define_method(cASN1EndOfContent, "initialize", ossl_asn1eoc_initialize, 0);
1931 
1932  class_tag_map = rb_hash_new();
1933  rb_hash_aset(class_tag_map, cASN1EndOfContent, INT2NUM(V_ASN1_EOC));
1934  rb_hash_aset(class_tag_map, cASN1Boolean, INT2NUM(V_ASN1_BOOLEAN));
1935  rb_hash_aset(class_tag_map, cASN1Integer, INT2NUM(V_ASN1_INTEGER));
1936  rb_hash_aset(class_tag_map, cASN1BitString, INT2NUM(V_ASN1_BIT_STRING));
1937  rb_hash_aset(class_tag_map, cASN1OctetString, INT2NUM(V_ASN1_OCTET_STRING));
1938  rb_hash_aset(class_tag_map, cASN1Null, INT2NUM(V_ASN1_NULL));
1939  rb_hash_aset(class_tag_map, cASN1ObjectId, INT2NUM(V_ASN1_OBJECT));
1940  rb_hash_aset(class_tag_map, cASN1Enumerated, INT2NUM(V_ASN1_ENUMERATED));
1941  rb_hash_aset(class_tag_map, cASN1UTF8String, INT2NUM(V_ASN1_UTF8STRING));
1942  rb_hash_aset(class_tag_map, cASN1Sequence, INT2NUM(V_ASN1_SEQUENCE));
1943  rb_hash_aset(class_tag_map, cASN1Set, INT2NUM(V_ASN1_SET));
1944  rb_hash_aset(class_tag_map, cASN1NumericString, INT2NUM(V_ASN1_NUMERICSTRING));
1945  rb_hash_aset(class_tag_map, cASN1PrintableString, INT2NUM(V_ASN1_PRINTABLESTRING));
1946  rb_hash_aset(class_tag_map, cASN1T61String, INT2NUM(V_ASN1_T61STRING));
1947  rb_hash_aset(class_tag_map, cASN1VideotexString, INT2NUM(V_ASN1_VIDEOTEXSTRING));
1948  rb_hash_aset(class_tag_map, cASN1IA5String, INT2NUM(V_ASN1_IA5STRING));
1949  rb_hash_aset(class_tag_map, cASN1UTCTime, INT2NUM(V_ASN1_UTCTIME));
1950  rb_hash_aset(class_tag_map, cASN1GeneralizedTime, INT2NUM(V_ASN1_GENERALIZEDTIME));
1951  rb_hash_aset(class_tag_map, cASN1GraphicString, INT2NUM(V_ASN1_GRAPHICSTRING));
1952  rb_hash_aset(class_tag_map, cASN1ISO64String, INT2NUM(V_ASN1_ISO64STRING));
1953  rb_hash_aset(class_tag_map, cASN1GeneralString, INT2NUM(V_ASN1_GENERALSTRING));
1954  rb_hash_aset(class_tag_map, cASN1UniversalString, INT2NUM(V_ASN1_UNIVERSALSTRING));
1955  rb_hash_aset(class_tag_map, cASN1BMPString, INT2NUM(V_ASN1_BMPSTRING));
1956  rb_global_variable(&class_tag_map);
1957 }
VALUE mOSSL
Definition: ossl.c:259
static int ossl_i2d_ASN1_TYPE(ASN1_TYPE *a, unsigned char **pp)
Definition: ossl_asn1.c:1185
VALUE cASN1Data
Definition: ossl_asn1.c:192
static VALUE decode_enum(unsigned char *der, long length)
Definition: ossl_asn1.c:402
VALUE rb_ary_entry(VALUE ary, long offset)
Definition: array.c:1088
#define ossl_asn1_get_tagging(o)
Definition: ossl_asn1.c:179
#define rb_hash_lookup
Definition: tcltklib.c:268
#define INT2NUM(x)
Definition: ruby.h:1178
int i
Definition: win32ole.c:784
VALUE cASN1ISO64String
Definition: ossl_asn1.c:204
VALUE rb_String(VALUE)
Definition: object.c:2791
static ASN1_NULL * obj_to_asn1null(VALUE obj)
Definition: ossl_asn1.c:280
static ID sIMPLICIT
Definition: ossl_asn1.c:211
#define NUM2INT(x)
Definition: ruby.h:622
int count
Definition: encoding.c:51
static VALUE int_ossl_asn1_decode0_cons(unsigned char **pp, long max_len, long length, long *offset, int depth, int yield, int j, int tag, VALUE tc, long *num_read)
Definition: ossl_asn1.c:868
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1497
static ID sAPPLICATION
Definition: ossl_asn1.c:212
#define CLASS_OF(v)
Definition: ruby.h:448
static ossl_asn1_info_t ossl_asn1_info[]
Definition: ossl_asn1.c:498
VALUE cASN1IA5String
Definition: ossl_asn1.c:203
#define ossl_asn1_put_object(pp, cons, len, tag, xc)
Definition: ossl_asn1.c:222
#define Qtrue
Definition: ruby.h:434
static VALUE ossl_asn1obj_get_oid(VALUE self)
Definition: ossl_asn1.c:1400
#define ossl_str_adjust(str, p)
Definition: ossl.h:138
VALUE rb_ary_each(VALUE array)
Definition: array.c:1658
VALUE cASN1Constructive
Definition: ossl_asn1.c:194
VALUE cASN1PrintableString
Definition: ossl_asn1.c:201
long tv_sec
Definition: ossl_asn1.c:17
VALUE mASN1
Definition: ossl_asn1.c:189
VALUE rb_eTypeError
Definition: error.c:516
static ASN1_UTCTIME * obj_to_asn1utime(VALUE time)
Definition: ossl_asn1.c:306
static VALUE ossl_asn1obj_s_register(VALUE self, VALUE oid, VALUE sn, VALUE ln)
Definition: ossl_asn1.c:1361
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:822
#define rb_long2int(n)
Definition: ruby.h:325
VALUE rb_str_new4(VALUE)
#define SYM2ID(x)
Definition: ruby.h:364
static VALUE ossl_asn1data_to_der(VALUE self)
Definition: ossl_asn1.c:762
VALUE asn1str_to_str(ASN1_STRING *str)
Definition: ossl_asn1.c:94
VALUE rb_protect(VALUE(*proc)(VALUE), VALUE data, int *state)
Definition: eval.c:771
VALUE cASN1BMPString
Definition: ossl_asn1.c:205
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:534
#define ossl_asn1_set_value(o, v)
Definition: ossl_asn1.c:183
VALUE rb_obj_is_kind_of(VALUE, VALUE)
Definition: object.c:593
static VALUE ossl_asn1data_initialize(VALUE self, VALUE value, VALUE tag, VALUE tag_class)
Definition: ossl_asn1.c:721
void rb_include_module(VALUE klass, VALUE module)
Definition: class.c:684
VALUE asn1time_to_time(ASN1_TIME *time)
Definition: ossl_asn1.c:32
VALUE rb_block_call(VALUE, ID, int, VALUE *, VALUE(*)(ANYARGS), VALUE)
Definition: vm_eval.c:1120
#define ossl_asn1_get_tag_class(o)
Definition: ossl_asn1.c:180
VALUE ossl_membio2str(BIO *bio)
Definition: ossl_bio.c:77
static ASN1_INTEGER * obj_to_asn1int(VALUE obj)
Definition: ossl_asn1.c:245
static VALUE decode_bstr(unsigned char *der, long length, long *unused_bits)
Definition: ossl_asn1.c:381
static VALUE ossl_asn1obj_get_ln(VALUE self)
Definition: ossl_asn1.c:1387
void rb_undef_method(VALUE klass, const char *name)
Definition: class.c:1362
#define ossl_asn1_set_tagging(o, v)
Definition: ossl_asn1.c:185
static VALUE join_der_i(VALUE i, VALUE str)
Definition: ossl_asn1.c:736
VALUE cASN1Null
Definition: ossl_asn1.c:206
VALUE cASN1OctetString
Definition: ossl_asn1.c:200
time_t time_to_time_t(VALUE time)
Definition: ossl_asn1.c:85
Win32OLEIDispatch * p
Definition: win32ole.c:786
void rb_global_variable(VALUE *var)
Definition: gc.c:426
VALUE cASN1BitString
Definition: ossl_asn1.c:199
static ID sPRIVATE
Definition: ossl_asn1.c:212
int args
Definition: win32ole.c:785
static ID sUNIVERSAL
Definition: ossl_asn1.c:212
static void int_ossl_decode_sanity_check(long len, long read, long offset)
Definition: ossl_asn1.c:997
VALUE ossl_to_der_if_possible(VALUE obj)
Definition: ossl.c:283
static ID sivVALUE
Definition: ossl_asn1.c:213
#define val
VALUE cASN1UniversalString
Definition: ossl_asn1.c:205
long tv_usec
Definition: ossl_asn1.c:18
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1426
void Init_ossl_asn1()
Definition: ossl_asn1.c:1443
void rb_attr(VALUE, ID, int, int, int)
Definition: vm_method.c:824
#define OSSL_ASN1_DEFINE_CLASS(name, super)
VALUE cASN1Boolean
Definition: ossl_asn1.c:197
VALUE rb_ary_new(void)
Definition: array.c:424
static ID sivTAGGING
Definition: ossl_asn1.c:213
VALUE cASN1ObjectId
Definition: ossl_asn1.c:207
#define NIL_P(v)
Definition: ruby.h:446
static VALUE ossl_asn1_traverse(VALUE self, VALUE obj)
Definition: ossl_asn1.c:1028
#define OSSL_ASN1_IMPL_FACTORY_METHOD(klass)
Definition: ossl_asn1.c:1414
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2204
void rb_ary_store(VALUE ary, long idx, VALUE val)
Definition: array.c:719
VALUE eOSSLError
Definition: ossl.c:264
int argc
Definition: ruby.c:130
#define Qfalse
Definition: ruby.h:433
VALUE rb_Integer(VALUE)
Definition: object.c:2539
static ID sivINFINITE_LENGTH
Definition: ossl_asn1.c:213
static VALUE ossl_asn1_decode(VALUE self, VALUE obj)
Definition: ossl_asn1.c:1056
static int ossl_asn1_tag(VALUE obj)
Definition: ossl_asn1.c:634
VALUE rb_obj_alloc(VALUE)
Definition: object.c:1740
VALUE rb_class_superclass(VALUE)
Definition: object.c:1824
static ASN1_STRING * obj_to_asn1str(VALUE obj)
Definition: ossl_asn1.c:267
ASN1_TYPE * ossl_asn1_get_asn1type(VALUE obj)
Definition: ossl_asn1.c:539
int ossl_asn1_info_size
Definition: ossl_asn1.c:532
VALUE cASN1Set
Definition: ossl_asn1.c:209
static VALUE decode_obj(unsigned char *der, long length)
Definition: ossl_asn1.c:435
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:1539
#define RSTRING_LEN(str)
Definition: ruby.h:862
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1512
#define ossl_asn1_set_tag(o, v)
Definition: ossl_asn1.c:184
VALUE rb_yield(VALUE)
Definition: vm_eval.c:933
static ID sivTAG
Definition: ossl_asn1.c:213
VALUE rb_funcall2(VALUE, ID, int, const VALUE *)
Calls a method.
Definition: vm_eval.c:804
VALUE rb_mEnumerable
Definition: enum.c:20
static VALUE ossl_asn1cons_each(VALUE self)
Definition: ossl_asn1.c:1354
static ID sCONTEXT_SPECIFIC
Definition: ossl_asn1.c:212
static VALUE decode_int(unsigned char *der, long length)
Definition: ossl_asn1.c:362
VALUE rb_hash_new(void)
Definition: hash.c:234
static VALUE class_tag_map
Definition: ossl_asn1.c:534
static void ossl_ASN1_TYPE_free(ASN1_TYPE *a)
Definition: ossl_asn1.c:1196
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1570
VALUE cASN1UTF8String
Definition: ossl_asn1.c:200
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1128
static VALUE ossl_asn1_decode0(unsigned char **pp, long length, long *offset, int depth, int yield, long *num_read)
Definition: ossl_asn1.c:934
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4308
#define PRIsVALUE
Definition: ruby.h:147
unsigned long ID
Definition: ruby.h:105
static ASN1_OBJECT * obj_to_asn1obj(VALUE obj)
Definition: ossl_asn1.c:293
static VALUE ossl_asn1_initialize(int argc, VALUE *argv, VALUE self)
Definition: ossl_asn1.c:1134
#define Qnil
Definition: ruby.h:435
VALUE cASN1GraphicString
Definition: ossl_asn1.c:203
unsigned long VALUE
Definition: ruby.h:104
static VALUE join_der(VALUE enumerable)
Definition: ossl_asn1.c:745
VALUE cBN
Definition: ossl_bn.c:36
#define ossl_asn1_set_tag_class(o, v)
Definition: ossl_asn1.c:186
static ASN1_STRING * obj_to_asn1derstr(VALUE obj)
Definition: ossl_asn1.c:332
static int ossl_asn1_default_tag(VALUE obj)
Definition: ossl_asn1.c:615
void rb_jump_tag(int tag)
Definition: eval.c:666
static int ossl_asn1_tag_class(VALUE obj)
Definition: ossl_asn1.c:667
VALUE cASN1Integer
Definition: ossl_asn1.c:198
#define _(args)
Definition: dln.h:28
#define LONG2NUM(x)
Definition: ruby.h:1199
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:626
VALUE cASN1Primitive
Definition: ossl_asn1.c:193
#define RSTRING_PTR(str)
Definition: ruby.h:866
VALUE cASN1T61String
Definition: ossl_asn1.c:202
static VALUE ossl_asn1prim_to_der(VALUE self)
Definition: ossl_asn1.c:1215
#define ossl_asn1_get_infinite_length(o)
Definition: ossl_asn1.c:181
VALUE cASN1UTCTime
Definition: ossl_asn1.c:208
VALUE cASN1EndOfContent
Definition: ossl_asn1.c:196
static VALUE decode_time(unsigned char *der, long length)
Definition: ossl_asn1.c:464
static VALUE int_ossl_asn1_decode0_prim(unsigned char **pp, long length, long hlen, int tag, VALUE tc, long *num_read)
Definition: ossl_asn1.c:795
static ID sivTAG_CLASS
Definition: ossl_asn1.c:213
static VALUE ossl_asn1cons_to_der(VALUE self)
Definition: ossl_asn1.c:1258
static VALUE ossl_asn1_decode_all(VALUE self, VALUE obj)
Definition: ossl_asn1.c:1086
static VALUE decode_eoc(unsigned char *der, long length)
Definition: ossl_asn1.c:483
#define RTEST(v)
Definition: ruby.h:445
static ID sivUNUSED_BITS
Definition: ossl_asn1.c:213
VALUE ossl_buf2str(char *buf, int len)
Definition: ossl.c:134
static ID sEXPLICIT
Definition: ossl_asn1.c:211
int ASN1_put_eoc(unsigned char **pp)
#define ossl_asn1_get_value(o)
Definition: ossl_asn1.c:177
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:333
static VALUE ossl_asn1_class2sym(int tc)
Definition: ossl_asn1.c:692
VALUE rb_cArray
Definition: array.c:29
VALUE cASN1Sequence
Definition: ossl_asn1.c:209
const char * name
Definition: ossl_asn1.c:494
#define assert(condition)
Definition: ossl.h:45
const char * name
Definition: nkf.c:208
#define ID2SYM(x)
Definition: ruby.h:363
static VALUE decode_bool(unsigned char *der, long length)
Definition: ossl_asn1.c:349
#define ossl_asn1_get_tag(o)
Definition: ossl_asn1.c:178
VALUE ossl_bn_new(const BIGNUM *bn)
Definition: ossl_bn.c:43
VALUE cASN1Enumerated
Definition: ossl_asn1.c:198
#define StringValuePtr(v)
Definition: ruby.h:547
#define ossl_asn1_set_infinite_length(o, v)
Definition: ossl_asn1.c:187
VALUE cASN1NumericString
Definition: ossl_asn1.c:201
VALUE cASN1VideotexString
Definition: ossl_asn1.c:202
void rb_warning(const char *fmt,...)
Definition: error.c:234
#define RSTRING_LENINT(str)
Definition: ruby.h:874
static ASN1_GENERALIZEDTIME * obj_to_asn1gtime(VALUE time)
Definition: ossl_asn1.c:319
VALUE asn1integer_to_num(ASN1_INTEGER *ai)
Definition: ossl_asn1.c:105
BIGNUM * GetBNPtr(VALUE obj)
Definition: ossl_bn.c:58
static VALUE ossl_asn1obj_get_sn(VALUE self)
Definition: ossl_asn1.c:1374
VALUE rb_define_module(const char *name)
Definition: class.c:606
VALUE rb_cstr_to_inum(const char *str, int base, int badcheck)
Definition: bignum.c:579
#define rb_intern(str)
#define ossl_asn1_object_size(cons, len, tag)
Definition: ossl_asn1.c:221
#define SYMBOL_P(x)
Definition: ruby.h:362
VALUE cASN1GeneralString
Definition: ossl_asn1.c:204
static ASN1_BOOLEAN obj_to_asn1bool(VALUE obj)
Definition: ossl_asn1.c:232
#define NULL
Definition: _sdbm.c:102
static VALUE ossl_asn1eoc_initialize(VALUE self)
Definition: ossl_asn1.c:1170
VALUE rb_hash_aset(VALUE, VALUE, VALUE)
RUBY_EXTERN VALUE rb_cTime
Definition: ruby.h:1460
static int ossl_asn1_is_explicit(VALUE obj)
Definition: ossl_asn1.c:646
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1344
VALUE cASN1GeneralizedTime
Definition: ossl_asn1.c:208
VALUE rb_str_append(VALUE, VALUE)
Definition: string.c:2125
VALUE rb_str_new2(const char *)
static VALUE decode_null(unsigned char *der, long length)
Definition: ossl_asn1.c:421
#define NUM2LONG(x)
Definition: ruby.h:592
VALUE ossl_to_der(VALUE obj)
Definition: ossl.c:272
VALUE eASN1Error
Definition: ossl_asn1.c:190
static ASN1_BIT_STRING * obj_to_asn1bstr(VALUE obj, long unused_bits)
Definition: ossl_asn1.c:251
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1122
char ** argv
Definition: ruby.c:131
#define StringValue(v)
Definition: ruby.h:546
struct timeval rb_time_timeval(VALUE)
Definition: time.c:2502
VALUE rb_obj_class(VALUE)
Definition: object.c:194
VALUE rb_str_new(const char *, long)
Definition: string.c:425
ASN1_INTEGER * num_to_asn1integer(VALUE obj, ASN1_INTEGER *ai)
Definition: ossl_asn1.c:157