3 * Copyright (c) 2006, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
14 int asn1_get_next(const u8 *buf, size_t len, struct asn1_hdr *hdr)
19 os_memset(hdr, 0, sizeof(*hdr));
23 hdr->identifier = *pos++;
24 hdr->class = hdr->identifier >> 6;
25 hdr->constructed = !!(hdr->identifier & (1 << 5));
27 if ((hdr->identifier & 0x1f) == 0x1f) {
31 wpa_printf(MSG_DEBUG, "ASN.1: Identifier "
36 wpa_printf(MSG_MSGDUMP, "ASN.1: Extended tag data: "
38 hdr->tag = (hdr->tag << 7) | (tmp & 0x7f);
41 hdr->tag = hdr->identifier & 0x1f;
46 wpa_printf(MSG_DEBUG, "ASN.1: Reserved length "
50 tmp &= 0x7f; /* number of subsequent octets */
53 wpa_printf(MSG_DEBUG, "ASN.1: Too long length field");
58 wpa_printf(MSG_DEBUG, "ASN.1: Length "
62 hdr->length = (hdr->length << 8) | *pos++;
65 /* Short form - length 0..127 in one octet */
69 if (end < pos || hdr->length > (unsigned int) (end - pos)) {
70 wpa_printf(MSG_DEBUG, "ASN.1: Contents underflow");
79 int asn1_parse_oid(const u8 *buf, size_t len, struct asn1_oid *oid)
85 os_memset(oid, 0, sizeof(*oid));
97 val = (val << 7) | (tmp & 0x7f);
100 if (oid->len >= ASN1_MAX_OID_LEN) {
101 wpa_printf(MSG_DEBUG, "ASN.1: Too long OID value");
106 * The first octet encodes the first two object
107 * identifier components in (X*40) + Y formula.
110 oid->oid[0] = val / 40;
113 oid->oid[1] = val - oid->oid[0] * 40;
116 oid->oid[oid->len++] = val;
123 int asn1_get_oid(const u8 *buf, size_t len, struct asn1_oid *oid,
128 if (asn1_get_next(buf, len, &hdr) < 0 || hdr.length == 0)
131 if (hdr.class != ASN1_CLASS_UNIVERSAL || hdr.tag != ASN1_TAG_OID) {
132 wpa_printf(MSG_DEBUG, "ASN.1: Expected OID - found class %d "
133 "tag 0x%x", hdr.class, hdr.tag);
137 *next = hdr.payload + hdr.length;
139 return asn1_parse_oid(hdr.payload, hdr.length, oid);
143 void asn1_oid_to_str(struct asn1_oid *oid, char *buf, size_t len)
154 for (i = 0; i < oid->len; i++) {
155 ret = os_snprintf(pos, buf + len - pos,
157 i == 0 ? "" : ".", oid->oid[i]);
158 if (ret < 0 || ret >= buf + len - pos)
166 static u8 rotate_bits(u8 octet)
172 for (i = 0; i < 8; i++) {
183 unsigned long asn1_bit_string_to_long(const u8 *buf, size_t len)
185 unsigned long val = 0;
188 /* BER requires that unused bits are zero, so we can ignore the number
193 val |= rotate_bits(*pos++);
195 val |= ((unsigned long) rotate_bits(*pos++)) << 8;
197 val |= ((unsigned long) rotate_bits(*pos++)) << 16;
199 val |= ((unsigned long) rotate_bits(*pos++)) << 24;
201 wpa_printf(MSG_DEBUG, "X509: %s - some bits ignored "
202 "(BIT STRING length %lu)",
203 __func__, (unsigned long) len);