/*=============================================================*/
/* general ASN1 declarations and parsing
*
* For now, this is used only for extracting the key from an
* X509 certificate, so the entire collection is hidden. But
* someday we should probably make the functions visible and
* give them their own man page.
*/
typedef struct Elem Elem;
typedef struct Tag Tag;
typedef struct Value Value;
typedef struct Bytes Bytes;
typedef struct Ints Ints;
typedef struct Bits Bits;
typedef struct Elist Elist;
/* tag classes */
#define Universal 0
#define Context 0x80
static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
static int length_decode(uchar** pp, uchar* pend, int* plength);
static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
static int uint7_decode(uchar** pp, uchar* pend, int* pint);
static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
static int enc(uchar** pp, Elem e, int lenonly);
static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
static void uint7_enc(uchar** pp, int num, int lenonly);
static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
n = strlen(s)+1;
d = emalloc(n);
memmove(d, s, n);
return d;
}
/*
* Decode a[0..len] as a BER encoding of an ASN1 type.
* The return value is one of ASN_OK, etc.
* Depending on the error, the returned elem may or may not
* be nil.
*/
static int
decode(uchar* a, int alen, Elem* pelem)
{
uchar* p = a;
int err;
/*
* All of the following decoding routines take arguments:
* uchar **pp;
* uchar *pend;
* Where parsing is supposed to start at **pp, and when parsing
* is done, *pp is updated to point at next char to be parsed.
* The pend pointer is just past end of string; an error should
* be returned parsing hasn't finished by then.
*
* The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
* The remaining argument(s) are pointers to where parsed entity goes.
*/
/* Decode an ASN1 'Elem' (tag, length, value) */
static int
ber_decode(uchar** pp, uchar* pend, Elem* pelem)
{
int err;
int isconstr;
int length;
Tag tag;
Value val;
/* Decode a value field */
static int
value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
{
int err;
Bytes* va;
int num;
int bitsunused;
int subids[MAXOBJIDLEN];
int isubid;
Elist* vl;
uchar* p;
uchar* pe;
case UTF8String:
case NumericString:
case PrintableString:
case TeletexString:
case VideotexString:
case IA5String:
case UTCTime:
case GeneralizedTime:
case GraphicString:
case VisibleString:
case GeneralString:
case UniversalString:
case BMPString:
err = octet_decode(&p, pend, length, isconstr, &va);
if(err == ASN_OK) {
uchar *s;
char *d;
Rune r;
int n;
switch(kind){
case UniversalString:
n = va->len / 4;
d = emalloc(n*UTFmax+1);
pval->u.stringval = d;
s = va->data;
while(n > 0){
r = s[0]<<24 | s[1]<<16 | s[2]<<8 | s[3];
if(r == 0)
break;
n--;
s += 4;
d += runetochar(d, &r);
}
*d = 0;
break;
case BMPString:
n = va->len / 2;
d = emalloc(n*UTFmax+1);
pval->u.stringval = d;
s = va->data;
while(n > 0){
r = s[0]<<8 | s[1];
if(r == 0)
break;
n--;
s += 2;
d += runetochar(d, &r);
}
*d = 0;
break;
default:
n = va->len;
d = emalloc(n+1);
pval->u.stringval = d;
s = va->data;
while(n > 0){
if((*d = *s) == 0)
break;
n--;
s++;
d++;
}
*d = 0;
break;
}
if(n != 0){
err = ASN_EINVAL;
free(pval->u.stringval);
} else
pval->tag = VString;
free(va);
}
break;
/*
* Decode an int in format where count bytes are
* concatenated to form value.
* Although ASN1 allows any size integer, we return
* an error if the result doesn't fit in a 32-bit int.
* If unsgned is not set, make sure to propagate sign bit.
*/
static int
int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
{
int err;
int num;
uchar* p;
/*
* Decode an unsigned int in format where each
* byte except last has high bit set, and remaining
* seven bits of each byte are concatenated to form value.
* Although ASN1 allows any size integer, we return
* an error if the result doesn't fit in a 32 bit int.
*/
static int
uint7_decode(uchar** pp, uchar* pend, int* pint)
{
int err;
int num;
int more;
int v;
uchar* p;
p = *pp;
err = ASN_OK;
num = 0;
more = 1;
while(more && p < pend) {
v = *p++;
if(num&0x7F000000) {
err = ASN_ETOOBIG;
break;
}
num <<= 7;
more = v&0x80;
num |= (v&0x7F);
}
if(p == pend)
err = ASN_ESHORT;
*pint = num;
*pp = p;
return err;
}
/*
* Decode an octet string, recursively if isconstr.
* We've already checked that length==-1 implies isconstr==1,
* and otherwise that specified length fits within (*pp..pend)
*/
static int
octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
{
int err;
uchar* p;
Bytes* ans;
Bytes* newans;
uchar* pstart;
uchar* pold;
Elem elem;
err = ASN_OK;
p = *pp;
ans = nil;
if(length >= 0 && !isconstr) {
ans = makebytes(p, length);
p += length;
}
else {
/* constructed, either definite or indefinite length */
pstart = p;
for(;;) {
if(length >= 0 && p >= pstart + length) {
if(p != pstart + length)
err = ASN_EVALLEN;
break;
}
pold = p;
err = ber_decode(&p, pend, &elem);
if(err != ASN_OK)
break;
switch(elem.val.tag) {
case VOctets:
newans = catbytes(ans, elem.val.u.octetsval);
freevalfields(&elem.val);
freebytes(ans);
ans = newans;
break;
/*
* Encode e by BER rules, putting answer in *pbytes.
* This is done by first calling enc with lenonly==1
* to get the length of the needed buffer,
* then allocating the buffer and using enc again to fill it up.
*/
static int
encode(Elem e, Bytes** pbytes)
{
uchar* p;
Bytes* ans;
int err;
uchar uc;
p = &uc;
err = enc(&p, e, 1);
if(err == ASN_OK) {
ans = newbytes(p-&uc);
p = ans->data;
err = enc(&p, e, 0);
*pbytes = ans;
}
return err;
}
/*
* The various enc functions take a pointer to a pointer
* into a buffer, and encode their entity starting there,
* updating the pointer afterwards.
* If lenonly is 1, only the pointer update is done,
* allowing enc to be called first to calculate the needed
* buffer length.
* If lenonly is 0, it is assumed that the answer will fit.
*/
static int
enc(uchar** pp, Elem e, int lenonly)
{
int err;
int vlen;
int constr;
Tag tag;
int v;
int ilen;
uchar* p;
uchar* psave;
static int
val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
{
int err;
uchar* p;
int kind;
int cl;
int v;
Bytes* bb = nil;
Bits* bits;
Ints* oid;
int k;
Elist* el;
char* s;
p = *pp;
err = ASN_OK;
kind = e.tag.num;
cl = e.tag.class;
*pconstr = 0;
if(cl != Universal) {
switch(e.val.tag) {
case VBool:
kind = BOOLEAN;
break;
case VInt:
kind = INTEGER;
break;
case VBigInt:
kind = INTEGER;
break;
case VOctets:
kind = OCTET_STRING;
break;
case VReal:
kind = REAL;
break;
case VOther:
kind = OCTET_STRING;
break;
case VBitString:
kind = BIT_STRING;
break;
case VNull:
kind = NULLTAG;
break;
case VObjId:
kind = OBJECT_ID;
break;
case VString:
kind = UniversalString;
break;
case VSeq:
kind = SEQUENCE;
break;
case VSet:
kind = SETOF;
break;
}
}
switch(kind) {
case BOOLEAN:
if(is_int(&e, &v)) {
if(v != 0)
v = 255;
int_enc(&p, v, 1, lenonly);
}
else
err = ASN_EINVAL;
break;
case INTEGER:
case ENUMERATED:
if(is_int(&e, &v))
int_enc(&p, v, 0, lenonly);
else {
if(is_bigint(&e, &bb)) {
if(!lenonly)
memmove(p, bb->data, bb->len);
p += bb->len;
}
else
err = ASN_EINVAL;
}
break;
case OCTET_STRING:
case ObjectDescriptor:
case EXTERNAL:
case REAL:
case EMBEDDED_PDV:
bb = nil;
switch(e.val.tag) {
case VOctets:
bb = e.val.u.octetsval;
break;
case VReal:
bb = e.val.u.realval;
break;
case VOther:
bb = e.val.u.otherval;
break;
}
if(bb != nil) {
if(!lenonly)
memmove(p, bb->data, bb->len);
p += bb->len;
}
else
err = ASN_EINVAL;
break;
case NULLTAG:
break;
case OBJECT_ID:
if(is_oid(&e, &oid)) {
for(k = 0; k < oid->len; k++) {
v = oid->data[k];
if(k == 0) {
v *= 40;
if(oid->len > 1)
v += oid->data[++k];
}
uint7_enc(&p, v, lenonly);
}
}
else
err = ASN_EINVAL;
break;
case SEQUENCE:
case SETOF:
el = nil;
if(e.val.tag == VSeq)
el = e.val.u.seqval;
else if(e.val.tag == VSet)
el = e.val.u.setval;
else
err = ASN_EINVAL;
if(el != nil) {
*pconstr = CONSTR_MASK;
for(; el != nil; el = el->tl) {
err = enc(&p, el->hd, lenonly);
if(err != ASN_OK)
break;
}
}
break;
case UTF8String:
case NumericString:
case PrintableString:
case TeletexString:
case VideotexString:
case IA5String:
case UTCTime:
case GeneralizedTime:
case GraphicString:
case VisibleString:
case GeneralString:
case UniversalString:
case BMPString:
if(e.val.tag == VString) {
s = e.val.u.stringval;
if(s != nil) {
v = strlen(s);
if(!lenonly)
memmove(p, s, v);
p += v;
}
}
else
err = ASN_EINVAL;
break;
/*
* Encode num as unsigned 7 bit values with top bit 1 on all bytes
* except last, only putting in bytes if !lenonly.
*/
static void
uint7_enc(uchar** pp, int num, int lenonly)
{
int n;
int v;
int k;
uchar* p;
p = *pp;
n = 1;
v = num >> 7;
while(v > 0) {
v >>= 7;
n++;
}
if(lenonly)
p += n;
else {
for(k = (n - 1)*7; k > 0; k -= 7)
*p++= ((num >> k)|0x80);
*p++ = (num&0x7F);
}
*pp = p;
}
/*
* Encode num as unsigned or signed integer,
* only putting in bytes if !lenonly.
* Encoding is length followed by bytes to concatenate.
*/
static void
int_enc(uchar** pp, int num, int unsgned, int lenonly)
{
int v;
int n;
int prevv;
int k;
uchar* p;
p = *pp;
v = num;
if(v < 0)
v = -(v + 1);
n = 1;
prevv = v;
v >>= 8;
while(v > 0) {
prevv = v;
v >>= 8;
n++;
}
if(!unsgned && (prevv&0x80))
n++;
if(lenonly)
p += n;
else {
for(k = (n - 1)*8; k >= 0; k -= 8)
*p++ = (num >> k);
}
*pp = p;
}
static int
ints_eq(Ints* a, Ints* b)
{
int alen;
int i;
/*
* Look up o in tab (which must have nil entry to terminate).
* Return index of matching entry, or -1 if none.
*/
static int
oid_lookup(Ints* o, Ints** tab)
{
int i;
/*
* Return true if *pe is a SEQUENCE, and set *pseq to
* the value of the sequence if so.
*/
static int
is_seq(Elem* pe, Elist** pseq)
{
if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
*pseq = pe->val.u.seqval;
return 1;
}
return 0;
}
/*
* for convience, all VInt's are readable via this routine,
* as well as all VBigInt's
*/
static int
is_bigint(Elem* pe, Bytes** pbigint)
{
if(pe->tag.class == Universal && pe->tag.num == INTEGER && pe->val.tag == VBigInt) {
*pbigint = pe->val.u.bigintval;
return 1;
}
return 0;
}
static int
is_string(Elem* pe, char** pstring)
{
if(pe->tag.class == Universal) {
switch(pe->tag.num) {
case UTF8String:
case NumericString:
case PrintableString:
case TeletexString:
case VideotexString:
case IA5String:
case GraphicString:
case VisibleString:
case GeneralString:
case UniversalString:
case BMPString:
if(pe->val.tag == VString) {
*pstring = pe->val.u.stringval;
return 1;
}
}
}
return 0;
}
/*
* newbytes(len), with data initialized from buf
*/
static Bytes*
makebytes(uchar* buf, int len)
{
Bytes* ans;
ans = newbytes(len);
memmove(ans->data, buf, len);
return ans;
}
static void
freebytes(Bytes* b)
{
free(b);
}
/*
* Make a new Bytes, containing bytes of b1 followed by those of b2.
* Either b1 or b2 or both can be nil.
*/
static Bytes*
catbytes(Bytes* b1, Bytes* b2)
{
Bytes* ans;
int n;
if(b1 == nil) {
if(b2 == nil)
ans = newbytes(0);
else
ans = makebytes(b2->data, b2->len);
}
else if(b2 == nil) {
ans = makebytes(b1->data, b1->len);
}
else {
n = b1->len + b2->len;
ans = newbytes(n);
ans->len = n;
memmove(ans->data, b1->data, b1->len);
memmove(ans->data+b1->len, b2->data, b2->len);
}
return ans;
}
/* len is number of ints */
static Ints*
newints(int len)
{
Ints* ans;
if(len < 0 || len > ((uint)-1>>1)/sizeof(int))
abort();
ans = emalloc(sizeof(Ints) + len*sizeof(int));
ans->len = len;
return ans;
}
static Ints*
makeints(int* buf, int len)
{
Ints* ans;
ans = newints(len);
memmove(ans->data, buf, len*sizeof(int));
return ans;
}
static void
freeints(Ints* b)
{
free(b);
}
/* len is number of bytes */
static Bits*
newbits(int len)
{
Bits* ans;
/*
* Parse the Name ASN1 type.
* The sequence of RelativeDistinguishedName's gives a sort of pathname,
* from most general to most specific. Each element of the path can be
* one or more (but usually just one) attribute-value pair, such as
* countryName="US".
* We'll just form a "postal-style" address string by concatenating the elements
* from most specific to least specific, separated by commas.
* Return name-as-string (which must be freed by caller).
*/
static char*
parse_name(Elem* e)
{
Elist* el;
Elem* es;
Elist* esetl;
Elem* eat;
Elist* eatl;
char* s;
enum { MAXPARTS = 100 };
char* parts[MAXPARTS];
int i;
int plen;
char* ans = nil;
/*
* Parse an AlgorithmIdentifer ASN1 type.
* Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
* or -1 if not found.
* For now, ignore parameters, since none of our algorithms need them.
*/
static int
parse_alg(Elem* e)
{
Elist* el;
Ints* oid;
/*
* digest(CertificateInfo)
* Our ASN.1 library doesn't return pointers into the original
* data array, so we need to do a little hand decoding.
*/
static int
digest_certinfo(uchar *cert, int ncert, DigestAlg *da, uchar *digest)
{
uchar *info, *p, *pend;
int isconstr, length;
Tag tag;
Elem elem;
mpint*
pkcs1padbuf(uchar *buf, int len, mpint *modulus, int blocktype)
{
int i, n = (mpsignif(modulus)-1)/8;
int pad = n - 2 - len;
uchar *p;
mpint *mp;
if(tag.class != Universal){
snprint(buf, sizeof(buf), "class%d,num%d", tag.class, tag.num);
return buf;
}
switch(tag.num){
case BOOLEAN: return "BOOLEAN";
case INTEGER: return "INTEGER";
case BIT_STRING: return "BIT STRING";
case OCTET_STRING: return "OCTET STRING";
case NULLTAG: return "NULLTAG";
case OBJECT_ID: return "OID";
case ObjectDescriptor: return "OBJECT_DES";
case EXTERNAL: return "EXTERNAL";
case REAL: return "REAL";
case ENUMERATED: return "ENUMERATED";
case EMBEDDED_PDV: return "EMBEDDED PDV";
case SEQUENCE: return "SEQUENCE";
case SETOF: return "SETOF";
case UTF8String: return "UTF8String";
case NumericString: return "NumericString";
case PrintableString: return "PrintableString";
case TeletexString: return "TeletexString";
case VideotexString: return "VideotexString";
case IA5String: return "IA5String";
case UTCTime: return "UTCTime";
case GeneralizedTime: return "GeneralizedTime";
case GraphicString: return "GraphicString";
case VisibleString: return "VisibleString";
case GeneralString: return "GeneralString";
case UniversalString: return "UniversalString";
case BMPString: return "BMPString";
default:
snprint(buf, sizeof(buf), "Universal,num%d", tag.num);
return buf;
}
}
static void
edump(Elem e)
{
Value v;
Elist *el;
int i;
print("%s{", tagdump(e.tag));
v = e.val;
switch(v.tag){
case VBool: print("Bool %d",v.u.boolval); break;
case VInt: print("Int %d",v.u.intval); break;
case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
case VReal: print("Real..."); break;
case VOther: print("Other..."); break;
case VBitString: print("BitString[%d]...", v.u.bitstringval->len*8 - v.u.bitstringval->unusedbits); break;
case VNull: print("Null"); break;
case VEOC: print("EOC..."); break;
case VObjId: print("ObjId");
for(i = 0; i<v.u.objidval->len; i++)
print(" %d", v.u.objidval->data[i]);
break;
case VString: print("String \"%s\"",v.u.stringval); break;
case VSeq: print("Seq\n");
for(el = v.u.seqval; el!=nil; el = el->tl)
edump(el->hd);
break;
case VSet: print("Set\n");
for(el = v.u.setval; el!=nil; el = el->tl)
edump(el->hd);
break;
}
print("}\n");
}