ext/openssl/ossl_asn1.c

Go to the documentation of this file.
00001 /*
00002  * $Id: ossl_asn1.c 46214 2014-05-28 14:44:07Z nagachika $
00003  * 'OpenSSL for Ruby' team members
00004  * Copyright (C) 2003
00005  * All rights reserved.
00006  */
00007 /*
00008  * This program is licenced under the same licence as Ruby.
00009  * (See the file 'LICENCE'.)
00010  */
00011 #include "ossl.h"
00012 
00013 #if defined(HAVE_SYS_TIME_H)
00014 #  include <sys/time.h>
00015 #elif !defined(NT) && !defined(_WIN32)
00016 struct timeval {
00017     long tv_sec;        /* seconds */
00018     long tv_usec;       /* and microseconds */
00019 };
00020 #endif
00021 
00022 static VALUE join_der(VALUE enumerable);
00023 static VALUE ossl_asn1_decode0(unsigned char **pp, long length, long *offset,
00024                                int depth, int yield, long *num_read);
00025 static VALUE ossl_asn1_initialize(int argc, VALUE *argv, VALUE self);
00026 static VALUE ossl_asn1eoc_initialize(VALUE self);
00027 
00028 /*
00029  * DATE conversion
00030  */
00031 VALUE
00032 asn1time_to_time(ASN1_TIME *time)
00033 {
00034     struct tm tm;
00035     VALUE argv[6];
00036     int count;
00037 
00038     if (!time || !time->data) return Qnil;
00039     memset(&tm, 0, sizeof(struct tm));
00040 
00041     switch (time->type) {
00042     case V_ASN1_UTCTIME:
00043         count = sscanf((const char *)time->data, "%2d%2d%2d%2d%2d%2dZ",
00044                 &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min,
00045                 &tm.tm_sec);
00046 
00047         if (count == 5) {
00048             tm.tm_sec = 0;
00049         } else if (count != 6) {
00050             ossl_raise(rb_eTypeError, "bad UTCTIME format: \"%s\"",
00051                     time->data);
00052         }
00053         if (tm.tm_year < 69) {
00054             tm.tm_year += 2000;
00055         } else {
00056             tm.tm_year += 1900;
00057         }
00058         break;
00059     case V_ASN1_GENERALIZEDTIME:
00060         if (sscanf((const char *)time->data, "%4d%2d%2d%2d%2d%2dZ", &tm.tm_year, &tm.tm_mon,
00061                 &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
00062             ossl_raise(rb_eTypeError, "bad GENERALIZEDTIME format" );
00063         }
00064         break;
00065     default:
00066         rb_warning("unknown time format");
00067         return Qnil;
00068     }
00069     argv[0] = INT2NUM(tm.tm_year);
00070     argv[1] = INT2NUM(tm.tm_mon);
00071     argv[2] = INT2NUM(tm.tm_mday);
00072     argv[3] = INT2NUM(tm.tm_hour);
00073     argv[4] = INT2NUM(tm.tm_min);
00074     argv[5] = INT2NUM(tm.tm_sec);
00075 
00076     return rb_funcall2(rb_cTime, rb_intern("utc"), 6, argv);
00077 }
00078 
00079 /*
00080  * This function is not exported in Ruby's *.h
00081  */
00082 extern struct timeval rb_time_timeval(VALUE);
00083 
00084 time_t
00085 time_to_time_t(VALUE time)
00086 {
00087     return (time_t)NUM2LONG(rb_Integer(time));
00088 }
00089 
00090 /*
00091  * STRING conversion
00092  */
00093 VALUE
00094 asn1str_to_str(ASN1_STRING *str)
00095 {
00096     return rb_str_new((const char *)str->data, str->length);
00097 }
00098 
00099 /*
00100  * ASN1_INTEGER conversions
00101  * TODO: Make a decision what's the right way to do this.
00102  */
00103 #define DO_IT_VIA_RUBY 0
00104 VALUE
00105 asn1integer_to_num(ASN1_INTEGER *ai)
00106 {
00107     BIGNUM *bn;
00108 #if DO_IT_VIA_RUBY
00109     char *txt;
00110 #endif
00111     VALUE num;
00112 
00113     if (!ai) {
00114         ossl_raise(rb_eTypeError, "ASN1_INTEGER is NULL!");
00115     }
00116     if (!(bn = ASN1_INTEGER_to_BN(ai, NULL))) {
00117         ossl_raise(eOSSLError, NULL);
00118     }
00119 #if DO_IT_VIA_RUBY
00120     if (!(txt = BN_bn2dec(bn))) {
00121         BN_free(bn);
00122         ossl_raise(eOSSLError, NULL);
00123     }
00124     num = rb_cstr_to_inum(txt, 10, Qtrue);
00125     OPENSSL_free(txt);
00126 #else
00127     num = ossl_bn_new(bn);
00128 #endif
00129     BN_free(bn);
00130 
00131     return num;
00132 }
00133 
00134 #if DO_IT_VIA_RUBY
00135 ASN1_INTEGER *
00136 num_to_asn1integer(VALUE obj, ASN1_INTEGER *ai)
00137 {
00138     BIGNUM *bn = NULL;
00139 
00140     if (RTEST(rb_obj_is_kind_of(obj, cBN))) {
00141         bn = GetBNPtr(obj);
00142     } else {
00143         obj = rb_String(obj);
00144         if (!BN_dec2bn(&bn, StringValuePtr(obj))) {
00145             ossl_raise(eOSSLError, NULL);
00146         }
00147     }
00148     if (!(ai = BN_to_ASN1_INTEGER(bn, ai))) {
00149         BN_free(bn);
00150         ossl_raise(eOSSLError, NULL);
00151     }
00152     BN_free(bn);
00153     return ai;
00154 }
00155 #else
00156 ASN1_INTEGER *
00157 num_to_asn1integer(VALUE obj, ASN1_INTEGER *ai)
00158 {
00159     BIGNUM *bn;
00160 
00161     if (NIL_P(obj))
00162         ossl_raise(rb_eTypeError, "Can't convert nil into Integer");
00163 
00164     bn = GetBNPtr(obj);
00165 
00166     if (!(ai = BN_to_ASN1_INTEGER(bn, ai)))
00167         ossl_raise(eOSSLError, NULL);
00168 
00169     return ai;
00170 }
00171 #endif
00172 
00173 /********/
00174 /*
00175  * ASN1 module
00176  */
00177 #define ossl_asn1_get_value(o)           rb_attr_get((o),sivVALUE)
00178 #define ossl_asn1_get_tag(o)             rb_attr_get((o),sivTAG)
00179 #define ossl_asn1_get_tagging(o)         rb_attr_get((o),sivTAGGING)
00180 #define ossl_asn1_get_tag_class(o)       rb_attr_get((o),sivTAG_CLASS)
00181 #define ossl_asn1_get_infinite_length(o) rb_attr_get((o),sivINFINITE_LENGTH)
00182 
00183 #define ossl_asn1_set_value(o,v)           rb_ivar_set((o),sivVALUE,(v))
00184 #define ossl_asn1_set_tag(o,v)             rb_ivar_set((o),sivTAG,(v))
00185 #define ossl_asn1_set_tagging(o,v)         rb_ivar_set((o),sivTAGGING,(v))
00186 #define ossl_asn1_set_tag_class(o,v)       rb_ivar_set((o),sivTAG_CLASS,(v))
00187 #define ossl_asn1_set_infinite_length(o,v) rb_ivar_set((o),sivINFINITE_LENGTH,(v))
00188 
00189 VALUE mASN1;
00190 VALUE eASN1Error;
00191 
00192 VALUE cASN1Data;
00193 VALUE cASN1Primitive;
00194 VALUE cASN1Constructive;
00195 
00196 VALUE cASN1EndOfContent;
00197 VALUE cASN1Boolean;                           /* BOOLEAN           */
00198 VALUE cASN1Integer, cASN1Enumerated;          /* INTEGER           */
00199 VALUE cASN1BitString;                         /* BIT STRING        */
00200 VALUE cASN1OctetString, cASN1UTF8String;      /* STRINGs           */
00201 VALUE cASN1NumericString, cASN1PrintableString;
00202 VALUE cASN1T61String, cASN1VideotexString;
00203 VALUE cASN1IA5String, cASN1GraphicString;
00204 VALUE cASN1ISO64String, cASN1GeneralString;
00205 VALUE cASN1UniversalString, cASN1BMPString;
00206 VALUE cASN1Null;                              /* NULL              */
00207 VALUE cASN1ObjectId;                          /* OBJECT IDENTIFIER */
00208 VALUE cASN1UTCTime, cASN1GeneralizedTime;     /* TIME              */
00209 VALUE cASN1Sequence, cASN1Set;                /* CONSTRUCTIVE      */
00210 
00211 static ID sIMPLICIT, sEXPLICIT;
00212 static ID sUNIVERSAL, sAPPLICATION, sCONTEXT_SPECIFIC, sPRIVATE;
00213 static ID sivVALUE, sivTAG, sivTAG_CLASS, sivTAGGING, sivINFINITE_LENGTH, sivUNUSED_BITS;
00214 
00215 /*
00216  * We need to implement these for backward compatibility
00217  * reasons, behavior of ASN1_put_object and ASN1_object_size
00218  * for infinite length values is different in OpenSSL <= 0.9.7
00219  */
00220 #if OPENSSL_VERSION_NUMBER < 0x00908000L
00221 #define ossl_asn1_object_size(cons, len, tag)           (cons) == 2 ? (len) + ASN1_object_size((cons), 0, (tag)) : ASN1_object_size((cons), (len), (tag))
00222 #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))
00223 #else
00224 #define ossl_asn1_object_size(cons, len, tag)           ASN1_object_size((cons), (len), (tag))
00225 #define ossl_asn1_put_object(pp, cons, len, tag, xc)    ASN1_put_object((pp), (cons), (len), (tag), (xc))
00226 #endif
00227 
00228 /*
00229  * Ruby to ASN1 converters
00230  */
00231 static ASN1_BOOLEAN
00232 obj_to_asn1bool(VALUE obj)
00233 {
00234     if (NIL_P(obj))
00235         ossl_raise(rb_eTypeError, "Can't convert nil into Boolean");
00236 
00237 #if OPENSSL_VERSION_NUMBER < 0x00907000L
00238      return RTEST(obj) ? 0xff : 0x100;
00239 #else
00240      return RTEST(obj) ? 0xff : 0x0;
00241 #endif
00242 }
00243 
00244 static ASN1_INTEGER*
00245 obj_to_asn1int(VALUE obj)
00246 {
00247     return num_to_asn1integer(obj, NULL);
00248 }
00249 
00250 static ASN1_BIT_STRING*
00251 obj_to_asn1bstr(VALUE obj, long unused_bits)
00252 {
00253     ASN1_BIT_STRING *bstr;
00254 
00255     if(unused_bits < 0) unused_bits = 0;
00256     StringValue(obj);
00257     if(!(bstr = ASN1_BIT_STRING_new()))
00258         ossl_raise(eASN1Error, NULL);
00259     ASN1_BIT_STRING_set(bstr, (unsigned char *)RSTRING_PTR(obj), RSTRING_LENINT(obj));
00260     bstr->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07); /* clear */
00261     bstr->flags |= ASN1_STRING_FLAG_BITS_LEFT|(unused_bits&0x07);
00262 
00263     return bstr;
00264 }
00265 
00266 static ASN1_STRING*
00267 obj_to_asn1str(VALUE obj)
00268 {
00269     ASN1_STRING *str;
00270 
00271     StringValue(obj);
00272     if(!(str = ASN1_STRING_new()))
00273         ossl_raise(eASN1Error, NULL);
00274     ASN1_STRING_set(str, RSTRING_PTR(obj), RSTRING_LENINT(obj));
00275 
00276     return str;
00277 }
00278 
00279 static ASN1_NULL*
00280 obj_to_asn1null(VALUE obj)
00281 {
00282     ASN1_NULL *null;
00283 
00284     if(!NIL_P(obj))
00285         ossl_raise(eASN1Error, "nil expected");
00286     if(!(null = ASN1_NULL_new()))
00287         ossl_raise(eASN1Error, NULL);
00288 
00289     return null;
00290 }
00291 
00292 static ASN1_OBJECT*
00293 obj_to_asn1obj(VALUE obj)
00294 {
00295     ASN1_OBJECT *a1obj;
00296 
00297     StringValue(obj);
00298     a1obj = OBJ_txt2obj(RSTRING_PTR(obj), 0);
00299     if(!a1obj) a1obj = OBJ_txt2obj(RSTRING_PTR(obj), 1);
00300     if(!a1obj) ossl_raise(eASN1Error, "invalid OBJECT ID");
00301 
00302     return a1obj;
00303 }
00304 
00305 static ASN1_UTCTIME*
00306 obj_to_asn1utime(VALUE time)
00307 {
00308     time_t sec;
00309     ASN1_UTCTIME *t;
00310 
00311     sec = time_to_time_t(time);
00312     if(!(t = ASN1_UTCTIME_set(NULL, sec)))
00313         ossl_raise(eASN1Error, NULL);
00314 
00315     return t;
00316 }
00317 
00318 static ASN1_GENERALIZEDTIME*
00319 obj_to_asn1gtime(VALUE time)
00320 {
00321     time_t sec;
00322     ASN1_GENERALIZEDTIME *t;
00323 
00324     sec = time_to_time_t(time);
00325     if(!(t =ASN1_GENERALIZEDTIME_set(NULL, sec)))
00326         ossl_raise(eASN1Error, NULL);
00327 
00328     return t;
00329 }
00330 
00331 static ASN1_STRING*
00332 obj_to_asn1derstr(VALUE obj)
00333 {
00334     ASN1_STRING *a1str;
00335     VALUE str;
00336 
00337     str = ossl_to_der(obj);
00338     if(!(a1str = ASN1_STRING_new()))
00339         ossl_raise(eASN1Error, NULL);
00340     ASN1_STRING_set(a1str, RSTRING_PTR(str), RSTRING_LENINT(str));
00341 
00342     return a1str;
00343 }
00344 
00345 /*
00346  * DER to Ruby converters
00347  */
00348 static VALUE
00349 decode_bool(unsigned char* der, long length)
00350 {
00351     int val;
00352     const unsigned char *p;
00353 
00354     p = der;
00355     if((val = d2i_ASN1_BOOLEAN(NULL, &p, length)) < 0)
00356         ossl_raise(eASN1Error, NULL);
00357 
00358     return val ? Qtrue : Qfalse;
00359 }
00360 
00361 static VALUE
00362 decode_int(unsigned char* der, long length)
00363 {
00364     ASN1_INTEGER *ai;
00365     const unsigned char *p;
00366     VALUE ret;
00367     int status = 0;
00368 
00369     p = der;
00370     if(!(ai = d2i_ASN1_INTEGER(NULL, &p, length)))
00371         ossl_raise(eASN1Error, NULL);
00372     ret = rb_protect((VALUE(*)_((VALUE)))asn1integer_to_num,
00373                      (VALUE)ai, &status);
00374     ASN1_INTEGER_free(ai);
00375     if(status) rb_jump_tag(status);
00376 
00377     return ret;
00378 }
00379 
00380 static VALUE
00381 decode_bstr(unsigned char* der, long length, long *unused_bits)
00382 {
00383     ASN1_BIT_STRING *bstr;
00384     const unsigned char *p;
00385     long len;
00386     VALUE ret;
00387 
00388     p = der;
00389     if(!(bstr = d2i_ASN1_BIT_STRING(NULL, &p, length)))
00390         ossl_raise(eASN1Error, NULL);
00391     len = bstr->length;
00392     *unused_bits = 0;
00393     if(bstr->flags & ASN1_STRING_FLAG_BITS_LEFT)
00394         *unused_bits = bstr->flags & 0x07;
00395     ret = rb_str_new((const char *)bstr->data, len);
00396     ASN1_BIT_STRING_free(bstr);
00397 
00398     return ret;
00399 }
00400 
00401 static VALUE
00402 decode_enum(unsigned char* der, long length)
00403 {
00404     ASN1_ENUMERATED *ai;
00405     const unsigned char *p;
00406     VALUE ret;
00407     int status = 0;
00408 
00409     p = der;
00410     if(!(ai = d2i_ASN1_ENUMERATED(NULL, &p, length)))
00411         ossl_raise(eASN1Error, NULL);
00412     ret = rb_protect((VALUE(*)_((VALUE)))asn1integer_to_num,
00413                      (VALUE)ai, &status);
00414     ASN1_ENUMERATED_free(ai);
00415     if(status) rb_jump_tag(status);
00416 
00417     return ret;
00418 }
00419 
00420 static VALUE
00421 decode_null(unsigned char* der, long length)
00422 {
00423     ASN1_NULL *null;
00424     const unsigned char *p;
00425 
00426     p = der;
00427     if(!(null = d2i_ASN1_NULL(NULL, &p, length)))
00428         ossl_raise(eASN1Error, NULL);
00429     ASN1_NULL_free(null);
00430 
00431     return Qnil;
00432 }
00433 
00434 static VALUE
00435 decode_obj(unsigned char* der, long length)
00436 {
00437     ASN1_OBJECT *obj;
00438     const unsigned char *p;
00439     VALUE ret;
00440     int nid;
00441     BIO *bio;
00442 
00443     p = der;
00444     if(!(obj = d2i_ASN1_OBJECT(NULL, &p, length)))
00445         ossl_raise(eASN1Error, NULL);
00446     if((nid = OBJ_obj2nid(obj)) != NID_undef){
00447         ASN1_OBJECT_free(obj);
00448         ret = rb_str_new2(OBJ_nid2sn(nid));
00449     }
00450     else{
00451         if(!(bio = BIO_new(BIO_s_mem()))){
00452             ASN1_OBJECT_free(obj);
00453             ossl_raise(eASN1Error, NULL);
00454         }
00455         i2a_ASN1_OBJECT(bio, obj);
00456         ASN1_OBJECT_free(obj);
00457         ret = ossl_membio2str(bio);
00458     }
00459 
00460     return ret;
00461 }
00462 
00463 static VALUE
00464 decode_time(unsigned char* der, long length)
00465 {
00466     ASN1_TIME *time;
00467     const unsigned char *p;
00468     VALUE ret;
00469     int status = 0;
00470 
00471     p = der;
00472     if(!(time = d2i_ASN1_TIME(NULL, &p, length)))
00473         ossl_raise(eASN1Error, NULL);
00474     ret = rb_protect((VALUE(*)_((VALUE)))asn1time_to_time,
00475                      (VALUE)time, &status);
00476     ASN1_TIME_free(time);
00477     if(status) rb_jump_tag(status);
00478 
00479     return ret;
00480 }
00481 
00482 static VALUE
00483 decode_eoc(unsigned char *der, long length)
00484 {
00485     if (length != 2 || !(der[0] == 0x00 && der[1] == 0x00))
00486         ossl_raise(eASN1Error, NULL);
00487 
00488     return rb_str_new("", 0);
00489 }
00490 
00491 /********/
00492 
00493 typedef struct {
00494     const char *name;
00495     VALUE *klass;
00496 } ossl_asn1_info_t;
00497 
00498 static ossl_asn1_info_t ossl_asn1_info[] = {
00499     { "EOC",               &cASN1EndOfContent,    },  /*  0 */
00500     { "BOOLEAN",           &cASN1Boolean,         },  /*  1 */
00501     { "INTEGER",           &cASN1Integer,         },  /*  2 */
00502     { "BIT_STRING",        &cASN1BitString,       },  /*  3 */
00503     { "OCTET_STRING",      &cASN1OctetString,     },  /*  4 */
00504     { "NULL",              &cASN1Null,            },  /*  5 */
00505     { "OBJECT",            &cASN1ObjectId,        },  /*  6 */
00506     { "OBJECT_DESCRIPTOR", NULL,                  },  /*  7 */
00507     { "EXTERNAL",          NULL,                  },  /*  8 */
00508     { "REAL",              NULL,                  },  /*  9 */
00509     { "ENUMERATED",        &cASN1Enumerated,      },  /* 10 */
00510     { "EMBEDDED_PDV",      NULL,                  },  /* 11 */
00511     { "UTF8STRING",        &cASN1UTF8String,      },  /* 12 */
00512     { "RELATIVE_OID",      NULL,                  },  /* 13 */
00513     { "[UNIVERSAL 14]",    NULL,                  },  /* 14 */
00514     { "[UNIVERSAL 15]",    NULL,                  },  /* 15 */
00515     { "SEQUENCE",          &cASN1Sequence,        },  /* 16 */
00516     { "SET",               &cASN1Set,             },  /* 17 */
00517     { "NUMERICSTRING",     &cASN1NumericString,   },  /* 18 */
00518     { "PRINTABLESTRING",   &cASN1PrintableString, },  /* 19 */
00519     { "T61STRING",         &cASN1T61String,       },  /* 20 */
00520     { "VIDEOTEXSTRING",    &cASN1VideotexString,  },  /* 21 */
00521     { "IA5STRING",         &cASN1IA5String,       },  /* 22 */
00522     { "UTCTIME",           &cASN1UTCTime,         },  /* 23 */
00523     { "GENERALIZEDTIME",   &cASN1GeneralizedTime, },  /* 24 */
00524     { "GRAPHICSTRING",     &cASN1GraphicString,   },  /* 25 */
00525     { "ISO64STRING",       &cASN1ISO64String,     },  /* 26 */
00526     { "GENERALSTRING",     &cASN1GeneralString,   },  /* 27 */
00527     { "UNIVERSALSTRING",   &cASN1UniversalString, },  /* 28 */
00528     { "CHARACTER_STRING",  NULL,                  },  /* 29 */
00529     { "BMPSTRING",         &cASN1BMPString,       },  /* 30 */
00530 };
00531 
00532 int ossl_asn1_info_size = (sizeof(ossl_asn1_info)/sizeof(ossl_asn1_info[0]));
00533 
00534 static VALUE class_tag_map;
00535 
00536 static int ossl_asn1_default_tag(VALUE obj);
00537 
00538 ASN1_TYPE*
00539 ossl_asn1_get_asn1type(VALUE obj)
00540 {
00541     ASN1_TYPE *ret;
00542     VALUE value, rflag;
00543     void *ptr;
00544     void (*free_func)();
00545     int tag, flag;
00546 
00547     tag = ossl_asn1_default_tag(obj);
00548     value = ossl_asn1_get_value(obj);
00549     switch(tag){
00550     case V_ASN1_BOOLEAN:
00551         ptr = (void*)(VALUE)obj_to_asn1bool(value);
00552         free_func = NULL;
00553         break;
00554     case V_ASN1_INTEGER:         /* FALLTHROUGH */
00555     case V_ASN1_ENUMERATED:
00556         ptr = obj_to_asn1int(value);
00557         free_func = ASN1_INTEGER_free;
00558         break;
00559     case V_ASN1_BIT_STRING:
00560         rflag = rb_attr_get(obj, sivUNUSED_BITS);
00561         flag = NIL_P(rflag) ? -1 : NUM2INT(rflag);
00562         ptr = obj_to_asn1bstr(value, flag);
00563         free_func = ASN1_BIT_STRING_free;
00564         break;
00565     case V_ASN1_NULL:
00566         ptr = obj_to_asn1null(value);
00567         free_func = ASN1_NULL_free;
00568         break;
00569     case V_ASN1_OCTET_STRING:    /* FALLTHROUGH */
00570     case V_ASN1_UTF8STRING:      /* FALLTHROUGH */
00571     case V_ASN1_NUMERICSTRING:   /* FALLTHROUGH */
00572     case V_ASN1_PRINTABLESTRING: /* FALLTHROUGH */
00573     case V_ASN1_T61STRING:       /* FALLTHROUGH */
00574     case V_ASN1_VIDEOTEXSTRING:  /* FALLTHROUGH */
00575     case V_ASN1_IA5STRING:       /* FALLTHROUGH */
00576     case V_ASN1_GRAPHICSTRING:   /* FALLTHROUGH */
00577     case V_ASN1_ISO64STRING:     /* FALLTHROUGH */
00578     case V_ASN1_GENERALSTRING:   /* FALLTHROUGH */
00579     case V_ASN1_UNIVERSALSTRING: /* FALLTHROUGH */
00580     case V_ASN1_BMPSTRING:
00581         ptr = obj_to_asn1str(value);
00582         free_func = ASN1_STRING_free;
00583         break;
00584     case V_ASN1_OBJECT:
00585         ptr = obj_to_asn1obj(value);
00586         free_func = ASN1_OBJECT_free;
00587         break;
00588     case V_ASN1_UTCTIME:
00589         ptr = obj_to_asn1utime(value);
00590         free_func = ASN1_TIME_free;
00591         break;
00592     case V_ASN1_GENERALIZEDTIME:
00593         ptr = obj_to_asn1gtime(value);
00594         free_func = ASN1_TIME_free;
00595         break;
00596     case V_ASN1_SET:             /* FALLTHROUGH */
00597     case V_ASN1_SEQUENCE:
00598         ptr = obj_to_asn1derstr(obj);
00599         free_func = ASN1_STRING_free;
00600         break;
00601     default:
00602         ossl_raise(eASN1Error, "unsupported ASN.1 type");
00603     }
00604     if(!(ret = OPENSSL_malloc(sizeof(ASN1_TYPE)))){
00605         if(free_func) free_func(ptr);
00606         ossl_raise(eASN1Error, "ASN1_TYPE alloc failure");
00607     }
00608     memset(ret, 0, sizeof(ASN1_TYPE));
00609     ASN1_TYPE_set(ret, tag, ptr);
00610 
00611     return ret;
00612 }
00613 
00614 static int
00615 ossl_asn1_default_tag(VALUE obj)
00616 {
00617     VALUE tmp_class, tag;
00618 
00619     tmp_class = CLASS_OF(obj);
00620     while (tmp_class) {
00621         tag = rb_hash_lookup(class_tag_map, tmp_class);
00622         if (tag != Qnil) {
00623             return NUM2INT(tag);
00624         }
00625         tmp_class = rb_class_superclass(tmp_class);
00626     }
00627     ossl_raise(eASN1Error, "universal tag for %"PRIsVALUE" not found",
00628                rb_obj_class(obj));
00629 
00630     return -1; /* dummy */
00631 }
00632 
00633 static int
00634 ossl_asn1_tag(VALUE obj)
00635 {
00636     VALUE tag;
00637 
00638     tag = ossl_asn1_get_tag(obj);
00639     if(NIL_P(tag))
00640         ossl_raise(eASN1Error, "tag number not specified");
00641 
00642     return NUM2INT(tag);
00643 }
00644 
00645 static int
00646 ossl_asn1_is_explicit(VALUE obj)
00647 {
00648     VALUE s;
00649     int ret = -1;
00650 
00651     s = ossl_asn1_get_tagging(obj);
00652     if(NIL_P(s)) return 0;
00653     else if(SYMBOL_P(s)){
00654         if (SYM2ID(s) == sIMPLICIT)
00655             ret = 0;
00656         else if (SYM2ID(s) == sEXPLICIT)
00657             ret = 1;
00658     }
00659     if(ret < 0){
00660         ossl_raise(eASN1Error, "invalid tag default");
00661     }
00662 
00663     return ret;
00664 }
00665 
00666 static int
00667 ossl_asn1_tag_class(VALUE obj)
00668 {
00669     VALUE s;
00670     int ret = -1;
00671 
00672     s = ossl_asn1_get_tag_class(obj);
00673     if(NIL_P(s)) ret = V_ASN1_UNIVERSAL;
00674     else if(SYMBOL_P(s)){
00675         if (SYM2ID(s) == sUNIVERSAL)
00676             ret = V_ASN1_UNIVERSAL;
00677         else if (SYM2ID(s) == sAPPLICATION)
00678             ret = V_ASN1_APPLICATION;
00679         else if (SYM2ID(s) == sCONTEXT_SPECIFIC)
00680             ret = V_ASN1_CONTEXT_SPECIFIC;
00681         else if (SYM2ID(s) == sPRIVATE)
00682             ret = V_ASN1_PRIVATE;
00683     }
00684     if(ret < 0){
00685         ossl_raise(eASN1Error, "invalid tag class");
00686     }
00687 
00688     return ret;
00689 }
00690 
00691 static VALUE
00692 ossl_asn1_class2sym(int tc)
00693 {
00694     if((tc & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
00695         return ID2SYM(sPRIVATE);
00696     else if((tc & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
00697         return ID2SYM(sCONTEXT_SPECIFIC);
00698     else if((tc & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
00699         return ID2SYM(sAPPLICATION);
00700     else
00701         return ID2SYM(sUNIVERSAL);
00702 }
00703 
00704 /*
00705  * call-seq:
00706  *    OpenSSL::ASN1::ASN1Data.new(value, tag, tag_class) => ASN1Data
00707  *
00708  * +value+: Please have a look at Constructive and Primitive to see how Ruby
00709  * types are mapped to ASN.1 types and vice versa.
00710  *
00711  * +tag+: A +Number+ indicating the tag number.
00712  *
00713  * +tag_class+: A +Symbol+ indicating the tag class. Please cf. ASN1 for
00714  * possible values.
00715  *
00716  * == Example
00717  *   asn1_int = OpenSSL::ASN1Data.new(42, 2, :UNIVERSAL) # => Same as OpenSSL::ASN1::Integer.new(42)
00718  *   tagged_int = OpenSSL::ASN1Data.new(42, 0, :CONTEXT_SPECIFIC) # implicitly 0-tagged INTEGER
00719  */
00720 static VALUE
00721 ossl_asn1data_initialize(VALUE self, VALUE value, VALUE tag, VALUE tag_class)
00722 {
00723     if(!SYMBOL_P(tag_class))
00724         ossl_raise(eASN1Error, "invalid tag class");
00725     if((SYM2ID(tag_class) == sUNIVERSAL) && NUM2INT(tag) > 31)
00726         ossl_raise(eASN1Error, "tag number for Universal too large");
00727     ossl_asn1_set_tag(self, tag);
00728     ossl_asn1_set_value(self, value);
00729     ossl_asn1_set_tag_class(self, tag_class);
00730     ossl_asn1_set_infinite_length(self, Qfalse);
00731 
00732     return self;
00733 }
00734 
00735 static VALUE
00736 join_der_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, str))
00737 {
00738     i = ossl_to_der_if_possible(i);
00739     StringValue(i);
00740     rb_str_append(str, i);
00741     return Qnil;
00742 }
00743 
00744 static VALUE
00745 join_der(VALUE enumerable)
00746 {
00747     VALUE str = rb_str_new(0, 0);
00748     rb_block_call(enumerable, rb_intern("each"), 0, 0, join_der_i, str);
00749     return str;
00750 }
00751 
00752 /*
00753  * call-seq:
00754  *    asn1.to_der => DER-encoded String
00755  *
00756  * Encodes this ASN1Data into a DER-encoded String value. The result is
00757  * DER-encoded except for the possibility of infinite length encodings.
00758  * Infinite length encodings are not allowed in strict DER, so strictly
00759  * speaking the result of such an encoding would be a BER-encoding.
00760  */
00761 static VALUE
00762 ossl_asn1data_to_der(VALUE self)
00763 {
00764     VALUE value, der, inf_length;
00765     int tag, tag_class, is_cons = 0;
00766     long length;
00767     unsigned char *p;
00768 
00769     value = ossl_asn1_get_value(self);
00770     if(rb_obj_is_kind_of(value, rb_cArray)){
00771         is_cons = 1;
00772         value = join_der(value);
00773     }
00774     StringValue(value);
00775 
00776     tag = ossl_asn1_tag(self);
00777     tag_class = ossl_asn1_tag_class(self);
00778     inf_length = ossl_asn1_get_infinite_length(self);
00779     if (inf_length == Qtrue) {
00780         is_cons = 2;
00781     }
00782     if((length = ossl_asn1_object_size(is_cons, RSTRING_LENINT(value), tag)) <= 0)
00783         ossl_raise(eASN1Error, NULL);
00784     der = rb_str_new(0, length);
00785     p = (unsigned char *)RSTRING_PTR(der);
00786     ossl_asn1_put_object(&p, is_cons, RSTRING_LENINT(value), tag, tag_class);
00787     memcpy(p, RSTRING_PTR(value), RSTRING_LEN(value));
00788     p += RSTRING_LEN(value);
00789     ossl_str_adjust(der, p);
00790 
00791     return der;
00792 }
00793 
00794 static VALUE
00795 int_ossl_asn1_decode0_prim(unsigned char **pp, long length, long hlen, int tag,
00796                            VALUE tc, long *num_read)
00797 {
00798     VALUE value, asn1data;
00799     unsigned char *p;
00800     long flag = 0;
00801 
00802     p = *pp;
00803 
00804     if(tc == sUNIVERSAL && tag < ossl_asn1_info_size) {
00805         switch(tag){
00806         case V_ASN1_EOC:
00807             value = decode_eoc(p, hlen+length);
00808             break;
00809         case V_ASN1_BOOLEAN:
00810             value = decode_bool(p, hlen+length);
00811             break;
00812         case V_ASN1_INTEGER:
00813             value = decode_int(p, hlen+length);
00814             break;
00815         case V_ASN1_BIT_STRING:
00816             value = decode_bstr(p, hlen+length, &flag);
00817             break;
00818         case V_ASN1_NULL:
00819             value = decode_null(p, hlen+length);
00820             break;
00821         case V_ASN1_ENUMERATED:
00822             value = decode_enum(p, hlen+length);
00823             break;
00824         case V_ASN1_OBJECT:
00825             value = decode_obj(p, hlen+length);
00826             break;
00827         case V_ASN1_UTCTIME:           /* FALLTHROUGH */
00828         case V_ASN1_GENERALIZEDTIME:
00829             value = decode_time(p, hlen+length);
00830             break;
00831         default:
00832             /* use original value */
00833             p += hlen;
00834             value = rb_str_new((const char *)p, length);
00835             break;
00836         }
00837     }
00838     else {
00839         p += hlen;
00840         value = rb_str_new((const char *)p, length);
00841     }
00842 
00843     *pp += hlen + length;
00844     *num_read = hlen + length;
00845 
00846     if (tc == sUNIVERSAL && tag < ossl_asn1_info_size && ossl_asn1_info[tag].klass) {
00847         VALUE klass = *ossl_asn1_info[tag].klass;
00848         VALUE args[4];
00849         args[0] = value;
00850         args[1] = INT2NUM(tag);
00851         args[2] = Qnil;
00852         args[3] = ID2SYM(tc);
00853         asn1data = rb_obj_alloc(klass);
00854         ossl_asn1_initialize(4, args, asn1data);
00855         if(tag == V_ASN1_BIT_STRING){
00856             rb_ivar_set(asn1data, sivUNUSED_BITS, LONG2NUM(flag));
00857         }
00858     }
00859     else {
00860         asn1data = rb_obj_alloc(cASN1Data);
00861         ossl_asn1data_initialize(asn1data, value, INT2NUM(tag), ID2SYM(tc));
00862     }
00863 
00864     return asn1data;
00865 }
00866 
00867 static VALUE
00868 int_ossl_asn1_decode0_cons(unsigned char **pp, long max_len, long length,
00869                            long *offset, int depth, int yield, int j,
00870                            int tag, VALUE tc, long *num_read)
00871 {
00872     VALUE value, asn1data, ary;
00873     int infinite;
00874     long off = *offset;
00875 
00876     infinite = (j == 0x21);
00877     ary = rb_ary_new();
00878 
00879     while (length > 0 || infinite) {
00880         long inner_read = 0;
00881         value = ossl_asn1_decode0(pp, max_len, &off, depth + 1, yield, &inner_read);
00882         *num_read += inner_read;
00883         max_len -= inner_read;
00884         rb_ary_push(ary, value);
00885         if (length > 0)
00886             length -= inner_read;
00887 
00888         if (infinite &&
00889             NUM2INT(ossl_asn1_get_tag(value)) == V_ASN1_EOC &&
00890             SYM2ID(ossl_asn1_get_tag_class(value)) == sUNIVERSAL) {
00891             break;
00892         }
00893     }
00894 
00895     if (tc == sUNIVERSAL) {
00896         VALUE args[4];
00897         int not_sequence_or_set;
00898 
00899         not_sequence_or_set = tag != V_ASN1_SEQUENCE && tag != V_ASN1_SET;
00900 
00901         if (not_sequence_or_set) {
00902             if (infinite) {
00903                 asn1data = rb_obj_alloc(cASN1Constructive);
00904             }
00905             else {
00906                 ossl_raise(eASN1Error, "invalid non-infinite tag");
00907                 return Qnil;
00908             }
00909         }
00910         else {
00911             VALUE klass = *ossl_asn1_info[tag].klass;
00912             asn1data = rb_obj_alloc(klass);
00913         }
00914         args[0] = ary;
00915         args[1] = INT2NUM(tag);
00916         args[2] = Qnil;
00917         args[3] = ID2SYM(tc);
00918         ossl_asn1_initialize(4, args, asn1data);
00919     }
00920     else {
00921         asn1data = rb_obj_alloc(cASN1Data);
00922         ossl_asn1data_initialize(asn1data, ary, INT2NUM(tag), ID2SYM(tc));
00923     }
00924 
00925     if (infinite)
00926         ossl_asn1_set_infinite_length(asn1data, Qtrue);
00927     else
00928         ossl_asn1_set_infinite_length(asn1data, Qfalse);
00929 
00930     *offset = off;
00931     return asn1data;
00932 }
00933 
00934 static VALUE
00935 ossl_asn1_decode0(unsigned char **pp, long length, long *offset, int depth,
00936                   int yield, long *num_read)
00937 {
00938     unsigned char *start, *p;
00939     const unsigned char *p0;
00940     long len = 0, inner_read = 0, off = *offset, hlen;
00941     int tag, tc, j;
00942     VALUE asn1data, tag_class;
00943 
00944     p = *pp;
00945     start = p;
00946     p0 = p;
00947     j = ASN1_get_object(&p0, &len, &tag, &tc, length);
00948     p = (unsigned char *)p0;
00949     if(j & 0x80) ossl_raise(eASN1Error, NULL);
00950     if(len > length) ossl_raise(eASN1Error, "value is too short");
00951     if((tc & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
00952         tag_class = sPRIVATE;
00953     else if((tc & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
00954         tag_class = sCONTEXT_SPECIFIC;
00955     else if((tc & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
00956         tag_class = sAPPLICATION;
00957     else
00958         tag_class = sUNIVERSAL;
00959 
00960     hlen = p - start;
00961 
00962     if(yield) {
00963         VALUE arg = rb_ary_new();
00964         rb_ary_push(arg, LONG2NUM(depth));
00965         rb_ary_push(arg, LONG2NUM(*offset));
00966         rb_ary_push(arg, LONG2NUM(hlen));
00967         rb_ary_push(arg, LONG2NUM(len));
00968         rb_ary_push(arg, (j & V_ASN1_CONSTRUCTED) ? Qtrue : Qfalse);
00969         rb_ary_push(arg, ossl_asn1_class2sym(tc));
00970         rb_ary_push(arg, INT2NUM(tag));
00971         rb_yield(arg);
00972     }
00973 
00974     if(j & V_ASN1_CONSTRUCTED) {
00975         *pp += hlen;
00976         off += hlen;
00977         asn1data = int_ossl_asn1_decode0_cons(pp, length, len, &off, depth, yield, j, tag, tag_class, &inner_read);
00978         inner_read += hlen;
00979     }
00980     else {
00981         if ((j & 0x01) && (len == 0)) ossl_raise(eASN1Error, "Infinite length for primitive value");
00982         asn1data = int_ossl_asn1_decode0_prim(pp, len, hlen, tag, tag_class, &inner_read);
00983         off += hlen + len;
00984     }
00985     if (num_read)
00986         *num_read = inner_read;
00987     if (len != 0 && inner_read != hlen + len) {
00988         ossl_raise(eASN1Error,
00989                    "Type mismatch. Bytes read: %ld Bytes available: %ld",
00990                    inner_read, hlen + len);
00991     }
00992 
00993     *offset = off;
00994     return asn1data;
00995 }
00996 
00997 static void
00998 int_ossl_decode_sanity_check(long len, long read, long offset)
00999 {
01000     if (len != 0 && (read != len || offset != len)) {
01001         ossl_raise(eASN1Error,
01002                    "Type mismatch. Total bytes read: %ld Bytes available: %ld Offset: %ld",
01003                    read, len, offset);
01004     }
01005 }
01006 
01007 /*
01008  * call-seq:
01009  *    OpenSSL::ASN1.traverse(asn1) -> nil
01010  *
01011  * If a block is given, it prints out each of the elements encountered.
01012  * Block parameters are (in that order):
01013  * * depth: The recursion depth, plus one with each constructed value being encountered (Number)
01014  * * offset: Current byte offset (Number)
01015  * * header length: Combined length in bytes of the Tag and Length headers. (Number)
01016  * * length: The overall remaining length of the entire data (Number)
01017  * * constructed: Whether this value is constructed or not (Boolean)
01018  * * tag_class: Current tag class (Symbol)
01019  * * tag: The current tag (Number)
01020  *
01021  * == Example
01022  *   der = File.binread('asn1data.der')
01023  *   OpenSSL::ASN1.traverse(der) do | depth, offset, header_len, length, constructed, tag_class, tag|
01024  *     puts "Depth: #{depth} Offset: #{offset} Length: #{length}"
01025  *     puts "Header length: #{header_len} Tag: #{tag} Tag class: #{tag_class} Constructed: #{constructed}"
01026  *   end
01027  */
01028 static VALUE
01029 ossl_asn1_traverse(VALUE self, VALUE obj)
01030 {
01031     unsigned char *p;
01032     volatile VALUE tmp;
01033     long len, read = 0, offset = 0;
01034 
01035     obj = ossl_to_der_if_possible(obj);
01036     tmp = rb_str_new4(StringValue(obj));
01037     p = (unsigned char *)RSTRING_PTR(tmp);
01038     len = RSTRING_LEN(tmp);
01039     ossl_asn1_decode0(&p, len, &offset, 0, 1, &read);
01040     int_ossl_decode_sanity_check(len, read, offset);
01041     return Qnil;
01042 }
01043 
01044 /*
01045  * call-seq:
01046  *    OpenSSL::ASN1.decode(der) -> ASN1Data
01047  *
01048  * Decodes a BER- or DER-encoded value and creates an ASN1Data instance. +der+
01049  * may be a +String+ or any object that features a +#to_der+ method transforming
01050  * it into a BER-/DER-encoded +String+.
01051  *
01052  * == Example
01053  *   der = File.binread('asn1data')
01054  *   asn1 = OpenSSL::ASN1.decode(der)
01055  */
01056 static VALUE
01057 ossl_asn1_decode(VALUE self, VALUE obj)
01058 {
01059     VALUE ret;
01060     unsigned char *p;
01061     volatile VALUE tmp;
01062     long len, read = 0, offset = 0;
01063 
01064     obj = ossl_to_der_if_possible(obj);
01065     tmp = rb_str_new4(StringValue(obj));
01066     p = (unsigned char *)RSTRING_PTR(tmp);
01067     len = RSTRING_LEN(tmp);
01068     ret = ossl_asn1_decode0(&p, len, &offset, 0, 0, &read);
01069     int_ossl_decode_sanity_check(len, read, offset);
01070     return ret;
01071 }
01072 
01073 /*
01074  * call-seq:
01075  *    OpenSSL::ASN1.decode_all(der) -> Array of ASN1Data
01076  *
01077  * Similar to +decode+ with the difference that +decode+ expects one
01078  * distinct value represented in +der+. +decode_all+ on the contrary
01079  * decodes a sequence of sequential BER/DER values lined up in +der+
01080  * and returns them as an array.
01081  *
01082  * == Example
01083  *   ders = File.binread('asn1data_seq')
01084  *   asn1_ary = OpenSSL::ASN1.decode_all(ders)
01085  */
01086 static VALUE
01087 ossl_asn1_decode_all(VALUE self, VALUE obj)
01088 {
01089     VALUE ary, val;
01090     unsigned char *p;
01091     long len, tmp_len = 0, read = 0, offset = 0;
01092     volatile VALUE tmp;
01093 
01094     obj = ossl_to_der_if_possible(obj);
01095     tmp = rb_str_new4(StringValue(obj));
01096     p = (unsigned char *)RSTRING_PTR(tmp);
01097     len = RSTRING_LEN(tmp);
01098     tmp_len = len;
01099     ary = rb_ary_new();
01100     while (tmp_len > 0) {
01101         long tmp_read = 0;
01102         val = ossl_asn1_decode0(&p, tmp_len, &offset, 0, 0, &tmp_read);
01103         rb_ary_push(ary, val);
01104         read += tmp_read;
01105         tmp_len -= tmp_read;
01106     }
01107     int_ossl_decode_sanity_check(len, read, offset);
01108     return ary;
01109 }
01110 
01111 /*
01112  * call-seq:
01113  *    OpenSSL::ASN1::Primitive.new( value [, tag, tagging, tag_class ]) => Primitive
01114  *
01115  * +value+: is mandatory.
01116  *
01117  * +tag+: optional, may be specified for tagged values. If no +tag+ is
01118  * specified, the UNIVERSAL tag corresponding to the Primitive sub-class
01119  * is used by default.
01120  *
01121  * +tagging+: may be used as an encoding hint to encode a value either
01122  * explicitly or implicitly, see ASN1 for possible values.
01123  *
01124  * +tag_class+: if +tag+ and +tagging+ are +nil+ then this is set to
01125  * +:UNIVERSAL+ by default. If either +tag+ or +tagging+ are set then
01126  * +:CONTEXT_SPECIFIC+ is used as the default. For possible values please
01127  * cf. ASN1.
01128  *
01129  * == Example
01130  *   int = OpenSSL::ASN1::Integer.new(42)
01131  *   zero_tagged_int = OpenSSL::ASN1::Integer.new(42, 0, :IMPLICIT)
01132  *   private_explicit_zero_tagged_int = OpenSSL::ASN1::Integer.new(42, 0, :EXPLICIT, :PRIVATE)
01133  */
01134 static VALUE
01135 ossl_asn1_initialize(int argc, VALUE *argv, VALUE self)
01136 {
01137     VALUE value, tag, tagging, tag_class;
01138 
01139     rb_scan_args(argc, argv, "13", &value, &tag, &tagging, &tag_class);
01140     if(argc > 1){
01141         if(NIL_P(tag))
01142             ossl_raise(eASN1Error, "must specify tag number");
01143         if(!NIL_P(tagging) && !SYMBOL_P(tagging))
01144             ossl_raise(eASN1Error, "invalid tagging method");
01145         if(NIL_P(tag_class)) {
01146             if (NIL_P(tagging))
01147                 tag_class = ID2SYM(sUNIVERSAL);
01148             else
01149                 tag_class = ID2SYM(sCONTEXT_SPECIFIC);
01150         }
01151         if(!SYMBOL_P(tag_class))
01152             ossl_raise(eASN1Error, "invalid tag class");
01153         if(!NIL_P(tagging) && SYM2ID(tagging) == sIMPLICIT && NUM2INT(tag) > 31)
01154             ossl_raise(eASN1Error, "tag number for Universal too large");
01155     }
01156     else{
01157         tag = INT2NUM(ossl_asn1_default_tag(self));
01158         tagging = Qnil;
01159         tag_class = ID2SYM(sUNIVERSAL);
01160     }
01161     ossl_asn1_set_tag(self, tag);
01162     ossl_asn1_set_value(self, value);
01163     ossl_asn1_set_tagging(self, tagging);
01164     ossl_asn1_set_tag_class(self, tag_class);
01165     ossl_asn1_set_infinite_length(self, Qfalse);
01166 
01167     return self;
01168 }
01169 
01170 static VALUE
01171 ossl_asn1eoc_initialize(VALUE self) {
01172     VALUE tag, tagging, tag_class, value;
01173     tag = INT2NUM(ossl_asn1_default_tag(self));
01174     tagging = Qnil;
01175     tag_class = ID2SYM(sUNIVERSAL);
01176     value = rb_str_new("", 0);
01177     ossl_asn1_set_tag(self, tag);
01178     ossl_asn1_set_value(self, value);
01179     ossl_asn1_set_tagging(self, tagging);
01180     ossl_asn1_set_tag_class(self, tag_class);
01181     ossl_asn1_set_infinite_length(self, Qfalse);
01182     return self;
01183 }
01184 
01185 static int
01186 ossl_i2d_ASN1_TYPE(ASN1_TYPE *a, unsigned char **pp)
01187 {
01188 #if OPENSSL_VERSION_NUMBER < 0x00907000L
01189     if(!a) return 0;
01190     if(a->type == V_ASN1_BOOLEAN)
01191         return i2d_ASN1_BOOLEAN(a->value.boolean, pp);
01192 #endif
01193     return i2d_ASN1_TYPE(a, pp);
01194 }
01195 
01196 static void
01197 ossl_ASN1_TYPE_free(ASN1_TYPE *a)
01198 {
01199 #if OPENSSL_VERSION_NUMBER < 0x00907000L
01200     if(!a) return;
01201     if(a->type == V_ASN1_BOOLEAN){
01202         OPENSSL_free(a);
01203         return;
01204     }
01205 #endif
01206     ASN1_TYPE_free(a);
01207 }
01208 
01209 /*
01210  * call-seq:
01211  *    asn1.to_der => DER-encoded String
01212  *
01213  * See ASN1Data#to_der for details. *
01214  */
01215 static VALUE
01216 ossl_asn1prim_to_der(VALUE self)
01217 {
01218     ASN1_TYPE *asn1;
01219     int tn, tc, explicit;
01220     long len, reallen;
01221     unsigned char *buf, *p;
01222     VALUE str;
01223 
01224     tn = NUM2INT(ossl_asn1_get_tag(self));
01225     tc = ossl_asn1_tag_class(self);
01226     explicit = ossl_asn1_is_explicit(self);
01227     asn1 = ossl_asn1_get_asn1type(self);
01228 
01229     len = ossl_asn1_object_size(1, ossl_i2d_ASN1_TYPE(asn1, NULL), tn);
01230     if(!(buf = OPENSSL_malloc(len))){
01231         ossl_ASN1_TYPE_free(asn1);
01232         ossl_raise(eASN1Error, "cannot alloc buffer");
01233     }
01234     p = buf;
01235     if (tc == V_ASN1_UNIVERSAL) {
01236         ossl_i2d_ASN1_TYPE(asn1, &p);
01237     } else if (explicit) {
01238         ossl_asn1_put_object(&p, 1, ossl_i2d_ASN1_TYPE(asn1, NULL), tn, tc);
01239         ossl_i2d_ASN1_TYPE(asn1, &p);
01240     } else {
01241         ossl_i2d_ASN1_TYPE(asn1, &p);
01242         *buf = tc | tn | (*buf & V_ASN1_CONSTRUCTED);
01243     }
01244     ossl_ASN1_TYPE_free(asn1);
01245     reallen = p - buf;
01246     assert(reallen <= len);
01247     str = ossl_buf2str((char *)buf, rb_long2int(reallen)); /* buf will be free in ossl_buf2str */
01248 
01249     return str;
01250 }
01251 
01252 /*
01253  * call-seq:
01254  *    asn1.to_der => DER-encoded String
01255  *
01256  * See ASN1Data#to_der for details.
01257  */
01258 static VALUE
01259 ossl_asn1cons_to_der(VALUE self)
01260 {
01261     int tag, tn, tc, explicit, constructed = 1;
01262     int found_prim = 0, seq_len;
01263     long length;
01264     unsigned char *p;
01265     VALUE value, str, inf_length;
01266 
01267     tn = NUM2INT(ossl_asn1_get_tag(self));
01268     tc = ossl_asn1_tag_class(self);
01269     inf_length = ossl_asn1_get_infinite_length(self);
01270     if (inf_length == Qtrue) {
01271         VALUE ary, example;
01272         constructed = 2;
01273         if (CLASS_OF(self) == cASN1Sequence ||
01274             CLASS_OF(self) == cASN1Set) {
01275             tag = ossl_asn1_default_tag(self);
01276         }
01277         else { /* must be a constructive encoding of a primitive value */
01278             ary = ossl_asn1_get_value(self);
01279             if (!rb_obj_is_kind_of(ary, rb_cArray))
01280                 ossl_raise(eASN1Error, "Constructive value must be an Array");
01281             /* Recursively descend until a primitive value is found.
01282             The overall value of the entire constructed encoding
01283             is of the type of the first primitive encoding to be
01284             found. */
01285             while (!found_prim){
01286                 example = rb_ary_entry(ary, 0);
01287                 if (rb_obj_is_kind_of(example, cASN1Primitive)){
01288                     found_prim = 1;
01289                 }
01290                 else {
01291                     /* example is another ASN1Constructive */
01292                     if (!rb_obj_is_kind_of(example, cASN1Constructive)){
01293                         ossl_raise(eASN1Error, "invalid constructed encoding");
01294                         return Qnil; /* dummy */
01295                     }
01296                     ary = ossl_asn1_get_value(example);
01297                 }
01298             }
01299             tag = ossl_asn1_default_tag(example);
01300         }
01301     }
01302     else {
01303         if (CLASS_OF(self) == cASN1Constructive)
01304             ossl_raise(eASN1Error, "Constructive shall only be used with infinite length");
01305         tag = ossl_asn1_default_tag(self);
01306     }
01307     explicit = ossl_asn1_is_explicit(self);
01308     value = join_der(ossl_asn1_get_value(self));
01309 
01310     seq_len = ossl_asn1_object_size(constructed, RSTRING_LENINT(value), tag);
01311     length = ossl_asn1_object_size(constructed, seq_len, tn);
01312     str = rb_str_new(0, length);
01313     p = (unsigned char *)RSTRING_PTR(str);
01314     if(tc == V_ASN1_UNIVERSAL)
01315         ossl_asn1_put_object(&p, constructed, RSTRING_LENINT(value), tn, tc);
01316     else{
01317         if(explicit){
01318             ossl_asn1_put_object(&p, constructed, seq_len, tn, tc);
01319             ossl_asn1_put_object(&p, constructed, RSTRING_LENINT(value), tag, V_ASN1_UNIVERSAL);
01320         }
01321         else{
01322             ossl_asn1_put_object(&p, constructed, RSTRING_LENINT(value), tn, tc);
01323         }
01324     }
01325     memcpy(p, RSTRING_PTR(value), RSTRING_LEN(value));
01326     p += RSTRING_LEN(value);
01327 
01328     /* In this case we need an additional EOC (one for the explicit part and
01329      * one for the Constructive itself. The EOC for the Constructive is
01330      * supplied by the user, but that for the "explicit wrapper" must be
01331      * added here.
01332      */
01333     if (explicit && inf_length == Qtrue) {
01334         ASN1_put_eoc(&p);
01335     }
01336     ossl_str_adjust(str, p);
01337 
01338     return str;
01339 }
01340 
01341 /*
01342  * call-seq:
01343  *    asn1_ary.each { |asn1| block } => asn1_ary
01344  *
01345  * Calls <i>block</i> once for each element in +self+, passing that element
01346  * as parameter +asn1+. If no block is given, an enumerator is returned
01347  * instead.
01348  *
01349  * == Example
01350  *   asn1_ary.each do |asn1|
01351  *     puts asn1
01352  *   end
01353  */
01354 static VALUE
01355 ossl_asn1cons_each(VALUE self)
01356 {
01357     rb_ary_each(ossl_asn1_get_value(self));
01358     return self;
01359 }
01360 
01361 /*
01362  * call-seq:
01363  *    ObjectId.register(object_id, short_name, long_name)
01364  *
01365  * This adds a new ObjectId to the internal tables. Where +object_id+ is the
01366  * numerical form, +short_name+ is the short name, and +long_name+ is the long
01367  * name.
01368  *
01369  * Returns +true+ if successful. Raises an ASN1Error otherwise.
01370  *
01371  */
01372 static VALUE
01373 ossl_asn1obj_s_register(VALUE self, VALUE oid, VALUE sn, VALUE ln)
01374 {
01375     StringValue(oid);
01376     StringValue(sn);
01377     StringValue(ln);
01378 
01379     if(!OBJ_create(RSTRING_PTR(oid), RSTRING_PTR(sn), RSTRING_PTR(ln)))
01380         ossl_raise(eASN1Error, NULL);
01381 
01382     return Qtrue;
01383 }
01384 
01385 /* Document-method: OpenSSL::ASN1::ObjectId#sn
01386  *
01387  * The short name of the ObjectId, as defined in +openssl/objects.h+.
01388  */
01389 /* Document-method: OpenSSL::ASN1::ObjectId#short_name
01390  *
01391  * #short_name is an alias to #sn
01392  */
01393 static VALUE
01394 ossl_asn1obj_get_sn(VALUE self)
01395 {
01396     VALUE val, ret = Qnil;
01397     int nid;
01398 
01399     val = ossl_asn1_get_value(self);
01400     if ((nid = OBJ_txt2nid(StringValuePtr(val))) != NID_undef)
01401         ret = rb_str_new2(OBJ_nid2sn(nid));
01402 
01403     return ret;
01404 }
01405 
01406 /* Document-method: OpenSSL::ASN1::ObjectId#ln
01407  *
01408  * The long name of the ObjectId, as defined in +openssl/objects.h+.
01409  */
01410 /* Document-method: OpenSSL::ASN1::ObjectId.long_name
01411  *
01412  * #long_name is an alias to #ln
01413  */
01414 static VALUE
01415 ossl_asn1obj_get_ln(VALUE self)
01416 {
01417     VALUE val, ret = Qnil;
01418     int nid;
01419 
01420     val = ossl_asn1_get_value(self);
01421     if ((nid = OBJ_txt2nid(StringValuePtr(val))) != NID_undef)
01422         ret = rb_str_new2(OBJ_nid2ln(nid));
01423 
01424     return ret;
01425 }
01426 
01427 /* Document-method: OpenSSL::ASN1::ObjectId#oid
01428  *
01429  * The object identifier as a String.
01430  */
01431 static VALUE
01432 ossl_asn1obj_get_oid(VALUE self)
01433 {
01434     VALUE val;
01435     ASN1_OBJECT *a1obj;
01436     char buf[128];
01437 
01438     val = ossl_asn1_get_value(self);
01439     a1obj = obj_to_asn1obj(val);
01440     OBJ_obj2txt(buf, sizeof(buf), a1obj, 1);
01441     ASN1_OBJECT_free(a1obj);
01442 
01443     return rb_str_new2(buf);
01444 }
01445 
01446 #define OSSL_ASN1_IMPL_FACTORY_METHOD(klass) \
01447 static VALUE ossl_asn1_##klass(int argc, VALUE *argv, VALUE self)\
01448 { return rb_funcall3(cASN1##klass, rb_intern("new"), argc, argv); }
01449 
01450 OSSL_ASN1_IMPL_FACTORY_METHOD(Boolean)
01451 OSSL_ASN1_IMPL_FACTORY_METHOD(Integer)
01452 OSSL_ASN1_IMPL_FACTORY_METHOD(Enumerated)
01453 OSSL_ASN1_IMPL_FACTORY_METHOD(BitString)
01454 OSSL_ASN1_IMPL_FACTORY_METHOD(OctetString)
01455 OSSL_ASN1_IMPL_FACTORY_METHOD(UTF8String)
01456 OSSL_ASN1_IMPL_FACTORY_METHOD(NumericString)
01457 OSSL_ASN1_IMPL_FACTORY_METHOD(PrintableString)
01458 OSSL_ASN1_IMPL_FACTORY_METHOD(T61String)
01459 OSSL_ASN1_IMPL_FACTORY_METHOD(VideotexString)
01460 OSSL_ASN1_IMPL_FACTORY_METHOD(IA5String)
01461 OSSL_ASN1_IMPL_FACTORY_METHOD(GraphicString)
01462 OSSL_ASN1_IMPL_FACTORY_METHOD(ISO64String)
01463 OSSL_ASN1_IMPL_FACTORY_METHOD(GeneralString)
01464 OSSL_ASN1_IMPL_FACTORY_METHOD(UniversalString)
01465 OSSL_ASN1_IMPL_FACTORY_METHOD(BMPString)
01466 OSSL_ASN1_IMPL_FACTORY_METHOD(Null)
01467 OSSL_ASN1_IMPL_FACTORY_METHOD(ObjectId)
01468 OSSL_ASN1_IMPL_FACTORY_METHOD(UTCTime)
01469 OSSL_ASN1_IMPL_FACTORY_METHOD(GeneralizedTime)
01470 OSSL_ASN1_IMPL_FACTORY_METHOD(Sequence)
01471 OSSL_ASN1_IMPL_FACTORY_METHOD(Set)
01472 OSSL_ASN1_IMPL_FACTORY_METHOD(EndOfContent)
01473 
01474 void
01475 Init_ossl_asn1()
01476 {
01477     VALUE ary;
01478     int i;
01479 
01480 #if 0
01481     mOSSL = rb_define_module("OpenSSL"); /* let rdoc know about mOSSL */
01482 #endif
01483 
01484     sUNIVERSAL = rb_intern("UNIVERSAL");
01485     sCONTEXT_SPECIFIC = rb_intern("CONTEXT_SPECIFIC");
01486     sAPPLICATION = rb_intern("APPLICATION");
01487     sPRIVATE = rb_intern("PRIVATE");
01488     sEXPLICIT = rb_intern("EXPLICIT");
01489     sIMPLICIT = rb_intern("IMPLICIT");
01490 
01491     sivVALUE = rb_intern("@value");
01492     sivTAG = rb_intern("@tag");
01493     sivTAGGING = rb_intern("@tagging");
01494     sivTAG_CLASS = rb_intern("@tag_class");
01495     sivINFINITE_LENGTH = rb_intern("@infinite_length");
01496     sivUNUSED_BITS = rb_intern("@unused_bits");
01497 
01498     /*
01499      * Document-module: OpenSSL::ASN1
01500      *
01501      * Abstract Syntax Notation One (or ASN.1) is a notation syntax to
01502      * describe data structures and is defined in ITU-T X.680. ASN.1 itself
01503      * does not mandate any encoding or parsing rules, but usually ASN.1 data
01504      * structures are encoded using the Distinguished Encoding Rules (DER) or
01505      * less often the Basic Encoding Rules (BER) described in ITU-T X.690. DER
01506      * and BER encodings are binary Tag-Length-Value (TLV) encodings that are
01507      * quite concise compared to other popular data description formats such
01508      * as XML, JSON etc.
01509      * ASN.1 data structures are very common in cryptographic applications,
01510      * e.g. X.509 public key certificates or certificate revocation lists
01511      * (CRLs) are all defined in ASN.1 and DER-encoded. ASN.1, DER and BER are
01512      * the building blocks of applied cryptography.
01513      * The ASN1 module provides the necessary classes that allow generation
01514      * of ASN.1 data structures and the methods to encode them using a DER
01515      * encoding. The decode method allows parsing arbitrary BER-/DER-encoded
01516      * data to a Ruby object that can then be modified and re-encoded at will.
01517      *
01518      * == ASN.1 class hierarchy
01519      *
01520      * The base class representing ASN.1 structures is ASN1Data. ASN1Data offers
01521      * attributes to read and set the +tag+, the +tag_class+ and finally the
01522      * +value+ of a particular ASN.1 item. Upon parsing, any tagged values
01523      * (implicit or explicit) will be represented by ASN1Data instances because
01524      * their "real type" can only be determined using out-of-band information
01525      * from the ASN.1 type declaration. Since this information is normally
01526      * known when encoding a type, all sub-classes of ASN1Data offer an
01527      * additional attribute +tagging+ that allows to encode a value implicitly
01528      * (+:IMPLICIT+) or explicitly (+:EXPLICIT+).
01529      *
01530      * === Constructive
01531      *
01532      * Constructive is, as its name implies, the base class for all
01533      * constructed encodings, i.e. those that consist of several values,
01534      * opposed to "primitive" encodings with just one single value.
01535      * Primitive values that are encoded with "infinite length" are typically
01536      * constructed (their values come in multiple chunks) and are therefore
01537      * represented by instances of Constructive. The value of an Constructive
01538      * is always an Array.
01539      *
01540      * ==== ASN1::Set and ASN1::Sequence
01541      *
01542      * The most common constructive encodings are SETs and SEQUENCEs, which is
01543      * why there are two sub-classes of Constructive representing each of
01544      * them.
01545      *
01546      * === Primitive
01547      *
01548      * This is the super class of all primitive values. Primitive
01549      * itself is not used when parsing ASN.1 data, all values are either
01550      * instances of a corresponding sub-class of Primitive or they are
01551      * instances of ASN1Data if the value was tagged implicitly or explicitly.
01552      * Please cf. Primitive documentation for details on sub-classes and
01553      * their respective mappings of ASN.1 data types to Ruby objects.
01554      *
01555      * == Possible values for +tagging+
01556      *
01557      * When constructing an ASN1Data object the ASN.1 type definition may
01558      * require certain elements to be either implicitly or explicitly tagged.
01559      * This can be achieved by setting the +tagging+ attribute manually for
01560      * sub-classes of ASN1Data. Use the symbol +:IMPLICIT+ for implicit
01561      * tagging and +:EXPLICIT+ if the element requires explicit tagging.
01562      *
01563      * == Possible values for +tag_class+
01564      *
01565      * It is possible to create arbitrary ASN1Data objects that also support
01566      * a PRIVATE or APPLICATION tag class. Possible values for the +tag_class+
01567      * attribute are:
01568      * * +:UNIVERSAL+ (the default for untagged values)
01569      * * +:CONTEXT_SPECIFIC+ (the default for tagged values)
01570      * * +:APPLICATION+
01571      * * +:PRIVATE+
01572      *
01573      * == Tag constants
01574      *
01575      * There is a constant defined for each universal tag:
01576      * * OpenSSL::ASN1::EOC (0)
01577      * * OpenSSL::ASN1::BOOLEAN (1)
01578      * * OpenSSL::ASN1::INTEGER (2)
01579      * * OpenSSL::ASN1::BIT_STRING (3)
01580      * * OpenSSL::ASN1::OCTET_STRING (4)
01581      * * OpenSSL::ASN1::NULL (5)
01582      * * OpenSSL::ASN1::OBJECT (6)
01583      * * OpenSSL::ASN1::ENUMERATED (10)
01584      * * OpenSSL::ASN1::UTF8STRING (12)
01585      * * OpenSSL::ASN1::SEQUENCE (16)
01586      * * OpenSSL::ASN1::SET (17)
01587      * * OpenSSL::ASN1::NUMERICSTRING (18)
01588      * * OpenSSL::ASN1::PRINTABLESTRING (19)
01589      * * OpenSSL::ASN1::T61STRING (20)
01590      * * OpenSSL::ASN1::VIDEOTEXSTRING (21)
01591      * * OpenSSL::ASN1::IA5STRING (22)
01592      * * OpenSSL::ASN1::UTCTIME (23)
01593      * * OpenSSL::ASN1::GENERALIZEDTIME (24)
01594      * * OpenSSL::ASN1::GRAPHICSTRING (25)
01595      * * OpenSSL::ASN1::ISO64STRING (26)
01596      * * OpenSSL::ASN1::GENERALSTRING (27)
01597      * * OpenSSL::ASN1::UNIVERSALSTRING (28)
01598      * * OpenSSL::ASN1::BMPSTRING (30)
01599      *
01600      * == UNIVERSAL_TAG_NAME constant
01601      *
01602      * An Array that stores the name of a given tag number. These names are
01603      * the same as the name of the tag constant that is additionally defined,
01604      * e.g. UNIVERSAL_TAG_NAME[2] = "INTEGER" and OpenSSL::ASN1::INTEGER = 2.
01605      *
01606      * == Example usage
01607      *
01608      * === Decoding and viewing a DER-encoded file
01609      *   require 'openssl'
01610      *   require 'pp'
01611      *   der = File.binread('data.der')
01612      *   asn1 = OpenSSL::ASN1.decode(der)
01613      *   pp der
01614      *
01615      * === Creating an ASN.1 structure and DER-encoding it
01616      *   require 'openssl'
01617      *   version = OpenSSL::ASN1::Integer.new(1)
01618      *   # Explicitly 0-tagged implies context-specific tag class
01619      *   serial = OpenSSL::ASN1::Integer.new(12345, 0, :EXPLICIT, :CONTEXT_SPECIFIC)
01620      *   name = OpenSSL::ASN1::PrintableString.new('Data 1')
01621      *   sequence = OpenSSL::ASN1::Sequence.new( [ version, serial, name ] )
01622      *   der = sequence.to_der
01623      */
01624     mASN1 = rb_define_module_under(mOSSL, "ASN1");
01625 
01626     /* Document-class: OpenSSL::ASN1::ASN1Error
01627      *
01628      * Generic error class for all errors raised in ASN1 and any of the
01629      * classes defined in it.
01630      */
01631     eASN1Error = rb_define_class_under(mASN1, "ASN1Error", eOSSLError);
01632     rb_define_module_function(mASN1, "traverse", ossl_asn1_traverse, 1);
01633     rb_define_module_function(mASN1, "decode", ossl_asn1_decode, 1);
01634     rb_define_module_function(mASN1, "decode_all", ossl_asn1_decode_all, 1);
01635     ary = rb_ary_new();
01636 
01637     /*
01638      * Array storing tag names at the tag's index.
01639      */
01640     rb_define_const(mASN1, "UNIVERSAL_TAG_NAME", ary);
01641     for(i = 0; i < ossl_asn1_info_size; i++){
01642         if(ossl_asn1_info[i].name[0] == '[') continue;
01643         rb_define_const(mASN1, ossl_asn1_info[i].name, INT2NUM(i));
01644         rb_ary_store(ary, i, rb_str_new2(ossl_asn1_info[i].name));
01645     }
01646 
01647     /* Document-class: OpenSSL::ASN1::ASN1Data
01648      *
01649      * The top-level class representing any ASN.1 object. When parsed by
01650      * ASN1.decode, tagged values are always represented by an instance
01651      * of ASN1Data.
01652      *
01653      * == The role of ASN1Data for parsing tagged values
01654      *
01655      * When encoding an ASN.1 type it is inherently clear what original
01656      * type (e.g. INTEGER, OCTET STRING etc.) this value has, regardless
01657      * of its tagging.
01658      * But opposed to the time an ASN.1 type is to be encoded, when parsing
01659      * them it is not possible to deduce the "real type" of tagged
01660      * values. This is why tagged values are generally parsed into ASN1Data
01661      * instances, but with a different outcome for implicit and explicit
01662      * tagging.
01663      *
01664      * === Example of a parsed implicitly tagged value
01665      *
01666      * An implicitly 1-tagged INTEGER value will be parsed as an
01667      * ASN1Data with
01668      * * +tag+ equal to 1
01669      * * +tag_class+ equal to +:CONTEXT_SPECIFIC+
01670      * * +value+ equal to a +String+ that carries the raw encoding
01671      *   of the INTEGER.
01672      * This implies that a subsequent decoding step is required to
01673      * completely decode implicitly tagged values.
01674      *
01675      * === Example of a parsed explicitly tagged value
01676      *
01677      * An explicitly 1-tagged INTEGER value will be parsed as an
01678      * ASN1Data with
01679      * * +tag+ equal to 1
01680      * * +tag_class+ equal to +:CONTEXT_SPECIFIC+
01681      * * +value+ equal to an +Array+ with one single element, an
01682      *   instance of OpenSSL::ASN1::Integer, i.e. the inner element
01683      *   is the non-tagged primitive value, and the tagging is represented
01684      *   in the outer ASN1Data
01685      *
01686      * == Example - Decoding an implicitly tagged INTEGER
01687      *   int = OpenSSL::ASN1::Integer.new(1, 0, :IMPLICIT) # implicit 0-tagged
01688      *   seq = OpenSSL::ASN1::Sequence.new( [int] )
01689      *   der = seq.to_der
01690      *   asn1 = OpenSSL::ASN1.decode(der)
01691      *   # pp asn1 => #<OpenSSL::ASN1::Sequence:0x87326e0
01692      *   #              @infinite_length=false,
01693      *   #              @tag=16,
01694      *   #              @tag_class=:UNIVERSAL,
01695      *   #              @tagging=nil,
01696      *   #              @value=
01697      *   #                [#<OpenSSL::ASN1::ASN1Data:0x87326f4
01698      *   #                   @infinite_length=false,
01699      *   #                   @tag=0,
01700      *   #                   @tag_class=:CONTEXT_SPECIFIC,
01701      *   #                   @value="\x01">]>
01702      *   raw_int = asn1.value[0]
01703      *   # manually rewrite tag and tag class to make it an UNIVERSAL value
01704      *   raw_int.tag = OpenSSL::ASN1::INTEGER
01705      *   raw_int.tag_class = :UNIVERSAL
01706      *   int2 = OpenSSL::ASN1.decode(raw_int)
01707      *   puts int2.value # => 1
01708      *
01709      * == Example - Decoding an explicitly tagged INTEGER
01710      *   int = OpenSSL::ASN1::Integer.new(1, 0, :EXPLICIT) # explicit 0-tagged
01711      *   seq = OpenSSL::ASN1::Sequence.new( [int] )
01712      *   der = seq.to_der
01713      *   asn1 = OpenSSL::ASN1.decode(der)
01714      *   # pp asn1 => #<OpenSSL::ASN1::Sequence:0x87326e0
01715      *   #              @infinite_length=false,
01716      *   #              @tag=16,
01717      *   #              @tag_class=:UNIVERSAL,
01718      *   #              @tagging=nil,
01719      *   #              @value=
01720      *   #                [#<OpenSSL::ASN1::ASN1Data:0x87326f4
01721      *   #                   @infinite_length=false,
01722      *   #                   @tag=0,
01723      *   #                   @tag_class=:CONTEXT_SPECIFIC,
01724      *   #                   @value=
01725      *   #                     [#<OpenSSL::ASN1::Integer:0x85bf308
01726      *   #                        @infinite_length=false,
01727      *   #                        @tag=2,
01728      *   #                        @tag_class=:UNIVERSAL
01729      *   #                        @tagging=nil,
01730      *   #                        @value=1>]>]>
01731      *   int2 = asn1.value[0].value[0]
01732      *   puts int2.value # => 1
01733      */
01734     cASN1Data = rb_define_class_under(mASN1, "ASN1Data", rb_cObject);
01735     /*
01736      * Carries the value of a ASN.1 type.
01737      * Please confer Constructive and Primitive for the mappings between
01738      * ASN.1 data types and Ruby classes.
01739      */
01740     rb_attr(cASN1Data, rb_intern("value"), 1, 1, 0);
01741     /*
01742      * A +Number+ representing the tag number of this ASN1Data. Never +nil+.
01743      */
01744     rb_attr(cASN1Data, rb_intern("tag"), 1, 1, 0);
01745     /*
01746      * A +Symbol+ representing the tag class of this ASN1Data. Never +nil+.
01747      * See ASN1Data for possible values.
01748      */
01749     rb_attr(cASN1Data, rb_intern("tag_class"), 1, 1, 0);
01750     /*
01751      * Never +nil+. A +Boolean+ indicating whether the encoding was infinite
01752      * length (in the case of parsing) or whether an infinite length encoding
01753      * shall be used (in the encoding case).
01754      * In DER, every value has a finite length associated with it. But in
01755      * scenarios where large amounts of data need to be transferred it
01756      * might be desirable to have some kind of streaming support available.
01757      * For example, huge OCTET STRINGs are preferably sent in smaller-sized
01758      * chunks, each at a time.
01759      * This is possible in BER by setting the length bytes of an encoding
01760      * to zero and by this indicating that the following value will be
01761      * sent in chunks. Infinite length encodings are always constructed.
01762      * The end of such a stream of chunks is indicated by sending a EOC
01763      * (End of Content) tag. SETs and SEQUENCEs may use an infinite length
01764      * encoding, but also primitive types such as e.g. OCTET STRINGS or
01765      * BIT STRINGS may leverage this functionality (cf. ITU-T X.690).
01766      */
01767     rb_attr(cASN1Data, rb_intern("infinite_length"), 1, 1, 0);
01768     rb_define_method(cASN1Data, "initialize", ossl_asn1data_initialize, 3);
01769     rb_define_method(cASN1Data, "to_der", ossl_asn1data_to_der, 0);
01770 
01771     /* Document-class: OpenSSL::ASN1::Primitive
01772      *
01773      * The parent class for all primitive encodings. Attributes are the same as
01774      * for ASN1Data, with the addition of +tagging+.
01775      * Primitive values can never be infinite length encodings, thus it is not
01776      * possible to set the +infinite_length+ attribute for Primitive and its
01777      * sub-classes.
01778      *
01779      * == Primitive sub-classes and their mapping to Ruby classes
01780      * * OpenSSL::ASN1::EndOfContent    <=> +value+ is always +nil+
01781      * * OpenSSL::ASN1::Boolean         <=> +value+ is a +Boolean+
01782      * * OpenSSL::ASN1::Integer         <=> +value+ is a +Number+
01783      * * OpenSSL::ASN1::BitString       <=> +value+ is a +String+
01784      * * OpenSSL::ASN1::OctetString     <=> +value+ is a +String+
01785      * * OpenSSL::ASN1::Null            <=> +value+ is always +nil+
01786      * * OpenSSL::ASN1::Object          <=> +value+ is a +String+
01787      * * OpenSSL::ASN1::Enumerated      <=> +value+ is a +Number+
01788      * * OpenSSL::ASN1::UTF8String      <=> +value+ is a +String+
01789      * * OpenSSL::ASN1::NumericString   <=> +value+ is a +String+
01790      * * OpenSSL::ASN1::PrintableString <=> +value+ is a +String+
01791      * * OpenSSL::ASN1::T61String       <=> +value+ is a +String+
01792      * * OpenSSL::ASN1::VideotexString  <=> +value+ is a +String+
01793      * * OpenSSL::ASN1::IA5String       <=> +value+ is a +String+
01794      * * OpenSSL::ASN1::UTCTime         <=> +value+ is a +Time+
01795      * * OpenSSL::ASN1::GeneralizedTime <=> +value+ is a +Time+
01796      * * OpenSSL::ASN1::GraphicString   <=> +value+ is a +String+
01797      * * OpenSSL::ASN1::ISO64String     <=> +value+ is a +String+
01798      * * OpenSSL::ASN1::GeneralString   <=> +value+ is a +String+
01799      * * OpenSSL::ASN1::UniversalString <=> +value+ is a +String+
01800      * * OpenSSL::ASN1::BMPString       <=> +value+ is a +String+
01801      *
01802      * == OpenSSL::ASN1::BitString
01803      *
01804      * === Additional attributes
01805      * +unused_bits+: if the underlying BIT STRING's
01806      * length is a multiple of 8 then +unused_bits+ is 0. Otherwise
01807      * +unused_bits+ indicates the number of bits that are to be ignored in
01808      * the final octet of the +BitString+'s +value+.
01809      *
01810      * == OpenSSL::ASN1::ObjectId
01811      *
01812      * While OpenSSL::ASN1::ObjectId.new will allocate a new ObjectId, it is
01813      * not typically allocated this way, but rather that are received from
01814      * parsed ASN1 encodings.
01815      *
01816      * === Additional attributes
01817      * * +sn+: the short name as defined in <openssl/objects.h>.
01818      * * +ln+: the long name as defined in <openssl/objects.h>.
01819      * * +oid+: the object identifier as a +String+, e.g. "1.2.3.4.5"
01820      * * +short_name+: alias for +sn+.
01821      * * +long_name+: alias for +ln+.
01822      *
01823      * == Examples
01824      * With the Exception of OpenSSL::ASN1::EndOfContent, each Primitive class
01825      * constructor takes at least one parameter, the +value+.
01826      *
01827      * === Creating EndOfContent
01828      *   eoc = OpenSSL::ASN1::EndOfContent.new
01829      *
01830      * === Creating any other Primitive
01831      *   prim = <class>.new(value) # <class> being one of the sub-classes except EndOfContent
01832      *   prim_zero_tagged_implicit = <class>.new(value, 0, :IMPLICIT)
01833      *   prim_zero_tagged_explicit = <class>.new(value, 0, :EXPLICIT)
01834      */
01835     cASN1Primitive = rb_define_class_under(mASN1, "Primitive", cASN1Data);
01836     /*
01837      * May be used as a hint for encoding a value either implicitly or
01838      * explicitly by setting it either to +:IMPLICIT+ or to +:EXPLICIT+.
01839      * +tagging+ is not set when a ASN.1 structure is parsed using
01840      * OpenSSL::ASN1.decode.
01841      */
01842     rb_attr(cASN1Primitive, rb_intern("tagging"), 1, 1, Qtrue);
01843     rb_undef_method(cASN1Primitive, "infinite_length=");
01844     rb_define_method(cASN1Primitive, "initialize", ossl_asn1_initialize, -1);
01845     rb_define_method(cASN1Primitive, "to_der", ossl_asn1prim_to_der, 0);
01846 
01847     /* Document-class: OpenSSL::ASN1::Constructive
01848      *
01849      * The parent class for all constructed encodings. The +value+ attribute
01850      * of a Constructive is always an +Array+. Attributes are the same as
01851      * for ASN1Data, with the addition of +tagging+.
01852      *
01853      * == SET and SEQUENCE
01854      *
01855      * Most constructed encodings come in the form of a SET or a SEQUENCE.
01856      * These encodings are represented by one of the two sub-classes of
01857      * Constructive:
01858      * * OpenSSL::ASN1::Set
01859      * * OpenSSL::ASN1::Sequence
01860      * Please note that tagged sequences and sets are still parsed as
01861      * instances of ASN1Data. Find further details on tagged values
01862      * there.
01863      *
01864      * === Example - constructing a SEQUENCE
01865      *   int = OpenSSL::ASN1::Integer.new(1)
01866      *   str = OpenSSL::ASN1::PrintableString.new('abc')
01867      *   sequence = OpenSSL::ASN1::Sequence.new( [ int, str ] )
01868      *
01869      * === Example - constructing a SET
01870      *   int = OpenSSL::ASN1::Integer.new(1)
01871      *   str = OpenSSL::ASN1::PrintableString.new('abc')
01872      *   set = OpenSSL::ASN1::Set.new( [ int, str ] )
01873      *
01874      * == Infinite length primitive values
01875      *
01876      * The only case where Constructive is used directly is for infinite
01877      * length encodings of primitive values. These encodings are always
01878      * constructed, with the contents of the +value+ +Array+ being either
01879      * UNIVERSAL non-infinite length partial encodings of the actual value
01880      * or again constructive encodings with infinite length (i.e. infinite
01881      * length primitive encodings may be constructed recursively with another
01882      * infinite length value within an already infinite length value). Each
01883      * partial encoding must be of the same UNIVERSAL type as the overall
01884      * encoding. The value of the overall encoding consists of the
01885      * concatenation of each partial encoding taken in sequence. The +value+
01886      * array of the outer infinite length value must end with a
01887      * OpenSSL::ASN1::EndOfContent instance.
01888      *
01889      * Please note that it is not possible to encode Constructive without
01890      * the +infinite_length+ attribute being set to +true+, use
01891      * OpenSSL::ASN1::Sequence or OpenSSL::ASN1::Set in these cases instead.
01892      *
01893      * === Example - Infinite length OCTET STRING
01894      *   partial1 = OpenSSL::ASN1::OctetString.new("\x01")
01895      *   partial2 = OpenSSL::ASN1::OctetString.new("\x02")
01896      *   inf_octets = OpenSSL::ASN1::Constructive.new( [ partial1,
01897      *                                                   partial2,
01898      *                                                   OpenSSL::ASN1::EndOfContent.new ],
01899      *                                                 OpenSSL::ASN1::OCTET_STRING,
01900      *                                                 nil,
01901      *                                                 :UNIVERSAL )
01902      *   # The real value of inf_octets is "\x01\x02", i.e. the concatenation
01903      *   # of partial1 and partial2
01904      *   inf_octets.infinite_length = true
01905      *   der = inf_octets.to_der
01906      *   asn1 = OpenSSL::ASN1.decode(der)
01907      *   puts asn1.infinite_length # => true
01908      */
01909     cASN1Constructive = rb_define_class_under(mASN1,"Constructive", cASN1Data);
01910     rb_include_module(cASN1Constructive, rb_mEnumerable);
01911     /*
01912      * May be used as a hint for encoding a value either implicitly or
01913      * explicitly by setting it either to +:IMPLICIT+ or to +:EXPLICIT+.
01914      * +tagging+ is not set when a ASN.1 structure is parsed using
01915      * OpenSSL::ASN1.decode.
01916      */
01917     rb_attr(cASN1Constructive, rb_intern("tagging"), 1, 1, Qtrue);
01918     rb_define_method(cASN1Constructive, "initialize", ossl_asn1_initialize, -1);
01919     rb_define_method(cASN1Constructive, "to_der", ossl_asn1cons_to_der, 0);
01920     rb_define_method(cASN1Constructive, "each", ossl_asn1cons_each, 0);
01921 
01922 #define OSSL_ASN1_DEFINE_CLASS(name, super) \
01923 do{\
01924     cASN1##name = rb_define_class_under(mASN1, #name, cASN1##super);\
01925     rb_define_module_function(mASN1, #name, ossl_asn1_##name, -1);\
01926 }while(0)
01927 
01928     OSSL_ASN1_DEFINE_CLASS(Boolean, Primitive);
01929     OSSL_ASN1_DEFINE_CLASS(Integer, Primitive);
01930     OSSL_ASN1_DEFINE_CLASS(Enumerated, Primitive);
01931     OSSL_ASN1_DEFINE_CLASS(BitString, Primitive);
01932     OSSL_ASN1_DEFINE_CLASS(OctetString, Primitive);
01933     OSSL_ASN1_DEFINE_CLASS(UTF8String, Primitive);
01934     OSSL_ASN1_DEFINE_CLASS(NumericString, Primitive);
01935     OSSL_ASN1_DEFINE_CLASS(PrintableString, Primitive);
01936     OSSL_ASN1_DEFINE_CLASS(T61String, Primitive);
01937     OSSL_ASN1_DEFINE_CLASS(VideotexString, Primitive);
01938     OSSL_ASN1_DEFINE_CLASS(IA5String, Primitive);
01939     OSSL_ASN1_DEFINE_CLASS(GraphicString, Primitive);
01940     OSSL_ASN1_DEFINE_CLASS(ISO64String, Primitive);
01941     OSSL_ASN1_DEFINE_CLASS(GeneralString, Primitive);
01942     OSSL_ASN1_DEFINE_CLASS(UniversalString, Primitive);
01943     OSSL_ASN1_DEFINE_CLASS(BMPString, Primitive);
01944     OSSL_ASN1_DEFINE_CLASS(Null, Primitive);
01945     OSSL_ASN1_DEFINE_CLASS(ObjectId, Primitive);
01946     OSSL_ASN1_DEFINE_CLASS(UTCTime, Primitive);
01947     OSSL_ASN1_DEFINE_CLASS(GeneralizedTime, Primitive);
01948 
01949     OSSL_ASN1_DEFINE_CLASS(Sequence, Constructive);
01950     OSSL_ASN1_DEFINE_CLASS(Set, Constructive);
01951 
01952     OSSL_ASN1_DEFINE_CLASS(EndOfContent, Data);
01953 
01954 
01955     /* Document-class: OpenSSL::ASN1::ObjectId
01956      *
01957      * Represents the primitive object id for OpenSSL::ASN1
01958      */
01959 #if 0
01960     cASN1ObjectId = rb_define_class_under(mASN1, "ObjectId", cASN1Primitive);  /* let rdoc know */
01961 #endif
01962     rb_define_singleton_method(cASN1ObjectId, "register", ossl_asn1obj_s_register, 3);
01963     rb_define_method(cASN1ObjectId, "sn", ossl_asn1obj_get_sn, 0);
01964     rb_define_method(cASN1ObjectId, "ln", ossl_asn1obj_get_ln, 0);
01965     rb_define_method(cASN1ObjectId, "oid", ossl_asn1obj_get_oid, 0);
01966     rb_define_alias(cASN1ObjectId, "short_name", "sn");
01967     rb_define_alias(cASN1ObjectId, "long_name", "ln");
01968     rb_attr(cASN1BitString, rb_intern("unused_bits"), 1, 1, 0);
01969 
01970     rb_define_method(cASN1EndOfContent, "initialize", ossl_asn1eoc_initialize, 0);
01971 
01972     class_tag_map = rb_hash_new();
01973     rb_hash_aset(class_tag_map, cASN1EndOfContent, INT2NUM(V_ASN1_EOC));
01974     rb_hash_aset(class_tag_map, cASN1Boolean, INT2NUM(V_ASN1_BOOLEAN));
01975     rb_hash_aset(class_tag_map, cASN1Integer, INT2NUM(V_ASN1_INTEGER));
01976     rb_hash_aset(class_tag_map, cASN1BitString, INT2NUM(V_ASN1_BIT_STRING));
01977     rb_hash_aset(class_tag_map, cASN1OctetString, INT2NUM(V_ASN1_OCTET_STRING));
01978     rb_hash_aset(class_tag_map, cASN1Null, INT2NUM(V_ASN1_NULL));
01979     rb_hash_aset(class_tag_map, cASN1ObjectId, INT2NUM(V_ASN1_OBJECT));
01980     rb_hash_aset(class_tag_map, cASN1Enumerated, INT2NUM(V_ASN1_ENUMERATED));
01981     rb_hash_aset(class_tag_map, cASN1UTF8String, INT2NUM(V_ASN1_UTF8STRING));
01982     rb_hash_aset(class_tag_map, cASN1Sequence, INT2NUM(V_ASN1_SEQUENCE));
01983     rb_hash_aset(class_tag_map, cASN1Set, INT2NUM(V_ASN1_SET));
01984     rb_hash_aset(class_tag_map, cASN1NumericString, INT2NUM(V_ASN1_NUMERICSTRING));
01985     rb_hash_aset(class_tag_map, cASN1PrintableString, INT2NUM(V_ASN1_PRINTABLESTRING));
01986     rb_hash_aset(class_tag_map, cASN1T61String, INT2NUM(V_ASN1_T61STRING));
01987     rb_hash_aset(class_tag_map, cASN1VideotexString, INT2NUM(V_ASN1_VIDEOTEXSTRING));
01988     rb_hash_aset(class_tag_map, cASN1IA5String, INT2NUM(V_ASN1_IA5STRING));
01989     rb_hash_aset(class_tag_map, cASN1UTCTime, INT2NUM(V_ASN1_UTCTIME));
01990     rb_hash_aset(class_tag_map, cASN1GeneralizedTime, INT2NUM(V_ASN1_GENERALIZEDTIME));
01991     rb_hash_aset(class_tag_map, cASN1GraphicString, INT2NUM(V_ASN1_GRAPHICSTRING));
01992     rb_hash_aset(class_tag_map, cASN1ISO64String, INT2NUM(V_ASN1_ISO64STRING));
01993     rb_hash_aset(class_tag_map, cASN1GeneralString, INT2NUM(V_ASN1_GENERALSTRING));
01994     rb_hash_aset(class_tag_map, cASN1UniversalString, INT2NUM(V_ASN1_UNIVERSALSTRING));
01995     rb_hash_aset(class_tag_map, cASN1BMPString, INT2NUM(V_ASN1_BMPSTRING));
01996     rb_global_variable(&class_tag_map);
01997 }
01998 

Generated on 19 Jul 2016 for Ruby by  doxygen 1.4.7