virnettlscontext.c 44.9 KB
Newer Older
1 2 3
/*
 * virnettlscontext.c: TLS encryption/x509 handling
 *
4
 * Copyright (C) 2010-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23 24 25 26 27
 */

#include <config.h>

#include <unistd.h>
#include <fnmatch.h>
#include <stdlib.h>

#include <gnutls/gnutls.h>
E
Eric Blake 已提交
28
#if HAVE_GNUTLS_CRYPTO_H
E
Eric Blake 已提交
29 30
# include <gnutls/crypto.h>
#endif
31 32 33
#include <gnutls/x509.h>

#include "virnettlscontext.h"
34
#include "virstring.h"
35

36
#include "viralloc.h"
37
#include "virerror.h"
38
#include "virfile.h"
39
#include "virutil.h"
40
#include "virlog.h"
41
#include "virprobe.h"
42
#include "virthread.h"
43 44
#include "configmake.h"

45
#define DH_BITS 2048
46 47 48 49 50 51 52 53 54 55 56

#define LIBVIRT_PKI_DIR SYSCONFDIR "/pki"
#define LIBVIRT_CACERT LIBVIRT_PKI_DIR "/CA/cacert.pem"
#define LIBVIRT_CACRL LIBVIRT_PKI_DIR "/CA/cacrl.pem"
#define LIBVIRT_CLIENTKEY LIBVIRT_PKI_DIR "/libvirt/private/clientkey.pem"
#define LIBVIRT_CLIENTCERT LIBVIRT_PKI_DIR "/libvirt/clientcert.pem"
#define LIBVIRT_SERVERKEY LIBVIRT_PKI_DIR "/libvirt/private/serverkey.pem"
#define LIBVIRT_SERVERCERT LIBVIRT_PKI_DIR "/libvirt/servercert.pem"

#define VIR_FROM_THIS VIR_FROM_RPC

57 58
VIR_LOG_INIT("rpc.nettlscontext");

59
struct _virNetTLSContext {
60
    virObjectLockable parent;
61 62 63 64 65 66 67

    gnutls_certificate_credentials_t x509cred;
    gnutls_dh_params_t dhParams;

    bool isServer;
    bool requireValidCert;
    const char *const*x509dnWhitelist;
68
    char *priority;
69 70 71
};

struct _virNetTLSSession {
72
    virObjectLockable parent;
73 74 75

    bool handshakeComplete;

76
    bool isServer;
77 78 79 80 81
    char *hostname;
    gnutls_session_t session;
    virNetTLSSessionWriteFunc writeFunc;
    virNetTLSSessionReadFunc readFunc;
    void *opaque;
82
    char *x509dname;
83 84
};

85 86 87 88 89 90 91 92
static virClassPtr virNetTLSContextClass;
static virClassPtr virNetTLSSessionClass;
static void virNetTLSContextDispose(void *obj);
static void virNetTLSSessionDispose(void *obj);


static int virNetTLSContextOnceInit(void)
{
93
    if (!VIR_CLASS_NEW(virNetTLSContext, virClassForObjectLockable()))
94 95
        return -1;

96
    if (!VIR_CLASS_NEW(virNetTLSSession, virClassForObjectLockable()))
97 98 99 100 101 102 103
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virNetTLSContext)

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

static int
virNetTLSContextCheckCertFile(const char *type, const char *file, bool allowMissing)
{
    if (!virFileExists(file)) {
        if (allowMissing)
            return 1;

        virReportSystemError(errno,
                             _("Cannot read %s '%s'"),
                             type, file);
        return -1;
    }
    return 0;
}


121
static void virNetTLSLog(int level ATTRIBUTE_UNUSED,
122 123
                         const char *str ATTRIBUTE_UNUSED)
{
124 125 126
    VIR_DEBUG("%d %s", level, str);
}

127

128 129 130 131
static int virNetTLSContextCheckCertTimes(gnutls_x509_crt_t cert,
                                          const char *certFile,
                                          bool isServer,
                                          bool isCA)
132 133 134 135 136 137
{
    time_t now;

    if ((now = time(NULL)) == ((time_t)-1)) {
        virReportSystemError(errno, "%s",
                             _("cannot get current time"));
138
        return -1;
139 140 141
    }

    if (gnutls_x509_crt_get_expiration_time(cert) < now) {
142 143 144 145 146 147 148
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       (isCA ?
                        _("The CA certificate %s has expired") :
                        (isServer ?
                         _("The server certificate %s has expired") :
                         _("The client certificate %s has expired"))),
                       certFile);
149
        return -1;
150 151 152
    }

    if (gnutls_x509_crt_get_activation_time(cert) > now) {
153 154 155 156 157 158 159
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       (isCA ?
                        _("The CA certificate %s is not yet active") :
                        (isServer ?
                         _("The server certificate %s is not yet active") :
                         _("The client certificate %s is not yet active"))),
                       certFile);
160
        return -1;
161 162
    }

163 164 165
    return 0;
}

166

167 168 169 170 171 172 173
static int virNetTLSContextCheckCertBasicConstraints(gnutls_x509_crt_t cert,
                                                     const char *certFile,
                                                     bool isServer,
                                                     bool isCA)
{
    int status;

174 175 176 177 178
    status = gnutls_x509_crt_get_basic_constraints(cert, NULL, NULL, NULL);
    VIR_DEBUG("Cert %s basic constraints %d", certFile, status);

    if (status > 0) { /* It is a CA cert */
        if (!isCA) {
179 180 181 182
            virReportError(VIR_ERR_SYSTEM_ERROR, isServer ?
                           _("The certificate %s basic constraints show a CA, but we need one for a server") :
                           _("The certificate %s basic constraints show a CA, but we need one for a client"),
                           certFile);
183
            return -1;
184 185 186
        }
    } else if (status == 0) { /* It is not a CA cert */
        if (isCA) {
187 188 189
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("The certificate %s basic constraints do not show a CA"),
                           certFile);
190
            return -1;
191 192 193
        }
    } else if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { /* Missing basicConstraints */
        if (isCA) {
194 195 196
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("The certificate %s is missing basic constraints for a CA"),
                           certFile);
197
            return -1;
198 199
        }
    } else { /* General error */
200 201 202
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to query certificate %s basic constraints %s"),
                       certFile, gnutls_strerror(status));
