virnettlscontext.c 42.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/*
 * virnettlscontext.c: TLS encryption/x509 handling
 *
 * Copyright (C) 2010-2011 Red Hat, Inc.
 *
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */

#include <config.h>

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

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include "gnutls_1_0_compat.h"

#include "virnettlscontext.h"

#include "memory.h"
#include "virterror_internal.h"
#include "util.h"
#include "logging.h"
37
#include "threads.h"
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include "configmake.h"

#define DH_BITS 1024

#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
#define virNetError(code, ...)                                    \
    virReportErrorHelper(VIR_FROM_THIS, code, __FILE__,           \
                         __FUNCTION__, __LINE__, __VA_ARGS__)

struct _virNetTLSContext {
56
    virMutex lock;
57 58 59 60 61 62 63 64 65 66 67
    int refs;

    gnutls_certificate_credentials_t x509cred;
    gnutls_dh_params_t dhParams;

    bool isServer;
    bool requireValidCert;
    const char *const*x509dnWhitelist;
};

struct _virNetTLSSession {
68 69
    virMutex lock;

70 71 72 73
    int refs;

    bool handshakeComplete;

74
    bool isServer;
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    char *hostname;
    gnutls_session_t session;
    virNetTLSSessionWriteFunc writeFunc;
    virNetTLSSessionReadFunc readFunc;
    void *opaque;
};


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;
}


static void virNetTLSLog(int level, const char *str) {
    VIR_DEBUG("%d %s", level, str);
}

103

104 105 106 107
static int virNetTLSContextCheckCertTimes(gnutls_x509_crt_t cert,
                                          const char *certFile,
                                          bool isServer,
                                          bool isCA)
108 109 110 111 112 113
{
    time_t now;

    if ((now = time(NULL)) == ((time_t)-1)) {
        virReportSystemError(errno, "%s",
                             _("cannot get current time"));
114
        return -1;
115 116 117
    }

    if (gnutls_x509_crt_get_expiration_time(cert) < now) {
118 119 120 121 122 123
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    (isCA ?
                     _("The CA certificate %s has expired") :
                     (isServer ?
                      _("The server certificate %s has expired") :
                      _("The client certificate %s has expired"))),
124
                    certFile);
125
        return -1;
126 127 128
    }

    if (gnutls_x509_crt_get_activation_time(cert) > now) {
129 130 131 132 133 134
        virNetError(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"))),
135
                    certFile);
136
        return -1;
137 138
    }

139 140 141
    return 0;
}

142 143 144 145 146 147 148 149 150

#ifndef GNUTLS_1_0_COMPAT
/*
 * The gnutls_x509_crt_get_basic_constraints function isn't
 * available in GNUTLS 1.0.x branches. This isn't critical
 * though, since gnutls_certificate_verify_peers2 will do
 * pretty much the same check at runtime, so we can just
 * disable this code
 */
151 152 153 154 155 156 157
static int virNetTLSContextCheckCertBasicConstraints(gnutls_x509_crt_t cert,
                                                     const char *certFile,
                                                     bool isServer,
                                                     bool isCA)
{
    int status;

158 159 160 161 162 163 164 165 166
    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) {
            virNetError(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);
167
            return -1;
168 169 170 171 172 173
        }
    } else if (status == 0) { /* It is not a CA cert */
        if (isCA) {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("The certificate %s basic constraints do not show a CA"),
                        certFile);
174
            return -1;
175 176 177 178 179 180
        }
    } else if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { /* Missing basicConstraints */
        if (isCA) {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("The certificate %s is missing basic constraints for a CA"),
                        certFile);
181
            return -1;
182 183 184 185 186
        }
    } else { /* General error */
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Unable to query certificate %s basic constraints %s"),
                    certFile, gnutls_strerror(status));
187
        return -1;
188 189
    }

190 191
    return 0;
}
192 193
#endif

194 195 196 197 198 199 200 201 202

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

203
    status = gnutls_x509_crt_get_key_usage(cert, &usage, &critical);
204

205
    VIR_DEBUG("Cert %s key usage status %d usage %d critical %u", certFile, status, usage, critical);
