xref: /qemu/tests/unit/crypto-tls-x509-helpers.c (revision 787148bf)
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 "crypto-tls-x509-helpers.h"
24 #include "crypto/init.h"
25 #include "qemu/sockets.h"
26 
27 #ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT
28 
29 /*
30  * This stores some static data that is needed when
31  * encoding extensions in the x509 certs
32  */
33 asn1_node pkix_asn1;
34 
35 /*
36  * To avoid consuming random entropy to generate keys,
37  * here's one we prepared earlier :-)
38  */
39 gnutls_x509_privkey_t privkey;
40 # define PRIVATE_KEY \
41     "-----BEGIN RSA PRIVATE KEY-----\n" \
42     "MIIG5AIBAAKCAYEAyjWyLSNm5PZvYUKUcDWGqbLX10b2ood+YaFjWSnJrqx/q3qh\n" \
43     "rVGBJglD25AJENJsmZF3zPP1oMhfIxsXu63Hdkb6Rdlc2RUoUP34x9VC1izH25mR\n" \
44     "6c8DPDp1d6IraZ/llDMI1HsBFz0qGWtvOHgm815XG4PAr/N8rDsuqfv/cJ01KlnO\n" \
45     "0OdO5QRXCJf9g/dYd41MPu7wOXk9FqjQlmRoP59HgtJ+zUpE4z+Keruw9cMT9VJj\n" \
46     "0oT+pQ9ysenqeZ3gbT224T1khrEhT5kifhtFLNyDssRchUUWH0hiqoOO1vgb+850\n" \
47     "W6/1VdxvuPam48py4diSPi1Vip8NITCOBaX9FIpVp4Ruw4rTPVMNMjq9Cpx/DwMP\n" \
48     "9MbfXfnaVaZaMrmq67/zPhl0eVbUrecH2hQ3ZB9oIF4GkNskzlWF5+yPy6zqk304\n" \
49     "AKaiFR6jRyh3YfHo2XFqV8x/hxdsIEXOtEUGhSIcpynsW+ckUCartzu7xbhXjd4b\n" \
50     "kxJT89+riPFYij09AgMBAAECggGBAKyFkaZXXROeejrmHlV6JZGlp+fhgM38gkRz\n" \
51     "+Jp7P7rLLAY3E7gXIPQ91WqAAmwazFNdvHPd9USfkCQYmnAi/VoZhrCPmlsQZRxt\n" \
52     "A5QjjOnEvSPMa6SrXZxGWDCg6R8uMCb4P+FhrPWR1thnRDZOtRTQ+crc50p3mHgt\n" \
53     "6ktXWIJRbqnag8zSfQqCYGtRmhe8sfsWT+Yl4El4+jjaAVU/B364u7+PLmaiphGp\n" \
54     "BdJfTsTwEpgtGkPj+osDmhzXcZkfq3V+fz5JLkemsCiQKmn4VJRpg8c3ZmE8NPNt\n" \
55     "gRtGWZ4W3WKDvhotT65WpQx4+6R8Duux/blNPBmH1Upmwd7kj7GYFBArbCjgd9PT\n" \
56     "xgfCSUZpgOZHHkcgSB+022a8XncXna7WYYij28SLtwImFyu0nNtqECFQHH5u+k6C\n" \
57     "LRYBSN+3t3At8dQuk01NVrJBndmjmXRfxpqUtTdeaNgVpdUYRY98s30G68NYGSra\n" \
58     "aEvhhRSghkcLNetkobpY9pUgeqW/tQKBwQDZHHK9nDMt/zk1TxtILeUSitPXcv1/\n" \
59     "8ufXqO0miHdH23XuXhIEA6Ef26RRVGDGgpjkveDJK/1w5feJ4H/ni4Vclil/cm38\n" \
60     "OwRqjjd7ElHJX6JQbsxEx/gNTk5/QW1iAL9TXUalgepsSXYT6AJ0/CJv0jmJSJ36\n" \
61     "YoKMOM8uqzb2KhN6i+RlJRi5iY53kUhWTJq5ArWvNhUzQNSYODI4bNxlsKSBL2Ik\n" \
62     "LZ5QKHuaEjQet0IlPlfIb4PzMm8CHa/urOcCgcEA7m3zW/lL5bIFoKPjWig5Lbn1\n" \
63     "aHfrG2ngqzWtgWtfZqMH8OkZc1Mdhhmvd46titjiLjeI+UP/uHXR0068PnrNngzl\n" \
64     "tTgwlakzu+bWzqhBm1F+3/341st/FEk07r0P/3/PhezVjwfO8c8Exj7pLxH4wrH0\n" \
65     "ROHgDbClmlJRu6OO78wk1+Vapf5DWa8YfA+q+fdvr7KvgGyytheKMT/b/dsqOq7y\n" \
66     "qZPjmaJKWAvV3RWG8lWHFSdHx2IAHMHfGr17Y/w7AoHBALzwZeYebeekiVucGSjq\n" \
67     "T8SgLhT7zCIx+JMUPjVfYzaUhP/Iu7Lkma6IzWm9nW6Drpy5pUpMzwUWDCLfzU9q\n" \
68     "eseFIl337kEn9wLn+t5OpgAyCqYmlftxbqvdrrBN9uvnrJjWvqk/8wsDrw9JxAGc\n" \
69     "fjeD4nBXUqvYWLXApoR9mZoGKedmoH9pFig4zlO9ig8YITnKYuQ0k6SD0b8agJHc\n" \
70     "Ir0YSUDnRGgpjvFBGbeOCe+FGbohk/EpItJc3IAh5740lwKBwAdXd2DjokSmYKn7\n" \
71     "oeqKxofz6+yVlLW5YuOiuX78sWlVp87xPolgi84vSEnkKM/Xsc8+goc6YstpRVa+\n" \
72     "W+mImoA9YW1dF5HkLeWhTAf9AlgoAEIhbeIfTgBv6KNZSv7RDrDPBBxtXx/vAfSg\n" \
73     "x0ldwk0scZsVYXLKd67yzfV7KdGUdaX4N/xYgfZm/9gCG3+q8NN2KxVHQ5F71BOE\n" \
74     "JeABOaGo9WvnU+DNMIDZjHJMUWVw4MHz/a/UArDf/2CxaPVBNQKBwASg6j4ohSTk\n" \
75     "J7aE6RQ3OBmmDDpixcoCJt9u9SjHVYMlbs5CEJGVSczk0SG3y8P1lOWNDSRnMksZ\n" \
76     "xWnHdP/ogcuYMuvK7UACNAF0zNddtzOhzcpNmejFj+WCHYY/UmPr2/Kf6t7Cxk2K\n" \
77     "3cZ4tqWsiTmBT8Bknmah7L5DrhS+ZBJliDeFAA8fZHdMH0Xjr4UBp9kF90EMTdW1\n" \
78     "Xr5uz7ZrMsYpYQI7mmyqV9SSjUg4iBXwVSoag1iDJ1K8Qg/L7Semgg==\n" \
79     "-----END RSA PRIVATE KEY-----\n"
80 
81 /*
82  * This loads the private key we defined earlier
83  */
84 static gnutls_x509_privkey_t test_tls_load_key(void)
85 {
86     gnutls_x509_privkey_t key;
87     const gnutls_datum_t data = { (unsigned char *)PRIVATE_KEY,
88                                   strlen(PRIVATE_KEY) };
89     int err;
90 
91     err = gnutls_x509_privkey_init(&key);
92     if (err < 0) {
93         g_critical("Failed to init key %s", gnutls_strerror(err));
94         abort();
95     }
96 
97     err = gnutls_x509_privkey_import(key, &data,
98                                      GNUTLS_X509_FMT_PEM);
99     if (err < 0) {
100         if (err != GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR &&
101             err != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
102             g_critical("Failed to import key %s", gnutls_strerror(err));
103             abort();
104         }
105 
106         err = gnutls_x509_privkey_import_pkcs8(
107             key, &data, GNUTLS_X509_FMT_PEM, NULL, 0);
108         if (err < 0) {
109             g_critical("Failed to import PKCS8 key %s", gnutls_strerror(err));
110             abort();
111         }
112     }
113 
114     return key;
115 }
116 
117 
118 void test_tls_init(const char *keyfile)
119 {
120     qcrypto_init(&error_abort);
121 
122     if (asn1_array2tree(pkix_asn1_tab, &pkix_asn1, NULL) != ASN1_SUCCESS) {
123         abort();
124     }
125 
126     privkey = test_tls_load_key();
127     if (!g_file_set_contents(keyfile, PRIVATE_KEY, -1, NULL)) {
128         abort();
129     }
130 }
131 
132 
133 void test_tls_cleanup(const char *keyfile)
134 {
135     asn1_delete_structure(&pkix_asn1);
136     unlink(keyfile);
137 }
138 
139 /*
140  * Turns an ASN1 object into a DER encoded byte array
141  */
142 static void test_tls_der_encode(asn1_node src,
143                                 const char *src_name,
144                                 gnutls_datum_t *res)
145 {
146   int size;
147   char *data = NULL;
148 
149   size = 0;
150   asn1_der_coding(src, src_name, NULL, &size, NULL);
151 
152   data = g_new0(char, size);
153 
154   asn1_der_coding(src, src_name, data, &size, NULL);
155 
156   res->data = (unsigned char *)data;
157   res->size = size;
158 }
159 
160 
161 static void
162 test_tls_get_ipaddr(const char *addrstr,
163                     char **data,
164                     int *datalen)
165 {
166     struct addrinfo *res;
167     struct addrinfo hints;
168 
169     memset(&hints, 0, sizeof(hints));
170     hints.ai_flags = AI_NUMERICHOST;
171     g_assert(getaddrinfo(addrstr, NULL, &hints, &res) == 0);
172 
173     *datalen = res->ai_addrlen;
174     *data = g_new(char, *datalen);
175     memcpy(*data, res->ai_addr, *datalen);
176     freeaddrinfo(res);
177 }
178 
179 /*
180  * This is a fairly lame x509 certificate generator.
181  *
182  * Do not copy/use this code for generating real certificates
183  * since it leaves out many things that you would want in
184  * certificates for real world usage.
185  *
186  * This is good enough only for doing tests of the QEMU
187  * TLS certificate code
188  */
189 void
190 test_tls_generate_cert(QCryptoTLSTestCertReq *req,
191                        gnutls_x509_crt_t ca)
192 {
193     gnutls_x509_crt_t crt;
194     int err;
195     static char buffer[1024 * 1024];
196     size_t size = sizeof(buffer);
197     char serial[5] = { 1, 2, 3, 4, 0 };
198     gnutls_datum_t der;
199     time_t start = time(NULL) + (60 * 60 * req->start_offset);
200     time_t expire = time(NULL) + (60 * 60 * (req->expire_offset
201                                              ? req->expire_offset : 24));
202 
203     /*
204      * Prepare our new certificate object
205      */
206     err = gnutls_x509_crt_init(&crt);
207     if (err < 0) {
208         g_critical("Failed to initialize certificate %s", gnutls_strerror(err));
209         abort();
210     }
211     err = gnutls_x509_crt_set_key(crt, privkey);
212     if (err < 0) {
213         g_critical("Failed to set certificate key %s", gnutls_strerror(err));
214         abort();
215     }
216 
217     /*
218      * A v3 certificate is required in order to be able
219      * set any of the basic constraints, key purpose and
220      * key usage data
221      */
222     gnutls_x509_crt_set_version(crt, 3);
223 
224     if (req->country) {
225         err = gnutls_x509_crt_set_dn_by_oid(
226             crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
227             req->country, strlen(req->country));
228         if (err < 0) {
229             g_critical("Failed to set certificate country name %s",
230                        gnutls_strerror(err));
231             abort();
232         }
233     }
234     if (req->cn) {
235         err = gnutls_x509_crt_set_dn_by_oid(
236             crt, GNUTLS_OID_X520_COMMON_NAME, 0,
237             req->cn, strlen(req->cn));
238         if (err < 0) {
239             g_critical("Failed to set certificate common name %s",
240                        gnutls_strerror(err));
241             abort();
242         }
243     }
244 
245     /*
246      * Setup the subject altnames, which are used
247      * for hostname checks in live sessions
248      */
249     if (req->altname1) {
250         err = gnutls_x509_crt_set_subject_alt_name(
251             crt, GNUTLS_SAN_DNSNAME,
252             req->altname1,
253             strlen(req->altname1),
254             GNUTLS_FSAN_APPEND);
255         if (err < 0) {
256             g_critical("Failed to set certificate alt name %s",
257                        gnutls_strerror(err));
258             abort();
259         }
260     }
261     if (req->altname2) {
262         err = gnutls_x509_crt_set_subject_alt_name(
263             crt, GNUTLS_SAN_DNSNAME,
264             req->altname2,
265             strlen(req->altname2),
266             GNUTLS_FSAN_APPEND);
267         if (err < 0) {
268             g_critical("Failed to set certificate %s alt name",
269                        gnutls_strerror(err));
270             abort();
271         }
272     }
273 
274     /*
275      * IP address need to be put into the cert in their
276      * raw byte form, not strings, hence this is a little
277      * more complicated
278      */
279     if (req->ipaddr1) {
280         char *data;
281         int len;
282 
283         test_tls_get_ipaddr(req->ipaddr1, &data, &len);
284 
285         err = gnutls_x509_crt_set_subject_alt_name(
286             crt, GNUTLS_SAN_IPADDRESS,
287             data, len, GNUTLS_FSAN_APPEND);
288         if (err < 0) {
289             g_critical("Failed to set certificate alt name %s",
290                        gnutls_strerror(err));
291             abort();
292         }
293         g_free(data);
294     }
295     if (req->ipaddr2) {
296         char *data;
297         int len;
298 
299         test_tls_get_ipaddr(req->ipaddr2, &data, &len);
300 
301         err = gnutls_x509_crt_set_subject_alt_name(
302             crt, GNUTLS_SAN_IPADDRESS,
303             data, len, GNUTLS_FSAN_APPEND);
304         if (err < 0) {
305             g_critical("Failed to set certificate alt name %s",
306                        gnutls_strerror(err));
307             abort();
308         }
309         g_free(data);
310     }
311 
312 
313     /*
314      * Basic constraints are used to decide if the cert
315      * is for a CA or not. We can't use the convenient
316      * gnutls API for setting this, since it hardcodes
317      * the 'critical' field which we want control over
318      */
319     if (req->basicConstraintsEnable) {
320         asn1_node ext = NULL;
321 
322         asn1_create_element(pkix_asn1, "PKIX1.BasicConstraints", &ext);
323         asn1_write_value(ext, "cA",
324                          req->basicConstraintsIsCA ? "TRUE" : "FALSE", 1);
325         asn1_write_value(ext, "pathLenConstraint", NULL, 0);
326         test_tls_der_encode(ext, "", &der);
327         err = gnutls_x509_crt_set_extension_by_oid(
328             crt, "2.5.29.19",
329             der.data, der.size,
330             req->basicConstraintsCritical);
331         if (err < 0) {
332             g_critical("Failed to set certificate basic constraints %s",
333                        gnutls_strerror(err));
334             g_free(der.data);
335             abort();
336         }
337         asn1_delete_structure(&ext);
338         g_free(der.data);
339     }
340 
341     /*
342      * Next up the key usage extension. Again we can't
343      * use the gnutls API since it hardcodes the extension
344      * to be 'critical'
345      */
346     if (req->keyUsageEnable) {
347         asn1_node ext = NULL;
348         char str[2];
349 
350         str[0] = req->keyUsageValue & 0xff;
351         str[1] = (req->keyUsageValue >> 8) & 0xff;
352 
353         asn1_create_element(pkix_asn1, "PKIX1.KeyUsage", &ext);
354         asn1_write_value(ext, "", str, 9);
355         test_tls_der_encode(ext, "", &der);
356         err = gnutls_x509_crt_set_extension_by_oid(
357             crt, "2.5.29.15",
358             der.data, der.size,
359             req->keyUsageCritical);
360         if (err < 0) {
361             g_critical("Failed to set certificate key usage %s",
362                        gnutls_strerror(err));
363             g_free(der.data);
364             abort();
365         }
366         asn1_delete_structure(&ext);
367         g_free(der.data);
368     }
369 
370     /*
371      * Finally the key purpose extension. This time
372      * gnutls has the opposite problem, always hardcoding
373      * it to be non-critical. So once again we have to
374      * set this the hard way building up ASN1 data ourselves
375      */
376     if (req->keyPurposeEnable) {
377         asn1_node ext = NULL;
378 
379         asn1_create_element(pkix_asn1, "PKIX1.ExtKeyUsageSyntax", &ext);
380         if (req->keyPurposeOID1) {
381             asn1_write_value(ext, "", "NEW", 1);
382             asn1_write_value(ext, "?LAST", req->keyPurposeOID1, 1);
383         }
384         if (req->keyPurposeOID2) {
385             asn1_write_value(ext, "", "NEW", 1);
386             asn1_write_value(ext, "?LAST", req->keyPurposeOID2, 1);
387         }
388         test_tls_der_encode(ext, "", &der);
389         err = gnutls_x509_crt_set_extension_by_oid(
390             crt, "2.5.29.37",
391             der.data, der.size,
392             req->keyPurposeCritical);
393         if (err < 0) {
394             g_critical("Failed to set certificate key purpose %s",
395                        gnutls_strerror(err));
396             g_free(der.data);
397             abort();
398         }
399         asn1_delete_structure(&ext);
400         g_free(der.data);
401     }
402 
403     /*
404      * Any old serial number will do, so lets pick 5
405      */
406     err = gnutls_x509_crt_set_serial(crt, serial, 5);
407     if (err < 0) {
408         g_critical("Failed to set certificate serial %s",
409                    gnutls_strerror(err));
410         abort();
411     }
412 
413     err = gnutls_x509_crt_set_activation_time(crt, start);
414     if (err < 0) {
415         g_critical("Failed to set certificate activation %s",
416                    gnutls_strerror(err));
417         abort();
418     }
419     err = gnutls_x509_crt_set_expiration_time(crt, expire);
420     if (err < 0) {
421         g_critical("Failed to set certificate expiration %s",
422                    gnutls_strerror(err));
423         abort();
424     }
425 
426 
427     /*
428      * If no 'ca' is set then we are self signing
429      * the cert. This is done for the root CA certs
430      */
431     err = gnutls_x509_crt_sign2(crt, ca ? ca : crt, privkey,
432                                 GNUTLS_DIG_SHA256, 0);
433     if (err < 0) {
434         g_critical("Failed to sign certificate %s",
435                    gnutls_strerror(err));
436         abort();
437     }
438 
439     /*
440      * Finally write the new cert out to disk
441      */
442     err = gnutls_x509_crt_export(
443         crt, GNUTLS_X509_FMT_PEM, buffer, &size);
444     if (err < 0) {
445         g_critical("Failed to export certificate %s: %d",
446                    gnutls_strerror(err), err);
447         abort();
448     }
449 
450     if (!g_file_set_contents(req->filename, buffer, -1, NULL)) {
451         g_critical("Failed to write certificate %s",
452                    req->filename);
453         abort();
454     }
455 
456     req->crt = crt;
457 }
458 
459 
460 void test_tls_write_cert_chain(const char *filename,
461                                gnutls_x509_crt_t *certs,
462                                size_t ncerts)
463 {
464     size_t i;
465     size_t capacity = 1024, offset = 0;
466     char *buffer = g_new0(char, capacity);
467     int err;
468 
469     for (i = 0; i < ncerts; i++) {
470         size_t len = capacity - offset;
471     retry:
472         err = gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
473                                      buffer + offset, &len);
474         if (err < 0) {
475             if (err == GNUTLS_E_SHORT_MEMORY_BUFFER) {
476                 buffer = g_renew(char, buffer, offset + len);
477                 capacity = offset + len;
478                 goto retry;
479             }
480             g_critical("Failed to export certificate chain %s: %d",
481                        gnutls_strerror(err), err);
482             abort();
483         }
484         offset += len;
485     }
486 
487     if (!g_file_set_contents(filename, buffer, offset, NULL)) {
488         abort();
489     }
490     g_free(buffer);
491 }
492 
493 
494 void test_tls_discard_cert(QCryptoTLSTestCertReq *req)
495 {
496     if (!req->crt) {
497         return;
498     }
499 
500     gnutls_x509_crt_deinit(req->crt);
501     req->crt = NULL;
502 
503     if (getenv("QEMU_TEST_DEBUG_CERTS") == NULL) {
504         unlink(req->filename);
505     }
506 }
507 
508 #endif /* QCRYPTO_HAVE_TLS_TEST_SUPPORT */
509