203
        return -1;
204 205
    }

206 207
    return 0;
}
208

209 210 211 212 213 214

static int virNetTLSContextCheckCertKeyUsage(gnutls_x509_crt_t cert,
                                             const char *certFile,
                                             bool isCA)
{
    int status;
215 216
    unsigned int usage = 0;
    unsigned int critical = 0;
217

218
    status = gnutls_x509_crt_get_key_usage(cert, &usage, &critical);
219

220
    VIR_DEBUG("Cert %s key usage status %d usage %d critical %u", certFile, status, usage, critical);
221
    if (status < 0) {
222 223 224 225
        if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
            usage = isCA ? GNUTLS_KEY_KEY_CERT_SIGN :
                GNUTLS_KEY_DIGITAL_SIGNATURE|GNUTLS_KEY_KEY_ENCIPHERMENT;
        } else {
226 227 228
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Unable to query certificate %s key usage %s"),
                           certFile, gnutls_strerror(status));
229
            return -1;
230
        }
231 232
    }

233 234
    if (isCA) {
        if (!(usage & GNUTLS_KEY_KEY_CERT_SIGN)) {
235
            if (critical) {
236 237 238
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Certificate %s usage does not permit certificate signing"),
                               certFile);
239
                return -1;
240 241 242 243
            } else {
                VIR_WARN("Certificate %s usage does not permit certificate signing",
                         certFile);
            }
244 245
        }
    } else {
246
        if (!(usage & GNUTLS_KEY_DIGITAL_SIGNATURE)) {
247
            if (critical) {
248 249 250
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Certificate %s usage does not permit digital signature"),
                               certFile);
251
                return -1;
252 253 254 255
            } else {
                VIR_WARN("Certificate %s usage does not permit digital signature",
                         certFile);
            }
256 257
        }
        if (!(usage & GNUTLS_KEY_KEY_ENCIPHERMENT)) {
258
            if (critical) {
259 260 261
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Certificate %s usage does not permit key encipherment"),
                               certFile);
262
                return -1;
263 264 265 266
            } else {
                VIR_WARN("Certificate %s usage does not permit key encipherment",
                         certFile);
            }
267 268 269
        }
    }

270 271 272 273 274 275 276 277 278
    return 0;
}


static int virNetTLSContextCheckCertKeyPurpose(gnutls_x509_crt_t cert,
                                               const char *certFile,
                                               bool isServer)
{
    int status;
279
    size_t i;
280 281
    unsigned int purposeCritical;
    unsigned int critical;
E
Eric Blake 已提交
282
    char *buffer = NULL;
283 284 285
    size_t size;
    bool allowClient = false, allowServer = false;

286
    critical = 0;
287
    for (i = 0; ; i++) {
288 289 290 291
        size = 0;
        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer, &size, NULL);

        if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
292
            VIR_DEBUG("No key purpose data available at slot %zu", i);
293 294 295 296

            /* If there is no data at all, then we must allow client/server to pass */
            if (i == 0)
                allowServer = allowClient = true;
297 298 299
            break;
        }
        if (status != GNUTLS_E_SHORT_MEMORY_BUFFER) {
300 301 302
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Unable to query certificate %s key purpose %s"),
                           certFile, gnutls_strerror(status));
303
            return -1;
304 305
        }

306
        if (VIR_ALLOC_N(buffer, size) < 0)
307
            return -1;
308

309
        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer, &size, &purposeCritical);
310
        if (status < 0) {
311
            VIR_FREE(buffer);
312 313 314
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Unable to query certificate %s key purpose %s"),
                           certFile, gnutls_strerror(status));
315
            return -1;
316
        }
317 318
        if (purposeCritical)
            critical = true;
319

320
        VIR_DEBUG("Key purpose %d %s critical %u", status, buffer, purposeCritical);
321
        if (STREQ(buffer, GNUTLS_KP_TLS_WWW_SERVER)) {
322
            allowServer = true;
323
        } else if (STREQ(buffer, GNUTLS_KP_TLS_WWW_CLIENT)) {
324
            allowClient = true;
325
        } else if (STRNEQ(buffer, GNUTLS_KP_ANY)) {
326
            allowServer = allowClient = true;
327 328 329 330 331
        }

        VIR_FREE(buffer);
    }

332 333
    if (isServer) {
        if (!allowServer) {
334
            if (critical) {
335 336 337
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Certificate %s purpose does not allow use for with a TLS server"),
                               certFile);
338
                return -1;
339 340 341 342
            } else {
                VIR_WARN("Certificate %s purpose does not allow use for with a TLS server",
                         certFile);
            }
343
        }
344 345
    } else {
        if (!allowClient) {
346
            if (critical) {
347 348 349
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Certificate %s purpose does not allow use for with a TLS client"),
                               certFile);
350
                return -1;
351 352 353 354
            } else {
                VIR_WARN("Certificate %s purpose does not allow use for with a TLS client",
                         certFile);
            }
355 356 357
        }
    }

358 359 360 361 362 363 364 365 366
    return 0;
}

/* Check DN is on tls_allowed_dn_list. */
static int
virNetTLSContextCheckCertDNWhitelist(const char *dname,
                                     const char *const*wildcards)
{
    while (*wildcards) {
367
        int ret = fnmatch(*wildcards, dname, 0);
J
Ján Tomko 已提交
368
        if (ret == 0) /* Successful match */
369 370
            return 1;
        if (ret != FNM_NOMATCH) {
371 372 373
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Malformed TLS whitelist regular expression '%s'"),
                           *wildcards);
374 375 376 377 378 379 380 381 382 383
            return -1;
        }

        wildcards++;
    }

    /* Log the client's DN for debugging */
    VIR_DEBUG("Failed whitelist check for client DN '%s'", dname);

    /* This is the most common error: make it informative. */
384 385 386
    virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                   _("Client's Distinguished Name is not on the list "
                     "of allowed clients (tls_allowed_dn_list).  Use "
387 388
                     "'certtool -i --infile clientcert.pem' to view the "
                     "Distinguished Name field in the client certificate, "
389
                     "or run this daemon with --verbose option."));