206
    if (status < 0) {
207 208 209 210 211 212 213
        if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
            usage = isCA ? GNUTLS_KEY_KEY_CERT_SIGN :
                GNUTLS_KEY_DIGITAL_SIGNATURE|GNUTLS_KEY_KEY_ENCIPHERMENT;
        } else {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("Unable to query certificate %s key usage %s"),
                        certFile, gnutls_strerror(status));
214
            return -1;
215
        }
216 217
    }

218 219
    if (isCA) {
        if (!(usage & GNUTLS_KEY_KEY_CERT_SIGN)) {
220 221 222 223
            if (critical) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Certificate %s usage does not permit certificate signing"),
                            certFile);
224
                return -1;
225 226 227 228
            } else {
                VIR_WARN("Certificate %s usage does not permit certificate signing",
                         certFile);
            }
229 230
        }
    } else {
231
        if (!(usage & GNUTLS_KEY_DIGITAL_SIGNATURE)) {
232 233 234 235
            if (critical) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Certificate %s usage does not permit digital signature"),
                            certFile);
236
                return -1;
237 238 239 240
            } else {
                VIR_WARN("Certificate %s usage does not permit digital signature",
                         certFile);
            }
241 242
        }
        if (!(usage & GNUTLS_KEY_KEY_ENCIPHERMENT)) {
243 244 245 246
            if (critical) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Certificate %s usage does not permit key encipherment"),
                            certFile);
247
                return -1;
248 249 250 251
            } else {
                VIR_WARN("Certificate %s usage does not permit key encipherment",
                         certFile);
            }
252 253 254
        }
    }

255 256 257 258 259 260 261 262 263 264 265 266
    return 0;
}


static int virNetTLSContextCheckCertKeyPurpose(gnutls_x509_crt_t cert,
                                               const char *certFile,
                                               bool isServer)
{
    int status;
    int i;
    unsigned int purposeCritical;
    unsigned int critical;
E
Eric Blake 已提交
267
    char *buffer = NULL;
268 269 270
    size_t size;
    bool allowClient = false, allowServer = false;

271
    critical = 0;
272 273 274 275 276
    for (i = 0 ; ; i++) {
        size = 0;
        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer, &size, NULL);

        if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
277 278 279 280 281
            VIR_DEBUG("No key purpose data available at slot %d", i);

            /* If there is no data at all, then we must allow client/server to pass */
            if (i == 0)
                allowServer = allowClient = true;
282 283 284 285 286 287
            break;
        }
        if (status != GNUTLS_E_SHORT_MEMORY_BUFFER) {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("Unable to query certificate %s key purpose %s"),
                        certFile, gnutls_strerror(status));
288
            return -1;
289 290 291 292
        }

        if (VIR_ALLOC_N(buffer, size) < 0) {
            virReportOOMError();
293
            return -1;
294 295
        }

296
        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer, &size, &purposeCritical);
297
        if (status < 0) {
298
            VIR_FREE(buffer);
299 300 301
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("Unable to query certificate %s key purpose %s"),
                        certFile, gnutls_strerror(status));
302
            return -1;
303
        }
304 305
        if (purposeCritical)
            critical = true;
306

307
        VIR_DEBUG("Key purpose %d %s critical %u", status, buffer, purposeCritical);
308
        if (STREQ(buffer, GNUTLS_KP_TLS_WWW_SERVER)) {
309
            allowServer = true;
310
        } else if (STREQ(buffer, GNUTLS_KP_TLS_WWW_CLIENT)) {
311
            allowClient = true;
312
        } else if (STRNEQ(buffer, GNUTLS_KP_ANY)) {
313
            allowServer = allowClient = true;
314 315 316 317 318
        }

        VIR_FREE(buffer);
    }

319 320
    if (isServer) {
        if (!allowServer) {
321 322 323 324
            if (critical) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Certificate %s purpose does not allow use for with a TLS server"),
                            certFile);
325
                return -1;
326 327 328 329
            } else {
                VIR_WARN("Certificate %s purpose does not allow use for with a TLS server",
                         certFile);
            }
330
        }
