source: creddy/id.c @ 405bba3

abac0-leakabac0-meicompt_changesgec13mei-idmei-rt0-nmei_rt0mei_rt2mei_rt2_fix_1meiyap-rt1meiyap1rt2tvf-new-xml
Last change on this file since 405bba3 was 405bba3, checked in by Mike Ryan <mikeryan@…>, 13 years ago

show cert validity period
see #17

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