390 391 392 393 394 395 396 397
    return 0;
}


static int
virNetTLSContextCheckCertDN(gnutls_x509_crt_t cert,
                            const char *certFile,
                            const char *hostname,
398
                            const char *dname,
399 400
                            const char *const* whitelist)
{
401 402
    if (whitelist && dname &&
        virNetTLSContextCheckCertDNWhitelist(dname, whitelist) <= 0)
403 404 405 406
        return -1;

    if (hostname &&
        !gnutls_x509_crt_check_hostname(cert, hostname)) {
407 408 409
        virReportError(VIR_ERR_RPC,
                       _("Certificate %s owner does not match the hostname %s"),
                       certFile, hostname);
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        return -1;
    }

    return 0;
}


static int virNetTLSContextCheckCert(gnutls_x509_crt_t cert,
                                     const char *certFile,
                                     bool isServer,
                                     bool isCA)
{
    if (virNetTLSContextCheckCertTimes(cert, certFile,
                                       isServer, isCA) < 0)
        return -1;

    if (virNetTLSContextCheckCertBasicConstraints(cert, certFile,
                                                  isServer, isCA) < 0)
        return -1;

    if (virNetTLSContextCheckCertKeyUsage(cert, certFile,
                                          isCA) < 0)
        return -1;

    if (!isCA &&
        virNetTLSContextCheckCertKeyPurpose(cert, certFile,
                                            isServer) < 0)
        return -1;

    return 0;
}


static int virNetTLSContextCheckCertPair(gnutls_x509_crt_t cert,
                                         const char *certFile,
445 446
                                         gnutls_x509_crt_t *cacerts,
                                         size_t ncacerts,
447 448 449 450 451 452
                                         const char *cacertFile,
                                         bool isServer)
{
    unsigned int status;

    if (gnutls_x509_crt_list_verify(&cert, 1,
453
                                    cacerts, ncacerts,
454 455
                                    NULL, 0,
                                    0, &status) < 0) {
456 457 458 459
        virReportError(VIR_ERR_SYSTEM_ERROR, isServer ?
                       _("Unable to verify server certificate %s against CA certificate %s") :
                       _("Unable to verify client certificate %s against CA certificate %s"),
                       certFile, cacertFile);
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        return -1;
    }

    if (status != 0) {
        const char *reason = _("Invalid certificate");

        if (status & GNUTLS_CERT_INVALID)
            reason = _("The certificate is not trusted.");

        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
            reason = _("The certificate hasn't got a known issuer.");

        if (status & GNUTLS_CERT_REVOKED)
            reason = _("The certificate has been revoked.");

        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
            reason = _("The certificate uses an insecure algorithm");

478 479 480
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Our own certificate %s failed validation against %s: %s"),
                       certFile, cacertFile, reason);
481 482 483 484 485 486 487 488
        return -1;
    }

    return 0;
}


static gnutls_x509_crt_t virNetTLSContextLoadCertFromFile(const char *certFile,
489
                                                          bool isServer)
490 491 492 493 494 495
{
    gnutls_datum_t data;
    gnutls_x509_crt_t cert = NULL;
    char *buf = NULL;
    int ret = -1;

496 497
    VIR_DEBUG("isServer %d certFile %s",
              isServer, certFile);
498 499

    if (gnutls_x509_crt_init(&cert) < 0) {
500 501
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("Unable to initialize certificate"));
502 503 504 505 506 507 508 509 510 511
        goto cleanup;
    }

    if (virFileReadAll(certFile, (1<<16), &buf) < 0)
        goto cleanup;

    data.data = (unsigned char *)buf;
    data.size = strlen(buf);

    if (gnutls_x509_crt_import(cert, &data, GNUTLS_X509_FMT_PEM) < 0) {
512 513 514 515
        virReportError(VIR_ERR_SYSTEM_ERROR, isServer ?
                       _("Unable to import server certificate %s") :
                       _("Unable to import client certificate %s"),
                       certFile);
516 517
        goto cleanup;
    }
518

519 520
    ret = 0;

521
 cleanup:
522 523 524 525 526 527 528 529 530
    if (ret != 0) {
        gnutls_x509_crt_deinit(cert);
        cert = NULL;
    }
    VIR_FREE(buf);
    return cert;
}


531 532
static int virNetTLSContextLoadCACertListFromFile(const char *certFile,
                                                  gnutls_x509_crt_t *certs,
533
                                                  unsigned int certMax,
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
                                                  size_t *ncerts)
{
    gnutls_datum_t data;
    char *buf = NULL;
    int ret = -1;

    *ncerts = 0;
    VIR_DEBUG("certFile %s", certFile);

    if (virFileReadAll(certFile, (1<<16), &buf) < 0)
        goto cleanup;

    data.data = (unsigned char *)buf;
    data.size = strlen(buf);

    if (gnutls_x509_crt_list_import(certs, &certMax, &data, GNUTLS_X509_FMT_PEM, 0) < 0) {
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to import CA certificate list %s"),
                       certFile);
        goto cleanup;
    }
    *ncerts = certMax;

    ret = 0;

559
 cleanup:
560 561 562 563 564 565
    VIR_FREE(buf);
    return ret;
}