331 332
    } else {
        if (!allowClient) {
333 334 335 336
            if (critical) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Certificate %s purpose does not allow use for with a TLS client"),
                            certFile);
337
                return -1;
338 339 340 341
            } else {
                VIR_WARN("Certificate %s purpose does not allow use for with a TLS client",
                         certFile);
            }
342 343 344
        }
    }

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    return 0;
}

/* Check DN is on tls_allowed_dn_list. */
static int
virNetTLSContextCheckCertDNWhitelist(const char *dname,
                                     const char *const*wildcards)
{
    while (*wildcards) {
        int ret = fnmatch (*wildcards, dname, 0);
        if (ret == 0) /* Succesful match */
            return 1;
        if (ret != FNM_NOMATCH) {
            virNetError(VIR_ERR_INTERNAL_ERROR,
                        _("Malformed TLS whitelist regular expression '%s'"),
                        *wildcards);
            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. */
    virNetError(VIR_ERR_SYSTEM_ERROR, "%s",
                _("Client's Distinguished Name is not on the list "
                  "of allowed clients (tls_allowed_dn_list).  Use "
                  "'certtool -i --infile clientcert.pem' to view the"
                  "Distinguished Name field in the client certificate,"
                  "or run this daemon with --verbose option."));
    return 0;
}


static int
virNetTLSContextCheckCertDN(gnutls_x509_crt_t cert,
                            const char *certFile,
                            const char *hostname,
                            const char *const* whitelist)
{
    int ret;
    char name[256];
    size_t namesize = sizeof name;

    memset(name, 0, namesize);

    ret = gnutls_x509_crt_get_dn(cert, name, &namesize);
    if (ret != 0) {
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Failed to get certificate %s distinguished name: %s"),
                    certFile, gnutls_strerror(ret));
        return -1;
    }
400
    VIR_DEBUG("Peer DN is %s", name);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    if (whitelist &&
        virNetTLSContextCheckCertDNWhitelist(name, whitelist) <= 0)
        return -1;

    if (hostname &&
        !gnutls_x509_crt_check_hostname(cert, hostname)) {
        virNetError(VIR_ERR_RPC,
                    _("Certificate %s owner does not match the hostname %s"),
                    certFile, hostname);
        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;

426
#ifndef GNUTLS_1_0_COMPAT
427 428 429
    if (virNetTLSContextCheckCertBasicConstraints(cert, certFile,
                                                  isServer, isCA) < 0)
        return -1;
430
#endif
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

    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,
                                         gnutls_x509_crt_t cacert,
                                         const char *cacertFile,
                                         bool isServer)
{
    unsigned int status;

    if (gnutls_x509_crt_list_verify(&cert, 1,
                                    &cacert, 1,
                                    NULL, 0,
                                    0, &status) < 0) {
        virNetError(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);
        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.");

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

        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Our own certificate %s failed validation against %s: %s"),
                    certFile, cacertFile, reason);
        return -1;
    }

    return 0;
}


static gnutls_x509_crt_t virNetTLSContextLoadCertFromFile(const char *certFile,
                                                          bool isServer,
                                                          bool isCA)
{
    gnutls_datum_t data;
    gnutls_x509_crt_t cert = NULL;
    char *buf = NULL;
    int ret = -1;

    VIR_DEBUG("isServer %d isCA %d certFile %s",
              isServer, isCA, certFile);

    if (gnutls_x509_crt_init(&cert) < 0) {
        virNetError(VIR_ERR_SYSTEM_ERROR, "%s",
                    _("Unable to initialize certificate"));
        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) {
        virNetError(VIR_ERR_SYSTEM_ERROR, isServer ?
                    _("Unable to import server certificate %s") :
                    _("Unable to import client certificate %s"),
                    certFile);
        goto cleanup;
    }
522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    ret = 0;

cleanup:
    if (ret != 0) {
        gnutls_x509_crt_deinit(cert);
        cert = NULL;
    }
    VIR_FREE(buf);
    return cert;
}


static int virNetTLSContextSanityCheckCredentials(bool isServer,
                                                  const char *cacertFile,
                                                  const char *certFile)
{
    gnutls_x509_crt_t cert = NULL;
    gnutls_x509_crt_t cacert = NULL;
    int ret = -1;

543 544 545 546 547 548
    if ((access(certFile, R_OK) == 0) &&
        !(cert = virNetTLSContextLoadCertFromFile(certFile, isServer, false)))
        goto cleanup;
    if ((access(cacertFile, R_OK) == 0) &&
        !(cacert = virNetTLSContextLoadCertFromFile(cacertFile, isServer, false)))
        goto cleanup;
549

550 551 552
    if (cert &&
        virNetTLSContextCheckCert(cert, certFile, isServer, false) < 0)
        goto cleanup;
553

554 555 556
    if (cacert &&
        virNetTLSContextCheckCert(cacert, cacertFile, isServer, true) < 0)
        goto cleanup;
557

558 559 560
    if (cert && cacert &&
        virNetTLSContextCheckCertPair(cert, certFile, cacert, cacertFile, isServer) < 0)
        goto cleanup;
561 562 563 564 565 566 567 568 569 570 571 572

    ret = 0;

cleanup:
    if (cert)
        gnutls_x509_crt_deinit(cert);
    if (cacert)
        gnutls_x509_crt_deinit(cacert);
    return ret;
}


573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
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) {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("Unable to set x509 CA certificate: %s: %s"),
                        cacert, gnutls_strerror (err));
            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) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Unable to set x509 certificate revocation list: %s: %s"),
                            cacrl, gnutls_strerror(err));
                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) {
                virNetError(VIR_ERR_SYSTEM_ERROR,
                            _("Unable to set x509 key and certificate: %s, %s: %s"),
                            key, cert, gnutls_strerror(err));
                goto cleanup;
            }
        } else {
            VIR_DEBUG("Skipping non-existant cert %s key %s on client", cert, key);
        }
    }

    ret = 0;

