blob: eea0fc5ac68816f8d01fb2d65374afbd949bb718 [file] [log] [blame]
Radek Krejci5da708a2015-09-01 17:33:23 +02001/**
Michal Vasko086311b2016-01-08 09:53:11 +01002 * \file session_server_tls.c
3 * \author Michal Vasko <mvasko@cesnet.cz>
4 * \brief libnetconf2 TLS server session manipulation functions
Radek Krejci5da708a2015-09-01 17:33:23 +02005 *
6 * Copyright (c) 2015 CESNET, z.s.p.o.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 * 3. Neither the name of the Company nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 */
22
Michal Vaskoc14e3c82016-01-11 16:14:30 +010023#define _GNU_SOURCE
24
25#include <string.h>
26#include <poll.h>
27
28#include <openssl/ssl.h>
29#include <openssl/evp.h>
30#include <openssl/err.h>
31#include <openssl/x509v3.h>
32
Michal Vasko1a38c862016-01-15 15:50:07 +010033#include "libnetconf.h"
Radek Krejci5da708a2015-09-01 17:33:23 +020034
Michal Vaskoc14e3c82016-01-11 16:14:30 +010035extern struct nc_server_opts server_opts;
36struct nc_tls_server_opts tls_opts;
37
38static char *
39asn1time_to_str(ASN1_TIME *t)
Michal Vasko086311b2016-01-08 09:53:11 +010040{
Michal Vaskoc14e3c82016-01-11 16:14:30 +010041 char *cp;
42 BIO *bio;
43 int n;
Radek Krejci5da708a2015-09-01 17:33:23 +020044
Michal Vaskoc14e3c82016-01-11 16:14:30 +010045 if (!t) {
46 return NULL;
47 }
48 bio = BIO_new(BIO_s_mem());
49 if (!bio) {
50 return NULL;
51 }
52 ASN1_TIME_print(bio, t);
53 n = BIO_pending(bio);
54 cp = malloc(n + 1);
55 n = BIO_read(bio, cp, n);
56 if (n < 0) {
57 BIO_free(bio);
58 free(cp);
59 return NULL;
60 }
61 cp[n] = '\0';
62 BIO_free(bio);
63 return cp;
64}
65
66static void
67digest_to_str(const unsigned char *digest, unsigned int dig_len, char **str)
68{
69 unsigned int i;
70
71 *str = malloc(dig_len * 3);
72 for (i = 0; i < dig_len - 1; ++i) {
73 sprintf((*str) + (i * 3), "%02x:", digest[i]);
74 }
75 sprintf((*str) + (i * 3), "%02x", digest[i]);
76}
77
78/* return NULL - SSL error can be retrieved */
79static X509 *
80base64der_to_cert(const char *in)
81{
82 X509 *out;
83 char *buf;
84 BIO *bio;
85
86 if (in == NULL) {
87 return NULL;
88 }
89
90 if (asprintf(&buf, "%s%s%s", "-----BEGIN CERTIFICATE-----\n", in, "\n-----END CERTIFICATE-----") == -1) {
91 return NULL;
92 }
93 bio = BIO_new_mem_buf(buf, strlen(buf));
94 if (!bio) {
95 free(buf);
96 return NULL;
97 }
98
99 out = PEM_read_bio_X509(bio, NULL, NULL, NULL);
100 if (!out) {
101 free(buf);
102 BIO_free(bio);
103 return NULL;
104 }
105
106 free(buf);
107 BIO_free(bio);
108 return out;
109}
110
111/* return NULL - either errno or SSL error */
112static X509 *
113pem_to_cert(const char *path)
114{
115 FILE *fp;
116 X509 *out;
117
118 fp = fopen(path, "r");
119 if (!fp) {
120 return NULL;
121 }
122
123 out = PEM_read_X509(fp, NULL, NULL, NULL);
124 fclose(fp);
125 return out;
126}
127
128static EVP_PKEY *
129base64der_to_privatekey(const char *in, int rsa)
130{
131 EVP_PKEY *out;
132 char *buf;
133 BIO *bio;
134
135 if (in == NULL) {
136 return NULL;
137 }
138
139 if (asprintf(&buf, "%s%s%s%s%s%s%s", "-----BEGIN ", (rsa ? "RSA" : "DSA"), " PRIVATE KEY-----\n", in, "\n-----END ", (rsa ? "RSA" : "DSA"), " PRIVATE KEY-----") == -1) {
140 return NULL;
141 }
142 bio = BIO_new_mem_buf(buf, strlen(buf));
143 if (!bio) {
144 free(buf);
145 return NULL;
146 }
147
148 out = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
149 if (!out) {
150 free(buf);
151 BIO_free(bio);
152 return NULL;
153 }
154
155 free(buf);
156 BIO_free(bio);
157 return out;
158}
159
160static int
161cert_pubkey_match(X509 *cert1, X509 *cert2)
162{
163 ASN1_BIT_STRING *bitstr1, *bitstr2;
164
165 bitstr1 = X509_get0_pubkey_bitstr(cert1);
166 bitstr2 = X509_get0_pubkey_bitstr(cert2);
167
168 if (!bitstr1 || !bitstr2 || (bitstr1->length != bitstr2->length) ||
169 memcmp(bitstr1->data, bitstr2->data, bitstr1->length)) {
170 return 0;
171 }
172
173 return 1;
174}
175
176static int
177nc_tls_ctn_get_username_from_cert(X509 *client_cert, NC_TLS_CTN_MAPTYPE map_type, char **username)
178{
179 STACK_OF(GENERAL_NAME) *san_names;
180 GENERAL_NAME *san_name;
181 ASN1_OCTET_STRING *ip;
182 int i, san_count;
183 char *subject, *common_name;
184
185 if (map_type == NC_TLS_CTN_COMMON_NAME) {
186 subject = X509_NAME_oneline(X509_get_subject_name(client_cert), NULL, 0);
187 common_name = strstr(subject, "CN=");
188 if (!common_name) {
189 WRN("%s: cert does not include the commonName field", __func__);
190 free(subject);
191 return 1;
192 }
193 common_name += 3;
194 if (strchr(common_name, '/')) {
195 *strchr(common_name, '/') = '\0';
196 }
197 *username = strdup(common_name);
198 free(subject);
199 } else {
200 /* retrieve subjectAltName's rfc822Name (email), dNSName and iPAddress values */
201 san_names = X509_get_ext_d2i(client_cert, NID_subject_alt_name, NULL, NULL);
202 if (!san_names) {
203 WRN("%s: cert has no SANs or failed to retrieve them", __func__);
204 return 1;
205 }
206
207 san_count = sk_GENERAL_NAME_num(san_names);
208 for (i = 0; i < san_count; ++i) {
209 san_name = sk_GENERAL_NAME_value(san_names, i);
210
211 /* rfc822Name (email) */
212 if ((map_type == NC_TLS_CTN_SAN_ANY || map_type == NC_TLS_CTN_SAN_RFC822_NAME) &&
213 san_name->type == GEN_EMAIL) {
214 *username = strdup((char *)ASN1_STRING_data(san_name->d.rfc822Name));
215 break;
216 }
217
218 /* dNSName */
219 if ((map_type == NC_TLS_CTN_SAN_ANY || map_type == NC_TLS_CTN_SAN_DNS_NAME) &&
220 san_name->type == GEN_DNS) {
221 *username = strdup((char *)ASN1_STRING_data(san_name->d.dNSName));
222 break;
223 }
224
225 /* iPAddress */
226 if ((map_type == NC_TLS_CTN_SAN_ANY || map_type == NC_TLS_CTN_SAN_IP_ADDRESS) &&
227 san_name->type == GEN_IPADD) {
228 ip = san_name->d.iPAddress;
229 if (ip->length == 4) {
230 if (asprintf(username, "%d.%d.%d.%d", ip->data[0], ip->data[1], ip->data[2], ip->data[3]) == -1) {
231 ERR("%s: asprintf() failed", __func__);
232 sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
233 return -1;
234 }
235 break;
236 } else if (ip->length == 16) {
237 if (asprintf(username, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
238 ip->data[0], ip->data[1], ip->data[2], ip->data[3], ip->data[4], ip->data[5],
239 ip->data[6], ip->data[7], ip->data[8], ip->data[9], ip->data[10], ip->data[11],
240 ip->data[12], ip->data[13], ip->data[14], ip->data[15]) == -1) {
241 ERR("%s: asprintf() failed", __func__);
242 sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
243 return -1;
244 }
245 break;
246 } else {
247 WRN("%s: SAN IP address in an unknown format (length is %d)", __func__, ip->length);
248 }
249 }
250 }
251 sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
252
253 if (i < san_count) {
254 switch (map_type) {
255 case NC_TLS_CTN_SAN_RFC822_NAME:
256 WRN("%s: cert does not include the SAN rfc822Name field", __func__);
257 break;
258 case NC_TLS_CTN_SAN_DNS_NAME:
259 WRN("%s: cert does not include the SAN dNSName field", __func__);
260 break;
261 case NC_TLS_CTN_SAN_IP_ADDRESS:
262 WRN("%s: cert does not include the SAN iPAddress field", __func__);
263 break;
264 case NC_TLS_CTN_SAN_ANY:
265 WRN("%s: cert does not include any relevant SAN fields", __func__);
266 break;
267 default:
268 break;
269 }
270 return 1;
271 }
272 }
273
274 return 0;
275}
276
277/* return: 0 - OK, 1 - no match, -1 - error */
278static int
279nc_tls_cert_to_name(X509 *cert, NC_TLS_CTN_MAPTYPE *map_type, const char **name)
280{
281 char *digest_md5 = NULL, *digest_sha1 = NULL, *digest_sha224 = NULL;
282 char *digest_sha256 = NULL, *digest_sha384 = NULL, *digest_sha512 = NULL;
283 uint16_t i;
284 unsigned char *buf = malloc(64);
285 unsigned int buf_len = 64;
286 int ret = 0;
287
288 if (cert == NULL || map_type == NULL || name == NULL) {
289 free(buf);
290 return -1;
291 }
292
293 for (i = 0; i < tls_opts.ctn_count; ++i) {
294 /* MD5 */
295 if (!strncmp(tls_opts.ctn[i].fingerprint, "01", 2)) {
296 if (!digest_md5) {
297 if (X509_digest(cert, EVP_md5(), buf, &buf_len) != 1) {
298 ERR("%s: calculating MD5 digest: %s", __func__, ERR_reason_error_string(ERR_get_error()));
299 ret = -1;
300 goto cleanup;
301 }
302 digest_to_str(buf, buf_len, &digest_md5);
303 }
304
305 if (!strcasecmp(tls_opts.ctn[i].fingerprint + 3, digest_md5)) {
306 /* we got ourselves a winner! */
307 VRB("Cert verify CTN: entry with a matching fingerprint found");
308 *map_type = tls_opts.ctn[i].map_type;
309 if (tls_opts.ctn[i].map_type == NC_TLS_CTN_SPECIFIED) {
310 *name = tls_opts.ctn[i].name;
311 }
312 break;
313 }
314
315 /* SHA-1 */
316 } else if (!strncmp(tls_opts.ctn[i].fingerprint, "02", 2)) {
317 if (!digest_sha1) {
318 if (X509_digest(cert, EVP_sha1(), buf, &buf_len) != 1) {
319 ERR("%s: calculating SHA-1 digest: %s", __func__, ERR_reason_error_string(ERR_get_error()));
320 ret = -1;
321 goto cleanup;
322 }
323 digest_to_str(buf, buf_len, &digest_sha1);
324 }
325
326 if (!strcasecmp(tls_opts.ctn[i].fingerprint + 3, digest_sha1)) {
327 /* we got ourselves a winner! */
328 VRB("Cert verify CTN: entry with a matching fingerprint found");
329 *map_type = tls_opts.ctn[i].map_type;
330 if (tls_opts.ctn[i].map_type == NC_TLS_CTN_SPECIFIED) {
331 *name = tls_opts.ctn[i].name;
332 }
333 break;
334 }
335
336 /* SHA-224 */
337 } else if (!strncmp(tls_opts.ctn[i].fingerprint, "03", 2)) {
338 if (!digest_sha224) {
339 if (X509_digest(cert, EVP_sha224(), buf, &buf_len) != 1) {
340 ERR("%s: calculating SHA-224 digest: %s", __func__, ERR_reason_error_string(ERR_get_error()));
341 ret = -1;
342 goto cleanup;
343 }
344 digest_to_str(buf, buf_len, &digest_sha224);
345 }
346
347 if (!strcasecmp(tls_opts.ctn[i].fingerprint + 3, digest_sha224)) {
348 /* we got ourselves a winner! */
349 VRB("Cert verify CTN: entry with a matching fingerprint found");
350 *map_type = tls_opts.ctn[i].map_type;
351 if (tls_opts.ctn[i].map_type == NC_TLS_CTN_SPECIFIED) {
352 *name = tls_opts.ctn[i].name;
353 }
354 break;
355 }
356
357 /* SHA-256 */
358 } else if (!strncmp(tls_opts.ctn[i].fingerprint, "04", 2)) {
359 if (!digest_sha256) {
360 if (X509_digest(cert, EVP_sha256(), buf, &buf_len) != 1) {
361 ERR("%s: calculating SHA-256 digest: %s", __func__, ERR_reason_error_string(ERR_get_error()));
362 ret = -1;
363 goto cleanup;
364 }
365 digest_to_str(buf, buf_len, &digest_sha256);
366 }
367
368 if (!strcasecmp(tls_opts.ctn[i].fingerprint + 3, digest_sha256)) {
369 /* we got ourselves a winner! */
370 VRB("Cert verify CTN: entry with a matching fingerprint found");
371 *map_type = tls_opts.ctn[i].map_type;
372 if (tls_opts.ctn[i].map_type == NC_TLS_CTN_SPECIFIED) {
373 *name = tls_opts.ctn[i].name;
374 }
375 break;
376 }
377
378 /* SHA-384 */
379 } else if (!strncmp(tls_opts.ctn[i].fingerprint, "05", 2)) {
380 if (!digest_sha384) {
381 if (X509_digest(cert, EVP_sha384(), buf, &buf_len) != 1) {
382 ERR("%s: calculating SHA-384 digest: %s", __func__, ERR_reason_error_string(ERR_get_error()));
383 ret = -1;
384 goto cleanup;
385 }
386 digest_to_str(buf, buf_len, &digest_sha384);
387 }
388
389 if (!strcasecmp(tls_opts.ctn[i].fingerprint + 3, digest_sha384)) {
390 /* we got ourselves a winner! */
391 VRB("Cert verify CTN: entry with a matching fingerprint found");
392 *map_type = tls_opts.ctn[i].map_type;
393 if (tls_opts.ctn[i].map_type == NC_TLS_CTN_SPECIFIED) {
394 *name = tls_opts.ctn[i].name;
395 }
396 break;
397 }
398
399 /* SHA-512 */
400 } else if (!strncmp(tls_opts.ctn[i].fingerprint, "06", 2)) {
401 if (!digest_sha512) {
402 if (X509_digest(cert, EVP_sha512(), buf, &buf_len) != 1) {
403 ERR("%s: calculating SHA-512 digest: %s", __func__, ERR_reason_error_string(ERR_get_error()));
404 ret = -1;
405 goto cleanup;
406 }
407 digest_to_str(buf, buf_len, &digest_sha512);
408 }
409
410 if (!strcasecmp(tls_opts.ctn[i].fingerprint + 3, digest_sha512)) {
411 /* we got ourselves a winner! */
412 VRB("Cert verify CTN: entry with a matching fingerprint found");
413 *map_type = tls_opts.ctn[i].map_type;
414 if (tls_opts.ctn[i].map_type == NC_TLS_CTN_SPECIFIED) {
415 *name = tls_opts.ctn[i].name;
416 }
417 break;
418 }
419
420 /* unknown */
421 } else {
422 WRN("%s: unknown fingerprint algorithm used (%s), skipping", __func__, tls_opts.ctn[i].fingerprint);
423 }
424 }
425
426 if (i == tls_opts.ctn_count) {
427 ret = 1;
428 }
429
430cleanup:
431 free(digest_md5);
432 free(digest_sha1);
433 free(digest_sha224);
434 free(digest_sha256);
435 free(digest_sha384);
436 free(digest_sha512);
437 free(buf);
438 return ret;
439}
440
441/* TODO */
442struct nc_session *glob_session;
443
444static int
445nc_tlsclb_verify(int preverify_ok, X509_STORE_CTX *x509_ctx)
446{
447 X509_STORE_CTX store_ctx;
448 X509_OBJECT obj;
449 X509_NAME *subject;
450 X509_NAME *issuer;
451 X509 *cert;
452 X509_CRL *crl;
453 X509_REVOKED *revoked;
454 STACK_OF(X509) *cert_stack;
455 EVP_PKEY *pubkey;
456 struct nc_session* session;
457 long serial;
458 int i, n, rc, depth;
459 char *cp;
460 const char *username = NULL;
461 NC_TLS_CTN_MAPTYPE map_type = 0;
462 ASN1_TIME *last_update = NULL, *next_update = NULL;
463
464 /* get the new client structure */
465 session = glob_session;
466
467 /* get the last certificate, that is the peer (client) certificate */
Michal Vasko06e22432016-01-15 10:30:06 +0100468 if (!session->tls_cert) {
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100469 cert_stack = X509_STORE_CTX_get1_chain(x509_ctx);
470 /* TODO all that is needed, but function X509_up_ref not present in older OpenSSL versions
471 session->cert = sk_X509_value(cert_stack, sk_X509_num(cert_stack) - 1);
472 X509_up_ref(session->cert);
473 sk_X509_pop_free(cert_stack, X509_free); */
474 while ((cert = sk_X509_pop(cert_stack))) {
Michal Vasko06e22432016-01-15 10:30:06 +0100475 X509_free(session->tls_cert);
476 session->tls_cert = cert;
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100477 }
478 sk_X509_pop_free(cert_stack, X509_free);
479 }
480
481 /* standard certificate verification failed, so a trusted client cert must match to continue */
482 if (!preverify_ok) {
Michal Vasko06e22432016-01-15 10:30:06 +0100483 subject = X509_get_subject_name(session->tls_cert);
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100484 cert_stack = X509_STORE_get1_certs(x509_ctx, subject);
485 if (cert_stack) {
486 for (i = 0; i < sk_X509_num(cert_stack); ++i) {
Michal Vasko06e22432016-01-15 10:30:06 +0100487 if (cert_pubkey_match(session->tls_cert, sk_X509_value(cert_stack, i))) {
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100488 /* we are just overriding the failed standard certificate verification (preverify_ok == 0),
489 * this callback will be called again with the same current certificate and preverify_ok == 1 */
Michal Vasko05ba9df2016-01-13 14:40:27 +0100490 VRB("Cert verify: fail (%s), but the client certificate is trusted, continuing.",
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100491 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx)));
492 X509_STORE_CTX_set_error(x509_ctx, X509_V_OK);
493 sk_X509_pop_free(cert_stack, X509_free);
494 return 1;
495 }
496 }
497 sk_X509_pop_free(cert_stack, X509_free);
498 }
499
500 ERR("Cert verify: fail (%s).", X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx)));
501 return 0;
502 }
503
504 /* print cert verify info */
505 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
506 VRB("Cert verify: depth %d", depth);
507
508 cert = X509_STORE_CTX_get_current_cert(x509_ctx);
509 subject = X509_get_subject_name(cert);
510 issuer = X509_get_issuer_name(cert);
511
512 cp = X509_NAME_oneline(subject, NULL, 0);
513 VRB("Cert verify: subject: %s", cp);
514 OPENSSL_free(cp);
515 cp = X509_NAME_oneline(issuer, NULL, 0);
516 VRB("Cert verify: issuer: %s", cp);
517 OPENSSL_free(cp);
518
519 /* check for revocation if set */
520 if (tls_opts.crl_store) {
521 /* try to retrieve a CRL corresponding to the _subject_ of
522 * the current certificate in order to verify it's integrity */
523 memset((char *)&obj, 0, sizeof(obj));
524 X509_STORE_CTX_init(&store_ctx, tls_opts.crl_store, NULL, NULL);
525 rc = X509_STORE_get_by_subject(&store_ctx, X509_LU_CRL, subject, &obj);
526 X509_STORE_CTX_cleanup(&store_ctx);
527 crl = obj.data.crl;
528 if (rc > 0 && crl) {
529 cp = X509_NAME_oneline(subject, NULL, 0);
530 VRB("Cert verify CRL: issuer: %s", cp);
531 OPENSSL_free(cp);
532
533 last_update = X509_CRL_get_lastUpdate(crl);
534 next_update = X509_CRL_get_nextUpdate(crl);
535 cp = asn1time_to_str(last_update);
536 VRB("Cert verify CRL: last update: %s", cp);
537 free(cp);
538 cp = asn1time_to_str(next_update);
539 VRB("Cert verify CRL: next update: %s", cp);
540 free(cp);
541
542 /* verify the signature on this CRL */
543 pubkey = X509_get_pubkey(cert);
544 if (X509_CRL_verify(crl, pubkey) <= 0) {
545 ERR("Cert verify CRL: invalid signature.");
546 X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
547 X509_OBJECT_free_contents(&obj);
548 if (pubkey) {
549 EVP_PKEY_free(pubkey);
550 }
551 return 0;
552 }
553 if (pubkey) {
554 EVP_PKEY_free(pubkey);
555 }
556
557 /* check date of CRL to make sure it's not expired */
558 if (!next_update) {
559 ERR("Cert verify CRL: invalid nextUpdate field.");
560 X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
561 X509_OBJECT_free_contents(&obj);
562 return 0;
563 }
564 if (X509_cmp_current_time(next_update) < 0) {
565 ERR("Cert verify CRL: expired - revoking all certificates.");
566 X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_CRL_HAS_EXPIRED);
567 X509_OBJECT_free_contents(&obj);
568 return 0;
569 }
570 X509_OBJECT_free_contents(&obj);
571 }
572
573 /* try to retrieve a CRL corresponding to the _issuer_ of
574 * the current certificate in order to check for revocation */
575 memset((char *)&obj, 0, sizeof(obj));
576 X509_STORE_CTX_init(&store_ctx, tls_opts.crl_store, NULL, NULL);
577 rc = X509_STORE_get_by_subject(&store_ctx, X509_LU_CRL, issuer, &obj);
578 X509_STORE_CTX_cleanup(&store_ctx);
579 crl = obj.data.crl;
580 if (rc > 0 && crl) {
581 /* check if the current certificate is revoked by this CRL */
582 n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
583 for (i = 0; i < n; i++) {
584 revoked = sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
585 if (ASN1_INTEGER_cmp(revoked->serialNumber, X509_get_serialNumber(cert)) == 0) {
586 serial = ASN1_INTEGER_get(revoked->serialNumber);
587 cp = X509_NAME_oneline(issuer, NULL, 0);
588 ERR("Cert verify CRL: certificate with serial %ld (0x%lX) revoked per CRL from issuer %s", serial, serial, cp);
589 OPENSSL_free(cp);
590 X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_CERT_REVOKED);
591 X509_OBJECT_free_contents(&obj);
592 return 0;
593 }
594 }
595 X509_OBJECT_free_contents(&obj);
596 }
597 }
598
599 /* cert-to-name already successful */
600 if (session->username) {
601 return 1;
602 }
603
604 /* cert-to-name */
605 rc = nc_tls_cert_to_name(cert, &map_type, &username);
606 if (rc) {
607 if (rc == -1) {
608 /* fatal error */
609 depth = 0;
610 }
611 /* rc == 1 is a normal CTN fail (no match found) */
612 goto fail;
613 }
614
615 /* cert-to-name match, now to extract the specific field from the peer cert */
616 if (map_type == NC_TLS_CTN_SPECIFIED) {
617 session->username = lydict_insert(server_opts.ctx, username, 0);
618 } else {
Michal Vasko06e22432016-01-15 10:30:06 +0100619 rc = nc_tls_ctn_get_username_from_cert(session->tls_cert, map_type, &cp);
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100620 if (rc) {
621 if (rc == -1) {
622 depth = 0;
623 }
624 goto fail;
625 }
626 session->username = lydict_insert_zc(server_opts.ctx, cp);
627 }
628
629 VRB("Cert verify CTN: new client username recognized as \"%s\".", session->username);
630 return 1;
631
632fail:
633 if (depth > 0) {
634 VRB("Cert verify CTN: cert fail, cert-to-name will continue on the next cert in chain.");
635 return 1;
636 }
637
638 VRB("Cert-to-name unsuccessful, dropping the new client.");
639 X509_STORE_CTX_set_error(x509_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
640 return 0;
641}
642
643API int
644nc_tls_server_set_cert(const char *cert)
645{
646 X509 *x509_cert;
647
648 if (!cert) {
649 ERRARG;
650 return -1;
651 }
652
653 if (!tls_opts.tls_ctx) {
654 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
655 if (!tls_opts.tls_ctx) {
656 ERR("%s: failed to create TLS context.", __func__);
657 return -1;
658 }
659 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
660 }
661
662 x509_cert = base64der_to_cert(cert);
663 if (!x509_cert || (SSL_CTX_use_certificate(tls_opts.tls_ctx, x509_cert) != 1)) {
664 ERR("%s: loading the server certificate failed (%s).", ERR_reason_error_string(ERR_get_error()));
665 X509_free(x509_cert);
666 return -1;
667 }
668 X509_free(x509_cert);
669
670 return 0;
671}
672
673/* PEM only */
674API int
675nc_tls_server_set_cert_path(const char *cert_path)
676{
677 if (!cert_path) {
678 ERRARG;
679 return -1;
680 }
681
682 if (!tls_opts.tls_ctx) {
683 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
684 if (!tls_opts.tls_ctx) {
685 ERR("%s: failed to create TLS context.", __func__);
686 return -1;
687 }
688 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
689 }
690
691 if (SSL_CTX_use_certificate_file(tls_opts.tls_ctx, cert_path, SSL_FILETYPE_PEM) != 1) {
692 ERR("%s: loading the server certificate failed (%s).", ERR_reason_error_string(ERR_get_error()));
693 return -1;
694 }
695
696 return 0;
697}
698
699API int
700nc_tls_server_set_key(const char *privkey, int is_rsa)
701{
702 EVP_PKEY *key;;
703
704 if (!privkey) {
705 ERRARG;
706 return -1;
707 }
708
709 if (!tls_opts.tls_ctx) {
710 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
711 if (!tls_opts.tls_ctx) {
712 ERR("%s: failed to create TLS context.", __func__);
713 return -1;
714 }
715 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
716 }
717
718 key = base64der_to_privatekey(privkey, is_rsa);
719 if (!key || (SSL_CTX_use_PrivateKey(tls_opts.tls_ctx, key) != 1)) {
720 ERR("%s: loading the server private key failed (%s).", ERR_reason_error_string(ERR_get_error()));
721 EVP_PKEY_free(key);
722 return -1;
723 }
724 EVP_PKEY_free(key);
725
726 return 0;
727}
728
729/* PEM only */
730API int
731nc_tls_server_set_key_path(const char *privkey_path)
732{
733 if (!privkey_path) {
734 ERRARG;
735 return -1;
736 }
737
738 if (!tls_opts.tls_ctx) {
739 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
740 if (!tls_opts.tls_ctx) {
741 ERR("%s: failed to create TLS context.", __func__);
742 return -1;
743 }
744 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
745 }
746
747 if (SSL_CTX_use_PrivateKey_file(tls_opts.tls_ctx, privkey_path, SSL_FILETYPE_PEM) != 1) {
748 ERR("%s: loading the server priavte key failed (%s).", ERR_reason_error_string(ERR_get_error()));
749 return -1;
750 }
751
752 return 0;
753}
754
755API int
756nc_tls_server_add_trusted_cert(const char *cert)
757{
758 X509_STORE *cert_store;
759 X509 *x509_cert;
760
761 if (!cert) {
762 ERRARG;
763 return -1;
764 }
765
766 if (!tls_opts.tls_ctx) {
767 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
768 if (!tls_opts.tls_ctx) {
769 ERR("%s: failed to create TLS context.", __func__);
770 return -1;
771 }
772 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
773 }
774
775 cert_store = SSL_CTX_get_cert_store(tls_opts.tls_ctx);
776 if (!cert_store) {
777 cert_store = X509_STORE_new();
778 SSL_CTX_set_cert_store(tls_opts.tls_ctx, cert_store);
779 }
780
781 x509_cert = base64der_to_cert(cert);
782 if (!x509_cert || (X509_STORE_add_cert(cert_store, x509_cert) != 1)) {
783 ERR("%s: adding a trusted certificate failed (%s).", ERR_reason_error_string(ERR_get_error()));
784 X509_free(x509_cert);
785 return -1;
786 }
787 X509_free(x509_cert);
788
789 return 0;
790}
791
792API int
793nc_tls_server_add_trusted_cert_path(const char *cert_path)
794{
795 X509_STORE *cert_store;
796 X509 *x509_cert;
797
798 if (!cert_path) {
799 ERRARG;
800 return -1;
801 }
802
803 if (!tls_opts.tls_ctx) {
804 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
805 if (!tls_opts.tls_ctx) {
806 ERR("%s: failed to create TLS context.", __func__);
807 return -1;
808 }
809 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
810 }
811
812 cert_store = SSL_CTX_get_cert_store(tls_opts.tls_ctx);
813 if (!cert_store) {
814 cert_store = X509_STORE_new();
815 SSL_CTX_set_cert_store(tls_opts.tls_ctx, cert_store);
816 }
817
818 errno = 0;
819 x509_cert = pem_to_cert(cert_path);
820 if (!x509_cert || (X509_STORE_add_cert(cert_store, x509_cert) != 1)) {
821 ERR("%s: adding a trusted certificate failed (%s).",
822 (errno ? strerror(errno) : ERR_reason_error_string(ERR_get_error())));
823 X509_free(x509_cert);
824 return -1;
825 }
826 X509_free(x509_cert);
827
828 return 0;
829}
830
831API int
832nc_tls_server_set_trusted_cacert_locations(const char *cacert_file_path, const char *cacert_dir_path)
833{
834 X509_STORE *cert_store;
835 X509_LOOKUP *lookup;
836
837 if (!cacert_file_path && !cacert_dir_path) {
838 ERRARG;
839 return -1;
840 }
841
842 if (!tls_opts.tls_ctx) {
843 tls_opts.tls_ctx = SSL_CTX_new(TLSv1_2_server_method());
844 if (!tls_opts.tls_ctx) {
845 ERR("%s: failed to create TLS context.", __func__);
846 return -1;
847 }
848 SSL_CTX_set_verify(tls_opts.tls_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nc_tlsclb_verify);
849 }
850
851 cert_store = SSL_CTX_get_cert_store(tls_opts.tls_ctx);
852 if (!cert_store) {
853 cert_store = X509_STORE_new();
854 SSL_CTX_set_cert_store(tls_opts.tls_ctx, cert_store);
855 }
856
857 if (cacert_file_path) {
858 lookup = X509_STORE_add_lookup(cert_store, X509_LOOKUP_file());
859 if (!lookup) {
860 ERR("%s: failed to add lookup method.", __func__);
861 return -1;
862 }
863
864 if (X509_LOOKUP_load_file(lookup, cacert_file_path, X509_FILETYPE_PEM) != 1) {
865 ERR("%s: failed to add trusted cert file (%s).", __func__, ERR_reason_error_string(ERR_get_error()));
866 return -1;
867 }
868 }
869
870 if (cacert_dir_path) {
871 lookup = X509_STORE_add_lookup(cert_store, X509_LOOKUP_hash_dir());
872 if (!lookup) {
873 ERR("%s: failed to add lookup method.", __func__);
874 return -1;
875 }
876
877 if (X509_LOOKUP_add_dir(lookup, cacert_dir_path, X509_FILETYPE_PEM) != 1) {
878 ERR("%s: failed to add trusted cert directory (%s).", __func__, ERR_reason_error_string(ERR_get_error()));
879 return -1;
880 }
881 }
882
883 return 0;
Michal Vasko086311b2016-01-08 09:53:11 +0100884}
885
886API void
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100887nc_tls_server_destroy_certs(void)
Michal Vasko086311b2016-01-08 09:53:11 +0100888{
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100889 if (!tls_opts.tls_ctx) {
890 return;
891 }
Michal Vasko086311b2016-01-08 09:53:11 +0100892
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100893 SSL_CTX_free(tls_opts.tls_ctx);
894 tls_opts.tls_ctx = NULL;
895}
896
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100897API int
898nc_tls_server_set_crl_locations(const char *crl_file_path, const char *crl_dir_path)
899{
900 X509_LOOKUP *lookup;
901
902 if (!crl_file_path && !crl_dir_path) {
903 ERRARG;
904 return -1;
905 }
906
907 if (!tls_opts.crl_store) {
908 tls_opts.crl_store = X509_STORE_new();
909 }
910
911 if (crl_file_path) {
912 lookup = X509_STORE_add_lookup(tls_opts.crl_store, X509_LOOKUP_file());
913 if (!lookup) {
914 ERR("%s: failed to add lookup method.", __func__);
915 return -1;
916 }
917
918 if (X509_LOOKUP_load_file(lookup, crl_file_path, X509_FILETYPE_PEM) != 1) {
919 ERR("%s: failed to add revocation lookup file (%s).", __func__, ERR_reason_error_string(ERR_get_error()));
920 return -1;
921 }
922 }
923
924 if (crl_dir_path) {
925 lookup = X509_STORE_add_lookup(tls_opts.crl_store, X509_LOOKUP_hash_dir());
926 if (!lookup) {
927 ERR("%s: failed to add lookup method.", __func__);
928 return -1;
929 }
930
931 if (X509_LOOKUP_add_dir(lookup, crl_dir_path, X509_FILETYPE_PEM) != 1) {
932 ERR("%s: failed to add revocation lookup directory (%s).", __func__, ERR_reason_error_string(ERR_get_error()));
933 return -1;
934 }
935 }
936
937 return 0;
938}
939
940API void
941nc_tls_server_destroy_crls(void)
942{
943 if (!tls_opts.crl_store) {
944 return;
945 }
946
947 X509_STORE_free(tls_opts.crl_store);
948 tls_opts.crl_store = NULL;
949}
950
951API int
952nc_tls_server_add_ctn(uint32_t id, const char *fingerprint, NC_TLS_CTN_MAPTYPE map_type, const char *name)
953{
Michal Vasko1a38c862016-01-15 15:50:07 +0100954 if (!fingerprint || !map_type || ((map_type == NC_TLS_CTN_SPECIFIED) && !name)
955 || ((map_type != NC_TLS_CTN_SPECIFIED) && name)) {
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100956 ERRARG;
957 return -1;
958 }
959
960 ++tls_opts.ctn_count;
961 tls_opts.ctn = realloc(tls_opts.ctn, tls_opts.ctn_count * sizeof *tls_opts.ctn);
962
963 tls_opts.ctn[tls_opts.ctn_count - 1].id = id;
964 tls_opts.ctn[tls_opts.ctn_count - 1].fingerprint = lydict_insert(server_opts.ctx, fingerprint, 0);
965 tls_opts.ctn[tls_opts.ctn_count - 1].map_type = map_type;
966 tls_opts.ctn[tls_opts.ctn_count - 1].name = lydict_insert(server_opts.ctx, name, 0);
967
968 return 0;
969}
970
971API int
972nc_tls_server_del_ctn(int64_t id, const char *fingerprint, NC_TLS_CTN_MAPTYPE map_type, const char *name)
973{
974 uint16_t i;
975 int ret = -1;
976
Michal Vasko1a38c862016-01-15 15:50:07 +0100977 if ((id < 0) && !fingerprint && !map_type && !name) {
978 for (i = 0; i < tls_opts.ctn_count; ++i) {
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100979 lydict_remove(server_opts.ctx, tls_opts.ctn[i].fingerprint);
980 lydict_remove(server_opts.ctx, tls_opts.ctn[i].name);
981
Michal Vaskoc14e3c82016-01-11 16:14:30 +0100982 ret = 0;
983 }
Michal Vasko1a38c862016-01-15 15:50:07 +0100984 free(tls_opts.ctn);
985 tls_opts.ctn = NULL;
986 tls_opts.ctn_count = 0;
987 } else {
988 for (i = 0; i < tls_opts.ctn_count; ++i) {
989 if (((id < 0) || (tls_opts.ctn[i].id == id))
990 && (!fingerprint || !strcmp(tls_opts.ctn[i].fingerprint, fingerprint))
991 && (!map_type || (tls_opts.ctn[i].map_type == map_type))
992 && (!name || (tls_opts.ctn[i].name && !strcmp(tls_opts.ctn[i].name, name)))) {
993 lydict_remove(server_opts.ctx, tls_opts.ctn[i].fingerprint);
994 lydict_remove(server_opts.ctx, tls_opts.ctn[i].name);
995
996 --tls_opts.ctn_count;
997 memmove(&tls_opts.ctn[i], &tls_opts.ctn[i + 1], (tls_opts.ctn_count - i) * sizeof *tls_opts.ctn);
998
999 ret = 0;
1000 }
1001 }
Michal Vaskoc14e3c82016-01-11 16:14:30 +01001002 }
1003
1004 return ret;
1005}
1006
1007API void
1008nc_tls_server_free_opts(void)
1009{
Michal Vaskoc14e3c82016-01-11 16:14:30 +01001010 nc_tls_server_destroy_certs();
1011 nc_tls_server_destroy_crls();
Michal Vasko1a38c862016-01-15 15:50:07 +01001012 nc_tls_server_del_ctn(-1, NULL, 0, NULL);
Michal Vasko086311b2016-01-08 09:53:11 +01001013}
Michal Vasko9e036d52016-01-08 10:49:26 +01001014
1015int
1016nc_accept_tls_session(struct nc_session *session, int sock, int timeout)
1017{
Michal Vaskoc14e3c82016-01-11 16:14:30 +01001018 int ret;
1019 struct pollfd pfd;
1020
1021 pfd.fd = sock;
1022 pfd.events = POLLIN;
1023 pfd.revents = 0;
1024
1025 /* poll for a new connection */
1026 errno = 0;
1027 ret = poll(&pfd, 1, timeout);
1028 if (!ret) {
1029 /* we timeouted */
1030 close(sock);
Michal Vasko1a38c862016-01-15 15:50:07 +01001031 return 0;
Michal Vaskoc14e3c82016-01-11 16:14:30 +01001032 } else if (ret == -1) {
1033 ERR("%s: poll failed (%s).", __func__, strerror(errno));
1034 close(sock);
1035 return -1;
1036 }
1037
1038 /* data waiting */
1039 session->ti_type = NC_TI_OPENSSL;
1040 session->ti.tls = SSL_new(tls_opts.tls_ctx);
1041 if (!session->ti.tls) {
1042 ERRMEM;
1043 close(sock);
1044 return -1;
1045 }
1046
1047 SSL_set_fd(session->ti.tls, sock);
1048 SSL_set_mode(session->ti.tls, SSL_MODE_AUTO_RETRY);
1049
1050 /* generate new index for TLS-specific data, for the verify callback */
1051 /*netopeer_state.tls_state->last_tls_idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1052 SSL_set_ex_data(new_client->tls, netopeer_state.tls_state->last_tls_idx, new_client);*/
1053 glob_session = session;
1054
1055 ret = SSL_accept(session->ti.tls);
1056 if (ret != 1) {
1057 switch (SSL_get_error(session->ti.tls, ret)) {
1058 case SSL_ERROR_SYSCALL:
1059 ERR("%s: SSL_accept failed (%s).", __func__, strerror(errno));
1060 break;
1061 case SSL_ERROR_SSL:
1062 ERR("%s: SSL_accept failed (%s).", __func__, ERR_reason_error_string(ERR_get_error()));
1063 break;
1064 default:
1065 ERR("%s: SSL_accept failed.", __func__);
1066 break;
1067 }
1068 return -1;
1069 }
1070
Michal Vasko1a38c862016-01-15 15:50:07 +01001071 return 1;
Michal Vasko9e036d52016-01-08 10:49:26 +01001072}