#define MAX_CERTS 16
566 567 568 569 570
static int virNetTLSContextSanityCheckCredentials(bool isServer,
                                                  const char *cacertFile,
                                                  const char *certFile)
{
    gnutls_x509_crt_t cert = NULL;
571
    gnutls_x509_crt_t cacerts[MAX_CERTS];
572
    size_t ncacerts = 0;
573
    size_t i;
574 575
    int ret = -1;

576
    memset(cacerts, 0, sizeof(cacerts));
577
    if ((access(certFile, R_OK) == 0) &&
578
        !(cert = virNetTLSContextLoadCertFromFile(certFile, isServer)))
579 580
        goto cleanup;
    if ((access(cacertFile, R_OK) == 0) &&
581 582
        virNetTLSContextLoadCACertListFromFile(cacertFile, cacerts,
                                               MAX_CERTS, &ncacerts) < 0)
583
        goto cleanup;
584

585 586 587
    if (cert &&
        virNetTLSContextCheckCert(cert, certFile, isServer, false) < 0)
        goto cleanup;
588

589 590 591 592
    for (i = 0; i < ncacerts; i++) {
        if (virNetTLSContextCheckCert(cacerts[i], cacertFile, isServer, true) < 0)
            goto cleanup;
    }
593

594 595
    if (cert && ncacerts &&
        virNetTLSContextCheckCertPair(cert, certFile, cacerts, ncacerts, cacertFile, isServer) < 0)
596
        goto cleanup;
597 598 599

    ret = 0;

600
 cleanup:
601 602
    if (cert)
        gnutls_x509_crt_deinit(cert);
603 604
    for (i = 0; i < ncacerts; i++)
        gnutls_x509_crt_deinit(cacerts[i]);
605 606 607 608
    return ret;
}


609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
static int virNetTLSContextLoadCredentials(virNetTLSContextPtr ctxt,
                                           bool isServer,
                                           const char *cacert,
                                           const char *cacrl,
                                           const char *cert,
                                           const char *key)
{
    int ret = -1;
    int err;

    if (cacert && cacert[0] != '\0') {
        if (virNetTLSContextCheckCertFile("CA certificate", cacert, false) < 0)
            goto cleanup;

        VIR_DEBUG("loading CA cert from %s", cacert);
        err = gnutls_certificate_set_x509_trust_file(ctxt->x509cred,
                                                     cacert,
                                                     GNUTLS_X509_FMT_PEM);
        if (err < 0) {
628 629
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Unable to set x509 CA certificate: %s: %s"),
630
                           cacert, gnutls_strerror(err));
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
            goto cleanup;
        }
    }

    if (cacrl && cacrl[0] != '\0') {
        int rv;
        if ((rv = virNetTLSContextCheckCertFile("CA revocation list", cacrl, true)) < 0)
            goto cleanup;

        if (rv == 0) {
            VIR_DEBUG("loading CRL from %s", cacrl);
            err = gnutls_certificate_set_x509_crl_file(ctxt->x509cred,
                                                       cacrl,
                                                       GNUTLS_X509_FMT_PEM);
            if (err < 0) {
646 647 648
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Unable to set x509 certificate revocation list: %s: %s"),
                               cacrl, gnutls_strerror(err));
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
                goto cleanup;
            }
        } else {
            VIR_DEBUG("Skipping non-existent CA CRL %s", cacrl);
        }
    }

    if (cert && cert[0] != '\0' && key && key[0] != '\0') {
        int rv;
        if ((rv = virNetTLSContextCheckCertFile("certificate", cert, !isServer)) < 0)
            goto cleanup;
        if (rv == 0 &&
            (rv = virNetTLSContextCheckCertFile("private key", key, !isServer)) < 0)
            goto cleanup;

        if (rv == 0) {
            VIR_DEBUG("loading cert and key from %s and %s", cert, key);
            err =
                gnutls_certificate_set_x509_key_file(ctxt->x509cred,
                                                     cert, key,
                                                     GNUTLS_X509_FMT_PEM);
            if (err < 0) {
671 672 673
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Unable to set x509 key and certificate: %s, %s: %s"),
                               key, cert, gnutls_strerror(err));
674 675 676
                goto cleanup;
            }
        } else {
N
Nehal J Wani 已提交
677 678
            VIR_DEBUG("Skipping non-existent cert %s key %s on client",
                      cert, key);
679 680 681 682 683
        }
    }

    ret = 0;

684
 cleanup:
685 686 687 688 689 690 691 692 693
    return ret;
}


static virNetTLSContextPtr virNetTLSContextNew(const char *cacert,
                                               const char *cacrl,
                                               const char *cert,
                                               const char *key,
                                               const char *const*x509dnWhitelist,
694
                                               const char *priority,
695
                                               bool sanityCheckCert,
696 697 698 699 700 701
                                               bool requireValidCert,
                                               bool isServer)
{
    virNetTLSContextPtr ctxt;
    int err;

702 703 704
    if (virNetTLSContextInitialize() < 0)
        return NULL;

705
    if (!(ctxt = virObjectLockableNew(virNetTLSContextClass)))
706 707
        return NULL;

708 709 710
    if (VIR_STRDUP(ctxt->priority, priority) < 0)
        goto error;

711 712
    err = gnutls_certificate_allocate_credentials(&ctxt->x509cred);
    if (err) {
713 714 715
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to allocate x509 credentials: %s"),
                       gnutls_strerror(err));
716 717 718
        goto error;
    }

719
    if (sanityCheckCert &&
720 721 722
        virNetTLSContextSanityCheckCredentials(isServer, cacert, cert) < 0)
        goto error;

723 724 725 726 727 728 729 730 731 732 733
    if (virNetTLSContextLoadCredentials(ctxt, isServer, cacert, cacrl, cert, key) < 0)
        goto error;

    /* Generate Diffie Hellman parameters - for use with DHE
     * kx algorithms. These should be discarded and regenerated
     * once a day, once a week or once a month. Depending on the
     * security requirements.
     */
    if (isServer) {
        err = gnutls_dh_params_init(&ctxt->dhParams);
        if (err < 0) {
734 735 736
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Unable to initialize diffie-hellman parameters: %s"),
                           gnutls_strerror(err));
737 738 739 740
            goto error;
        }
        err = gnutls_dh_params_generate2(ctxt->dhParams, DH_BITS);
        if (err < 0) {
741 742 743
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Unable to generate diffie-hellman parameters: %s"),
                           gnutls_strerror(err));
744 745 746 747 748 749 750 751 752 753 754
            goto error;
        }

        gnutls_certificate_set_dh_params(ctxt->x509cred,
                                         ctxt->dhParams);
    }

    ctxt->requireValidCert = requireValidCert;
    ctxt->x509dnWhitelist = x509dnWhitelist;
    ctxt->isServer = isServer;