cleanup:
    return ret;
}


static virNetTLSContextPtr virNetTLSContextNew(const char *cacert,
                                               const char *cacrl,
                                               const char *cert,
                                               const char *key,
                                               const char *const*x509dnWhitelist,
657
                                               bool sanityCheckCert,
658 659 660 661 662 663 664
                                               bool requireValidCert,
                                               bool isServer)
{
    virNetTLSContextPtr ctxt;
    char *gnutlsdebug;
    int err;

665 666
    VIR_DEBUG("cacert=%s cacrl=%s cert=%s key=%s sanityCheckCert=%d requireValid=%d isServer=%d",
              cacert, NULLSTR(cacrl), cert, key, sanityCheckCert, requireValidCert, isServer);
667 668 669 670 671 672

    if (VIR_ALLOC(ctxt) < 0) {
        virReportOOMError();
        return NULL;
    }

673 674 675 676 677 678 679
    if (virMutexInit(&ctxt->lock) < 0) {
        virNetError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Failed to initialized mutex"));
        VIR_FREE(ctxt);
        return NULL;
    }

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    ctxt->refs = 1;

    /* Initialise GnuTLS. */
    gnutls_global_init();

    if ((gnutlsdebug = getenv("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");
    }


    err = gnutls_certificate_allocate_credentials(&ctxt->x509cred);
    if (err) {
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Unable to allocate x509 credentials: %s"),
                    gnutls_strerror(err));
        goto error;
    }

703
    if (sanityCheckCert &&
704 705 706
        virNetTLSContextSanityCheckCredentials(isServer, cacert, cert) < 0)
        goto error;

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 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 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    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) {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("Unable to initialize diffie-hellman parameters: %s"),
                        gnutls_strerror(err));
            goto error;
        }
        err = gnutls_dh_params_generate2(ctxt->dhParams, DH_BITS);
        if (err < 0) {
            virNetError(VIR_ERR_SYSTEM_ERROR,
                        _("Unable to generate diffie-hellman parameters: %s"),
                        gnutls_strerror(err));
            goto error;
        }

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

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

    return ctxt;

