source: creddy/id.c @ 8f58012

abac0-leakabac0-meicompt_changesgec13mei-idmei-rt0-nmei_rt0mei_rt2mei_rt2_fix_1meiyap-rt1meiyap1rt2tvf-new-xml
Last change on this file since 8f58012 was 8f58012, checked in by Ted Faber <faber@…>, 13 years ago

Missing return, shows up in amd64

  • Property mode set to 100644
File size: 12.7 KB
Line 
1#include <assert.h>
2#include <err.h>
3#include <termios.h>
4#include <time.h>
5
6// include the GNU extension of asprintf
7#define _GNU_SOURCE
8#include <stdio.h>
9
10#include "libcreddy_common.h"
11
12#define KEY_SUFFIX  "_private.pem"
13#define CERT_SUFFIX "_ID.pem"
14/* Size of password memory allocation */
15#define PWLEN 128
16
17//
18// ID object
19//
20struct _creddy_id_t {
21    char *keyid;
22    char *cn;
23    certificate_t *cert;
24    private_key_t *key;
25
26    int refcount;
27};
28
29/* Callback configuration */
30struct cb_opts {
31    bool use_prompt;    /* Print a prompt to stderr */
32    bool use_echo;      /* If true, turn off input echo on stdin */
33    unsigned int tries; /* Number of attempts allowed */
34    char prompt[20];    /* The prompt to display if use_echo is true */
35};
36
37static char *_get_keyid(certificate_t *cert);
38static chunk_t _passphrase_callback(void *user, int try);
39static private_key_t *_generate_key(void);
40static certificate_t *_generate_cert(private_key_t *private, char *cn, int validity);
41static void _encode_base64(FILE *out, chunk_t encoding);
42
43/**
44 * Helper function for building a creddy ID from a cert. Used by
45 * creddy_id_from_*
46 */
47creddy_id_t *_creddy_id_from_cert(certificate_t *cert) {
48    creddy_id_t *id = creddy_xmalloc(sizeof(creddy_id_t));
49    id->keyid = NULL;
50    id->cn = NULL;
51    id->cert = cert;
52    id->key = NULL;
53
54    id->keyid = _get_keyid(id->cert);
55
56    // get the CN from the cert
57    id_part_t type;
58    chunk_t data;
59
60    identification_t *cert_id = id->cert->get_subject(id->cert);
61    enumerator_t *id_enum = cert_id->create_part_enumerator(cert_id);
62    while (id_enum->enumerate(id_enum, &type, &data))
63        if (type == ID_PART_RDN_CN) {
64            id->cn = creddy_xmalloc(data.len + 1);
65            memcpy(id->cn, data.ptr, data.len);
66            id->cn[data.len] = 0;
67        }
68    id_enum->destroy(id_enum);
69
70    id->refcount = 1;
71
72    return id;
73}
74
75/**
76 * Load an ID cert from a file.
77 */
78creddy_id_t *creddy_id_from_file(char *filename) {
79    libabac_init();
80
81    certificate_t *cert = lib->creds->create(lib->creds,
82        CRED_CERTIFICATE, CERT_X509,
83        BUILD_FROM_FILE, filename,
84        BUILD_X509_FLAG, X509_AA,
85        BUILD_END
86    );
87
88    if (cert == NULL)
89        return NULL;
90
91    return _creddy_id_from_cert(cert);
92}
93
94/**
95 * Load an ID cert from a chunk.
96 */
97creddy_id_t *creddy_id_from_chunk(abac_chunk_t achunk) {
98    chunk_t chunk = { .ptr = achunk.ptr, .len = achunk.len };
99
100    libabac_init();
101
102    certificate_t *cert = lib->creds->create(lib->creds,
103        CRED_CERTIFICATE, CERT_X509,
104        BUILD_BLOB_ASN1_DER, chunk,
105        BUILD_X509_FLAG, X509_AA,
106        BUILD_END
107    );
108
109    if (cert == NULL)
110        return NULL;
111
112    return _creddy_id_from_cert(cert);
113}
114
115/**
116 * Load private key for a cert.
117 */
118int creddy_id_load_privkey(creddy_id_t *id, char *filename) {
119    struct cb_opts c_opts = { 1, 0, 3, "Key password:" };
120
121    assert(id != NULL);
122
123    libabac_init();
124
125    // load signer key
126    private_key_t *key = lib->creds->create(lib->creds,
127        CRED_PRIVATE_KEY, KEY_RSA,
128        BUILD_FROM_FILE, filename,
129        /* Ask for password if the key's encrypted */
130        BUILD_PASSPHRASE_CALLBACK, _passphrase_callback, &c_opts,
131        BUILD_END
132    );
133    if (key == NULL)
134        return 0;
135
136    id->key = key;
137    return 1;
138}
139
140/**
141 * Generate an ID with the specified CN and validity.
142 *
143 * validity is measured in seconds (as of 0.2.0)
144 */
145int creddy_id_generate(creddy_id_t **ret, char *cn, int validity) {
146    if (cn == NULL || !creddy_clean_name(cn))
147        return CREDDY_GENERATE_INVALID_CN;
148
149    if (validity < 0)
150        return CREDDY_GENERATE_INVALID_VALIDITY;
151
152    creddy_id_t *id = creddy_xmalloc(sizeof(creddy_id_t));
153
154    id->cn = creddy_xstrdup(cn);
155    id->key = _generate_key();
156    id->cert = _generate_cert(id->key, cn, validity);
157    id->keyid = _get_keyid(id->cert);
158
159    id->refcount = 1;
160
161    *ret = id;
162    return CREDDY_SUCCESS;
163}
164
165char *creddy_id_keyid(creddy_id_t *id) {
166    assert(id != NULL);
167
168    return id->keyid;
169}
170
171/**
172 * Get the issuer of an ID cert.
173 * Returns a malloc'd string that must be free'd.
174 */
175char *creddy_id_issuer(creddy_id_t *id) {
176    char *ret;
177    int rv = asprintf(&ret, "%Y", id->cert->get_issuer(id->cert));
178
179    if (rv < 0)
180        err(1, "couldn't malloc string for issuer\n");
181
182    return ret;
183}
184
185/**
186 * Gets the subject DN of an ID cert.
187 * Returns a malloc'd string that must be free'd.
188 */
189char *creddy_id_subject(creddy_id_t *id) {
190    char *ret;
191    int rv = asprintf(&ret, "%Y", id->cert->get_subject(id->cert));
192
193    if (rv < 0)
194        err(1, "couldn't malloc string for subject\n");
195
196    return ret;
197}
198
199/**
200 * Get the validity period.
201 */
202void creddy_id_validity(creddy_id_t *id, time_t *not_before, time_t *not_after) {
203    id->cert->get_validity(id->cert, NULL, not_before, not_after);
204}
205
206certificate_t *creddy_id_cert(creddy_id_t *id) {
207    assert(id != NULL);
208
209    return id->cert;
210}
211
212private_key_t *creddy_id_privkey(creddy_id_t *id) {
213    assert(id != NULL);
214
215    return id->key;
216}
217
218/**
219 * Get the default filename for the cert. Value must be freed by caller.
220 */
221char *creddy_id_cert_filename(creddy_id_t *id) {
222    assert(id != NULL);
223    assert(id->cn != NULL);
224
225    // malloc the filename
226    int len = strlen(id->cn) + strlen(CERT_SUFFIX) + 1;
227    char *filename = creddy_xmalloc(len);
228    sprintf(filename, "%s" CERT_SUFFIX, id->cn);
229
230    return filename;
231}
232
233/**
234 * Write the ID cert to an open file pointer.
235 */
236void creddy_id_write_cert(creddy_id_t *id, FILE *out) {
237    assert(id != NULL);
238
239    chunk_t encoding = id->cert->get_encoding(id->cert);
240    _encode_base64(out, encoding);
241    free(encoding.ptr);
242}
243
244/**
245 * Default private key filename. Value must be freed by caller.
246 */
247char *creddy_id_privkey_filename(creddy_id_t *id) {
248    assert(id != NULL);
249    assert(id->cn != NULL);
250
251    // malloc the filename
252    int len = strlen(id->cn) + strlen(KEY_SUFFIX) + 1;
253    char *filename = creddy_xmalloc(len);
254    sprintf(filename, "%s" KEY_SUFFIX, id->cn);
255
256    return filename;
257}
258
259/**
260 * Write the private key to a file.
261 * Returns false if there's no private key loaded
262 */
263int creddy_id_write_privkey(creddy_id_t *id, FILE *out) {
264    int ret;
265    chunk_t encoding;
266
267    assert(id != NULL);
268
269    if (id->key == NULL)
270        return 0;
271
272    ret = id->key->get_encoding(id->key, KEY_PRIV_PEM, &encoding);
273    if (!ret)
274        errx(1, "Couldn't encode private key");
275
276    fwrite(encoding.ptr, encoding.len, 1, out);
277
278    free(encoding.ptr);
279    return 1;
280}
281
282/**
283 * Get a DER-encoded chunk representing the cert.
284 */
285abac_chunk_t creddy_id_cert_chunk(creddy_id_t *id) {
286    chunk_t encoding = id->cert->get_encoding(id->cert);
287    abac_chunk_t ret = { encoding.ptr, encoding.len };
288    return ret;
289}
290
291/**
292 * Copy a creddy ID. Actually just increases its reference count.
293 */
294creddy_id_t *creddy_id_dup(creddy_id_t *id) {
295    ++id->refcount;
296    return id;
297}
298
299void creddy_id_free(creddy_id_t *id) {
300    if (id == NULL)
301        return;
302
303    --id->refcount;
304    if (id->refcount > 0)
305        return;
306
307    // free once the reference count reaches 0
308    DESTROY_IF(id->cert);
309    DESTROY_IF(id->key);
310
311    free(id->keyid);
312    free(id);
313}
314
315//
316// Helper functions below
317//
318
319static char *_get_keyid(certificate_t *cert) {
320    // get the keyid
321    x509_t *x509 = (x509_t *)cert;
322    chunk_t keyid = x509->get_subjectKeyIdentifier(x509);
323    chunk_t string = chunk_to_hex(keyid, NULL, 0);
324    return (char *)string.ptr;
325}
326
327static chunk_t _passphrase_callback(void *user, int try) {
328    /* Get a password from stdin and return it as a chunk_t.  If too many tries
329     * have occurred or there is any other problem, return an empty chunk_t,
330     * which libstrongswan takes as giving up.  The chunk is alloated here
331     * (inside getline), and presumably freed by libstrongswan. User points to
332     * a cb_opts struct, which affects this routine in the obvious ways.
333     */
334    /* Configuration options */
335    struct cb_opts *opts = (struct cb_opts *) user;
336    chunk_t rv = chunk_empty;   /* Return value, starts empty */
337
338    if (try -1 < opts->tries ) {
339        struct termios t;   /* Terminal settings */
340        size_t len = 0;     /* Length of string from getline */
341        tcflag_t orig = 0;  /* Holds the original local flags (echo in here) */
342
343        if (!opts->use_echo) {
344            /* Use tc{get,set}attr to turn echo off and restore the intial
345             * echo settings */
346            if (!tcgetattr(0, &t)) {
347                orig = t.c_lflag;
348
349                t.c_lflag &= ~ECHO;
350                if ( tcsetattr(0, TCSANOW, &t) ) {
351                    perror("Cannot turn off echo");
352                    return rv;
353                }
354            }
355            else {
356                perror("Cannot turn get attributes to off echo");
357                return rv;
358            }
359        }
360        if (opts->use_prompt) printf("%s", opts->prompt);
361
362        /* Because rv.ptr starts as NULL, getline allocates memory.  The size
363         * of the allocation returns in rv.len and the size of the string
364         * (including newline and NUL) is in len.  */
365        if ((rv.ptr = (u_char *) malloc(rv.len = PWLEN))) {
366            if ( fgets(rv.ptr, rv.len, stdin) ) {
367                /* Readjust the chunk_t's len field to the size of the string
368                 * w/o the newline or NUL */
369                /* would prefer strnlen, but no such luck in FBSD7 or earlier*/
370                size_t len = strlen(rv.ptr);
371
372                if (rv.ptr[len-2] == '\n') rv.len = len-2;
373                else rv.len = len -1;
374            }
375            else {
376                /* Read failed.  Deallocate and clear rv */
377                free(rv.ptr);
378                rv = chunk_empty;
379            }
380        }
381        else {
382            /* Failed malloc.  Restore rv to empty and return it */
383            perror("malloc");
384            rv = chunk_empty;
385            return rv;
386        }
387
388        if (!opts->use_echo ) {
389            /* Pop echo beck to its original setting. */
390            t.c_lflag = orig;
391
392            if ( tcsetattr(0, TCSANOW, &t) )
393                perror("Cannot restore echo setting?");
394
395            if (opts->use_prompt) printf("\n");
396        }
397    }
398    else fprintf(stderr, "Too many tries (%d)", try-1);
399    return rv;
400}
401
402/**
403 * Generate a private key.
404 */
405static private_key_t *_generate_key(void) {
406    private_key_t *key;
407    libabac_init();
408
409    // generate the key
410    key = lib->creds->create(
411        lib->creds,
412        CRED_PRIVATE_KEY, KEY_RSA,
413        BUILD_KEY_SIZE, 2048,
414        BUILD_END
415    );
416    if (key == NULL)
417        errx(1, "Key generation failed");
418
419    return key;
420}
421
422static char *_create_dn(char *cn) {
423
424#define DN "cn="
425
426    char *dn = creddy_xmalloc(sizeof(DN) + strlen(cn));
427    memcpy(dn, DN, sizeof(DN));
428    strcat(dn, cn);
429
430    return dn;
431}
432
433/**
434 * Generate certificate.
435 *
436 * validity is measured in seconds (as of 0.2.0)
437 */
438static certificate_t *_generate_cert(private_key_t *private, char *cn, int validity) {
439    // build the DN
440    char *dn_string = _create_dn(cn);
441    libabac_init();
442
443    identification_t *id = identification_create_from_string(dn_string);
444    if (id == NULL)
445        errx(1, "couldn't create ID from DN %s", dn_string);
446    free(dn_string);
447
448    // get the public key
449    public_key_t *public = private->get_public_key(private);
450    if (public == NULL)
451        errx(1, "couldn't get public key from private key");
452
453    // create a serial (stolen from strongswan pki)
454    rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
455    if (!rng)
456        errx(1, "no random number generator");
457
458    // random serial
459    chunk_t serial = creddy_generate_serial();
460
461    // validity period
462    time_t not_before = time(NULL);
463    time_t not_after = not_before + validity;
464
465    // create!
466    certificate_t *cert = lib->creds->create(lib->creds,
467        CRED_CERTIFICATE, CERT_X509,
468        BUILD_SIGNING_KEY, private,
469        BUILD_PUBLIC_KEY, public,
470        BUILD_SUBJECT, id,
471        BUILD_NOT_BEFORE_TIME, not_before,
472        BUILD_NOT_AFTER_TIME, not_after,
473        BUILD_SERIAL, serial,
474        BUILD_DIGEST_ALG, HASH_SHA1,
475        BUILD_X509_FLAG, X509_CA,
476        BUILD_PATHLEN, X509_NO_PATH_LEN_CONSTRAINT,
477        BUILD_END
478    );
479    if (cert == NULL)
480        errx(1, "couldn't build cert :(");
481
482    DESTROY_IF(id);
483    DESTROY_IF(public);
484    free(serial.ptr);
485
486    return cert;
487}
488
489#define BYTES_PER_LINE 64
490
491// thx libstrongswan
492static void _encode_base64(FILE *out, chunk_t encoding) {
493    int start;
494
495    chunk_t b64 = chunk_to_base64(encoding, NULL);
496
497    fprintf(out, "-----BEGIN CERTIFICATE-----\n");
498
499    for (start = 0; start < b64.len; start += BYTES_PER_LINE) {
500        int left = b64.len - start;
501        int len = left < BYTES_PER_LINE ? left : BYTES_PER_LINE;
502        fwrite(b64.ptr + start, len, 1, out);
503        fprintf(out, "\n");
504    }
505
506    fprintf(out, "-----END CERTIFICATE-----\n");
507
508    free(b64.ptr);
509}
Note: See TracBrowser for help on using the repository browser.