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