error:
    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)
            goto out_of_memory;
        if ((virAsprintf(cacrl, "%s/%s", pkipath,
                         "cacrl.pem")) < 0)
            goto out_of_memory;
        if ((virAsprintf(key, "%s/%s", pkipath,
                         isServer ? "serverkey.pem" : "clientkey.pem")) < 0)
            goto out_of_memory;

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

        if (!userdir)
            goto out_of_memory;

        if (virAsprintf(&user_pki_path, "%s/.pki/libvirt", userdir) < 0)
            goto out_of_memory;

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

        if ((virAsprintf(cacert, "%s/%s", user_pki_path,
                         "cacert.pem")) < 0)
            goto out_of_memory;

        if ((virAsprintf(cacrl, "%s/%s", user_pki_path,
                         "cacrl.pem")) < 0)
            goto out_of_memory;

        if ((virAsprintf(key, "%s/%s", user_pki_path,
                         isServer ? "serverkey.pem" : "clientkey.pem")) < 0)
            goto out_of_memory;

        if ((virAsprintf(cert, "%s/%s", user_pki_path,
                         isServer ? "servercert.pem" : "clientcert.pem")) < 0)
            goto out_of_memory;

        /*
         * 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");
        if (!(*cacert = strdup(LIBVIRT_CACERT)))
            goto out_of_memory;
    }

    if (!*cacrl) {
        VIR_DEBUG("Using default TLS CA revocation list path");
        if (!(*cacrl = strdup(LIBVIRT_CACRL)))
            goto out_of_memory;
    }

    if (!*key && !*cert) {
        VIR_DEBUG("Using default TLS key/certificate path");
        if (!(*key = strdup(isServer ? LIBVIRT_SERVERKEY : LIBVIRT_CLIENTKEY)))
            goto out_of_memory;

        if (!(*cert = strdup(isServer ? LIBVIRT_SERVERCERT : LIBVIRT_CLIENTCERT)))
            goto out_of_memory;
    }

    VIR_FREE(user_pki_path);
    VIR_FREE(userdir);

    return 0;

out_of_memory:
    virReportOOMError();
    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,
879
                                                   bool sanityCheckCert,
880 881 882 883 884 885 886
                                                   bool requireValidCert,
                                                   bool isServer)
{
    char *cacert = NULL, *cacrl = NULL, *key = NULL, *cert = NULL;
    virNetTLSContextPtr ctxt = NULL;

    if (virNetTLSContextLocateCredentials(pkipath, tryUserPkiPath, isServer,
887
                                          &cacert, &cacrl, &cert, &key) < 0)
888 889
        return NULL;

890
    ctxt = virNetTLSContextNew(cacert, cacrl, cert, key,
891 892
                               x509dnWhitelist, sanityCheckCert,
                               requireValidCert, isServer);
893 894 895 896 897 898 899 900 901 902 903 904

    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,
905
                                                  bool sanityCheckCert,
906 907
                                                  bool requireValidCert)
{
908 909
    return virNetTLSContextNewPath(pkipath, tryUserPkiPath, x509dnWhitelist,
                                   sanityCheckCert, requireValidCert, true);
910 911 912 913
}

virNetTLSContextPtr virNetTLSContextNewClientPath(const char *pkipath,
                                                  bool tryUserPkiPath,
914
                                                  bool sanityCheckCert,
915 916
                                                  bool requireValidCert)
{
917 918
    return virNetTLSContextNewPath(pkipath, tryUserPkiPath, NULL,
                                   sanityCheckCert, requireValidCert, false);
919 920 921 922 923 924 925 926
}


virNetTLSContextPtr virNetTLSContextNewServer(const char *cacert,
                                              const char *cacrl,
                                              const char *cert,
                                              const char *key,
                                              const char *const*x509dnWhitelist,
927
                                              bool sanityCheckCert,
928 929
                                              bool requireValidCert)
{
930 931
    return virNetTLSContextNew(cacert, cacrl, cert, key, x509dnWhitelist,
                               sanityCheckCert, requireValidCert, true);
932 933 934 935 936 937 938
}


virNetTLSContextPtr virNetTLSContextNewClient(const char *cacert,
                                              const char *cacrl,
                                              const char *cert,
                                              const char *key,
939
                                              bool sanityCheckCert,
940 941
                                              bool requireValidCert)
{
942 943
    return virNetTLSContextNew(cacert, cacrl, cert, key, NULL,
                               sanityCheckCert, requireValidCert, false);
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
}


void virNetTLSContextRef(virNetTLSContextPtr ctxt)
{
    ctxt->refs++;
}


static int virNetTLSContextValidCertificate(virNetTLSContextPtr ctxt,
                                            virNetTLSSessionPtr sess)
{
    int ret;
    unsigned int status;
    const gnutls_datum_t *certs;
    unsigned int nCerts, i;

    if ((ret = gnutls_certificate_verify_peers2(sess->session, &status)) < 0){
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Unable to verify TLS peer: %s"),
                    gnutls_strerror(ret));
        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.");

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

        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Certificate failed validation: %s"),
                    reason);
        goto authdeny;
    }

    if (gnutls_certificate_type_get(sess->session) != GNUTLS_CRT_X509) {
        virNetError(VIR_ERR_SYSTEM_ERROR, "%s",
                    _("Only x509 certificates are supported"));
        goto authdeny;
    }

    if (!(certs = gnutls_certificate_get_peers(sess->session, &nCerts))) {
        virNetError(VIR_ERR_SYSTEM_ERROR, "%s",
                    _("The certificate has no peers"));
        goto authdeny;
    }

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

        if (gnutls_x509_crt_init(&cert) < 0) {
            virNetError(VIR_ERR_SYSTEM_ERROR, "%s",
                        _("Unable to initialize certificate"));
            goto authfail;
        }

        if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
            virNetError(VIR_ERR_SYSTEM_ERROR, "%s",
                        _("Unable to load certificate"));
            gnutls_x509_crt_deinit(cert);
            goto authfail;
        }

1019 1020
        if (virNetTLSContextCheckCertTimes(cert, "[session]",
                                           sess->isServer, i > 0) < 0) {
1021 1022 1023 1024 1025
            gnutls_x509_crt_deinit(cert);
            goto authdeny;
        }

        if (i == 0) {
1026 1027
            if (virNetTLSContextCheckCertDN(cert, "[session]", sess->hostname,
                                            ctxt->x509dnWhitelist) < 0) {
1028
                gnutls_x509_crt_deinit(cert);
1029 1030 1031 1032 1033 1034
                goto authdeny;
            }

            /* !sess->isServer, since on the client, we're validating the
             * server's cert, and on the server, the client's cert
             */
