summaryrefslogtreecommitdiff
path: root/client/certutil.c
blob: 7b0c81f5bd8af69a7c2060d60a3c0de5f18dcefc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*

  Copyright (c) 2011 Samuel Lidén Borell <samuel@kodafritt.se>
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include <stdbool.h>
#include <stdlib.h>
#include <glib.h>
#include <openssl/asn1t.h>
#include <openssl/err.h>

#include "../common/defines.h"
#if ENABLE_PKCS11
#include <libp11.h>
#endif

#include "misc.h"
#include "platform.h"
#include "certutil.h"


static char *error_string = NULL;

typedef struct {
    const char name[7]; /* length of "STREET" + terminator */
    const int nid;
} DNAttrInfo;

#define NUM_DN_ATTRS 14

/**
 * Returns an object identifier NID for a field name. This function uses
 * the names used in old versions of OpenSSL, BankID and probably other
 * software. These are different from RFC 2256.
 */
static bool get_non_rfc2256(const char *field, int *nid, ASN1_OBJECT **obj) {
    static const DNAttrInfo attrdefs[NUM_DN_ATTRS] = {
        // These are supported in Nexus Personal 4.10.4.3 and 4.16.1 on Win32
        { "C", NID_countryName, },
        { "CN", NID_commonName, },
        { "D", NID_description, },
        { "EM", NID_pkcs9_emailAddress, },
        { "G", NID_givenName, },
        { "L", NID_localityName, },
        { "N", NID_name, },
        { "O", NID_organizationName, },
        { "OU", NID_organizationalUnitName, },
        { "S", NID_surname, },
        { "SN", NID_serialNumber, },
        { "ST", NID_stateOrProvinceName, },
        { "STREET", NID_streetAddress, },
        { "T", NID_title, },
    };
            
    // Check for OID.x.x.x
    if (!g_ascii_strncasecmp(field, "OID.", 4)) {
        *obj = OBJ_txt2obj(field+4, 1);
        if (!*obj) return false;
        
        *nid = OBJ_obj2nid(*obj);
        return true;
    }
    
    for (size_t i = 0; i < NUM_DN_ATTRS; i++) {
        // Check for aliases
        if (!g_ascii_strcasecmp(field, attrdefs[i].name)) {
            *nid = attrdefs[i].nid;
            *obj = OBJ_nid2obj(*nid);
            return (*obj != NULL);
        }
    }
    
    return false;
}

/**
 * Determines which type a string should have in ASN1 (ASCII or UTF8).
 *
 * By default, OpenSSL seems to encode our UTF-8 strings as a T61STRING,
 * which is not what BankID does (and is also wrong).
 */
static int determine_string_type(const char *s, int length) {
    return (g_utf8_strlen(s, length) == length) ?
        V_ASN1_PRINTABLESTRING : V_ASN1_UTF8STRING;
}

/**
 * Parses a subject name in RFC 2253 format, for example:
 *  CN=John Doe,SN=197711223334
 *
 * If fullDN is false, then only the name (OID 2.5.4.41) is included.
 */
X509_NAME *certutil_parse_dn(const char *s, bool fullDN) {
    X509_NAME *subject = X509_NAME_new();
    STACK_OF(X509_NAME_ENTRY) *entries = sk_X509_NAME_ENTRY_new_null();
    ASN1_OBJECT *obj = NULL;
    // check for allocation failures and insane name lengths
    if (!subject || !entries || !checkstrlen(s, 4096)) goto error;
    
    while (*s != '\0') {
        // Ignore leading whitespace (this includes whitespace after a comma)
        while (g_ascii_isspace(*s)) s++;
        
        // Parse attribute
        size_t nameLength = strcspn(s, "=,;+");
        if (s[nameLength] != '=') goto error;
        
        const char *value = &s[nameLength+1];
        // TODO handle escaped data
        size_t valueLength = strcspn(value, ",;+");
        if (value[valueLength] == '+') goto error; // Not supported
        
        // Ignore trailing whitespace
        const char *end = &s[nameLength+1+valueLength];
        while (g_ascii_isspace(value[valueLength-1])) valueLength--;
        
        // Parse attribute name
        char *field = g_strndup(s, nameLength);
        if (!field) goto error;
        int nid;
        bool ok = get_non_rfc2256(field, &nid, &obj);
        g_free(field);
        if (!ok) goto error; // Unsupported attribute
        
        if (fullDN || nid == NID_name) {
            // Add attribute
            X509_NAME_ENTRY *entry = X509_NAME_ENTRY_create_by_OBJ(NULL, obj,
                determine_string_type(value, valueLength),
                (unsigned char*)value, valueLength);
            if (!entry) goto error;
            sk_X509_NAME_ENTRY_push(entries, entry);
        }
        
        ASN1_OBJECT_free(obj);
        obj = NULL;
        
        // Go to next attribute
        s = end;
        if (*s == ',' || *s == ';') s++;
    }
    
    // Add the attributes to the subject name in reverse order
    int num = sk_X509_NAME_ENTRY_num(entries);
    for (int i = num; i-- > 0; ) {
        X509_NAME_ENTRY *entry = sk_X509_NAME_ENTRY_value(entries, i);
        if (!entry) goto error;
        if (!X509_NAME_add_entry(subject, entry, -1, 0)) goto error;
        X509_NAME_ENTRY_free(entry);
    }
    sk_X509_NAME_ENTRY_free(entries);
    
    return subject;
    
  error:
    fprintf(stderr, BINNAME ": failed to parse subject name: %s\n", s);
    ASN1_OBJECT_free(obj);
    X509_NAME_free(subject);
    sk_X509_NAME_ENTRY_pop_free(entries, X509_NAME_ENTRY_free);
    return NULL;
}


