PageRenderTime 103ms CodeModel.GetById 3ms app.highlight 90ms RepoModel.GetById 1ms app.codeStats 0ms

/release/src-rt-6.x.4708/router/openvpn/src/openvpn/ssl_verify.c

https://bitbucket.org/oglop/tomato-arm-kille72
C | 1545 lines | 1164 code | 184 blank | 197 comment | 229 complexity | 4dd9a4d1bc016f5cefaf51d7f21aedda MD5 | raw file
   1/*
   2 *  OpenVPN -- An application to securely tunnel IP networks
   3 *             over a single TCP/UDP port, with support for SSL/TLS-based
   4 *             session authentication and key exchange,
   5 *             packet encryption, packet authentication, and
   6 *             packet compression.
   7 *
   8 *  Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
   9 *  Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
  10 *
  11 *  This program is free software; you can redistribute it and/or modify
  12 *  it under the terms of the GNU General Public License version 2
  13 *  as published by the Free Software Foundation.
  14 *
  15 *  This program is distributed in the hope that it will be useful,
  16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18 *  GNU General Public License for more details.
  19 *
  20 *  You should have received a copy of the GNU General Public License along
  21 *  with this program; if not, write to the Free Software Foundation, Inc.,
  22 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23 */
  24
  25/**
  26 * @file Control Channel Verification Module
  27 */
  28
  29#ifdef HAVE_CONFIG_H
  30#include "config.h"
  31#elif defined(_MSC_VER)
  32#include "config-msvc.h"
  33#endif
  34
  35#include "syshead.h"
  36
  37#ifdef ENABLE_CRYPTO
  38
  39#include "misc.h"
  40#include "manage.h"
  41#include "otime.h"
  42#include "base64.h"
  43#include "ssl_verify.h"
  44#include "ssl_verify_backend.h"
  45
  46#ifdef ENABLE_CRYPTO_OPENSSL
  47#include "ssl_verify_openssl.h"
  48#endif
  49
  50/** Maximum length of common name */
  51#define TLS_USERNAME_LEN 64
  52
  53/** Legal characters in an X509 name with --compat-names */
  54#define X509_NAME_CHAR_CLASS   (CC_ALNUM|CC_UNDERBAR|CC_DASH|CC_DOT|CC_AT|CC_SLASH|CC_COLON|CC_EQUAL)
  55
  56/** Legal characters in a common name with --compat-names */
  57#define COMMON_NAME_CHAR_CLASS (CC_ALNUM|CC_UNDERBAR|CC_DASH|CC_DOT|CC_AT|CC_SLASH)
  58
  59static void
  60string_mod_remap_name(char *str, const unsigned int restrictive_flags)
  61{
  62    if (compat_flag(COMPAT_FLAG_QUERY | COMPAT_NAMES)
  63        && !compat_flag(COMPAT_FLAG_QUERY | COMPAT_NO_NAME_REMAPPING))
  64    {
  65        string_mod(str, restrictive_flags, 0, '_');
  66    }
  67    else
  68    {
  69        string_mod(str, CC_PRINT, CC_CRLF, '_');
  70    }
  71}
  72
  73/*
  74 * Export the untrusted IP address and port to the environment
  75 */
  76static void
  77setenv_untrusted(struct tls_session *session)
  78{
  79    setenv_link_socket_actual(session->opt->es, "untrusted", &session->untrusted_addr, SA_IP_PORT);
  80}
  81
  82
  83/**
  84 *  Wipes the authentication token out of the memory, frees and cleans up related buffers and flags
  85 *
  86 *  @param multi  Pointer to a multi object holding the auth_token variables
  87 */
  88static void
  89wipe_auth_token(struct tls_multi *multi)
  90{
  91    if(multi)
  92    {
  93        if (multi->auth_token)
  94        {
  95            secure_memzero(multi->auth_token, AUTH_TOKEN_SIZE);
  96            free(multi->auth_token);
  97        }
  98        multi->auth_token = NULL;
  99        multi->auth_token_sent = false;
 100    }
 101}
 102
 103
 104/*
 105 * Remove authenticated state from all sessions in the given tunnel
 106 */
 107static void
 108tls_deauthenticate(struct tls_multi *multi)
 109{
 110    if (multi)
 111    {
 112        wipe_auth_token(multi);
 113        for (int i = 0; i < TM_SIZE; ++i)
 114        {
 115            for (int j = 0; j < KS_SIZE; ++j)
 116            {
 117                multi->session[i].key[j].authenticated = false;
 118            }
 119        }
 120    }
 121}
 122
 123/*
 124 * Set the given session's common_name
 125 */
 126static void
 127set_common_name(struct tls_session *session, const char *common_name)
 128{
 129    if (session->common_name)
 130    {
 131        free(session->common_name);
 132        session->common_name = NULL;
 133#ifdef ENABLE_PF
 134        session->common_name_hashval = 0;
 135#endif
 136    }
 137    if (common_name)
 138    {
 139        /* FIXME: Last alloc will never be freed */
 140        session->common_name = string_alloc(common_name, NULL);
 141#ifdef ENABLE_PF
 142        {
 143            const uint32_t len = (uint32_t) strlen(common_name);
 144            if (len)
 145            {
 146                session->common_name_hashval = hash_func((const uint8_t *)common_name, len+1, 0);
 147            }
 148            else
 149            {
 150                session->common_name_hashval = 0;
 151            }
 152        }
 153#endif
 154    }
 155}
 156
 157/*
 158 * Retrieve the common name for the given tunnel's active session. If the
 159 * common name is NULL or empty, return NULL if null is true, or "UNDEF" if
 160 * null is false.
 161 */
 162const char *
 163tls_common_name(const struct tls_multi *multi, const bool null)
 164{
 165    const char *ret = NULL;
 166    if (multi)
 167    {
 168        ret = multi->session[TM_ACTIVE].common_name;
 169    }
 170    if (ret && strlen(ret))
 171    {
 172        return ret;
 173    }
 174    else if (null)
 175    {
 176        return NULL;
 177    }
 178    else
 179    {
 180        return "UNDEF";
 181    }
 182}
 183
 184/*
 185 * Lock the common name for the given tunnel.
 186 */
 187void
 188tls_lock_common_name(struct tls_multi *multi)
 189{
 190    const char *cn = multi->session[TM_ACTIVE].common_name;
 191    if (cn && !multi->locked_cn)
 192    {
 193        multi->locked_cn = string_alloc(cn, NULL);
 194    }
 195}
 196
 197/*
 198 * Lock the username for the given tunnel
 199 */
 200static bool
 201tls_lock_username(struct tls_multi *multi, const char *username)
 202{
 203    if (multi->locked_username)
 204    {
 205        if (!username || strcmp(username, multi->locked_username))
 206        {
 207            msg(D_TLS_ERRORS, "TLS Auth Error: username attempted to change from '%s' to '%s' -- tunnel disabled",
 208                multi->locked_username,
 209                np(username));
 210
 211            /* disable the tunnel */
 212            tls_deauthenticate(multi);
 213            return false;
 214        }
 215    }
 216    else
 217    {
 218        if (username)
 219        {
 220            multi->locked_username = string_alloc(username, NULL);
 221        }
 222    }
 223    return true;
 224}
 225
 226const char *
 227tls_username(const struct tls_multi *multi, const bool null)
 228{
 229    const char *ret = NULL;
 230    if (multi)
 231    {
 232        ret = multi->locked_username;
 233    }
 234    if (ret && strlen(ret))
 235    {
 236        return ret;
 237    }
 238    else if (null)
 239    {
 240        return NULL;
 241    }
 242    else
 243    {
 244        return "UNDEF";
 245    }
 246}
 247
 248void
 249cert_hash_remember(struct tls_session *session, const int error_depth,
 250                   const struct buffer *cert_hash)
 251{
 252    if (error_depth >= 0 && error_depth < MAX_CERT_DEPTH)
 253    {
 254        if (!session->cert_hash_set)
 255        {
 256            ALLOC_OBJ_CLEAR(session->cert_hash_set, struct cert_hash_set);
 257        }
 258        if (!session->cert_hash_set->ch[error_depth])
 259        {
 260            ALLOC_OBJ(session->cert_hash_set->ch[error_depth], struct cert_hash);
 261        }
 262
 263        struct cert_hash *ch = session->cert_hash_set->ch[error_depth];
 264        ASSERT(sizeof(ch->sha256_hash) == BLEN(cert_hash));
 265        memcpy(ch->sha256_hash, BPTR(cert_hash), sizeof(ch->sha256_hash));
 266    }
 267}
 268
 269void
 270cert_hash_free(struct cert_hash_set *chs)
 271{
 272    if (chs)
 273    {
 274        int i;
 275        for (i = 0; i < MAX_CERT_DEPTH; ++i)
 276        {
 277            free(chs->ch[i]);
 278        }
 279        free(chs);
 280    }
 281}
 282
 283bool
 284cert_hash_compare(const struct cert_hash_set *chs1, const struct cert_hash_set *chs2)
 285{
 286    if (chs1 && chs2)
 287    {
 288        int i;
 289        for (i = 0; i < MAX_CERT_DEPTH; ++i)
 290        {
 291            const struct cert_hash *ch1 = chs1->ch[i];
 292            const struct cert_hash *ch2 = chs2->ch[i];
 293
 294            if (!ch1 && !ch2)
 295            {
 296                continue;
 297            }
 298            else if (ch1 && ch2 && !memcmp(ch1->sha256_hash, ch2->sha256_hash,
 299                                           sizeof(ch1->sha256_hash)))
 300            {
 301                continue;
 302            }
 303            else
 304            {
 305                return false;
 306            }
 307        }
 308        return true;
 309    }
 310    else if (!chs1 && !chs2)
 311    {
 312        return true;
 313    }
 314    else
 315    {
 316        return false;
 317    }
 318}
 319
 320static struct cert_hash_set *
 321cert_hash_copy(const struct cert_hash_set *chs)
 322{
 323    struct cert_hash_set *dest = NULL;
 324    if (chs)
 325    {
 326        int i;
 327        ALLOC_OBJ_CLEAR(dest, struct cert_hash_set);
 328        for (i = 0; i < MAX_CERT_DEPTH; ++i)
 329        {
 330            const struct cert_hash *ch = chs->ch[i];
 331            if (ch)
 332            {
 333                ALLOC_OBJ(dest->ch[i], struct cert_hash);
 334                memcpy(dest->ch[i]->sha256_hash, ch->sha256_hash,
 335                       sizeof(dest->ch[i]->sha256_hash));
 336            }
 337        }
 338    }
 339    return dest;
 340}
 341void
 342tls_lock_cert_hash_set(struct tls_multi *multi)
 343{
 344    const struct cert_hash_set *chs = multi->session[TM_ACTIVE].cert_hash_set;
 345    if (chs && !multi->locked_cert_hash_set)
 346    {
 347        multi->locked_cert_hash_set = cert_hash_copy(chs);
 348    }
 349}
 350
 351/*
 352 * Returns the string associated with the given certificate type.
 353 */
 354static const char *
 355print_nsCertType(int type)
 356{
 357    switch (type)
 358    {
 359        case NS_CERT_CHECK_SERVER:
 360            return "SERVER";
 361
 362        case NS_CERT_CHECK_CLIENT:
 363            return "CLIENT";
 364
 365        default:
 366            return "?";
 367    }
 368}
 369
 370/*
 371 * Verify the peer's certificate fields.
 372 *
 373 * @param opt the tls options to verify against
 374 * @param peer_cert the peer's certificate
 375 * @param subject the peer's extracted subject name
 376 * @param subject the peer's extracted common name
 377 */
 378static result_t
 379verify_peer_cert(const struct tls_options *opt, openvpn_x509_cert_t *peer_cert,
 380                 const char *subject, const char *common_name)
 381{
 382    /* verify certificate nsCertType */
 383    if (opt->ns_cert_type != NS_CERT_CHECK_NONE)
 384    {
 385        if (SUCCESS == x509_verify_ns_cert_type(peer_cert, opt->ns_cert_type))
 386        {
 387            msg(D_HANDSHAKE, "VERIFY OK: nsCertType=%s",
 388                print_nsCertType(opt->ns_cert_type));
 389        }
 390        else
 391        {
 392            msg(D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
 393                subject, print_nsCertType(opt->ns_cert_type));
 394            return FAILURE;             /* Reject connection */
 395        }
 396    }
 397
 398    /* verify certificate ku */
 399    if (opt->remote_cert_ku[0] != 0)
 400    {
 401        if (SUCCESS == x509_verify_cert_ku(peer_cert, opt->remote_cert_ku, MAX_PARMS))
 402        {
 403            msg(D_HANDSHAKE, "VERIFY KU OK");
 404        }
 405        else
 406        {
 407            msg(D_HANDSHAKE, "VERIFY KU ERROR");
 408            return FAILURE;             /* Reject connection */
 409        }
 410    }
 411
 412    /* verify certificate eku */
 413    if (opt->remote_cert_eku != NULL)
 414    {
 415        if (SUCCESS == x509_verify_cert_eku(peer_cert, opt->remote_cert_eku))
 416        {
 417            msg(D_HANDSHAKE, "VERIFY EKU OK");
 418        }
 419        else
 420        {
 421            msg(D_HANDSHAKE, "VERIFY EKU ERROR");
 422            return FAILURE;             /* Reject connection */
 423        }
 424    }
 425
 426    /* verify X509 name or username against --verify-x509-[user]name */
 427    if (opt->verify_x509_type != VERIFY_X509_NONE)
 428    {
 429        if ( (opt->verify_x509_type == VERIFY_X509_SUBJECT_DN
 430              && strcmp(opt->verify_x509_name, subject) == 0)
 431             || (opt->verify_x509_type == VERIFY_X509_SUBJECT_RDN
 432                 && strcmp(opt->verify_x509_name, common_name) == 0)
 433             || (opt->verify_x509_type == VERIFY_X509_SUBJECT_RDN_PREFIX
 434                 && strncmp(opt->verify_x509_name, common_name,
 435                            strlen(opt->verify_x509_name)) == 0) )
 436        {
 437            msg(D_HANDSHAKE, "VERIFY X509NAME OK: %s", subject);
 438        }
 439        else
 440        {
 441            msg(D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
 442                subject, opt->verify_x509_name);
 443            return FAILURE;             /* Reject connection */
 444        }
 445    }
 446
 447    return SUCCESS;
 448}
 449
 450/*
 451 * Export the subject, common_name, and raw certificate fields to the
 452 * environment for later verification by scripts and plugins.
 453 */
 454static void
 455verify_cert_set_env(struct env_set *es, openvpn_x509_cert_t *peer_cert, int cert_depth,
 456                    const char *subject, const char *common_name,
 457                    const struct x509_track *x509_track)
 458{
 459    char envname[64];
 460    char *serial = NULL;
 461    struct gc_arena gc = gc_new();
 462
 463    /* Save X509 fields in environment */
 464    if (x509_track)
 465    {
 466        x509_setenv_track(x509_track, es, cert_depth, peer_cert);
 467    }
 468    else
 469    {
 470        x509_setenv(es, cert_depth, peer_cert);
 471    }
 472
 473    /* export subject name string as environmental variable */
 474    openvpn_snprintf(envname, sizeof(envname), "tls_id_%d", cert_depth);
 475    setenv_str(es, envname, subject);
 476
 477#if 0
 478    /* export common name string as environmental variable */
 479    openvpn_snprintf(envname, sizeof(envname), "tls_common_name_%d", cert_depth);
 480    setenv_str(es, envname, common_name);
 481#endif
 482
 483    /* export X509 cert fingerprints */
 484    {
 485        struct buffer sha1 = x509_get_sha1_fingerprint(peer_cert, &gc);
 486        struct buffer sha256 = x509_get_sha256_fingerprint(peer_cert, &gc);
 487
 488        openvpn_snprintf(envname, sizeof(envname), "tls_digest_%d", cert_depth);
 489        setenv_str(es, envname,
 490                   format_hex_ex(BPTR(&sha1), BLEN(&sha1), 0, 1, ":", &gc));
 491
 492        openvpn_snprintf(envname, sizeof(envname), "tls_digest_sha256_%d",
 493                         cert_depth);
 494        setenv_str(es, envname,
 495                   format_hex_ex(BPTR(&sha256), BLEN(&sha256), 0, 1, ":", &gc));
 496    }
 497
 498    /* export serial number as environmental variable */
 499    serial = backend_x509_get_serial(peer_cert, &gc);
 500    openvpn_snprintf(envname, sizeof(envname), "tls_serial_%d", cert_depth);
 501    setenv_str(es, envname, serial);
 502
 503    /* export serial number in hex as environmental variable */
 504    serial = backend_x509_get_serial_hex(peer_cert, &gc);
 505    openvpn_snprintf(envname, sizeof(envname), "tls_serial_hex_%d", cert_depth);
 506    setenv_str(es, envname, serial);
 507
 508    gc_free(&gc);
 509}
 510
 511/*
 512 * call --tls-verify plug-in(s)
 513 */
 514static result_t
 515verify_cert_call_plugin(const struct plugin_list *plugins, struct env_set *es,
 516                        int cert_depth, openvpn_x509_cert_t *cert, char *subject)
 517{
 518    if (plugin_defined(plugins, OPENVPN_PLUGIN_TLS_VERIFY))
 519    {
 520        int ret;
 521        struct argv argv = argv_new();
 522
 523        argv_printf(&argv, "%d %s", cert_depth, subject);
 524
 525        ret = plugin_call_ssl(plugins, OPENVPN_PLUGIN_TLS_VERIFY, &argv, NULL, es, cert_depth, cert);
 526
 527        argv_reset(&argv);
 528
 529        if (ret == OPENVPN_PLUGIN_FUNC_SUCCESS)
 530        {
 531            msg(D_HANDSHAKE, "VERIFY PLUGIN OK: depth=%d, %s",
 532                cert_depth, subject);
 533        }
 534        else
 535        {
 536            msg(D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=%d, %s",
 537                cert_depth, subject);
 538            return FAILURE;             /* Reject connection */
 539        }
 540    }
 541    return SUCCESS;
 542}
 543
 544static const char *
 545verify_cert_export_cert(openvpn_x509_cert_t *peercert, const char *tmp_dir, struct gc_arena *gc)
 546{
 547    FILE *peercert_file;
 548    const char *peercert_filename = "";
 549
 550    /* create tmp file to store peer cert */
 551    if (!tmp_dir
 552        || !(peercert_filename = create_temp_file(tmp_dir, "pcf", gc)))
 553    {
 554        msg (M_WARN, "Failed to create peer cert file");
 555        return NULL;
 556    }
 557
 558    /* write peer-cert in tmp-file */
 559    peercert_file = fopen(peercert_filename, "w+");
 560    if (!peercert_file)
 561    {
 562        msg(M_ERR, "Failed to open temporary file : %s", peercert_filename);
 563        return NULL;
 564    }
 565
 566    if (SUCCESS != x509_write_pem(peercert_file, peercert))
 567    {
 568        msg(M_ERR, "Error writing PEM file containing certificate");
 569    }
 570
 571    fclose(peercert_file);
 572    return peercert_filename;
 573}
 574
 575
 576/*
 577 * run --tls-verify script
 578 */
 579static result_t
 580verify_cert_call_command(const char *verify_command, struct env_set *es,
 581                         int cert_depth, openvpn_x509_cert_t *cert, char *subject, const char *verify_export_cert)
 582{
 583    const char *tmp_file = NULL;
 584    int ret;
 585    struct gc_arena gc = gc_new();
 586    struct argv argv = argv_new();
 587
 588    setenv_str(es, "script_type", "tls-verify");
 589
 590    if (verify_export_cert)
 591    {
 592        tmp_file = verify_cert_export_cert(cert, verify_export_cert, &gc);
 593        if (!tmp_file)
 594        {
 595            ret = false;
 596            goto cleanup;
 597        }
 598        setenv_str(es, "peer_cert", tmp_file);
 599    }
 600
 601    argv_parse_cmd(&argv, verify_command);
 602    argv_printf_cat(&argv, "%d %s", cert_depth, subject);
 603
 604    argv_msg_prefix(D_TLS_DEBUG, &argv, "TLS: executing verify command");
 605    ret = openvpn_run_script(&argv, es, 0, "--tls-verify script");
 606
 607    if (verify_export_cert)
 608    {
 609        if (tmp_file)
 610        {
 611            platform_unlink(tmp_file);
 612        }
 613    }
 614
 615cleanup:
 616    gc_free(&gc);
 617    argv_reset(&argv);
 618
 619    if (ret)
 620    {
 621        msg(D_HANDSHAKE, "VERIFY SCRIPT OK: depth=%d, %s",
 622            cert_depth, subject);
 623        return SUCCESS;
 624    }
 625
 626    msg(D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=%d, %s",
 627        cert_depth, subject);
 628    return FAILURE;             /* Reject connection */
 629}
 630
 631/*
 632 * check peer cert against CRL directory
 633 */
 634static result_t
 635verify_check_crl_dir(const char *crl_dir, openvpn_x509_cert_t *cert)
 636{
 637    result_t ret = FAILURE;
 638    char fn[256];
 639    int fd = -1;
 640    struct gc_arena gc = gc_new();
 641
 642    char *serial = backend_x509_get_serial(cert, &gc);
 643
 644    if (!openvpn_snprintf(fn, sizeof(fn), "%s%c%s", crl_dir, OS_SPECIFIC_DIRSEP, serial))
 645    {
 646        msg(D_HANDSHAKE, "VERIFY CRL: filename overflow");
 647        goto cleanup;
 648    }
 649    fd = platform_open(fn, O_RDONLY, 0);
 650    if (fd >= 0)
 651    {
 652        msg(D_HANDSHAKE, "VERIFY CRL: certificate serial number %s is revoked", serial);
 653        goto cleanup;
 654    }
 655
 656    ret = SUCCESS;
 657
 658cleanup:
 659
 660    if (fd != -1)
 661    {
 662        close(fd);
 663    }
 664    gc_free(&gc);
 665    return ret;
 666}
 667
 668result_t
 669verify_cert(struct tls_session *session, openvpn_x509_cert_t *cert, int cert_depth)
 670{
 671    result_t ret = FAILURE;
 672    char *subject = NULL;
 673    char common_name[TLS_USERNAME_LEN+1] = {0}; /* null-terminated */
 674    const struct tls_options *opt;
 675    struct gc_arena gc = gc_new();
 676
 677    opt = session->opt;
 678    ASSERT(opt);
 679
 680    session->verified = false;
 681
 682    /* get the X509 name */
 683    subject = x509_get_subject(cert, &gc);
 684    if (!subject)
 685    {
 686        msg(D_TLS_ERRORS, "VERIFY ERROR: depth=%d, could not extract X509 "
 687            "subject string from certificate", cert_depth);
 688        goto cleanup;
 689    }
 690
 691    /* enforce character class restrictions in X509 name */
 692    string_mod_remap_name(subject, X509_NAME_CHAR_CLASS);
 693    string_replace_leading(subject, '-', '_');
 694
 695    /* extract the username (default is CN) */
 696    if (SUCCESS != backend_x509_get_username(common_name, sizeof(common_name),
 697                                             opt->x509_username_field, cert))
 698    {
 699        if (!cert_depth)
 700        {
 701            msg(D_TLS_ERRORS, "VERIFY ERROR: could not extract %s from X509 "
 702                "subject string ('%s') -- note that the username length is "
 703                "limited to %d characters",
 704                opt->x509_username_field,
 705                subject,
 706                TLS_USERNAME_LEN);
 707            goto cleanup;
 708        }
 709    }
 710
 711    /* enforce character class restrictions in common name */
 712    string_mod_remap_name(common_name, COMMON_NAME_CHAR_CLASS);
 713
 714    /* warn if cert chain is too deep */
 715    if (cert_depth >= MAX_CERT_DEPTH)
 716    {
 717        msg(D_TLS_ERRORS, "TLS Error: Convoluted certificate chain detected with depth [%d] greater than %d", cert_depth, MAX_CERT_DEPTH);
 718        goto cleanup;                   /* Reject connection */
 719    }
 720
 721    /* verify level 1 cert, i.e. the CA that signed our leaf cert */
 722    if (cert_depth == 1 && opt->verify_hash)
 723    {
 724        struct buffer ca_hash = {0};
 725
 726        switch (opt->verify_hash_algo)
 727        {
 728        case MD_SHA1:
 729            ca_hash = x509_get_sha1_fingerprint(cert, &gc);
 730            break;
 731
 732        case MD_SHA256:
 733            ca_hash = x509_get_sha256_fingerprint(cert, &gc);
 734            break;
 735
 736        default:
 737            /* This should normally not happen at all; the algorithm used
 738             * is parsed by add_option() [options.c] and set to a predefined
 739             * value in an enumerated type.  So if this unlikely scenario
 740             * happens, consider this a failure
 741             */
 742            msg(M_WARN, "Unexpected invalid algorithm used with "
 743                "--verify-hash (%i)", opt->verify_hash_algo);
 744            ret = FAILURE;
 745            goto cleanup;
 746        }
 747
 748        if (memcmp(BPTR(&ca_hash), opt->verify_hash, BLEN(&ca_hash)))
 749        {
 750            msg(D_TLS_ERRORS, "TLS Error: level-1 certificate hash verification failed");
 751            goto cleanup;
 752        }
 753    }
 754
 755    /* save common name in session object */
 756    if (cert_depth == 0)
 757    {
 758        set_common_name(session, common_name);
 759    }
 760
 761    session->verify_maxlevel = max_int(session->verify_maxlevel, cert_depth);
 762
 763    /* export certificate values to the environment */
 764    verify_cert_set_env(opt->es, cert, cert_depth, subject, common_name,
 765                        opt->x509_track);
 766
 767    /* export current untrusted IP */
 768    setenv_untrusted(session);
 769
 770    /* If this is the peer's own certificate, verify it */
 771    if (cert_depth == 0 && SUCCESS != verify_peer_cert(opt, cert, subject, common_name))
 772    {
 773        goto cleanup;
 774    }
 775
 776    /* call --tls-verify plug-in(s), if registered */
 777    if (SUCCESS != verify_cert_call_plugin(opt->plugins, opt->es, cert_depth, cert, subject))
 778    {
 779        goto cleanup;
 780    }
 781
 782    /* run --tls-verify script */
 783    if (opt->verify_command && SUCCESS != verify_cert_call_command(opt->verify_command,
 784                                                                   opt->es, cert_depth, cert, subject, opt->verify_export_cert))
 785    {
 786        goto cleanup;
 787    }
 788
 789    /* check peer cert against CRL */
 790    if (opt->crl_file)
 791    {
 792        if (opt->ssl_flags & SSLF_CRL_VERIFY_DIR)
 793        {
 794            if (SUCCESS != verify_check_crl_dir(opt->crl_file, cert))
 795            {
 796                goto cleanup;
 797            }
 798        }
 799        else
 800        {
 801            if (tls_verify_crl_missing(opt))
 802            {
 803                msg(D_TLS_ERRORS, "VERIFY ERROR: CRL not loaded");
 804                goto cleanup;
 805            }
 806        }
 807    }
 808
 809    msg(D_HANDSHAKE, "VERIFY OK: depth=%d, %s", cert_depth, subject);
 810    session->verified = true;
 811    ret = SUCCESS;
 812
 813cleanup:
 814
 815    if (ret != SUCCESS)
 816    {
 817        tls_clear_error(); /* always? */
 818        session->verified = false; /* double sure? */
 819    }
 820    gc_free(&gc);
 821
 822    return ret;
 823}
 824
 825/* ***************************************************************************
 826* Functions for the management of deferred authentication when using
 827* user/password authentication.
 828*************************************************************************** */
 829
 830#ifdef ENABLE_DEF_AUTH
 831/* key_state_test_auth_control_file return values,
 832 * NOTE: acf_merge indexing depends on these values */
 833#define ACF_UNDEFINED 0
 834#define ACF_SUCCEEDED 1
 835#define ACF_DISABLED  2
 836#define ACF_FAILED    3
 837#endif
 838
 839#ifdef MANAGEMENT_DEF_AUTH
 840void
 841man_def_auth_set_client_reason(struct tls_multi *multi, const char *client_reason)
 842{
 843    if (multi->client_reason)
 844    {
 845        free(multi->client_reason);
 846        multi->client_reason = NULL;
 847    }
 848    if (client_reason && strlen(client_reason))
 849    {
 850        /* FIXME: Last alloc will never be freed */
 851        multi->client_reason = string_alloc(client_reason, NULL);
 852    }
 853}
 854
 855static inline unsigned int
 856man_def_auth_test(const struct key_state *ks)
 857{
 858    if (management_enable_def_auth(management))
 859    {
 860        return ks->mda_status;
 861    }
 862    else
 863    {
 864        return ACF_DISABLED;
 865    }
 866}
 867#endif /* ifdef MANAGEMENT_DEF_AUTH */
 868
 869#ifdef PLUGIN_DEF_AUTH
 870
 871/*
 872 * auth_control_file functions
 873 */
 874
 875void
 876key_state_rm_auth_control_file(struct key_state *ks)
 877{
 878    if (ks && ks->auth_control_file)
 879    {
 880        platform_unlink(ks->auth_control_file);
 881        free(ks->auth_control_file);
 882        ks->auth_control_file = NULL;
 883    }
 884}
 885
 886static bool
 887key_state_gen_auth_control_file(struct key_state *ks, const struct tls_options *opt)
 888{
 889    struct gc_arena gc = gc_new();
 890
 891    key_state_rm_auth_control_file(ks);
 892    const char *acf = create_temp_file(opt->tmp_dir, "acf", &gc);
 893    if (acf)
 894    {
 895        ks->auth_control_file = string_alloc(acf, NULL);
 896        setenv_str(opt->es, "auth_control_file", ks->auth_control_file);
 897    }
 898
 899    gc_free(&gc);
 900    return acf;
 901}
 902
 903static unsigned int
 904key_state_test_auth_control_file(struct key_state *ks)
 905{
 906    if (ks && ks->auth_control_file)
 907    {
 908        unsigned int ret = ks->auth_control_status;
 909        if (ret == ACF_UNDEFINED)
 910        {
 911            FILE *fp = fopen(ks->auth_control_file, "r");
 912            if (fp)
 913            {
 914                const int c = fgetc(fp);
 915                if (c == '1')
 916                {
 917                    ret = ACF_SUCCEEDED;
 918                }
 919                else if (c == '0')
 920                {
 921                    ret = ACF_FAILED;
 922                }
 923                fclose(fp);
 924                ks->auth_control_status = ret;
 925            }
 926        }
 927        return ret;
 928    }
 929    return ACF_DISABLED;
 930}
 931
 932#endif /* ifdef PLUGIN_DEF_AUTH */
 933
 934/*
 935 * Return current session authentication state.  Return
 936 * value is TLS_AUTHENTICATION_x.
 937 */
 938
 939int
 940tls_authentication_status(struct tls_multi *multi, const int latency)
 941{
 942    bool deferred = false;
 943    bool success = false;
 944    bool active = false;
 945
 946#ifdef ENABLE_DEF_AUTH
 947    static const unsigned char acf_merge[] =
 948    {
 949        ACF_UNDEFINED, /* s1=ACF_UNDEFINED s2=ACF_UNDEFINED */
 950        ACF_UNDEFINED, /* s1=ACF_UNDEFINED s2=ACF_SUCCEEDED */
 951        ACF_UNDEFINED, /* s1=ACF_UNDEFINED s2=ACF_DISABLED */
 952        ACF_FAILED,  /* s1=ACF_UNDEFINED s2=ACF_FAILED */
 953        ACF_UNDEFINED, /* s1=ACF_SUCCEEDED s2=ACF_UNDEFINED */
 954        ACF_SUCCEEDED, /* s1=ACF_SUCCEEDED s2=ACF_SUCCEEDED */
 955        ACF_SUCCEEDED, /* s1=ACF_SUCCEEDED s2=ACF_DISABLED */
 956        ACF_FAILED,  /* s1=ACF_SUCCEEDED s2=ACF_FAILED */
 957        ACF_UNDEFINED, /* s1=ACF_DISABLED  s2=ACF_UNDEFINED */
 958        ACF_SUCCEEDED, /* s1=ACF_DISABLED  s2=ACF_SUCCEEDED */
 959        ACF_DISABLED, /* s1=ACF_DISABLED  s2=ACF_DISABLED */
 960        ACF_FAILED,  /* s1=ACF_DISABLED  s2=ACF_FAILED */
 961        ACF_FAILED,  /* s1=ACF_FAILED    s2=ACF_UNDEFINED */
 962        ACF_FAILED,  /* s1=ACF_FAILED    s2=ACF_SUCCEEDED */
 963        ACF_FAILED,  /* s1=ACF_FAILED    s2=ACF_DISABLED */
 964        ACF_FAILED   /* s1=ACF_FAILED    s2=ACF_FAILED */
 965    };
 966#endif /* ENABLE_DEF_AUTH */
 967
 968    if (multi)
 969    {
 970        int i;
 971
 972#ifdef ENABLE_DEF_AUTH
 973        if (latency && multi->tas_last && multi->tas_last + latency >= now)
 974        {
 975            return TLS_AUTHENTICATION_UNDEFINED;
 976        }
 977        multi->tas_last = now;
 978#endif /* ENABLE_DEF_AUTH */
 979
 980        for (i = 0; i < KEY_SCAN_SIZE; ++i)
 981        {
 982            struct key_state *ks = multi->key_scan[i];
 983            if (DECRYPT_KEY_ENABLED(multi, ks))
 984            {
 985                active = true;
 986                if (ks->authenticated)
 987                {
 988#ifdef ENABLE_DEF_AUTH
 989                    unsigned int s1 = ACF_DISABLED;
 990                    unsigned int s2 = ACF_DISABLED;
 991#ifdef PLUGIN_DEF_AUTH
 992                    s1 = key_state_test_auth_control_file(ks);
 993#endif /* PLUGIN_DEF_AUTH */
 994#ifdef MANAGEMENT_DEF_AUTH
 995                    s2 = man_def_auth_test(ks);
 996#endif /* MANAGEMENT_DEF_AUTH */
 997                    ASSERT(s1 < 4 && s2 < 4);
 998                    switch (acf_merge[(s1<<2) + s2])
 999                    {
1000                        case ACF_SUCCEEDED:
1001                        case ACF_DISABLED:
1002                            success = true;
1003                            ks->auth_deferred = false;
1004                            break;
1005
1006                        case ACF_UNDEFINED:
1007                            if (now < ks->auth_deferred_expire)
1008                            {
1009                                deferred = true;
1010                            }
1011                            break;
1012
1013                        case ACF_FAILED:
1014                            ks->authenticated = false;
1015                            break;
1016
1017                        default:
1018                            ASSERT(0);
1019                    }
1020#else /* !ENABLE_DEF_AUTH */
1021                    success = true;
1022#endif /* ENABLE_DEF_AUTH */
1023                }
1024            }
1025        }
1026    }
1027
1028#if 0
1029    dmsg(D_TLS_ERRORS, "TAS: a=%d s=%d d=%d", active, success, deferred);
1030#endif
1031
1032    if (success)
1033    {
1034        return TLS_AUTHENTICATION_SUCCEEDED;
1035    }
1036    else if (!active || deferred)
1037    {
1038        return TLS_AUTHENTICATION_DEFERRED;
1039    }
1040    else
1041    {
1042        return TLS_AUTHENTICATION_FAILED;
1043    }
1044}
1045
1046#ifdef MANAGEMENT_DEF_AUTH
1047/*
1048 * For deferred auth, this is where the management interface calls (on server)
1049 * to indicate auth failure/success.
1050 */
1051bool
1052tls_authenticate_key(struct tls_multi *multi, const unsigned int mda_key_id, const bool auth, const char *client_reason)
1053{
1054    bool ret = false;
1055    if (multi)
1056    {
1057        int i;
1058        man_def_auth_set_client_reason(multi, client_reason);
1059        for (i = 0; i < KEY_SCAN_SIZE; ++i)
1060        {
1061            struct key_state *ks = multi->key_scan[i];
1062            if (ks->mda_key_id == mda_key_id)
1063            {
1064                ks->mda_status = auth ? ACF_SUCCEEDED : ACF_FAILED;
1065                ret = true;
1066            }
1067        }
1068    }
1069    return ret;
1070}
1071#endif /* ifdef MANAGEMENT_DEF_AUTH */
1072
1073
1074/* ****************************************************************************
1075 * Functions to verify username and password
1076 *
1077 * Authenticate a client using username/password.
1078 * Runs on server.
1079 *
1080 * If you want to add new authentication methods,
1081 * this is the place to start.
1082 *************************************************************************** */
1083
1084/*
1085 * Verify the user name and password using a script
1086 */
1087static bool
1088verify_user_pass_script(struct tls_session *session, const struct user_pass *up)
1089{
1090    struct gc_arena gc = gc_new();
1091    struct argv argv = argv_new();
1092    const char *tmp_file = "";
1093    bool ret = false;
1094
1095    /* Is username defined? */
1096    if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen(up->username))
1097    {
1098        /* Set environmental variables prior to calling script */
1099        setenv_str(session->opt->es, "script_type", "user-pass-verify");
1100
1101        if (session->opt->auth_user_pass_verify_script_via_file)
1102        {
1103            struct status_output *so;
1104
1105            tmp_file = create_temp_file(session->opt->tmp_dir, "up", &gc);
1106            if (tmp_file)
1107            {
1108                so = status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
1109                status_printf(so, "%s", up->username);
1110                status_printf(so, "%s", up->password);
1111                if (!status_close(so))
1112                {
1113                    msg(D_TLS_ERRORS, "TLS Auth Error: could not write username/password to file: %s",
1114                        tmp_file);
1115                    goto done;
1116                }
1117            }
1118            else
1119            {
1120                msg(D_TLS_ERRORS, "TLS Auth Error: could not create write "
1121                    "username/password to temp file");
1122            }
1123        }
1124        else
1125        {
1126            setenv_str(session->opt->es, "username", up->username);
1127            setenv_str(session->opt->es, "password", up->password);
1128        }
1129
1130        /* setenv incoming cert common name for script */
1131        setenv_str(session->opt->es, "common_name", session->common_name);
1132
1133        /* setenv client real IP address */
1134        setenv_untrusted(session);
1135
1136        /* format command line */
1137        argv_parse_cmd(&argv, session->opt->auth_user_pass_verify_script);
1138        argv_printf_cat(&argv, "%s", tmp_file);
1139
1140        /* call command */
1141        ret = openvpn_run_script(&argv, session->opt->es, 0,
1142                                 "--auth-user-pass-verify");
1143
1144        if (!session->opt->auth_user_pass_verify_script_via_file)
1145        {
1146            setenv_del(session->opt->es, "password");
1147        }
1148    }
1149    else
1150    {
1151        msg(D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
1152    }
1153
1154done:
1155    if (tmp_file && strlen(tmp_file) > 0)
1156    {
1157        platform_unlink(tmp_file);
1158    }
1159
1160    argv_reset(&argv);
1161    gc_free(&gc);
1162    return ret;
1163}
1164
1165/*
1166 * Verify the username and password using a plugin
1167 */
1168static int
1169verify_user_pass_plugin(struct tls_session *session, const struct user_pass *up, const char *raw_username)
1170{
1171    int retval = OPENVPN_PLUGIN_FUNC_ERROR;
1172#ifdef PLUGIN_DEF_AUTH
1173    struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1174#endif
1175
1176    /* Is username defined? */
1177    if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen(up->username))
1178    {
1179        /* set username/password in private env space */
1180        setenv_str(session->opt->es, "username", (raw_username ? raw_username : up->username));
1181        setenv_str(session->opt->es, "password", up->password);
1182
1183        /* setenv incoming cert common name for script */
1184        setenv_str(session->opt->es, "common_name", session->common_name);
1185
1186        /* setenv client real IP address */
1187        setenv_untrusted(session);
1188
1189#ifdef PLUGIN_DEF_AUTH
1190        /* generate filename for deferred auth control file */
1191        if (!key_state_gen_auth_control_file(ks, session->opt))
1192        {
1193            msg (D_TLS_ERRORS, "TLS Auth Error (%s): "
1194                 "could not create deferred auth control file", __func__);
1195            goto cleanup;
1196        }
1197#endif
1198
1199        /* call command */
1200        retval = plugin_call(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, NULL, session->opt->es);
1201
1202#ifdef PLUGIN_DEF_AUTH
1203        /* purge auth control filename (and file itself) for non-deferred returns */
1204        if (retval != OPENVPN_PLUGIN_FUNC_DEFERRED)
1205        {
1206            key_state_rm_auth_control_file(ks);
1207        }
1208#endif
1209
1210        setenv_del(session->opt->es, "password");
1211        if (raw_username)
1212        {
1213            setenv_str(session->opt->es, "username", up->username);
1214        }
1215    }
1216    else
1217    {
1218        msg(D_TLS_ERRORS, "TLS Auth Error (verify_user_pass_plugin): peer provided a blank username");
1219    }
1220
1221cleanup:
1222    return retval;
1223}
1224
1225
1226#ifdef MANAGEMENT_DEF_AUTH
1227/*
1228 * MANAGEMENT_DEF_AUTH internal ssl_verify.c status codes
1229 */
1230#define KMDA_ERROR   0
1231#define KMDA_SUCCESS 1
1232#define KMDA_UNDEF   2
1233#define KMDA_DEF     3
1234
1235static int
1236verify_user_pass_management(struct tls_session *session, const struct user_pass *up, const char *raw_username)
1237{
1238    int retval = KMDA_ERROR;
1239    struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1240
1241    /* Is username defined? */
1242    if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen(up->username))
1243    {
1244        /* set username/password in private env space */
1245        setenv_str(session->opt->es, "username", (raw_username ? raw_username : up->username));
1246        setenv_str(session->opt->es, "password", up->password);
1247
1248        /* setenv incoming cert common name for script */
1249        setenv_str(session->opt->es, "common_name", session->common_name);
1250
1251        /* setenv client real IP address */
1252        setenv_untrusted(session);
1253
1254        if (management)
1255        {
1256            management_notify_client_needing_auth(management, ks->mda_key_id, session->opt->mda_context, session->opt->es);
1257        }
1258
1259        setenv_del(session->opt->es, "password");
1260        if (raw_username)
1261        {
1262            setenv_str(session->opt->es, "username", up->username);
1263        }
1264
1265        retval = KMDA_SUCCESS;
1266    }
1267    else
1268    {
1269        msg(D_TLS_ERRORS, "TLS Auth Error (verify_user_pass_management): peer provided a blank username");
1270    }
1271
1272    return retval;
1273}
1274#endif /* ifdef MANAGEMENT_DEF_AUTH */
1275
1276/*
1277 * Main username/password verification entry point
1278 */
1279void
1280verify_user_pass(struct user_pass *up, struct tls_multi *multi,
1281                 struct tls_session *session)
1282{
1283    int s1 = OPENVPN_PLUGIN_FUNC_SUCCESS;
1284    bool s2 = true;
1285    struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1286
1287    struct gc_arena gc = gc_new();
1288    char *raw_username = NULL;
1289
1290#ifdef MANAGEMENT_DEF_AUTH
1291    int man_def_auth = KMDA_UNDEF;
1292
1293    if (management_enable_def_auth(management))
1294    {
1295        man_def_auth = KMDA_DEF;
1296    }
1297#endif
1298
1299    /*
1300     * Preserve the raw username before string_mod remapping, for plugins
1301     * and management clients when in --compat-names mode
1302     */
1303    if (compat_flag(COMPAT_FLAG_QUERY | COMPAT_NAMES))
1304    {
1305        ALLOC_ARRAY_CLEAR_GC(raw_username, char, USER_PASS_LEN, &gc);
1306        strcpy(raw_username, up->username);
1307        string_mod(raw_username, CC_PRINT, CC_CRLF, '_');
1308    }
1309
1310    /* enforce character class restrictions in username/password */
1311    string_mod_remap_name(up->username, COMMON_NAME_CHAR_CLASS);
1312    string_mod(up->password, CC_PRINT, CC_CRLF, '_');
1313
1314    /* If server is configured with --auth-gen-token and we have an
1315     * authentication token for this client, this authentication
1316     * round will be done internally using the token instead of
1317     * calling any external authentication modules.
1318     */
1319    if (session->opt->auth_token_generate && multi->auth_token_sent
1320        && NULL != multi->auth_token)
1321    {
1322        unsigned int ssl_flags = session->opt->ssl_flags;
1323
1324        /* Ensure that the username has not changed */
1325        if (!tls_lock_username(multi, up->username))
1326        {
1327            /* auth-token cleared in tls_lock_username() on failure */
1328            ks->authenticated = false;
1329            goto done;
1330        }
1331
1332        /* If auth-token lifetime has been enabled,
1333         * ensure the token has not expired
1334         */
1335        if (session->opt->auth_token_lifetime > 0
1336            && (multi->auth_token_tstamp + session->opt->auth_token_lifetime) < now)
1337        {
1338            msg(D_HANDSHAKE, "Auth-token for client expired\n");
1339            wipe_auth_token(multi);
1340            ks->authenticated = false;
1341            goto done;
1342        }
1343
1344        /* The core authentication of the token itself */
1345        if (memcmp_constant_time(multi->auth_token, up->password,
1346                                 strlen(multi->auth_token)) != 0)
1347        {
1348            ks->authenticated = false;
1349            tls_deauthenticate(multi);
1350
1351            msg(D_TLS_ERRORS, "TLS Auth Error: Auth-token verification "
1352                "failed for username '%s' %s", up->username,
1353                (ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
1354        }
1355        else
1356        {
1357            ks->authenticated = true;
1358
1359            if (ssl_flags & SSLF_USERNAME_AS_COMMON_NAME)
1360            {
1361                set_common_name(session, up->username);
1362            }
1363            msg(D_HANDSHAKE, "TLS: Username/auth-token authentication "
1364                "succeeded for username '%s' %s",
1365                up->username,
1366                (ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
1367        }
1368        goto done;
1369    }
1370
1371    /* call plugin(s) and/or script */
1372#ifdef MANAGEMENT_DEF_AUTH
1373    if (man_def_auth == KMDA_DEF)
1374    {
1375        man_def_auth = verify_user_pass_management(session, up, raw_username);
1376    }
1377#endif
1378    if (plugin_defined(session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
1379    {
1380        s1 = verify_user_pass_plugin(session, up, raw_username);
1381    }
1382    if (session->opt->auth_user_pass_verify_script)
1383    {
1384        s2 = verify_user_pass_script(session, up);
1385    }
1386
1387    /* check sizing of username if it will become our common name */
1388    if ((session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) && strlen(up->username) > TLS_USERNAME_LEN)
1389    {
1390        msg(D_TLS_ERRORS, "TLS Auth Error: --username-as-common name specified and username is longer than the maximum permitted Common Name length of %d characters", TLS_USERNAME_LEN);
1391        s1 = OPENVPN_PLUGIN_FUNC_ERROR;
1392    }
1393
1394    /* auth succeeded? */
1395    if ((s1 == OPENVPN_PLUGIN_FUNC_SUCCESS
1396#ifdef PLUGIN_DEF_AUTH
1397         || s1 == OPENVPN_PLUGIN_FUNC_DEFERRED
1398#endif
1399         ) && s2
1400#ifdef MANAGEMENT_DEF_AUTH
1401        && man_def_auth != KMDA_ERROR
1402#endif
1403        && tls_lock_username(multi, up->username))
1404    {
1405        ks->authenticated = true;
1406#ifdef PLUGIN_DEF_AUTH
1407        if (s1 == OPENVPN_PLUGIN_FUNC_DEFERRED)
1408        {
1409            ks->auth_deferred = true;
1410        }
1411#endif
1412#ifdef MANAGEMENT_DEF_AUTH
1413        if (man_def_auth != KMDA_UNDEF)
1414        {
1415            ks->auth_deferred = true;
1416        }
1417#endif
1418
1419        if ((session->opt->auth_token_generate) && (NULL == multi->auth_token))
1420        {
1421            /* Server is configured with --auth-gen-token but no token has yet
1422             * been generated for this client.  Generate one and save it.
1423             */
1424            uint8_t tok[AUTH_TOKEN_SIZE];
1425
1426            if (!rand_bytes(tok, AUTH_TOKEN_SIZE))
1427            {
1428                msg( M_FATAL, "Failed to get enough randomness for "
1429                     "authentication token");
1430            }
1431
1432            /* The token should be longer than the input when
1433             * being base64 encoded
1434             */
1435            ASSERT(openvpn_base64_encode(tok, AUTH_TOKEN_SIZE,
1436                                         &multi->auth_token) > AUTH_TOKEN_SIZE);
1437            multi->auth_token_tstamp = now;
1438            dmsg(D_SHOW_KEYS, "Generated token for client: %s",
1439                 multi->auth_token);
1440        }
1441
1442        if ((session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME))
1443        {
1444            set_common_name(session, up->username);
1445        }
1446
1447#ifdef ENABLE_DEF_AUTH
1448        msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
1449            ks->auth_deferred ? "deferred" : "succeeded",
1450            up->username,
1451            (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
1452#else
1453        msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
1454            "succeeded",
1455            up->username,
1456            (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
1457#endif
1458    }
1459    else
1460    {
1461        msg(D_TLS_ERRORS, "TLS Auth Error: Auth Username/Password verification failed for peer");
1462    }
1463
1464done:
1465    gc_free(&gc);
1466}
1467
1468void
1469verify_final_auth_checks(struct tls_multi *multi, struct tls_session *session)
1470{
1471    struct key_state *ks = &session->key[KS_PRIMARY];      /* primary key */
1472
1473    /* While it shouldn't really happen, don't allow the common name to be NULL */
1474    if (!session->common_name)
1475    {
1476        set_common_name(session, "");
1477    }
1478
1479    /* Don't allow the CN to change once it's been locked */
1480    if (ks->authenticated && multi->locked_cn)
1481    {
1482        const char *cn = session->common_name;
1483        if (cn && strcmp(cn, multi->locked_cn))
1484        {
1485            msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
1486                multi->locked_cn,
1487                cn);
1488
1489            /* change the common name back to its original value and disable the tunnel */
1490            set_common_name(session, multi->locked_cn);
1491            tls_deauthenticate(multi);
1492        }
1493    }
1494
1495    /* Don't allow the cert hashes to change once they have been locked */
1496    if (ks->authenticated && multi->locked_cert_hash_set)
1497    {
1498        const struct cert_hash_set *chs = session->cert_hash_set;
1499        if (chs && !cert_hash_compare(chs, multi->locked_cert_hash_set))
1500        {
1501            msg(D_TLS_ERRORS, "TLS Auth Error: TLS object CN=%s client-provided SSL certs unexpectedly changed during mid-session reauth",
1502                session->common_name);
1503
1504            /* disable the tunnel */
1505            tls_deauthenticate(multi);
1506        }
1507    }
1508
1509    /* verify --client-config-dir based authentication */
1510    if (ks->authenticated && session->opt->client_config_dir_exclusive)
1511    {
1512        struct gc_arena gc = gc_new();
1513
1514        const char *cn = session->common_name;
1515        const char *path = gen_path(session->opt->client_config_dir_exclusive, cn, &gc);
1516        if (!cn || !strcmp(cn, CCD_DEFAULT) || !test_file(path))
1517        {
1518            ks->authenticated = false;
1519            wipe_auth_token(multi);
1520            msg(D_TLS_ERRORS, "TLS Auth Error: --client-config-dir authentication failed for common name '%s' file='%s'",
1521                session->common_name,
1522                path ? path : "UNDEF");
1523        }
1524
1525        gc_free(&gc);
1526    }
1527}
1528
1529void
1530tls_x509_clear_env(struct env_set *es)
1531{
1532    struct env_item *item = es->list;
1533    while (item)
1534    {
1535        struct env_item *next = item->next;
1536        if (item->string
1537            && 0 == strncmp("X509_", item->string, strlen("X509_")))
1538        {
1539            env_set_del(es, item->string);
1540        }
1541        item = next;
1542    }
1543}
1544
1545#endif /* ENABLE_CRYPTO */