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