/**
 * Returns the BASE64-encoded DER representation of a certificate.
 */
char *certutil_derEncode(X509 *cert) {
    unsigned char *der = NULL;
    char *base64 = NULL;
    int len;
    
    if (!cert) return NULL;
    len = i2d_X509(cert, &der);
    if (!der) return NULL;
    base64 = base64_encode((const char*)der, len);
    free(der);
    return base64;
}

const int opensslKeyUsages[] = {
    X509v3_KU_KEY_CERT_SIGN,     // KeyUsage_Issuing
    X509v3_KU_NON_REPUDIATION,   // KeyUsage_Signing
    X509v3_KU_DIGITAL_SIGNATURE, // KeyUsage_Authentication
};

/**
 * Returns true if a certificate supports the given key usage (such as
 * authentication or signing).
 */
bool certutil_hasKeyUsage(X509 *cert, KeyUsage keyUsage) {
    ASN1_BIT_STRING *usage;
    bool supported = false;

    usage = X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL);
    if (usage) {
        int opensslKeyUsage = opensslKeyUsages[keyUsage];
        supported = (usage->length > 0) &&
                    ((usage->data[0] & opensslKeyUsage) == opensslKeyUsage);
        ASN1_BIT_STRING_free(usage);
    }
    return supported;
}

/**
 * Gets a property of an X509_NAME, such as a subject name (NID_commonName),
 */
char *certutil_getNamePropertyByNID(X509_NAME *name, int nid) {
    char *text;
    int length;
    
    length = X509_NAME_get_text_by_NID(name, nid, NULL, 0);
    if (length < 0) return NULL;
    
    text = malloc(length+1);
    if (text) {
        text[0] = '\0'; // if the function would fail
        X509_NAME_get_text_by_NID(name, nid, text, length+1);
    }
    return text;
}

/**
 * Returns a string to be displayed for a X509_NAME. First, it tries NID_name,
 * then it falls backs to concatenate the firstnames and lastnames.
 */
char *certutil_getDisplayNameFromDN(X509_NAME *xname) {
    char *display = certutil_getNamePropertyByNID(xname, NID_name);
    
    if (!display) {
        /* Try with First Last */
        char *first = certutil_getNamePropertyByNID(xname, NID_givenName);
        char *last = certutil_getNamePropertyByNID(xname, NID_surname);
        if (first && last) {
            display = rasprintf("%s %s", first, last);
        } else if (first) {
            display = first;
            first = NULL;
        } else if (last) {
            display = last;
            last = NULL;
        }
        free(first);
        free(last);
    }
    return display;
}

bool certutil_matchSubjectFilter(const char *subjectFilter, X509_NAME *name) {
    if (!subjectFilter) return true;
    
    // TODO use OBJ_txt2nid and support arbitrary OIDs?
    if ((strncmp(subjectFilter, "2.5.4.5=", 8) != 0) ||
        (strchr(subjectFilter, ',') != NULL)) {
        // OID 2.5.4.5 (Serial number) is the only supported/allowed filter
        return true; // Nothing to filter with
    }
    
    const char *wantedSerial = subjectFilter + 8;
    
    char *actualSerial = certutil_getNamePropertyByNID(name, NID_serialNumber);
    
    bool ok = actualSerial && !strcmp(actualSerial, wantedSerial);
    free(actualSerial);
    return ok;
}