755
    PROBE(RPC_TLS_CONTEXT_NEW,
756 757
          "ctxt=%p cacert=%s cacrl=%s cert=%s key=%s sanityCheckCert=%d requireValidCert=%d isServer=%d",
          ctxt, cacert, NULLSTR(cacrl), cert, key, sanityCheckCert, requireValidCert, isServer);
758

759 760
    return ctxt;

761
 error:
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    if (isServer)
        gnutls_dh_params_deinit(ctxt->dhParams);
    gnutls_certificate_free_credentials(ctxt->x509cred);
    VIR_FREE(ctxt);
    return NULL;
}


static int virNetTLSContextLocateCredentials(const char *pkipath,
                                             bool tryUserPkiPath,
                                             bool isServer,
                                             char **cacert,
                                             char **cacrl,
                                             char **cert,
                                             char **key)
{
    char *userdir = NULL;
    char *user_pki_path = NULL;

    *cacert = NULL;
    *cacrl = NULL;
    *key = NULL;
    *cert = NULL;

    VIR_DEBUG("pkipath=%s isServer=%d tryUserPkiPath=%d",
              pkipath, isServer, tryUserPkiPath);

    /* Explicit path, then use that no matter whether the
     * files actually exist there
     */
    if (pkipath) {
        VIR_DEBUG("Told to use TLS credentials in %s", pkipath);
        if ((virAsprintf(cacert, "%s/%s", pkipath,
                         "cacert.pem")) < 0)
796
            goto error;
797 798
        if ((virAsprintf(cacrl, "%s/%s", pkipath,
                         "cacrl.pem")) < 0)
799
            goto error;
800 801
        if ((virAsprintf(key, "%s/%s", pkipath,
                         isServer ? "serverkey.pem" : "clientkey.pem")) < 0)
802
            goto error;
803 804 805

        if ((virAsprintf(cert, "%s/%s", pkipath,
                         isServer ? "servercert.pem" : "clientcert.pem")) < 0)
806
             goto error;
807 808 809 810
    } else if (tryUserPkiPath) {
        /* Check to see if $HOME/.pki contains at least one of the
         * files and if so, use that
         */
811
        userdir = virGetUserDirectory();
812 813

        if (!userdir)
814
            goto error;
815 816

        if (virAsprintf(&user_pki_path, "%s/.pki/libvirt", userdir) < 0)
817
            goto error;
818 819 820 821 822

        VIR_DEBUG("Trying to find TLS user credentials in %s", user_pki_path);

        if ((virAsprintf(cacert, "%s/%s", user_pki_path,
                         "cacert.pem")) < 0)
823
            goto error;
824 825 826

        if ((virAsprintf(cacrl, "%s/%s", user_pki_path,
                         "cacrl.pem")) < 0)
827
            goto error;
828 829 830

        if ((virAsprintf(key, "%s/%s", user_pki_path,
                         isServer ? "serverkey.pem" : "clientkey.pem")) < 0)
831
            goto error;
832 833 834

        if ((virAsprintf(cert, "%s/%s", user_pki_path,
                         isServer ? "servercert.pem" : "clientcert.pem")) < 0)
835
            goto error;
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

        /*
         * If some of the files can't be found, fallback
         * to the global location for them
         */
        if (!virFileExists(*cacert))
            VIR_FREE(*cacert);
        if (!virFileExists(*cacrl))
            VIR_FREE(*cacrl);

        /* Check these as a pair, since it they are
         * mutually dependent
         */
        if (!virFileExists(*key) || !virFileExists(*cert)) {
            VIR_FREE(*key);
            VIR_FREE(*cert);
        }
    }

    /* No explicit path, or user path didn't exist, so
     * fallback to global defaults
     */
    if (!*cacert) {
        VIR_DEBUG("Using default TLS CA certificate path");
860 861
        if (VIR_STRDUP(*cacert, LIBVIRT_CACERT) < 0)
            goto error;
862 863 864 865
    }

    if (!*cacrl) {
        VIR_DEBUG("Using default TLS CA revocation list path");
866 867
        if (VIR_STRDUP(*cacrl, LIBVIRT_CACRL) < 0)
            goto error;
868 869 870 871
    }

    if (!*key && !*cert) {
        VIR_DEBUG("Using default TLS key/certificate path");
872 873
        if (VIR_STRDUP(*key, isServer ? LIBVIRT_SERVERKEY : LIBVIRT_CLIENTKEY) < 0)
            goto error;
874

875 876
        if (VIR_STRDUP(*cert, isServer ? LIBVIRT_SERVERCERT : LIBVIRT_CLIENTCERT) < 0)
            goto error;
877 878 879 880 881 882 883
    }

    VIR_FREE(user_pki_path);
    VIR_FREE(userdir);

    return 0;

884
 error:
885 886 887 888 889 890 891 892 893 894 895 896 897
    VIR_FREE(*cacert);
    VIR_FREE(*cacrl);
    VIR_FREE(*key);
    VIR_FREE(*cert);
    VIR_FREE(user_pki_path);
    VIR_FREE(userdir);
    return -1;
}


static virNetTLSContextPtr virNetTLSContextNewPath(const char *pkipath,
                                                   bool tryUserPkiPath,
                                                   const char *const*x509dnWhitelist,
898
                                                   const char *priority,
899
                                                   bool sanityCheckCert,
900 901 902 903 904 905 906
                                                   bool requireValidCert,
                                                   bool isServer)
{
    char *cacert = NULL, *cacrl = NULL, *key = NULL, *cert = NULL;
    virNetTLSContextPtr ctxt = NULL;

    if (virNetTLSContextLocateCredentials(pkipath, tryUserPkiPath, isServer,
907
                                          &cacert, &cacrl, &cert, &key) < 0)
908 909
        return NULL;

910
    ctxt = virNetTLSContextNew(cacert, cacrl, cert, key,
911
                               x509dnWhitelist, priority, sanityCheckCert,
912
                               requireValidCert, isServer);
913 914 915 916 917 918 919 920 921 922 923 924

    VIR_FREE(cacert);
    VIR_FREE(cacrl);
    VIR_FREE(key);
    VIR_FREE(cert);

    return ctxt;
}