1035
#ifndef GNUTLS_1_0_COMPAT
1036 1037 1038 1039
            if (virNetTLSContextCheckCertBasicConstraints(cert, "[session]",
                                                          !sess->isServer, false) < 0) {
                gnutls_x509_crt_deinit(cert);
                goto authdeny;
1040
            }
1041
#endif
1042

1043 1044
            if (virNetTLSContextCheckCertKeyUsage(cert, "[session]",
                                                  false) < 0) {
1045 1046 1047 1048
                gnutls_x509_crt_deinit(cert);
                goto authdeny;
            }

1049 1050 1051
            /* !sess->isServer - as above */
            if (virNetTLSContextCheckCertKeyPurpose(cert, "[session]",
                                                    !sess->isServer) < 0) {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
                gnutls_x509_crt_deinit(cert);
                goto authdeny;
            }
        }
    }

#if 0
    PROBE(CLIENT_TLS_ALLOW, "fd=%d, name=%s",
          virNetServerClientGetFD(client), name);
#endif
    return 0;

authdeny:
#if 0
    PROBE(CLIENT_TLS_DENY, "fd=%d, name=%s",
          virNetServerClientGetFD(client), name);
#endif
    return -1;

authfail:
#if 0
    PROBE(CLIENT_TLS_FAIL, "fd=%d",
          virNetServerClientGetFD(client));
#endif
    return -1;
}

