at91: 5.15: remove old config and patch files
[openwrt/openwrt.git] / package / utils / px5g-mbedtls / px5g-mbedtls.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 #include <sys/random.h>
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <time.h>
29 #include <limits.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <stdbool.h>
33 #include <errno.h>
34
35 #include <mbedtls/bignum.h>
36 #include <mbedtls/entropy.h>
37 #include <mbedtls/x509_crt.h>
38 #include <mbedtls/ecp.h>
39 #include <mbedtls/rsa.h>
40 #include <mbedtls/pk.h>
41
42 #define PX5G_VERSION "0.2"
43 #define PX5G_COPY "Copyright (c) 2009 Steven Barth <steven@midlink.org>"
44 #define PX5G_LICENSE "Licensed under the GNU Lesser General Public License v2.1"
45
46 static char buf[16384];
47
48 static int _urandom(void *ctx, unsigned char *out, size_t len)
49 {
50 ssize_t ret;
51
52 ret = getrandom(out, len, 0);
53 if (ret < 0 || (size_t)ret != len)
54 return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
55
56 return 0;
57 }
58
59 static void write_file(const char *path, size_t len, bool pem, bool cert)
60 {
61 mode_t mode = S_IRUSR | S_IWUSR;
62 const char *buf_start = buf;
63 int fd = STDERR_FILENO;
64 ssize_t written;
65 int err;
66
67 if (!pem)
68 buf_start += sizeof(buf) - len;
69
70 if (!len) {
71 fprintf(stderr, "No data to write\n");
72 exit(1);
73 }
74
75 if (cert)
76 mode |= S_IRGRP | S_IROTH;
77
78 if (path)
79 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
80
81 if (fd < 0) {
82 fprintf(stderr, "error: I/O error\n");
83 exit(1);
84 }
85
86 written = write(fd, buf_start, len);
87 if (written != len) {
88 fprintf(stderr, "writing key failed with: %s\n", strerror(errno));
89 exit(1);
90 }
91 err = fsync(fd);
92 if (err < 0) {
93 fprintf(stderr, "syncing key failed with: %s\n", strerror(errno));
94 exit(1);
95 }
96 if (path)
97 close(fd);
98 }
99
100 static mbedtls_ecp_group_id ecp_curve(const char *name)
101 {
102 const mbedtls_ecp_curve_info *curve_info;
103
104 if (!strcmp(name, "P-256"))
105 return MBEDTLS_ECP_DP_SECP256R1;
106 else if (!strcmp(name, "P-384"))
107 return MBEDTLS_ECP_DP_SECP384R1;
108 else if (!strcmp(name, "P-521"))
109 return MBEDTLS_ECP_DP_SECP521R1;
110 curve_info = mbedtls_ecp_curve_info_from_name(name);
111 if (curve_info == NULL)
112 return MBEDTLS_ECP_DP_NONE;
113 else
114 return curve_info->grp_id;
115 }
116
117 static void write_key(mbedtls_pk_context *key, const char *path, bool pem)
118 {
119 int len = 0;
120
121 if (pem) {
122 if (mbedtls_pk_write_key_pem(key, (void *) buf, sizeof(buf)) == 0)
123 len = strlen(buf);
124 } else {
125 len = mbedtls_pk_write_key_der(key, (void *) buf, sizeof(buf));
126 if (len < 0)
127 len = 0;
128 }
129
130 write_file(path, len, pem, false);
131 }
132
133 static void gen_key(mbedtls_pk_context *key, bool rsa, int ksize, int exp,
134 mbedtls_ecp_group_id curve, bool pem)
135 {
136 mbedtls_pk_init(key);
137 if (rsa) {
138 fprintf(stderr, "Generating RSA private key, %i bit long modulus\n", ksize);
139 mbedtls_pk_setup(key, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
140 if (!mbedtls_rsa_gen_key(mbedtls_pk_rsa(*key), _urandom, NULL, ksize, exp))
141 return;
142 } else {
143 fprintf(stderr, "Generating EC private key\n");
144 mbedtls_pk_setup(key, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY));
145 if (!mbedtls_ecp_gen_key(curve, mbedtls_pk_ec(*key), _urandom, NULL))
146 return;
147 }
148 fprintf(stderr, "error: key generation failed\n");
149 exit(1);
150 }
151
152 int dokey(bool rsa, char **arg)
153 {
154 mbedtls_pk_context key;
155 unsigned int ksize = 512;
156 int exp = 65537;
157 char *path = NULL;
158 bool pem = true;
159 mbedtls_ecp_group_id curve = MBEDTLS_ECP_DP_SECP256R1;
160
161 while (*arg && **arg == '-') {
162 if (!strcmp(*arg, "-out") && arg[1]) {
163 path = arg[1];
164 arg++;
165 } else if (!strcmp(*arg, "-3")) {
166 exp = 3;
167 } else if (!strcmp(*arg, "-der")) {
168 pem = false;
169 }
170 arg++;
171 }
172
173 if (*arg && rsa) {
174 ksize = (unsigned int)atoi(*arg);
175 } else if (*arg) {
176 curve = ecp_curve((const char *)*arg);
177 if (curve == MBEDTLS_ECP_DP_NONE) {
178 fprintf(stderr, "error: invalid curve name: %s\n", *arg);
179 return 1;
180 }
181 }
182
183 gen_key(&key, rsa, ksize, exp, curve, pem);
184 write_key(&key, path, pem);
185
186 mbedtls_pk_free(&key);
187
188 return 0;
189 }
190
191 int selfsigned(char **arg)
192 {
193 mbedtls_pk_context key;
194 mbedtls_x509write_cert cert;
195 mbedtls_mpi serial;
196
197 char *subject = "";
198 unsigned int ksize = 512;
199 int exp = 65537;
200 unsigned int days = 30;
201 char *keypath = NULL, *certpath = NULL;
202 bool pem = true;
203 time_t from = time(NULL), to;
204 char fstr[20], tstr[20], sstr[17];
205 int len;
206 bool rsa = true;
207 mbedtls_ecp_group_id curve = MBEDTLS_ECP_DP_SECP256R1;
208
209 while (*arg && **arg == '-') {
210 if (!strcmp(*arg, "-der")) {
211 pem = false;
212 } else if (!strcmp(*arg, "-newkey") && arg[1]) {
213 if (!strncmp(arg[1], "rsa:", 4)) {
214 rsa = true;
215 ksize = (unsigned int)atoi(arg[1] + 4);
216 } else if (!strcmp(arg[1], "ec")) {
217 rsa = false;
218 } else {
219 fprintf(stderr, "error: invalid algorithm\n");
220 return 1;
221 }
222 arg++;
223 } else if (!strcmp(*arg, "-days") && arg[1]) {
224 days = (unsigned int)atoi(arg[1]);
225 arg++;
226 } else if (!strcmp(*arg, "-pkeyopt") && arg[1]) {
227 if (strncmp(arg[1], "ec_paramgen_curve:", 18)) {
228 fprintf(stderr, "error: invalid pkey option: %s\n", arg[1]);
229 return 1;
230 }
231 curve = ecp_curve((const char *)(arg[1] + 18));
232 if (curve == MBEDTLS_ECP_DP_NONE) {
233 fprintf(stderr, "error: invalid curve name: %s\n", arg[1] + 18);
234 return 1;
235 }
236 arg++;
237 } else if (!strcmp(*arg, "-keyout") && arg[1]) {
238 keypath = arg[1];
239 arg++;
240 } else if (!strcmp(*arg, "-out") && arg[1]) {
241 certpath = arg[1];
242 arg++;
243 } else if (!strcmp(*arg, "-subj") && arg[1]) {
244 if (arg[1][0] != '/' || strchr(arg[1], ';')) {
245 fprintf(stderr, "error: invalid subject");
246 return 1;
247 }
248 subject = calloc(strlen(arg[1]) + 1, 1);
249 char *oldc = arg[1] + 1, *newc = subject, *delim;
250 do {
251 delim = strchr(oldc, '=');
252 if (!delim) {
253 fprintf(stderr, "error: invalid subject");
254 return 1;
255 }
256 memcpy(newc, oldc, delim - oldc + 1);
257 newc += delim - oldc + 1;
258 oldc = delim + 1;
259
260 delim = strchr(oldc, '/');
261 if (!delim) {
262 delim = arg[1] + strlen(arg[1]);
263 }
264 memcpy(newc, oldc, delim - oldc);
265 newc += delim - oldc;
266 *newc++ = ',';
267 oldc = delim + 1;
268 } while(*delim);
269 arg++;
270 }
271 arg++;
272 }
273 gen_key(&key, rsa, ksize, exp, curve, pem);
274
275 if (keypath)
276 write_key(&key, keypath, pem);
277
278 from = (from < 1000000000) ? 1000000000 : from;
279 strftime(fstr, sizeof(fstr), "%Y%m%d%H%M%S", gmtime(&from));
280 to = from + 60 * 60 * 24 * days;
281 if (to < from)
282 to = INT_MAX;
283 strftime(tstr, sizeof(tstr), "%Y%m%d%H%M%S", gmtime(&to));
284
285 fprintf(stderr, "Generating selfsigned certificate with subject '%s'"
286 " and validity %s-%s\n", subject, fstr, tstr);
287
288 mbedtls_x509write_crt_init(&cert);
289 mbedtls_x509write_crt_set_md_alg(&cert, MBEDTLS_MD_SHA256);
290 mbedtls_x509write_crt_set_issuer_key(&cert, &key);
291 mbedtls_x509write_crt_set_subject_key(&cert, &key);
292 mbedtls_x509write_crt_set_subject_name(&cert, subject);
293 mbedtls_x509write_crt_set_issuer_name(&cert, subject);
294 mbedtls_x509write_crt_set_validity(&cert, fstr, tstr);
295 mbedtls_x509write_crt_set_basic_constraints(&cert, 0, -1);
296 mbedtls_x509write_crt_set_subject_key_identifier(&cert);
297 mbedtls_x509write_crt_set_authority_key_identifier(&cert);
298
299 _urandom(NULL, (void *) buf, 8);
300 for (len = 0; len < 8; len++)
301 sprintf(sstr + len*2, "%02x", (unsigned char) buf[len]);
302
303 mbedtls_mpi_init(&serial);
304 mbedtls_mpi_read_string(&serial, 16, sstr);
305 mbedtls_x509write_crt_set_serial(&cert, &serial);
306
307 if (pem) {
308 if (mbedtls_x509write_crt_pem(&cert, (void *) buf, sizeof(buf), _urandom, NULL) < 0) {
309 fprintf(stderr, "Failed to generate certificate\n");
310 return 1;
311 }
312
313 len = strlen(buf);
314 } else {
315 len = mbedtls_x509write_crt_der(&cert, (void *) buf, sizeof(buf), _urandom, NULL);
316 if (len < 0) {
317 fprintf(stderr, "Failed to generate certificate: %d\n", len);
318 return 1;
319 }
320 }
321 write_file(certpath, len, pem, true);
322
323 mbedtls_x509write_crt_free(&cert);
324 mbedtls_mpi_free(&serial);
325 mbedtls_pk_free(&key);
326
327 return 0;
328 }
329
330 int main(int argc, char *argv[])
331 {
332 if (!argv[1]) {
333 //Usage
334 } else if (!strcmp(argv[1], "eckey")) {
335 return dokey(false, argv+2);
336 } else if (!strcmp(argv[1], "rsakey")) {
337 return dokey(true, argv+2);
338 } else if (!strcmp(argv[1], "selfsigned")) {
339 return selfsigned(argv+2);
340 }
341
342 fprintf(stderr,
343 "PX5G X.509 Certificate Generator Utility v" PX5G_VERSION "\n" PX5G_COPY
344 "\nbased on PolarSSL by Christophe Devine and Paul Bakker\n\n");
345 fprintf(stderr, "Usage: %s [eckey|rsakey|selfsigned]\n", *argv);
346 return 1;
347 }