1 /*
2 * Copyright (C) 2015 Red Hat, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library. If not, see
16 * <http://www.gnu.org/licenses/>.
17 *
18 * Author: Daniel P. Berrange <berrange@redhat.com>
19 */
20
21 #include "qemu/osdep.h"
22
23 #include <libtasn1.h>
24
25 #include "crypto-tls-x509-helpers.h"
26 #include "crypto/init.h"
27 #include "qemu/sockets.h"
28
29 #include "pkix_asn1_tab.c.inc"
30
31 /*
32 * This stores some static data that is needed when
33 * encoding extensions in the x509 certs
34 */
35 static asn1_node pkix_asn1;
36
37 /*
38 * To avoid consuming random entropy to generate keys,
39 * here's one we prepared earlier :-)
40 */
41 gnutls_x509_privkey_t privkey;
42 # define PRIVATE_KEY \
43 "-----BEGIN RSA PRIVATE KEY-----\n" \
44 "MIIG5AIBAAKCAYEAyjWyLSNm5PZvYUKUcDWGqbLX10b2ood+YaFjWSnJrqx/q3qh\n" \
45 "rVGBJglD25AJENJsmZF3zPP1oMhfIxsXu63Hdkb6Rdlc2RUoUP34x9VC1izH25mR\n" \
46 "6c8DPDp1d6IraZ/llDMI1HsBFz0qGWtvOHgm815XG4PAr/N8rDsuqfv/cJ01KlnO\n" \
47 "0OdO5QRXCJf9g/dYd41MPu7wOXk9FqjQlmRoP59HgtJ+zUpE4z+Keruw9cMT9VJj\n" \
48 "0oT+pQ9ysenqeZ3gbT224T1khrEhT5kifhtFLNyDssRchUUWH0hiqoOO1vgb+850\n" \
49 "W6/1VdxvuPam48py4diSPi1Vip8NITCOBaX9FIpVp4Ruw4rTPVMNMjq9Cpx/DwMP\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Bp9kF90EMTdW1\n" \
80 "Xr5uz7ZrMsYpYQI7mmyqV9SSjUg4iBXwVSoag1iDJ1K8Qg/L7Semgg==\n" \
81 "-----END RSA PRIVATE KEY-----\n"
82
83 /*
84 * This loads the private key we defined earlier
85 */
test_tls_load_key(void)86 static gnutls_x509_privkey_t test_tls_load_key(void)
87 {
88 gnutls_x509_privkey_t key;
89 const gnutls_datum_t data = { (unsigned char *)PRIVATE_KEY,
90 strlen(PRIVATE_KEY) };
91 int err;
92
93 err = gnutls_x509_privkey_init(&key);
94 if (err < 0) {
95 g_critical("Failed to init key %s", gnutls_strerror(err));
96 abort();
97 }
98
99 err = gnutls_x509_privkey_import(key, &data,
100 GNUTLS_X509_FMT_PEM);
101 if (err < 0) {
102 if (err != GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR &&
103 err != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
104 g_critical("Failed to import key %s", gnutls_strerror(err));
105 abort();
106 }
107
108 err = gnutls_x509_privkey_import_pkcs8(
109 key, &data, GNUTLS_X509_FMT_PEM, NULL, 0);
110 if (err < 0) {
111 g_critical("Failed to import PKCS8 key %s", gnutls_strerror(err));
112 abort();
113 }
114 }
115
116 return key;
117 }
118
119
test_tls_init(const char * keyfile)120 void test_tls_init(const char *keyfile)
121 {
122 qcrypto_init(&error_abort);
123
124 if (asn1_array2tree(pkix_asn1_tab, &pkix_asn1, NULL) != ASN1_SUCCESS) {
125 abort();
126 }
127
128 privkey = test_tls_load_key();
129 if (!g_file_set_contents(keyfile, PRIVATE_KEY, -1, NULL)) {
130 abort();
131 }
132 }
133
134
test_tls_cleanup(const char * keyfile)135 void test_tls_cleanup(const char *keyfile)
136 {
137 asn1_delete_structure(&pkix_asn1);
138 gnutls_x509_privkey_deinit(privkey);
139 unlink(keyfile);
140 }
141
142 /*
143 * Turns an ASN1 object into a DER encoded byte array
144 */
test_tls_der_encode(asn1_node src,const char * src_name,gnutls_datum_t * res)145 static void test_tls_der_encode(asn1_node src,
146 const char *src_name,
147 gnutls_datum_t *res)
148 {
149 int size;
150 char *data = NULL;
151
152 size = 0;
153 asn1_der_coding(src, src_name, NULL, &size, NULL);
154
155 data = g_new0(char, size);
156
157 asn1_der_coding(src, src_name, data, &size, NULL);
158
159 res->data = (unsigned char *)data;
160 res->size = size;
161 }
162
163
164 static void
test_tls_get_ipaddr(const char * addrstr,char ** data,int * datalen)165 test_tls_get_ipaddr(const char *addrstr,
166 char **data,
167 int *datalen)
168 {
169 struct addrinfo *res;
170 struct addrinfo hints;
171
172 memset(&hints, 0, sizeof(hints));
173 hints.ai_flags = AI_NUMERICHOST;
174 g_assert(getaddrinfo(addrstr, NULL, &hints, &res) == 0);
175
176 if (res->ai_family == AF_INET) {
177 struct sockaddr_in *in = (struct sockaddr_in *)res->ai_addr;
178 *datalen = sizeof(in->sin_addr);
179 *data = g_new(char, *datalen);
180 memcpy(*data, &in->sin_addr, *datalen);
181 } else if (res->ai_family == AF_INET6) {
182 struct sockaddr_in6 *in = (struct sockaddr_in6 *)res->ai_addr;
183 *datalen = sizeof(in->sin6_addr);
184 *data = g_new(char, *datalen);
185 memcpy(*data, &in->sin6_addr, *datalen);
186 } else {
187 g_assert_not_reached();
188 }
189 freeaddrinfo(res);
190 }
191
192 /*
193 * This is a fairly lame x509 certificate generator.
194 *
195 * Do not copy/use this code for generating real certificates
196 * since it leaves out many things that you would want in
197 * certificates for real world usage.
198 *
199 * This is good enough only for doing tests of the QEMU
200 * TLS certificate code
201 */
202 void
test_tls_generate_cert(QCryptoTLSTestCertReq * req,gnutls_x509_crt_t ca)203 test_tls_generate_cert(QCryptoTLSTestCertReq *req,
204 gnutls_x509_crt_t ca)
205 {
206 gnutls_x509_crt_t crt;
207 int err;
208 static char buffer[1024 * 1024];
209 size_t size = sizeof(buffer);
210 char serial[5] = { 1, 2, 3, 4, 0 };
211 gnutls_datum_t der;
212 time_t start = time(NULL) + (60 * 60 * req->start_offset);
213 time_t expire = time(NULL) + (60 * 60 * (req->expire_offset
214 ? req->expire_offset : 24));
215
216 /*
217 * Prepare our new certificate object
218 */
219 err = gnutls_x509_crt_init(&crt);
220 if (err < 0) {
221 g_critical("Failed to initialize certificate %s", gnutls_strerror(err));
222 abort();
223 }
224 err = gnutls_x509_crt_set_key(crt, privkey);
225 if (err < 0) {
226 g_critical("Failed to set certificate key %s", gnutls_strerror(err));
227 abort();
228 }
229
230 /*
231 * A v3 certificate is required in order to be able
232 * set any of the basic constraints, key purpose and
233 * key usage data
234 */
235 gnutls_x509_crt_set_version(crt, 3);
236
237 if (req->country) {
238 err = gnutls_x509_crt_set_dn_by_oid(
239 crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
240 req->country, strlen(req->country));
241 if (err < 0) {
242 g_critical("Failed to set certificate country name %s",
243 gnutls_strerror(err));
244 abort();
245 }
246 }
247 if (req->cn) {
248 err = gnutls_x509_crt_set_dn_by_oid(
249 crt, GNUTLS_OID_X520_COMMON_NAME, 0,
250 req->cn, strlen(req->cn));
251 if (err < 0) {
252 g_critical("Failed to set certificate common name %s",
253 gnutls_strerror(err));
254 abort();
255 }
256 }
257
258 /*
259 * Setup the subject altnames, which are used
260 * for hostname checks in live sessions
261 */
262 if (req->altname1) {
263 err = gnutls_x509_crt_set_subject_alt_name(
264 crt, GNUTLS_SAN_DNSNAME,
265 req->altname1,
266 strlen(req->altname1),
267 GNUTLS_FSAN_APPEND);
268 if (err < 0) {
269 g_critical("Failed to set certificate alt name %s",
270 gnutls_strerror(err));
271 abort();
272 }
273 }
274 if (req->altname2) {
275 err = gnutls_x509_crt_set_subject_alt_name(
276 crt, GNUTLS_SAN_DNSNAME,
277 req->altname2,
278 strlen(req->altname2),
279 GNUTLS_FSAN_APPEND);
280 if (err < 0) {
281 g_critical("Failed to set certificate %s alt name",
282 gnutls_strerror(err));
283 abort();
284 }
285 }
286
287 /*
288 * IP address need to be put into the cert in their
289 * raw byte form, not strings, hence this is a little
290 * more complicated
291 */
292 if (req->ipaddr1) {
293 char *data;
294 int len;
295
296 test_tls_get_ipaddr(req->ipaddr1, &data, &len);
297
298 err = gnutls_x509_crt_set_subject_alt_name(
299 crt, GNUTLS_SAN_IPADDRESS,
300 data, len, GNUTLS_FSAN_APPEND);
301 if (err < 0) {
302 g_critical("Failed to set certificate alt name %s",
303 gnutls_strerror(err));
304 abort();
305 }
306 g_free(data);
307 }
308 if (req->ipaddr2) {
309 char *data;
310 int len;
311
312 test_tls_get_ipaddr(req->ipaddr2, &data, &len);
313
314 err = gnutls_x509_crt_set_subject_alt_name(
315 crt, GNUTLS_SAN_IPADDRESS,
316 data, len, GNUTLS_FSAN_APPEND);
317 if (err < 0) {
318 g_critical("Failed to set certificate alt name %s",
319 gnutls_strerror(err));
320 abort();
321 }
322 g_free(data);
323 }
324
325
326 /*
327 * Basic constraints are used to decide if the cert
328 * is for a CA or not. We can't use the convenient
329 * gnutls API for setting this, since it hardcodes
330 * the 'critical' field which we want control over
331 */
332 if (req->basicConstraintsEnable) {
333 asn1_node ext = NULL;
334
335 asn1_create_element(pkix_asn1, "PKIX1.BasicConstraints", &ext);
336 asn1_write_value(ext, "cA",
337 req->basicConstraintsIsCA ? "TRUE" : "FALSE", 1);
338 asn1_write_value(ext, "pathLenConstraint", NULL, 0);
339 test_tls_der_encode(ext, "", &der);
340 err = gnutls_x509_crt_set_extension_by_oid(
341 crt, "2.5.29.19",
342 der.data, der.size,
343 req->basicConstraintsCritical);
344 if (err < 0) {
345 g_critical("Failed to set certificate basic constraints %s",
346 gnutls_strerror(err));
347 g_free(der.data);
348 abort();
349 }
350 asn1_delete_structure(&ext);
351 g_free(der.data);
352 }
353
354 /*
355 * Next up the key usage extension. Again we can't
356 * use the gnutls API since it hardcodes the extension
357 * to be 'critical'
358 */
359 if (req->keyUsageEnable) {
360 asn1_node ext = NULL;
361 char str[2];
362
363 str[0] = req->keyUsageValue & 0xff;
364 str[1] = (req->keyUsageValue >> 8) & 0xff;
365
366 asn1_create_element(pkix_asn1, "PKIX1.KeyUsage", &ext);
367 asn1_write_value(ext, "", str, 9);
368 test_tls_der_encode(ext, "", &der);
369 err = gnutls_x509_crt_set_extension_by_oid(
370 crt, "2.5.29.15",
371 der.data, der.size,
372 req->keyUsageCritical);
373 if (err < 0) {
374 g_critical("Failed to set certificate key usage %s",
375 gnutls_strerror(err));
376 g_free(der.data);
377 abort();
378 }
379 asn1_delete_structure(&ext);
380 g_free(der.data);
381 }
382
383 /*
384 * Finally the key purpose extension. This time
385 * gnutls has the opposite problem, always hardcoding
386 * it to be non-critical. So once again we have to
387 * set this the hard way building up ASN1 data ourselves
388 */
389 if (req->keyPurposeEnable) {
390 asn1_node ext = NULL;
391
392 asn1_create_element(pkix_asn1, "PKIX1.ExtKeyUsageSyntax", &ext);
393 if (req->keyPurposeOID1) {
394 asn1_write_value(ext, "", "NEW", 1);
395 asn1_write_value(ext, "?LAST", req->keyPurposeOID1, 1);
396 }
397 if (req->keyPurposeOID2) {
398 asn1_write_value(ext, "", "NEW", 1);
399 asn1_write_value(ext, "?LAST", req->keyPurposeOID2, 1);
400 }
401 test_tls_der_encode(ext, "", &der);
402 err = gnutls_x509_crt_set_extension_by_oid(
403 crt, "2.5.29.37",
404 der.data, der.size,
405 req->keyPurposeCritical);
406 if (err < 0) {
407 g_critical("Failed to set certificate key purpose %s",
408 gnutls_strerror(err));
409 g_free(der.data);
410 abort();
411 }
412 asn1_delete_structure(&ext);
413 g_free(der.data);
414 }
415
416 /*
417 * Any old serial number will do, so lets pick 5
418 */
419 err = gnutls_x509_crt_set_serial(crt, serial, 5);
420 if (err < 0) {
421 g_critical("Failed to set certificate serial %s",
422 gnutls_strerror(err));
423 abort();
424 }
425
426 err = gnutls_x509_crt_set_activation_time(crt, start);
427 if (err < 0) {
428 g_critical("Failed to set certificate activation %s",
429 gnutls_strerror(err));
430 abort();
431 }
432 err = gnutls_x509_crt_set_expiration_time(crt, expire);
433 if (err < 0) {
434 g_critical("Failed to set certificate expiration %s",
435 gnutls_strerror(err));
436 abort();
437 }
438
439
440 /*
441 * If no 'ca' is set then we are self signing
442 * the cert. This is done for the root CA certs
443 */
444 err = gnutls_x509_crt_sign2(crt, ca ? ca : crt, privkey,
445 GNUTLS_DIG_SHA256, 0);
446 if (err < 0) {
447 g_critical("Failed to sign certificate %s",
448 gnutls_strerror(err));
449 abort();
450 }
451
452 /*
453 * Finally write the new cert out to disk
454 */
455 err = gnutls_x509_crt_export(
456 crt, GNUTLS_X509_FMT_PEM, buffer, &size);
457 if (err < 0) {
458 g_critical("Failed to export certificate %s: %d",
459 gnutls_strerror(err), err);
460 abort();
461 }
462
463 if (!g_file_set_contents(req->filename, buffer, -1, NULL)) {
464 g_critical("Failed to write certificate %s",
465 req->filename);
466 abort();
467 }
468
469 req->crt = crt;
470 }
471
472
test_tls_write_cert_chain(const char * filename,gnutls_x509_crt_t * certs,size_t ncerts)473 void test_tls_write_cert_chain(const char *filename,
474 gnutls_x509_crt_t *certs,
475 size_t ncerts)
476 {
477 size_t i;
478 size_t capacity = 1024, offset = 0;
479 char *buffer = g_new0(char, capacity);
480 int err;
481
482 for (i = 0; i < ncerts; i++) {
483 size_t len = capacity - offset;
484 retry:
485 err = gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
486 buffer + offset, &len);
487 if (err < 0) {
488 if (err == GNUTLS_E_SHORT_MEMORY_BUFFER) {
489 buffer = g_renew(char, buffer, offset + len);
490 capacity = offset + len;
491 goto retry;
492 }
493 g_critical("Failed to export certificate chain %s: %d",
494 gnutls_strerror(err), err);
495 abort();
496 }
497 offset += len;
498 }
499
500 if (!g_file_set_contents(filename, buffer, offset, NULL)) {
501 abort();
502 }
503 g_free(buffer);
504 }
505
test_tls_deinit_cert(QCryptoTLSTestCertReq * req)506 void test_tls_deinit_cert(QCryptoTLSTestCertReq *req)
507 {
508 if (!req->crt) {
509 return;
510 }
511
512 gnutls_x509_crt_deinit(req->crt);
513 req->crt = NULL;
514 }
515
test_tls_discard_cert(QCryptoTLSTestCertReq * req)516 void test_tls_discard_cert(QCryptoTLSTestCertReq *req)
517 {
518 if (!req->crt) {
519 return;
520 }
521
522 test_tls_deinit_cert(req);
523
524 if (getenv("QEMU_TEST_DEBUG_CERTS") == NULL) {
525 unlink(req->filename);
526 }
527 }
528