bool certutil_compareX509Names(const X509_NAME *a, const X509_NAME *b,
                               bool orderMightDiffer) {
#if 0   // this might work in OpenSSL 1.0.0
    return X509_NAME_cmp(a, b);
#else
    if (!orderMightDiffer) return X509_NAME_cmp(a, b);
    
    int num = sk_X509_NAME_ENTRY_num(a->entries);
    if (sk_X509_NAME_ENTRY_num(b->entries) != num) return false;
    
    for (int i = 0; i < num; i++) {
        bool match = false;
        for (int j = i; j < num; j++) {
            X509_NAME_ENTRY *ae = sk_X509_NAME_ENTRY_value(a->entries, i);
            X509_NAME_ENTRY *be = sk_X509_NAME_ENTRY_value(b->entries, j);
            
            if (!OBJ_cmp(ae->object, be->object) &&
                !ASN1_STRING_cmp(ae->value, be->value)) {
                match = true;
                break;
            }
        }
        if (!match) return false;
    }
    return true;
#endif
}

X509 *certutil_findCert(const STACK_OF(X509) *certList,
                        const X509_NAME *name,
                        KeyUsage keyUsage,
                        bool orderMightDiffer) {
    int num = sk_X509_num(certList);
    for (int i = 0; i < num; i++) {
        X509 *cert = sk_X509_value(certList, i);
        if (!cert) continue;
        X509_NAME *certname = X509_get_subject_name(cert);
        if (!certname) continue;
        
        if (!certutil_compareX509Names(certname, name, orderMightDiffer) &&
            certutil_hasKeyUsage(cert, keyUsage)) {
            return cert;
        }
    }
    return NULL;
}

/**
 * Adds a certificate to a list. The certificate will be DER-encoded.
 * For empty lists, list should point to a NULL pointer and count point
 * to a zero integer.
 */
bool certutil_addToList(char ***list, size_t *count, X509 *cert) {
    
    if (*count >= 100) return false; // insane length for a chain
    
    char *certDer = certutil_derEncode(cert);
    if (!certDer) goto error;
    
    char **extended = realloc(*list, (*count+1) * sizeof(char*));
    if (!extended) goto error;
    
    extended[*count] = certDer;
    *list = extended;
    (*count)++;
    return true;
    
  error:
    free(certDer);
    return false;
}

/**
 * Frees a list of certificates.
 */
void certutil_freeList(char ***list, size_t *count) {
    if (!*list) return;
    
    for (size_t i = *count; i-- > 0; ) {
        free((*list)[i]);
    }
    free(*list);
}


PKCS7 *certutil_parseP7SignedData(const char *p7data, size_t length) {
    // If the PKCS7 data is bigger than 100 kB then something is really wrong
    if (!p7data || length > 100*1024) return NULL;
    
    // Parse data
    const unsigned char *temp = (const unsigned char*)p7data;
    PKCS7 *p7 = d2i_PKCS7(NULL, &temp, length);
    
    // Check that it's valid and contains certificates
    if (!p7 || !PKCS7_type_is_signed(p7) || !p7->d.sign || !p7->d.sign->cert ||
        sk_X509_num(p7->d.sign->cert) == 0) {
        PKCS7_free(p7);
        return NULL;
    }
    
    return p7;
}

/**
 * Makes a filename for a certificate.
 */
char *certutil_makeFilename(X509_NAME *xname) {
    if (!xname) return NULL;
    
    char *nameAttr = certutil_getNamePropertyByNID(xname, NID_name);
    if (!nameAttr) return NULL;
    
    char *filename = platform_getFilenameForKey(nameAttr);
    free(nameAttr);
    
    return filename;
}

/**
 * Gets an attribute of the type PRINTABLESTRING from a PKCS12 bag.
 */
char *certutil_getBagAttr(PKCS12_SAFEBAG *bag, ASN1_OBJECT *oid) {
    // Find the attribute
    ASN1_TYPE *at = NULL;
    
    if (!bag->attrib || !oid) return NULL;
    
    int numattr = sk_X509_ATTRIBUTE_num(bag->attrib);
    for (int i = 0; i < numattr; i++) {
        X509_ATTRIBUTE *xattr = sk_X509_ATTRIBUTE_value(bag->attrib, i);
        if (xattr && xattr->object && !OBJ_cmp(xattr->object, oid)) {
            // Match
            at = sk_ASN1_TYPE_value(xattr->value.set, 0);
            break;
        }
    }
    
    if (!at || at->type != V_ASN1_PRINTABLESTRING) return NULL;
    
    // Copy the value to a string
    int len = at->value.printablestring->length;
    if (len < 0 || len > 100*1024) return NULL;
    char *str = malloc(len+1);
    if (str) {
        memcpy(str, at->value.printablestring->data, len);
        str[len] = '\0';
    }
    return str;
}

void certutil_clearErrorString(void) {
    error_string = NULL;
}

void certutil_updateErrorString(void) {
    ERR_load_crypto_strings();
#if ENABLE_PKCS11
    ERR_load_PKCS11_strings();
#endif
    error_string = ERR_error_string(ERR_get_error(), NULL);
    fprintf(stderr, BINNAME ": error from OpenSSL or libP11: %s\n", error_string);
}

char *certutil_getErrorString(void) {
    return error_string;
}