First git repo commit for the libreCMC project
[librecmc/librecmc.git] / package / utils / px5g / px5g.c
1 /*
2  * px5g - Embedded x509 key and certificate generator based on PolarSSL
3  *
4  *   Copyright (C) 2009 Steven Barth <steven@midlink.org>
5  *   Copyright (C) 2014 Felix Fietkau <nbd@nbd.name>
6  *
7  *  This library is free software; you can redistribute it and/or
8  *  modify it under the terms of the GNU Lesser General Public
9  *  License, version 2.1 as published by the Free Software Foundation.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include <sys/types.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28 #include <limits.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <stdbool.h>
32
33 #ifdef MBEDTLS
34 #include <mbedtls/bignum.h>
35 #include <mbedtls/x509_crt.h>
36 #include <mbedtls/rsa.h>
37 #include <mbedtls/pk.h>
38 #define lib_wrapper(x) mbedtls_##x
39 #define MD_SHA256       MBEDTLS_MD_SHA256
40 #else
41 #include <polarssl/bignum.h>
42 #include <polarssl/x509_crt.h>
43 #include <polarssl/rsa.h>
44 #define lib_wrapper(x)  x
45 #define MD_SHA256       POLARSSL_MD_SHA256
46 #endif
47
48 #define PX5G_VERSION "0.2"
49 #define PX5G_COPY "Copyright (c) 2009 Steven Barth <steven@midlink.org>"
50 #define PX5G_LICENSE "Licensed under the GNU Lesser General Public License v2.1"
51
52 static int urandom_fd;
53 static char buf[16384];
54
55 static int _urandom(void *ctx, unsigned char *out, size_t len)
56 {
57         read(urandom_fd, out, len);
58         return 0;
59 }
60
61 static void write_file(const char *path, int len, bool pem)
62 {
63         FILE *f = stdout;
64         const char *buf_start = buf;
65
66         if (!pem)
67                 buf_start += sizeof(buf) - len;
68
69         if (!len) {
70                 fprintf(stderr, "No data to write\n");
71                 exit(1);
72         }
73
74         if (!f) {
75                 fprintf(stderr, "error: I/O error\n");
76                 exit(1);
77         }
78
79         if (path)
80                 f = fopen(path, "w");
81
82         fwrite(buf_start, 1, len, f);
83         fclose(f);
84 }
85
86 static void write_key(lib_wrapper(pk_context) *key, const char *path, bool pem)
87 {
88         int len = 0;
89
90         if (pem) {
91                 if (lib_wrapper(pk_write_key_pem(key, (void *) buf, sizeof(buf)) == 0))
92                         len = strlen(buf);
93         } else {
94                 len = lib_wrapper(pk_write_key_der(key, (void *) buf, sizeof(buf)));
95                 if (len < 0)
96                         len = 0;
97         }
98
99         write_file(path, len, pem);
100 }
101
102 static void gen_key(lib_wrapper(pk_context) *key, int ksize, int exp, bool pem)
103 {
104         lib_wrapper(pk_init(key));
105         fprintf(stderr, "Generating RSA private key, %i bit long modulus\n", ksize);
106 #ifdef MBEDTLS
107         mbedtls_pk_setup(key, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
108         if (mbedtls_rsa_gen_key(mbedtls_pk_rsa(*key), _urandom, NULL, ksize, exp)) {
109 #else
110         pk_init_ctx(key, lib_wrapper(pk_info_from_type(POLARSSL_PK_RSA)));
111         if (rsa_gen_key(pk_rsa(*key), _urandom, NULL, ksize, exp)) {
112 #endif
113                 fprintf(stderr, "error: key generation failed\n");
114                 exit(1);
115         }
116 }
117
118 int rsakey(char **arg)
119 {
120         lib_wrapper(pk_context) key;
121         unsigned int ksize = 512;
122         int exp = 65537;
123         char *path = NULL;
124         bool pem = true;
125
126         while (*arg && **arg == '-') {
127                 if (!strcmp(*arg, "-out") && arg[1]) {
128                         path = arg[1];
129                         arg++;
130                 } else if (!strcmp(*arg, "-3")) {
131                         exp = 3;
132                 } else if (!strcmp(*arg, "-der")) {
133                         pem = false;
134                 }
135                 arg++;
136         }
137
138         if (*arg)
139                 ksize = (unsigned int)atoi(*arg);
140
141         gen_key(&key, ksize, exp, pem);
142         write_key(&key, path, pem);
143
144         lib_wrapper(pk_free(&key));
145
146         return 0;
147 }
148
149 int selfsigned(char **arg)
150 {
151         lib_wrapper(pk_context) key;
152         lib_wrapper(x509write_cert) cert;
153         lib_wrapper(mpi) serial;
154
155         char *subject = "";
156         unsigned int ksize = 512;
157         int exp = 65537;
158         unsigned int days = 30;
159         char *keypath = NULL, *certpath = NULL;
160         bool pem = true;
161         time_t from = time(NULL), to;
162         char fstr[20], tstr[20], sstr[17];
163         int len;
164
165         while (*arg && **arg == '-') {
166                 if (!strcmp(*arg, "-der")) {
167                         pem = false;
168                 } else if (!strcmp(*arg, "-newkey") && arg[1]) {
169                         if (strncmp(arg[1], "rsa:", 4)) {
170                                 fprintf(stderr, "error: invalid algorithm");
171                                 return 1;
172                         }
173                         ksize = (unsigned int)atoi(arg[1] + 4);
174                         arg++;
175                 } else if (!strcmp(*arg, "-days") && arg[1]) {
176                         days = (unsigned int)atoi(arg[1]);
177                         arg++;
178                 } else if (!strcmp(*arg, "-keyout") && arg[1]) {
179                         keypath = arg[1];
180                         arg++;
181                 } else if (!strcmp(*arg, "-out") && arg[1]) {
182                         certpath = arg[1];
183                         arg++;
184                 } else if (!strcmp(*arg, "-subj") && arg[1]) {
185                         if (arg[1][0] != '/' || strchr(arg[1], ';')) {
186                                 fprintf(stderr, "error: invalid subject");
187                                 return 1;
188                         }
189                         subject = calloc(strlen(arg[1]) + 1, 1);
190                         char *oldc = arg[1] + 1, *newc = subject, *delim;
191                         do {
192                                 delim = strchr(oldc, '=');
193                                 if (!delim) {
194                                         fprintf(stderr, "error: invalid subject");
195                                         return 1;
196                                 }
197                                 memcpy(newc, oldc, delim - oldc + 1);
198                                 newc += delim - oldc + 1;
199                                 oldc = delim + 1;
200
201                                 delim = strchr(oldc, '/');
202                                 if (!delim) {
203                                         delim = arg[1] + strlen(arg[1]);
204                                 }
205                                 memcpy(newc, oldc, delim - oldc);
206                                 newc += delim - oldc;
207                                 *newc++ = ',';
208                                 oldc = delim + 1;
209                         } while(*delim);
210                         arg++;
211                 }
212                 arg++;
213         }
214
215         gen_key(&key, ksize, exp, pem);
216
217         if (keypath)
218                 write_key(&key, keypath, pem);
219
220         from = (from < 1000000000) ? 1000000000 : from;
221         strftime(fstr, sizeof(fstr), "%Y%m%d%H%M%S", gmtime(&from));
222         to = from + 60 * 60 * 24 * days;
223         if (to < from)
224                 to = INT_MAX;
225         strftime(tstr, sizeof(tstr), "%Y%m%d%H%M%S", gmtime(&to));
226
227         fprintf(stderr, "Generating selfsigned certificate with subject '%s'"
228                         " and validity %s-%s\n", subject, fstr, tstr);
229
230         lib_wrapper(x509write_crt_init(&cert));
231         lib_wrapper(x509write_crt_set_md_alg(&cert, MD_SHA256));
232         lib_wrapper(x509write_crt_set_issuer_key(&cert, &key));
233         lib_wrapper(x509write_crt_set_subject_key(&cert, &key));
234         lib_wrapper(x509write_crt_set_subject_name(&cert, subject));
235         lib_wrapper(x509write_crt_set_issuer_name(&cert, subject));
236         lib_wrapper(x509write_crt_set_validity(&cert, fstr, tstr));
237         lib_wrapper(x509write_crt_set_basic_constraints(&cert, 0, -1));
238         lib_wrapper(x509write_crt_set_subject_key_identifier(&cert));
239         lib_wrapper(x509write_crt_set_authority_key_identifier(&cert));
240
241         _urandom(NULL, buf, 8);
242         for (len = 0; len < 8; len++)
243                 sprintf(sstr + len*2, "%02x", (unsigned char) buf[len]);
244
245         lib_wrapper(mpi_init(&serial));
246         lib_wrapper(mpi_read_string(&serial, 16, sstr));
247         lib_wrapper(x509write_crt_set_serial(&cert, &serial));
248
249         if (pem) {
250                 if (lib_wrapper(x509write_crt_pem(&cert, (void *) buf, sizeof(buf), _urandom, NULL) < 0)) {
251                         fprintf(stderr, "Failed to generate certificate\n");
252                         return 1;
253                 }
254
255                 len = strlen(buf);
256         } else {
257                 len = lib_wrapper(x509write_crt_der(&cert, (void *) buf, sizeof(buf), _urandom, NULL));
258                 if (len < 0) {
259                         fprintf(stderr, "Failed to generate certificate: %d\n", len);
260                         return 1;
261                 }
262         }
263         write_file(certpath, len, pem);
264
265         lib_wrapper(x509write_crt_free(&cert));
266         lib_wrapper(mpi_free(&serial));
267         lib_wrapper(pk_free(&key));
268
269         return 0;
270 }
271
272 int main(int argc, char *argv[])
273 {
274         urandom_fd = open("/dev/urandom", O_RDONLY);
275
276         if (!argv[1]) {
277                 //Usage
278         } else if (!strcmp(argv[1], "rsakey")) {
279                 return rsakey(argv+2);
280         } else if (!strcmp(argv[1], "selfsigned")) {
281                 return selfsigned(argv+2);
282         }
283
284         fprintf(stderr,
285                 "PX5G X.509 Certificate Generator Utility v" PX5G_VERSION "\n" PX5G_COPY
286                 "\nbased on PolarSSL by Christophe Devine and Paul Bakker\n\n");
287         fprintf(stderr, "Usage: %s [rsakey|selfsigned]\n", *argv);
288         return 1;
289 }