int virNetTLSContextCheckCertificate(virNetTLSContextPtr ctxt,
                                     virNetTLSSessionPtr sess)
{
1082 1083 1084 1085
    int ret = -1;

    virMutexLock(&ctxt->lock);
    virMutexLock(&sess->lock);
1086
    if (virNetTLSContextValidCertificate(ctxt, sess) < 0) {
1087 1088
        virErrorPtr err = virGetLastError();
        VIR_WARN("Certificate check failed %s", err && err->message ? err->message : "<unknown>");
1089 1090 1091
        if (ctxt->requireValidCert) {
            virNetError(VIR_ERR_AUTH_FAILED, "%s",
                        _("Failed to verify peer's certificate"));
1092
            goto cleanup;
1093
        }
1094
        virResetLastError();
1095 1096
        VIR_INFO("Ignoring bad certificate at user request");
    }
1097 1098 1099 1100 1101 1102 1103 1104

    ret = 0;

cleanup:
    virMutexUnlock(&ctxt->lock);
    virMutexUnlock(&sess->lock);

    return ret;
1105 1106 1107 1108 1109 1110 1111
}

void virNetTLSContextFree(virNetTLSContextPtr ctxt)
{
    if (!ctxt)
        return;

1112
    virMutexLock(&ctxt->lock);
1113
    ctxt->refs--;
1114 1115
    if (ctxt->refs > 0) {
        virMutexUnlock(&ctxt->lock);
1116
        return;
1117
    }
1118 1119 1120

    gnutls_dh_params_deinit(ctxt->dhParams);
    gnutls_certificate_free_credentials(ctxt->x509cred);
1121 1122
    virMutexUnlock(&ctxt->lock);
    virMutexDestroy(&ctxt->lock);
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    VIR_FREE(ctxt);
}



static ssize_t
virNetTLSSessionPush(void *opaque, const void *buf, size_t len)
{
    virNetTLSSessionPtr sess = opaque;
    if (!sess->writeFunc) {
1133
        VIR_WARN("TLS session push with missing write function");
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
        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;

    VIR_DEBUG("ctxt=%p hostname=%s isServer=%d", ctxt, NULLSTR(hostname), ctxt->isServer);

    if (VIR_ALLOC(sess) < 0) {
        virReportOOMError();
        return NULL;
    }

1169 1170 1171 1172 1173 1174 1175
    if (virMutexInit(&sess->lock) < 0) {
        virNetError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Failed to initialized mutex"));
        VIR_FREE(ctxt);
        return NULL;
    }

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    sess->refs = 1;
    if (hostname &&
        !(sess->hostname = strdup(hostname))) {
        virReportOOMError();
        goto error;
    }

    if ((err = gnutls_init(&sess->session,
                           ctxt->isServer ? GNUTLS_SERVER : GNUTLS_CLIENT)) != 0) {
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Failed to initialize TLS session: %s"),
                    gnutls_strerror(err));
        goto error;
    }

    /* avoid calling all the priority functions, since the defaults
     * are adequate.
     */
1194
    if ((err = gnutls_set_default_priority(sess->session)) != 0) {
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Failed to set TLS session priority %s"),
                    gnutls_strerror(err));
        goto error;
    }

    if ((err = gnutls_credentials_set(sess->session,
                                      GNUTLS_CRD_CERTIFICATE,
                                      ctxt->x509cred)) != 0) {
        virNetError(VIR_ERR_SYSTEM_ERROR,
                    _("Failed set TLS x509 credentials: %s"),
                    gnutls_strerror(err));
        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);

1224 1225
    sess->isServer = ctxt->isServer;

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    return sess;

error:
    virNetTLSSessionFree(sess);
    return NULL;
}


void virNetTLSSessionRef(virNetTLSSessionPtr sess)
{
1236
    virMutexLock(&sess->lock);
1237
    sess->refs++;
1238
    virMutexUnlock(&sess->lock);
1239 1240 1241 1242 1243 1244 1245
}

void virNetTLSSessionSetIOCallbacks(virNetTLSSessionPtr sess,
                                    virNetTLSSessionWriteFunc writeFunc,
                                    virNetTLSSessionReadFunc readFunc,
                                    void *opaque)
{
1246
    virMutexLock(&sess->lock);
1247 1248 1249
    sess->writeFunc = writeFunc;
    sess->readFunc = readFunc;
    sess->opaque = opaque;
1250
    virMutexUnlock(&sess->lock);
1251 1252 1253 1254 1255 1256 1257
}


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

    virMutexLock(&sess->lock);
