source: creddy/id.c @ 11e3eb7

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

return binary representations of ID and attr certs in abac_chunk_t
suitable for passing off to libabac
supported in perl and python natively
closes #9

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