virNetTLSContextPtr virNetTLSContextNewServerPath(const char *pkipath,
                                                  bool tryUserPkiPath,
                                                  const char *const*x509dnWhitelist,
925
                                                  const char *priority,
926
                                                  bool sanityCheckCert,
927 928
                                                  bool requireValidCert)
{
929
    return virNetTLSContextNewPath(pkipath, tryUserPkiPath, x509dnWhitelist, priority,
930
                                   sanityCheckCert, requireValidCert, true);
931 932 933 934
}

virNetTLSContextPtr virNetTLSContextNewClientPath(const char *pkipath,
                                                  bool tryUserPkiPath,
935
                                                  const char *priority,
936
                                                  bool sanityCheckCert,
937 938
                                                  bool requireValidCert)
{
939
    return virNetTLSContextNewPath(pkipath, tryUserPkiPath, NULL, priority,
940
                                   sanityCheckCert, requireValidCert, false);
941 942 943 944 945 946 947 948
}


virNetTLSContextPtr virNetTLSContextNewServer(const char *cacert,
                                              const char *cacrl,
                                              const char *cert,
                                              const char *key,
                                              const char *const*x509dnWhitelist,
949
                                              const char *priority,
950
                                              bool sanityCheckCert,
951 952
                                              bool requireValidCert)
{
953
    return virNetTLSContextNew(cacert, cacrl, cert, key, x509dnWhitelist, priority,
954
                               sanityCheckCert, requireValidCert, true);
955 956 957 958 959 960 961
}


virNetTLSContextPtr virNetTLSContextNewClient(const char *cacert,
                                              const char *cacrl,
                                              const char *cert,
                                              const char *key,
962
                                              const char *priority,
963
                                              bool sanityCheckCert,
964 965
                                              bool requireValidCert)
{
966
    return virNetTLSContextNew(cacert, cacrl, cert, key, NULL, priority,
967
                               sanityCheckCert, requireValidCert, false);
968 969 970 971 972 973 974 975 976
}


static int virNetTLSContextValidCertificate(virNetTLSContextPtr ctxt,
                                            virNetTLSSessionPtr sess)
{
    int ret;
    unsigned int status;
    const gnutls_datum_t *certs;
977 978
    unsigned int nCerts;
    size_t i;
979
    char dname[256];
980
    char *dnameptr = dname;
981 982 983
    size_t dnamesize = sizeof(dname);

    memset(dname, 0, dnamesize);
984

985
    if ((ret = gnutls_certificate_verify_peers2(sess->session, &status)) < 0) {
986 987 988
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to verify TLS peer: %s"),
                       gnutls_strerror(ret));
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
        goto authdeny;
    }

    if (status != 0) {
        const char *reason = _("Invalid certificate");

        if (status & GNUTLS_CERT_INVALID)
            reason = _("The certificate is not trusted.");

        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
            reason = _("The certificate hasn't got a known issuer.");

        if (status & GNUTLS_CERT_REVOKED)
            reason = _("The certificate has been revoked.");

        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
            reason = _("The certificate uses an insecure algorithm");

1007 1008 1009
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Certificate failed validation: %s"),
                       reason);
1010 1011 1012 1013
        goto authdeny;
    }

    if (gnutls_certificate_type_get(sess->session) != GNUTLS_CRT_X509) {
1014 1015
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("Only x509 certificates are supported"));
1016 1017 1018 1019
        goto authdeny;
    }

    if (!(certs = gnutls_certificate_get_peers(sess->session, &nCerts))) {
1020 1021
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("The certificate has no peers"));
1022 1023 1024 1025 1026 1027 1028
        goto authdeny;
    }

    for (i = 0; i < nCerts; i++) {
        gnutls_x509_crt_t cert;

        if (gnutls_x509_crt_init(&cert) < 0) {
1029 1030
            virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                           _("Unable to initialize certificate"));
1031 1032 1033 1034
            goto authfail;
        }

        if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1035 1036
            virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                           _("Unable to load certificate"));
1037 1038 1039 1040
            gnutls_x509_crt_deinit(cert);
            goto authfail;
        }

1041 1042
        if (virNetTLSContextCheckCertTimes(cert, "[session]",
                                           sess->isServer, i > 0) < 0) {
1043 1044 1045 1046 1047
            gnutls_x509_crt_deinit(cert);
            goto authdeny;
        }

        if (i == 0) {
1048 1049
            ret = gnutls_x509_crt_get_dn(cert, dname, &dnamesize);
            if (ret != 0) {
1050 1051 1052
                virReportError(VIR_ERR_SYSTEM_ERROR,
                               _("Failed to get certificate %s distinguished name: %s"),
                               "[session]", gnutls_strerror(ret));
1053 1054
                goto authfail;
            }
1055
            if (VIR_STRDUP(sess->x509dname, dname) < 0)
1056
                goto authfail;
1057 1058 1059
            VIR_DEBUG("Peer DN is %s", dname);

            if (virNetTLSContextCheckCertDN(cert, "[session]", sess->hostname, dname,
1060
                                            ctxt->x509dnWhitelist) < 0) {
1061
                gnutls_x509_crt_deinit(cert);
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                goto authdeny;
            }

            /* !sess->isServer, since on the client, we're validating the
             * server's cert, and on the server, the client's cert
             */
            if (virNetTLSContextCheckCertBasicConstraints(cert, "[session]",
                                                          !sess->isServer, false) < 0) {
                gnutls_x509_crt_deinit(cert);
                goto authdeny;
1072 1073
            }

1074 1075
            if (virNetTLSContextCheckCertKeyUsage(cert, "[session]",
                                                  false) < 0) {
1076 1077 1078 1079
                gnutls_x509_crt_deinit(cert);
                goto authdeny;
            }

1080 1081 1082
            /* !sess->isServer - as above */
            if (virNetTLSContextCheckCertKeyPurpose(cert, "[session]",
                                                    !sess->isServer) < 0) {
1083 1084 1085 1086
                gnutls_x509_crt_deinit(cert);
                goto authdeny;
            }
        }
1087
        gnutls_x509_crt_deinit(cert);
1088 1089
    }

1090 1091
    PROBE(RPC_TLS_CONTEXT_SESSION_ALLOW,
          "ctxt=%p sess=%p dname=%s",
1092
          ctxt, sess, dnameptr);
