1 | |
---|
2 | /* generate.c */ |
---|
3 | |
---|
4 | #include <unistd.h> |
---|
5 | #include <fcntl.h> |
---|
6 | #include <err.h> |
---|
7 | |
---|
8 | #include "libabac_common.h" |
---|
9 | #include "creddy_common.h" |
---|
10 | |
---|
11 | void generate_main(options_t *opts) { |
---|
12 | int ret, fd; |
---|
13 | abac_id_t *id; |
---|
14 | char *filename; |
---|
15 | FILE *out; |
---|
16 | |
---|
17 | // make sure we have at least a CN |
---|
18 | if (opts->cn == NULL) |
---|
19 | usage(opts); |
---|
20 | |
---|
21 | // if we have an outdir, chdir there |
---|
22 | if (opts->out) { |
---|
23 | ret = chdir(opts->out); |
---|
24 | if (ret < 0) |
---|
25 | err(1, "can't open output directory '%s'", opts->out); |
---|
26 | } |
---|
27 | |
---|
28 | if(opts->key) { |
---|
29 | ret = abac_id_generate_with_key(&id, opts->cn, opts->validity, opts->key); |
---|
30 | } else { |
---|
31 | printf("Generating key, this will take a while. Create entropy!\n"); |
---|
32 | printf(" - move the mouse\n"); |
---|
33 | printf(" - generate disk activity (run find)\n"); |
---|
34 | ret = abac_id_generate(&id, opts->cn, opts->validity); |
---|
35 | } |
---|
36 | |
---|
37 | if (ret == ABAC_GENERATE_INVALID_CN) { |
---|
38 | printf("Invalid CN: must start with a letter and be alphanumeric\n"); |
---|
39 | usage(opts); |
---|
40 | } |
---|
41 | if (ret == ABAC_GENERATE_INVALID_VALIDITY) { |
---|
42 | printf("Validity must be >= 1 day\n"); |
---|
43 | usage(opts); |
---|
44 | } |
---|
45 | // in both above cases: usage(opts) exits |
---|
46 | |
---|
47 | // |
---|
48 | // success! |
---|
49 | // |
---|
50 | |
---|
51 | // write the cert |
---|
52 | filename = abac_id_cert_filename(id); |
---|
53 | out = fopen(filename, "w"); |
---|
54 | if (out == NULL) |
---|
55 | err(1, "Can't open cert file %s", filename); |
---|
56 | abac_id_write_cert(id, out); |
---|
57 | fclose(out); |
---|
58 | free(filename); |
---|
59 | |
---|
60 | // write the key if not supplied |
---|
61 | if(!opts->key) { |
---|
62 | filename = abac_id_privkey_filename(id); |
---|
63 | fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); // mode 600 |
---|
64 | if (fd < 0) |
---|
65 | err(1, "Can't open private key file %s", filename); |
---|
66 | out = fdopen(fd, "w"); |
---|
67 | abac_id_write_privkey(id, out); |
---|
68 | fclose(out); |
---|
69 | } |
---|
70 | |
---|
71 | abac_id_free(id); |
---|
72 | } |
---|