1260 1261 1262
    ret = gnutls_record_send(sess->session, buf, len);

    if (ret >= 0)
1263
        goto cleanup;
1264 1265 1266 1267 1268 1269 1270 1271

    switch (ret) {
    case GNUTLS_E_AGAIN:
        errno = EAGAIN;
        break;
    case GNUTLS_E_INTERRUPTED:
        errno = EINTR;
        break;
1272 1273 1274
    case GNUTLS_E_UNEXPECTED_PACKET_LENGTH:
        errno = ENOMSG;
        break;
1275 1276 1277 1278 1279
    default:
        errno = EIO;
        break;
    }

1280 1281 1282 1283 1284
    ret = -1;

cleanup:
    virMutexUnlock(&sess->lock);
    return ret;
1285 1286 1287 1288 1289 1290 1291
}

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

1292
    virMutexLock(&sess->lock);
1293 1294 1295
    ret = gnutls_record_recv(sess->session, buf, len);

    if (ret >= 0)
1296
        goto cleanup;
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

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

1310 1311 1312 1313 1314
    ret = -1;

cleanup:
    virMutexUnlock(&sess->lock);
    return ret;
1315 1316 1317 1318
}

int virNetTLSSessionHandshake(virNetTLSSessionPtr sess)
{
1319
    int ret;
1320
    VIR_DEBUG("sess=%p", sess);
1321 1322
    virMutexLock(&sess->lock);
    ret = gnutls_handshake(sess->session);
1323 1324 1325 1326
    VIR_DEBUG("Ret=%d", ret);
    if (ret == 0) {
        sess->handshakeComplete = true;
        VIR_DEBUG("Handshake is complete");
1327 1328 1329 1330 1331
        goto cleanup;
    }
    if (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN) {
        ret = 1;
        goto cleanup;
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    }

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

    virNetError(VIR_ERR_AUTH_FAILED,
                _("TLS handshake failed %s"),
                gnutls_strerror(ret));
1342 1343 1344 1345 1346
    ret = -1;

cleanup:
    virMutexUnlock(&sess->lock);
    return ret;
1347 1348 1349 1350 1351
}

virNetTLSSessionHandshakeStatus
virNetTLSSessionGetHandshakeStatus(virNetTLSSessionPtr sess)
{
1352 1353
    virNetTLSSessionHandshakeStatus ret;
    virMutexLock(&sess->lock);
1354
    if (sess->handshakeComplete)
1355
        ret = VIR_NET_TLS_HANDSHAKE_COMPLETE;
1356
    else if (gnutls_record_get_direction(sess->session) == 0)
1357
        ret = VIR_NET_TLS_HANDSHAKE_RECVING;
1358
    else
1359 1360 1361
        ret = VIR_NET_TLS_HANDSHAKE_SENDING;
    virMutexUnlock(&sess->lock);
    return ret;
1362 1363 1364 1365 1366 1367
}

int virNetTLSSessionGetKeySize(virNetTLSSessionPtr sess)
{
    gnutls_cipher_algorithm_t cipher;
    int ssf;
1368
    virMutexLock(&sess->lock);
1369 1370 1371 1372
    cipher = gnutls_cipher_get(sess->session);
    if (!(ssf = gnutls_cipher_get_key_size(cipher))) {
        virNetError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("invalid cipher size for TLS session"));
1373 1374
        ssf = -1;
        goto cleanup;
1375 1376
    }

1377 1378
cleanup:
    virMutexUnlock(&sess->lock);
1379 1380 1381 1382 1383 1384 1385 1386 1387
    return ssf;
}


void virNetTLSSessionFree(virNetTLSSessionPtr sess)
{
    if (!sess)
        return;

1388
    virMutexLock(&sess->lock);
1389
    sess->refs--;
1390 1391
    if (sess->refs > 0) {
        virMutexUnlock(&sess->lock);
1392
        return;
1393
    }
1394 1395 1396

    VIR_FREE(sess->hostname);
    gnutls_deinit(sess->session);
1397 1398
    virMutexUnlock(&sess->lock);
    virMutexDestroy(&sess->lock);
1399 1400
    VIR_FREE(sess);
}