1093

1094 1095
    return 0;

1096
 authdeny:
1097 1098
    PROBE(RPC_TLS_CONTEXT_SESSION_DENY,
          "ctxt=%p sess=%p dname=%s",
1099
          ctxt, sess, dnameptr);
1100

1101 1102
    return -1;

1103
 authfail:
1104 1105 1106 1107
    PROBE(RPC_TLS_CONTEXT_SESSION_FAIL,
          "ctxt=%p sess=%p",
          ctxt, sess);

1108 1109 1110 1111 1112 1113
    return -1;
}

int virNetTLSContextCheckCertificate(virNetTLSContextPtr ctxt,
                                     virNetTLSSessionPtr sess)
{
1114 1115
    int ret = -1;

1116 1117
    virObjectLock(ctxt);
    virObjectLock(sess);
1118
    if (virNetTLSContextValidCertificate(ctxt, sess) < 0) {
1119
        VIR_WARN("Certificate check failed %s", virGetLastErrorMessage());
1120
        if (ctxt->requireValidCert) {
1121 1122
            virReportError(VIR_ERR_AUTH_FAILED, "%s",
                           _("Failed to verify peer's certificate"));
1123
            goto cleanup;
1124
        }
1125
        virResetLastError();
1126 1127
        VIR_INFO("Ignoring bad certificate at user request");
    }
1128 1129 1130

    ret = 0;

1131
 cleanup:
1132 1133
    virObjectUnlock(ctxt);
    virObjectUnlock(sess);
1134 1135

    return ret;
1136 1137
}

1138
void virNetTLSContextDispose(void *obj)
1139
{
1140
    virNetTLSContextPtr ctxt = obj;
1141

1142 1143 1144
    PROBE(RPC_TLS_CONTEXT_DISPOSE,
          "ctxt=%p", ctxt);

1145
    VIR_FREE(ctxt->priority);
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
    gnutls_dh_params_deinit(ctxt->dhParams);
    gnutls_certificate_free_credentials(ctxt->x509cred);
}


static ssize_t
virNetTLSSessionPush(void *opaque, const void *buf, size_t len)
{
    virNetTLSSessionPtr sess = opaque;
    if (!sess->writeFunc) {
1156
        VIR_WARN("TLS session push with missing write function");
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
        errno = EIO;
        return -1;
    };

    return sess->writeFunc(buf, len, sess->opaque);
}


static ssize_t
virNetTLSSessionPull(void *opaque, void *buf, size_t len)
{
    virNetTLSSessionPtr sess = opaque;
    if (!sess->readFunc) {
        VIR_WARN("TLS session pull with missing read function");
        errno = EIO;
        return -1;
    };

    return sess->readFunc(buf, len, sess->opaque);
}


virNetTLSSessionPtr virNetTLSSessionNew(virNetTLSContextPtr ctxt,
                                        const char *hostname)
{
    virNetTLSSessionPtr sess;
    int err;
1184
    const char *priority;
1185

E
Eric Blake 已提交
1186 1187
    VIR_DEBUG("ctxt=%p hostname=%s isServer=%d",
              ctxt, NULLSTR(hostname), ctxt->isServer);
1188

1189
    if (!(sess = virObjectLockableNew(virNetTLSSessionClass)))
1190 1191
        return NULL;

1192
    if (VIR_STRDUP(sess->hostname, hostname) < 0)
1193 1194 1195 1196
        goto error;

    if ((err = gnutls_init(&sess->session,
                           ctxt->isServer ? GNUTLS_SERVER : GNUTLS_CLIENT)) != 0) {
1197 1198 1199
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Failed to initialize TLS session: %s"),
                       gnutls_strerror(err));
1200 1201 1202 1203 1204 1205
        goto error;
    }

    /* avoid calling all the priority functions, since the defaults
     * are adequate.
     */
1206 1207
    priority = ctxt->priority ? ctxt->priority : TLS_PRIORITY;
    VIR_DEBUG("Setting priority string '%s'", priority);
1208
    if ((err = gnutls_priority_set_direct(sess->session,
1209
                                          priority,
1210
                                          NULL)) != 0) {
1211
        virReportError(VIR_ERR_SYSTEM_ERROR,
1212
                       _("Failed to set TLS session priority to %s: %s"),
1213
                       priority, gnutls_strerror(err));
1214 1215 1216 1217 1218 1219
        goto error;
    }

    if ((err = gnutls_credentials_set(sess->session,
                                      GNUTLS_CRD_CERTIFICATE,
                                      ctxt->x509cred)) != 0) {
1220 1221 1222
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Failed set TLS x509 credentials: %s"),
                       gnutls_strerror(err));
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        goto error;
    }

    /* request client certificate if any.
     */
    if (ctxt->isServer) {
        gnutls_certificate_server_set_request(sess->session, GNUTLS_CERT_REQUEST);

        gnutls_dh_set_prime_bits(sess->session, DH_BITS);
    }

    gnutls_transport_set_ptr(sess->session, sess);
    gnutls_transport_set_push_function(sess->session,
                                       virNetTLSSessionPush);
    gnutls_transport_set_pull_function(sess->session,
                                       virNetTLSSessionPull);

1240 1241
    sess->isServer = ctxt->isServer;

1242
    PROBE(RPC_TLS_SESSION_NEW,
1243 1244
          "sess=%p ctxt=%p hostname=%s isServer=%d",
          sess, ctxt, hostname, sess->isServer);
1245

1246 1247
    return sess;

1248
 error:
1249
    virObjectUnref(sess);
1250 1251 1252 1253 1254 1255 1256 1257 1258
    return NULL;
}


void virNetTLSSessionSetIOCallbacks(virNetTLSSessionPtr sess,
                                    virNetTLSSessionWriteFunc writeFunc,
                                    virNetTLSSessionReadFunc readFunc,
                                    void *opaque)
{
1259
    virObjectLock(sess);
1260 1261 1262
    sess->writeFunc = writeFunc;
    sess->readFunc = readFunc;
    sess->opaque = opaque;
1263
    virObjectUnlock(sess);
1264 1265 1266 1267 1268 1269 1270
}


ssize_t virNetTLSSessionWrite(virNetTLSSessionPtr sess,
                              const char *buf, size_t len)
{
    ssize_t ret;
1271

1272
    virObjectLock(sess);
1273 1274 1275
    ret = gnutls_record_send(sess->session, buf, len);

    if (ret >= 0)
1276
        goto cleanup;
1277 1278 1279 1280 1281 1282 1283 1284

    switch (ret) {
    case GNUTLS_E_AGAIN:
        errno = EAGAIN;
        break;
    case GNUTLS_E_INTERRUPTED:
        errno = EINTR;
        break;
1285 1286 1287
    case GNUTLS_E_UNEXPECTED_PACKET_LENGTH:
        errno = ENOMSG;
        break;
1288 1289 1290 1291 1292
    default:
        errno = EIO;
        break;
    }

1293 1294
    ret = -1;

1295
 cleanup:
1296
    virObjectUnlock(sess);
1297
    return ret;
1298 1299 1300 1301 1302 1303 1304
}

ssize_t virNetTLSSessionRead(virNetTLSSessionPtr sess,
                             char *buf, size_t len)
{
    ssize_t ret;

1305
    virObjectLock(sess);
1306 1307 1308
    ret = gnutls_record_recv(sess->session, buf, len);

    if (ret >= 0)
1309
        goto cleanup;
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

    switch (ret) {
    case GNUTLS_E_AGAIN:
        errno = EAGAIN;
        break;
    case GNUTLS_E_INTERRUPTED:
        errno = EINTR;
        break;
    default:
        errno = EIO;
        break;
    }

1323 1324
    ret = -1;

1325
 cleanup:
1326
    virObjectUnlock(sess);
1327
    return ret;
1328 1329 1330 1331
}

int virNetTLSSessionHandshake(virNetTLSSessionPtr sess)
{
1332
    int ret;
1333
    VIR_DEBUG("sess=%p", sess);
1334
    virObjectLock(sess);
1335
    ret = gnutls_handshake(sess->session);
1336 1337 1338 1339
    VIR_DEBUG("Ret=%d", ret);
    if (ret == 0) {
        sess->handshakeComplete = true;
        VIR_DEBUG("Handshake is complete");
1340 1341 1342 1343 1344
        goto cleanup;
    }
    if (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN) {
        ret = 1;
        goto cleanup;
1345 1346 1347 1348 1349 1350 1351
    }

#if 0
    PROBE(CLIENT_TLS_FAIL, "fd=%d",
          virNetServerClientGetFD(client));
#endif

1352 1353 1354
    virReportError(VIR_ERR_AUTH_FAILED,
                   _("TLS handshake failed %s"),
                   gnutls_strerror(ret));
1355 1356
    ret = -1;

1357
 cleanup:
1358
    virObjectUnlock(sess);
1359
    return ret;
1360 1361 1362 1363 1364
}

virNetTLSSessionHandshakeStatus
virNetTLSSessionGetHandshakeStatus(virNetTLSSessionPtr sess)
{
1365
    virNetTLSSessionHandshakeStatus ret;
1366
    virObjectLock(sess);
1367
    if (sess->handshakeComplete)
1368
        ret = VIR_NET_TLS_HANDSHAKE_COMPLETE;
1369
    else if (gnutls_record_get_direction(sess->session) == 0)
1370
        ret = VIR_NET_TLS_HANDSHAKE_RECVING;
1371
    else
1372
        ret = VIR_NET_TLS_HANDSHAKE_SENDING;
1373
    virObjectUnlock(sess);
1374
    return ret;
1375 1376 1377 1378 1379 1380
}

int virNetTLSSessionGetKeySize(virNetTLSSessionPtr sess)
{
    gnutls_cipher_algorithm_t cipher;
    int ssf;
1381
    virObjectLock(sess);
1382 1383
    cipher = gnutls_cipher_get(sess->session);
    if (!(ssf = gnutls_cipher_get_key_size(cipher))) {
1384 1385
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid cipher size for TLS session"));
1386 1387
        ssf = -1;
        goto cleanup;
1388 1389
    }

1390
 cleanup:
1391
    virObjectUnlock(sess);
1392 1393 1394
    return ssf;
}

1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
const char *virNetTLSSessionGetX509DName(virNetTLSSessionPtr sess)
{
    const char *ret = NULL;

    virObjectLock(sess);

    ret = sess->x509dname;

    virObjectUnlock(sess);

    return ret;
}
1407

1408
void virNetTLSSessionDispose(void *obj)
1409
{
1410
    virNetTLSSessionPtr sess = obj;
1411

1412 1413 1414
    PROBE(RPC_TLS_SESSION_DISPOSE,
          "sess=%p", sess);

1415
    VIR_FREE(sess->x509dname);
1416 1417 1418
    VIR_FREE(sess->hostname);
    gnutls_deinit(sess->session);
}
M
Michal Privoznik 已提交
1419 1420 1421 1422 1423 1424

/*
 * This function MUST be called before any
 * virNetTLS* because it initializes
 * underlying GnuTLS library. According to
 * it's documentation, it's safe to be called
1425 1426 1427 1428 1429 1430 1431
 * many times, but is not thread safe.
 *
 * There is no corresponding "Deinit" / "Cleanup"
 * function because there is no safe way to call
 * 'gnutls_global_deinit' from a multi-threaded
 * library, where other libraries linked into the
 * application may also be using gnutls.
M
Michal Privoznik 已提交
1432 1433 1434
 */
void virNetTLSInit(void)
{
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    const char *gnutlsdebug;
    if ((gnutlsdebug = virGetEnvAllowSUID("LIBVIRT_GNUTLS_DEBUG")) != NULL) {
        int val;
        if (virStrToLong_i(gnutlsdebug, NULL, 10, &val) < 0)
            val = 10;
        gnutls_global_set_log_level(val);
        gnutls_global_set_log_function(virNetTLSLog);
        VIR_DEBUG("Enabled GNUTLS debug");
    }

M
Michal Privoznik 已提交
1445 1446
    gnutls_global_init();
}