yassl_int.cpp 45.4 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/* yassl_int.cpp                                
 *
 * Copyright (C) 2003 Sawtooth Consulting Ltd.
 *
 * This file is part of yaSSL.
 *
 * yaSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * yaSSL 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */


/* yaSSL internal source implements SSL supporting types not specified in the
 * draft along with type conversion functions.
 */

#include "runtime.hpp"
#include "yassl_int.hpp"
#include "handshake.hpp"
#include "timer.hpp"
#include "openssl/ssl.h"  // for DH



namespace yaSSL {


using mySTL::min;



// convert a 32 bit integer into a 24 bit one
void c32to24(uint32 u32, uint24& u24)
{
    u24[0] = (u32 >> 16) & 0xff;
    u24[1] = (u32 >>  8) & 0xff;
    u24[2] =  u32 & 0xff;
}


// convert a 24 bit integer into a 32 bit one
void c24to32(const uint24 u24, uint32& u32)
{
    u32 = 0;
    u32 = (u24[0] << 16) | (u24[1] << 8) | u24[2];
}


// convert with return for ease of use
uint32 c24to32(const uint24 u24)
{
    uint32 ret;
    c24to32(u24, ret);

    return ret;
}


// using a for opaque since underlying type is unsgined char and o is not a
// good leading identifier

// convert opaque to 16 bit integer
void ato16(const opaque* c, uint16& u16)
{
    u16 = 0;
    u16 = (c[0] << 8) | (c[1]);
}


// convert (copy) opaque to 24 bit integer
void ato24(const opaque* c, uint24& u24)
{
    u24[0] = c[0];
    u24[1] = c[1];
    u24[2] = c[2];
}


// convert 16 bit integer to opaque
void c16toa(uint16 u16, opaque* c)
{
    c[0] = (u16 >> 8) & 0xff;
    c[1] =  u16 & 0xff;
}


// convert 24 bit integer to opaque
void c24toa(const uint24 u24, opaque* c)
{
    c[0] =  u24[0]; 
    c[1] =  u24[1];
    c[2] =  u24[2];
}


// convert 32 bit integer to opaque
void c32toa(uint32 u32, opaque* c)
{
    c[0] = (u32 >> 24) & 0xff;
    c[1] = (u32 >> 16) & 0xff;
    c[2] = (u32 >>  8) & 0xff;
    c[3] =  u32 & 0xff;
}


States::States() : recordLayer_(recordReady), handshakeLayer_(preHandshake),
           clientState_(serverNull),  serverState_(clientNull),
           what_(no_error) {}

const RecordLayerState& States::getRecord() const 
{
    return recordLayer_;
}


const HandShakeState& States::getHandShake() const
{
    return handshakeLayer_;
}


const ClientState& States::getClient() const
{
    return clientState_;
}


const ServerState& States::getServer() const
{
    return serverState_;
}


const char* States::getString() const
{
    return errorString_;
}


YasslError States::What() const
{
    return what_;
}


RecordLayerState& States::useRecord()
{
    return recordLayer_;
}


HandShakeState& States::useHandShake()
{
    return handshakeLayer_;
}


ClientState& States::useClient()
{
    return clientState_;
}


ServerState& States::useServer()
{
    return serverState_;
}


char* States::useString()
{
    return errorString_;
}


void States::SetError(YasslError ye)
{
    what_ = ye;
}


sslFactory::sslFactory() :           
        messageFactory_(InitMessageFactory),
        handShakeFactory_(InitHandShakeFactory),
        serverKeyFactory_(InitServerKeyFactory),
        clientKeyFactory_(InitClientKeyFactory) 
{}


const MessageFactory& sslFactory::getMessage() const
{
    return messageFactory_;
}


const HandShakeFactory& sslFactory::getHandShake() const
{
    return handShakeFactory_;
}


const ServerKeyFactory& sslFactory::getServerKey() const
{
    return serverKeyFactory_;
}


const ClientKeyFactory& sslFactory::getClientKey() const
{
    return clientKeyFactory_;
}


// extract context parameters and store
SSL::SSL(SSL_CTX* ctx) 
    : secure_(ctx->getMethod()->getVersion(), crypto_.use_random(),
              ctx->getMethod()->getSide(), ctx->GetCiphers(), ctx)
{
    if (int err = crypto_.get_random().GetError()) {
        SetError(YasslError(err));
        return;
    }

    CertManager& cm = crypto_.use_certManager();
    cm.CopySelfCert(ctx->getCert());

    bool serverSide = secure_.use_parms().entity_ == server_end;

    if (ctx->getKey()) {
        if (int err = cm.SetPrivateKey(*ctx->getKey())) {
            SetError(YasslError(err));
            return;
        }
    }
    else if (serverSide) {
        SetError(no_key_file);
        return;
    }

    if (ctx->getMethod()->verifyPeer())
        cm.setVerifyPeer();
    if (ctx->getMethod()->failNoCert())
        cm.setFailNoCert();

    if (serverSide)
        crypto_.SetDH(ctx->GetDH_Parms());

    const SSL_CTX::CertList& ca = ctx->GetCA_List();
    SSL_CTX::CertList::const_iterator first(ca.begin());
    SSL_CTX::CertList::const_iterator last(ca.end());

    while (first != last) {
        if (int err = cm.CopyCaCert(*first)) {
            SetError(YasslError(err));
            return;
        }
        ++first;
    }
}


// store pending security parameters from Server Hello
void SSL::set_pending(Cipher suite)
{
    Parameters& parms = secure_.use_parms();

    switch (suite) {

    case TLS_RSA_WITH_AES_256_CBC_SHA:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = AES_256_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
287 288
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new AES(AES_256_KEY_SZ));
289 290 291 292 293 294 295 296 297 298 299 300
        strncpy(parms.cipher_name_, cipher_names[TLS_RSA_WITH_AES_256_CBC_SHA],
                MAX_SUITE_NAME);
        break;

    case TLS_RSA_WITH_AES_128_CBC_SHA:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = AES_128_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
301 302
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new AES);
303 304 305 306 307 308 309 310 311 312 313 314
        strncpy(parms.cipher_name_, cipher_names[TLS_RSA_WITH_AES_128_CBC_SHA],
                MAX_SUITE_NAME);
        break;

    case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
        parms.bulk_cipher_algorithm_ = triple_des;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = DES_EDE_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
315 316
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new DES_EDE);
317 318 319 320 321 322 323 324 325 326 327 328
        strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_3DES_EDE_CBC_SHA]
                , MAX_SUITE_NAME);
        break;

    case SSL_RSA_WITH_DES_CBC_SHA:
        parms.bulk_cipher_algorithm_ = des;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = DES_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
329 330
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new DES);
331 332 333 334 335 336 337 338 339 340 341 342
        strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_DES_CBC_SHA],
                MAX_SUITE_NAME);
        break;

    case SSL_RSA_WITH_RC4_128_SHA:
        parms.bulk_cipher_algorithm_ = rc4;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = RC4_KEY_SZ;
        parms.iv_size_   = 0;
        parms.cipher_type_ = stream;
unknown's avatar
unknown committed
343 344
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new RC4);
345 346 347 348 349 350 351 352 353 354 355 356
        strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_RC4_128_SHA],
                MAX_SUITE_NAME);
        break;

    case SSL_RSA_WITH_RC4_128_MD5:
        parms.bulk_cipher_algorithm_ = rc4;
        parms.mac_algorithm_         = md5;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = MD5_LEN;
        parms.key_size_  = RC4_KEY_SZ;
        parms.iv_size_   = 0;
        parms.cipher_type_ = stream;
unknown's avatar
unknown committed
357 358
        crypto_.setDigest(new MD5);
        crypto_.setCipher(new RC4);
359 360 361 362 363 364 365 366 367 368 369 370 371 372
        strncpy(parms.cipher_name_, cipher_names[SSL_RSA_WITH_RC4_128_MD5],
                MAX_SUITE_NAME);
        break;

    case SSL_DHE_RSA_WITH_DES_CBC_SHA:
        parms.bulk_cipher_algorithm_ = des;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = DES_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
373 374
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new DES);
375 376 377 378 379 380 381 382 383 384 385 386 387 388
        strncpy(parms.cipher_name_, cipher_names[SSL_DHE_RSA_WITH_DES_CBC_SHA],
                MAX_SUITE_NAME);
        break;

    case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
        parms.bulk_cipher_algorithm_ = triple_des;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = DES_EDE_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
389 390
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new DES_EDE);
391 392 393 394 395 396 397 398 399 400 401 402 403 404
        strncpy(parms.cipher_name_,
              cipher_names[SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA], MAX_SUITE_NAME);
        break;

    case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = AES_256_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
405 406
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new AES(AES_256_KEY_SZ));
407 408 409 410 411 412 413 414 415 416 417 418 419 420
        strncpy(parms.cipher_name_,
               cipher_names[TLS_DHE_RSA_WITH_AES_256_CBC_SHA], MAX_SUITE_NAME);
        break;

    case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = AES_128_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
421 422
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new AES);
423 424 425 426 427 428 429 430 431 432 433 434 435 436
        strncpy(parms.cipher_name_,
               cipher_names[TLS_DHE_RSA_WITH_AES_128_CBC_SHA], MAX_SUITE_NAME);
        break;

    case SSL_DHE_DSS_WITH_DES_CBC_SHA:
        parms.bulk_cipher_algorithm_ = des;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = DES_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
437 438
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new DES);
439 440 441 442 443 444 445 446 447 448 449 450 451 452
        strncpy(parms.cipher_name_, cipher_names[SSL_DHE_DSS_WITH_DES_CBC_SHA],
                MAX_SUITE_NAME);
        break;

    case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
        parms.bulk_cipher_algorithm_ = triple_des;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = DES_EDE_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
453 454
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new DES_EDE);
455 456 457 458 459 460 461 462 463 464 465 466 467 468
        strncpy(parms.cipher_name_,
              cipher_names[SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA], MAX_SUITE_NAME);
        break;

    case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = AES_256_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
469 470
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new AES(AES_256_KEY_SZ));
471 472 473 474 475 476 477 478 479 480 481 482 483 484
        strncpy(parms.cipher_name_,
               cipher_names[TLS_DHE_DSS_WITH_AES_256_CBC_SHA], MAX_SUITE_NAME);
        break;

    case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = sha;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = SHA_LEN;
        parms.key_size_  = AES_128_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
485 486
        crypto_.setDigest(new SHA);
        crypto_.setCipher(new AES);
487 488 489 490 491 492 493 494 495 496 497 498
        strncpy(parms.cipher_name_,
               cipher_names[TLS_DHE_DSS_WITH_AES_128_CBC_SHA], MAX_SUITE_NAME);
        break;

    case TLS_RSA_WITH_AES_256_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = AES_256_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
499 500
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new AES(AES_256_KEY_SZ));
501 502 503 504 505 506 507 508 509 510 511 512
        strncpy(parms.cipher_name_,
                cipher_names[TLS_RSA_WITH_AES_256_CBC_RMD160], MAX_SUITE_NAME);
        break;

    case TLS_RSA_WITH_AES_128_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = AES_128_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
513 514
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new AES);
515 516 517 518 519 520 521 522 523 524 525 526
        strncpy(parms.cipher_name_,
                cipher_names[TLS_RSA_WITH_AES_128_CBC_RMD160], MAX_SUITE_NAME);
        break;

    case TLS_RSA_WITH_3DES_EDE_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = triple_des;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = rsa_kea;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = DES_EDE_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
unknown's avatar
unknown committed
527 528
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new DES_EDE);
529 530 531 532 533 534 535 536 537 538 539 540 541 542
        strncpy(parms.cipher_name_,
               cipher_names[TLS_RSA_WITH_3DES_EDE_CBC_RMD160], MAX_SUITE_NAME);
        break;

    case TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = triple_des;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = DES_EDE_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
543 544
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new DES_EDE);
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        strncpy(parms.cipher_name_,
                cipher_names[TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD160],
                MAX_SUITE_NAME);
        break;

    case TLS_DHE_RSA_WITH_AES_256_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = AES_256_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
560 561
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new AES(AES_256_KEY_SZ));
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
        strncpy(parms.cipher_name_,
                cipher_names[TLS_DHE_RSA_WITH_AES_256_CBC_RMD160],
                MAX_SUITE_NAME);
        break;

    case TLS_DHE_RSA_WITH_AES_128_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = rsa_sa_algo;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = AES_128_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
577 578
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new AES);
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
        strncpy(parms.cipher_name_,
                cipher_names[TLS_DHE_RSA_WITH_AES_128_CBC_RMD160],
                MAX_SUITE_NAME);
        break;

    case TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = triple_des;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = DES_EDE_KEY_SZ;
        parms.iv_size_   = DES_IV_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
594 595
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new DES_EDE);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
        strncpy(parms.cipher_name_,
                cipher_names[TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD160],
                MAX_SUITE_NAME);
        break;

    case TLS_DHE_DSS_WITH_AES_256_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = AES_256_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
611 612
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new AES(AES_256_KEY_SZ));
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
        strncpy(parms.cipher_name_,
                cipher_names[TLS_DHE_DSS_WITH_AES_256_CBC_RMD160],
                MAX_SUITE_NAME);
        break;

    case TLS_DHE_DSS_WITH_AES_128_CBC_RMD160:
        parms.bulk_cipher_algorithm_ = aes;
        parms.mac_algorithm_         = rmd;
        parms.kea_                   = diffie_hellman_kea;
        parms.sig_algo_              = dsa_sa_algo;
        parms.hash_size_ = RMD_LEN;
        parms.key_size_  = AES_128_KEY_SZ;
        parms.iv_size_   = AES_BLOCK_SZ;
        parms.cipher_type_ = block;
        secure_.use_connection().send_server_key_  = true; // eph
unknown's avatar
unknown committed
628 629
        crypto_.setDigest(new RMD);
        crypto_.setCipher(new AES);
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 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 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 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
        strncpy(parms.cipher_name_,
                cipher_names[TLS_DHE_DSS_WITH_AES_128_CBC_RMD160],
                MAX_SUITE_NAME);
        break;

    default:
        SetError(unknown_cipher);
    }
}


// store peer's random
void SSL::set_random(const opaque* random, ConnectionEnd sender)
{
    if (sender == client_end)
        memcpy(secure_.use_connection().client_random_, random, RAN_LEN);
    else
        memcpy(secure_.use_connection().server_random_, random, RAN_LEN);
}


// store client pre master secret
void SSL::set_preMaster(const opaque* pre, uint sz)
{
    secure_.use_connection().AllocPreSecret(sz);
    memcpy(secure_.use_connection().pre_master_secret_, pre, sz);
}


// store master secret
void SSL::set_masterSecret(const opaque* sec)
{
    memcpy(secure_.use_connection().master_secret_, sec, SECRET_LEN);
}

// store server issued id
void SSL::set_sessionID(const opaque* sessionID)
{
    memcpy(secure_.use_connection().sessionID_, sessionID, ID_LEN);
}


// store error 
void SSL::SetError(YasslError ye)
{
    states_.SetError(ye);
    //strncpy(states_.useString(), e.what(), mySTL::named_exception::NAME_SIZE);
    // TODO: add string here
}


// locals
namespace {

// DeriveKeys and MasterSecret helper sets prefix letters
static bool setPrefix(opaque* sha_input, int i)
{
    switch (i) {
    case 0:
        memcpy(sha_input, "A", 1);
        break;
    case 1:
        memcpy(sha_input, "BB", 2);
        break;
    case 2:
        memcpy(sha_input, "CCC", 3);
        break;
    case 3:
        memcpy(sha_input, "DDDD", 4);
        break;
    case 4:
        memcpy(sha_input, "EEEEE", 5);
        break;
    case 5:
        memcpy(sha_input, "FFFFFF", 6);
        break;
    case 6:
        memcpy(sha_input, "GGGGGGG", 7);
        break;
    default:
        return false;  // prefix_error
    }
    return true;
}


const char handshake_order[] = "Out of order HandShake Message!";


} // namespcae for locals


void SSL::order_error()
{
    SetError(out_of_order);
}


// Create and store the master secret see page 32, 6.1
void SSL::makeMasterSecret()
{
    if (isTLS())
        makeTLSMasterSecret();
    else {
        opaque sha_output[SHA_LEN];

        const uint& preSz = secure_.get_connection().pre_secret_len_;
        output_buffer md5_input(preSz + SHA_LEN);
        output_buffer sha_input(PREFIX + preSz + 2 * RAN_LEN);

        MD5 md5;
        SHA sha;

        md5_input.write(secure_.get_connection().pre_master_secret_, preSz);

        for (int i = 0; i < MASTER_ROUNDS; ++i) {
            opaque prefix[PREFIX];
            if (!setPrefix(prefix, i)) {
                SetError(prefix_error);
                return;
            }

            sha_input.set_current(0);
            sha_input.write(prefix, i + 1);

            sha_input.write(secure_.get_connection().pre_master_secret_,preSz);
            sha_input.write(secure_.get_connection().client_random_, RAN_LEN);
            sha_input.write(secure_.get_connection().server_random_, RAN_LEN);
            sha.get_digest(sha_output, sha_input.get_buffer(),
                           sha_input.get_size());

            md5_input.set_current(preSz);
            md5_input.write(sha_output, SHA_LEN);
            md5.get_digest(&secure_.use_connection().master_secret_[i*MD5_LEN],
                           md5_input.get_buffer(), md5_input.get_size());
        }
        deriveKeys();
    }
    secure_.use_connection().CleanPreMaster();
}


// create TLSv1 master secret
void SSL::makeTLSMasterSecret()
{
    opaque seed[SEED_LEN];
    
    memcpy(seed, secure_.get_connection().client_random_, RAN_LEN);
    memcpy(&seed[RAN_LEN], secure_.get_connection().server_random_, RAN_LEN);

    PRF(secure_.use_connection().master_secret_, SECRET_LEN,
        secure_.get_connection().pre_master_secret_,
        secure_.get_connection().pre_secret_len_,
        master_label, MASTER_LABEL_SZ, 
        seed, SEED_LEN);

    deriveTLSKeys();
}


// derive mac, write, and iv keys for server and client, see page 34, 6.2.2
void SSL::deriveKeys()
{
    int length = 2 * secure_.get_parms().hash_size_ + 
                 2 * secure_.get_parms().key_size_  +
                 2 * secure_.get_parms().iv_size_;
    int rounds = length / MD5_LEN + ((length % MD5_LEN) ? 1 : 0);
    input_buffer key_data(rounds * MD5_LEN);

    opaque sha_output[SHA_LEN];
    opaque md5_input[SECRET_LEN + SHA_LEN];
    opaque sha_input[KEY_PREFIX + SECRET_LEN + 2 * RAN_LEN];
  
    MD5 md5;
    SHA sha;

    memcpy(md5_input, secure_.get_connection().master_secret_, SECRET_LEN);

    for (int i = 0; i < rounds; ++i) {
        int j = i + 1;
        if (!setPrefix(sha_input, i)) {
            SetError(prefix_error);
            return;
        }

        memcpy(&sha_input[j], secure_.get_connection().master_secret_,
               SECRET_LEN);
        memcpy(&sha_input[j+SECRET_LEN],
               secure_.get_connection().server_random_, RAN_LEN);
        memcpy(&sha_input[j + SECRET_LEN + RAN_LEN],
               secure_.get_connection().client_random_, RAN_LEN);
        sha.get_digest(sha_output, sha_input,
                       sizeof(sha_input) - KEY_PREFIX + j);

        memcpy(&md5_input[SECRET_LEN], sha_output, SHA_LEN);
        md5.get_digest(key_data.get_buffer() + i * MD5_LEN,
                       md5_input, sizeof(md5_input));
    }
    storeKeys(key_data.get_buffer());
}


// derive mac, write, and iv keys for server and client
void SSL::deriveTLSKeys()
{
    int length = 2 * secure_.get_parms().hash_size_ + 
                 2 * secure_.get_parms().key_size_  +
                 2 * secure_.get_parms().iv_size_;
    opaque       seed[SEED_LEN];
    input_buffer key_data(length);

    memcpy(seed, secure_.get_connection().server_random_, RAN_LEN);
    memcpy(&seed[RAN_LEN], secure_.get_connection().client_random_, RAN_LEN);

    PRF(key_data.get_buffer(), length, secure_.get_connection().master_secret_,
        SECRET_LEN, key_label, KEY_LABEL_SZ, seed, SEED_LEN);

    storeKeys(key_data.get_buffer());
}


// store mac, write, and iv keys for client and server
void SSL::storeKeys(const opaque* key_data)
{
    int sz = secure_.get_parms().hash_size_;
    memcpy(secure_.use_connection().client_write_MAC_secret_, key_data, sz);
    int i = sz;
    memcpy(secure_.use_connection().server_write_MAC_secret_,&key_data[i], sz);
    i += sz;

    sz = secure_.get_parms().key_size_;
    memcpy(secure_.use_connection().client_write_key_, &key_data[i], sz);
    i += sz;
    memcpy(secure_.use_connection().server_write_key_, &key_data[i], sz);
    i += sz;

    sz = secure_.get_parms().iv_size_;
    memcpy(secure_.use_connection().client_write_IV_, &key_data[i], sz);
    i += sz;
    memcpy(secure_.use_connection().server_write_IV_, &key_data[i], sz);

    setKeys();
}


// set encrypt/decrypt keys and ivs
void SSL::setKeys()
{
    Connection& conn = secure_.use_connection();

    if (secure_.get_parms().entity_ == client_end) {
        crypto_.use_cipher().set_encryptKey(conn.client_write_key_, 
                                            conn.client_write_IV_);
        crypto_.use_cipher().set_decryptKey(conn.server_write_key_,
                                            conn.server_write_IV_);
    }
    else {
        crypto_.use_cipher().set_encryptKey(conn.server_write_key_,
                                            conn.server_write_IV_);
        crypto_.use_cipher().set_decryptKey(conn.client_write_key_,
                                            conn.client_write_IV_);
    }
}



// local functors
unknown's avatar
unknown committed
897
namespace yassl_int_cpp_local1 {
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

struct SumData {
    uint total_;
    SumData() : total_(0) {}
    void operator()(input_buffer* data) { total_ += data->get_remaining(); }
};


struct SumBuffer {
    uint total_;
    SumBuffer() : total_(0) {}
    void operator()(output_buffer* buffer) { total_ += buffer->get_size(); }
};

} // namespace for locals
unknown's avatar
unknown committed
913
using namespace yassl_int_cpp_local1;
914

unknown's avatar
unknown committed
915

916 917 918 919 920 921
uint SSL::bufferedData()
{
    return mySTL::for_each(buffers_.getData().begin(),buffers_.getData().end(),
                           SumData()).total_;
}

unknown's avatar
unknown committed
922

923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 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 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 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 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 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 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 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 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
// use input buffer to fill data
void SSL::fillData(Data& data)
{
    if (GetError()) return;
    uint dataSz   = data.get_length();        // input, data size to fill
    uint elements = buffers_.getData().size();

    data.set_length(0);                         // output, actual data filled
    dataSz = min(dataSz, bufferedData());

    for (uint i = 0; i < elements; i++) {
        input_buffer* front = buffers_.getData().front();
        uint frontSz = front->get_remaining();
        uint readSz  = min(dataSz - data.get_length(), frontSz);

        front->read(data.set_buffer() + data.get_length(), readSz);
        data.set_length(data.get_length() + readSz);

        if (readSz == frontSz) {
            buffers_.useData().pop_front();
            delete front;
        }
        if (data.get_length() == dataSz)
            break;
    }
}


// flush output buffer
void SSL::flushBuffer()
{
    if (GetError()) return;

    uint sz = mySTL::for_each(buffers_.getHandShake().begin(),
                            buffers_.getHandShake().end(),
                            SumBuffer()).total_;
    output_buffer out(sz);
    uint elements = buffers_.getHandShake().size();

    for (uint i = 0; i < elements; i++) {
        output_buffer* front = buffers_.getHandShake().front();
        out.write(front->get_buffer(), front->get_size());

        buffers_.useHandShake().pop_front();
        delete front;
    }
    Send(out.get_buffer(), out.get_size());
}


void SSL::Send(const byte* buffer, uint sz)
{
    if (socket_.send(buffer, sz) != sz)
        SetError(send_error);
}


// get sequence number, if verify get peer's
uint SSL::get_SEQIncrement(bool verify) 
{ 
    if (verify)
        return secure_.use_connection().peer_sequence_number_++; 
    else
        return secure_.use_connection().sequence_number_++; 
}


const byte* SSL::get_macSecret(bool verify)
{
    if ( (secure_.get_parms().entity_ == client_end && !verify) ||
         (secure_.get_parms().entity_ == server_end &&  verify) )
        return secure_.get_connection().client_write_MAC_secret_;
    else
        return secure_.get_connection().server_write_MAC_secret_;
}


void SSL::verifyState(const RecordLayerHeader& rlHeader)
{
    if (GetError()) return;

    if (states_.getRecord() == recordNotReady || 
            (rlHeader.type_ == application_data &&        // data and handshake
             states_.getHandShake() != handShakeReady) )  // isn't complete yet
              SetError(record_layer);
}


void SSL::verifyState(const HandShakeHeader& hsHeader)
{
    if (GetError()) return;

    if (states_.getHandShake() == handShakeNotReady) {
        SetError(handshake_layer);
        return;
    }

    if (secure_.get_parms().entity_ == client_end)
        verifyClientState(hsHeader.get_handshakeType());
    else
        verifyServerState(hsHeader.get_handshakeType());
}


void SSL::verifyState(ClientState cs)
{
    if (GetError()) return;
    if (states_.getClient() != cs) order_error();
}


void SSL::verifyState(ServerState ss)
{
    if (GetError()) return;
    if (states_.getServer() != ss) order_error();
}


void SSL::verfiyHandShakeComplete()
{
    if (GetError()) return;
    if (states_.getHandShake() != handShakeReady) order_error();
}


void SSL::verifyClientState(HandShakeType hsType)
{
    if (GetError()) return;

    switch(hsType) {
    case server_hello :
        if (states_.getClient() != serverNull)
            order_error();
        break;
    case certificate :
        if (states_.getClient() != serverHelloComplete)
            order_error();
        break;
    case server_key_exchange :
        if (states_.getClient() != serverCertComplete)
            order_error();
        break;
    case certificate_request :
        if (states_.getClient() != serverCertComplete &&
            states_.getClient() != serverKeyExchangeComplete)
            order_error();
        break;
    case server_hello_done :
        if (states_.getClient() != serverCertComplete &&
            states_.getClient() != serverKeyExchangeComplete)
            order_error();
        break;
    case finished :
        if (states_.getClient() != serverHelloDoneComplete || 
            secure_.get_parms().pending_)    // no change
                order_error();          // cipher yet
        break;
    default :
        order_error();
    };
}


void SSL::verifyServerState(HandShakeType hsType)
{
    if (GetError()) return;

    switch(hsType) {
    case client_hello :
        if (states_.getServer() != clientNull)
            order_error();
        break;
    case certificate :
        if (states_.getServer() != clientHelloComplete)
            order_error();
        break;
    case client_key_exchange :
        if (states_.getServer() != clientHelloComplete)
            order_error();
        break;
    case certificate_verify :
        if (states_.getServer() != clientKeyExchangeComplete)
            order_error();
        break;
    case finished :
        if (states_.getServer() != clientKeyExchangeComplete || 
            secure_.get_parms().pending_)    // no change
                order_error();               // cipher yet
        break;
    default :
        order_error();
    };
}


// try to find a suite match
void SSL::matchSuite(const opaque* peer, uint length)
{
    if (length == 0 || (length % 2) != 0) {
        SetError(bad_input);
        return;
    }

    // start with best, if a match we are good, Ciphers are at odd index
    // since all SSL and TLS ciphers have 0x00 first byte
    for (uint i = 1; i < secure_.get_parms().suites_size_; i += 2)
        for (uint j = 1; j < length; j+= 2)
            if (secure_.use_parms().suites_[i] == peer[j]) {
                secure_.use_parms().suite_[0] = 0x00;
                secure_.use_parms().suite_[1] = peer[j];
                return;
            }

    SetError(match_error);
}


void SSL::set_session(SSL_SESSION* s) 
{ 
    if (s && GetSessions().lookup(s->GetID(), &secure_.use_resume()))
        secure_.set_resuming(true);
}


const Crypto& SSL::getCrypto() const
{
    return crypto_;
}


const Security& SSL::getSecurity() const
{
    return secure_;
}


const States& SSL::getStates() const
{
    return states_;
}


const sslHashes& SSL::getHashes() const
{
    return hashes_;
}


const sslFactory& SSL::getFactory() const
{
    return GetSSL_Factory();
}


const Socket& SSL::getSocket() const
{
    return socket_;
}


YasslError SSL::GetError() const
{
    return states_.What();
}


Crypto& SSL::useCrypto()
{
    return crypto_;
}


Security& SSL::useSecurity()
{
    return secure_;
}


States& SSL::useStates()
{
    return states_;
}


sslHashes& SSL::useHashes()
{
    return hashes_;
}


Socket& SSL::useSocket()
{
    return socket_;
}


Log& SSL::useLog()
{
    return log_;
}


bool SSL::isTLS() const
{
    return secure_.get_connection().TLS_;
}


void SSL::addData(input_buffer* data)
{
    buffers_.useData().push_back(data);
}


void SSL::addBuffer(output_buffer* b)
{
    buffers_.useHandShake().push_back(b);
}


// store connection parameters
SSL_SESSION::SSL_SESSION(const SSL& ssl, RandomPool& ran) 
    : timeout_(DEFAULT_TIMEOUT), random_(ran)
{
    const Connection& conn = ssl.getSecurity().get_connection();

    memcpy(sessionID_, conn.sessionID_, ID_LEN);
    memcpy(master_secret_, conn.master_secret_, SECRET_LEN);
    memcpy(suite_, ssl.getSecurity().get_parms().suite_, SUITE_LEN);

    bornOn_ = lowResTimer();
}


// for resumption copy in ssl::parameters
SSL_SESSION::SSL_SESSION(RandomPool& ran) 
    : bornOn_(0), timeout_(0), random_(ran)
{
    memset(sessionID_, 0, ID_LEN);
    memset(master_secret_, 0, SECRET_LEN);
    memset(suite_, 0, SUITE_LEN);
}


SSL_SESSION& SSL_SESSION::operator=(const SSL_SESSION& that)
{
    memcpy(sessionID_, that.sessionID_, ID_LEN);
    memcpy(master_secret_, that.master_secret_, SECRET_LEN);
    memcpy(suite_, that.suite_, SUITE_LEN);
    
    bornOn_  = that.bornOn_;
    timeout_ = that.timeout_;

    return *this;
}


const opaque* SSL_SESSION::GetID() const
{
    return sessionID_;
}


const opaque* SSL_SESSION::GetSecret() const
{
    return master_secret_;
}


const Cipher* SSL_SESSION::GetSuite() const
{
    return suite_;
}


uint SSL_SESSION::GetBornOn() const
{
    return bornOn_;
}


uint SSL_SESSION::GetTimeOut() const
{
    return timeout_;
}


void SSL_SESSION::SetTimeOut(uint t)
{
    timeout_ = t;
}


extern void clean(volatile opaque*, uint, RandomPool&);


// clean up secret data
SSL_SESSION::~SSL_SESSION()
{
    volatile opaque* p = master_secret_;
    clean(p, SECRET_LEN, random_);
}


unknown's avatar
unknown committed
1327 1328
Sessions Sessions::instance; // simple singleton

1329 1330
Sessions& GetSessions()
{
unknown's avatar
unknown committed
1331
    return Sessions::instance;
1332 1333
}

unknown's avatar
unknown committed
1334
sslFactory sslFactory::instance;
1335 1336 1337

sslFactory& GetSSL_Factory()
{   
unknown's avatar
unknown committed
1338
    return sslFactory::instance;
1339 1340 1341 1342 1343 1344 1345 1346 1347
}


typedef Mutex::Lock Lock;

 
void Sessions::add(const SSL& ssl) 
{
    Lock guard(mutex_);
unknown's avatar
unknown committed
1348
    list_.push_back(new SSL_SESSION(ssl, random_));
1349 1350 1351 1352 1353 1354 1355 1356 1357
}


Sessions::~Sessions() 
{ 
    mySTL::for_each(list_.begin(), list_.end(), del_ptr_zero()); 
}


unknown's avatar
unknown committed
1358
namespace yassl_int_cpp_local2 { // locals
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

typedef mySTL::list<SSL_SESSION*>::iterator iterator;

struct sess_match {
    const opaque* id_;
    explicit sess_match(const opaque* p) : id_(p) {}

    bool operator()(SSL_SESSION* sess)
    {
        if ( memcmp(sess->GetID(), id_, ID_LEN) == 0)
            return true;
        return false;
    }
};


} // local namespace
unknown's avatar
unknown committed
1376
using namespace yassl_int_cpp_local2;
1377

unknown's avatar
unknown committed
1378

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
// lookup session by id, return a copy if space provided
SSL_SESSION* Sessions::lookup(const opaque* id, SSL_SESSION* copy)
{
    Lock guard(mutex_);
    iterator find = mySTL::find_if(list_.begin(), list_.end(), sess_match(id));

    if (find != list_.end()) {
        uint current = lowResTimer();
        if ( ((*find)->GetBornOn() + (*find)->GetTimeOut()) < current) {
            del_ptr_zero()(*find);
            list_.erase(find);
            return 0;
        }
        if (copy)
            *copy = *(*find);
        return *find;
    }
    return 0;
}


// remove a session by id
void Sessions::remove(const opaque* id)
{
    Lock guard(mutex_);
    iterator find = mySTL::find_if(list_.begin(), list_.end(), sess_match(id));

    if (find != list_.end()) {
        del_ptr_zero()(*find);
        list_.erase(find);
    }
}


SSL_METHOD::SSL_METHOD(ConnectionEnd ce, ProtocolVersion pv) 
    : version_(pv), side_(ce), verifyPeer_(false), failNoCert_(false) 
{}


ProtocolVersion SSL_METHOD::getVersion() const
{
    return version_;
}


ConnectionEnd SSL_METHOD::getSide() const
{
    return side_;
}


void SSL_METHOD::setVerifyPeer()
{
    verifyPeer_ = true;
}


void SSL_METHOD::setFailNoCert()
{
    failNoCert_ = true;
}


bool SSL_METHOD::verifyPeer() const
{
    return verifyPeer_;
}


bool SSL_METHOD::failNoCert() const
{
    return failNoCert_;
}


SSL_CTX::SSL_CTX(SSL_METHOD* meth) 
    : method_(meth), certificate_(0), privateKey_(0)
{}


SSL_CTX::~SSL_CTX()
{
    delete method_;
    delete certificate_;
    delete privateKey_;

    mySTL::for_each(caList_.begin(), caList_.end(), del_ptr_zero());
}


void SSL_CTX::AddCA(x509* ca)
{
    caList_.push_back(ca);
}


const SSL_CTX::CertList& 
SSL_CTX::GetCA_List() const
{
    return caList_;
}


const x509* SSL_CTX::getCert() const
{
    return certificate_;
}


const x509* SSL_CTX::getKey() const
{
    return privateKey_;
}


const SSL_METHOD* SSL_CTX::getMethod() const
{
    return method_;
}


const Ciphers& SSL_CTX::GetCiphers() const
{
    return ciphers_;
}


const DH_Parms& SSL_CTX::GetDH_Parms() const
{
    return dhParms_;
}


const Stats& SSL_CTX::GetStats() const
{
    return stats_;
}


void SSL_CTX::setVerifyPeer()
{
    method_->setVerifyPeer();
}


void SSL_CTX::setFailNoCert()
{
    method_->setFailNoCert();
}


bool SSL_CTX::SetDH(const DH& dh)
{
    dhParms_.p_ = dh.p->int_;
    dhParms_.g_ = dh.g->int_;

    return dhParms_.set_ = true;
}


bool SSL_CTX::SetCipherList(const char* list)
{
    if (!list)
        return false;

    bool ret = false;
    char name[MAX_SUITE_NAME];

    char  needle[] = ":";
    char* haystack = const_cast<char*>(list);
    char* prev;

    const int suiteSz = sizeof(cipher_names) / sizeof(cipher_names[0]);
    int idx = 0;

    for(;;) {
        int len;
        prev = haystack;
        haystack = strstr(haystack, needle);

        if (!haystack)    // last cipher
            len = min(sizeof(name), strlen(prev));
        else
            len = min(sizeof(name), (size_t)(haystack - prev));

        strncpy(name, prev, len);
        name[(len == sizeof(name)) ? len - 1 : len] = 0;

        for (int i = 0; i < suiteSz; i++)
            if (strncmp(name, cipher_names[i], sizeof(name)) == 0) {

                ciphers_.suites_[idx++] = 0x00;  // first byte always zero
                ciphers_.suites_[idx++] = i;

                if (!ret) ret = true;   // found at least one
                break;
            }
        if (!haystack) break;
        haystack++;
    }

    if (ret) {
        ciphers_.setSuites_ = true;
        ciphers_.suiteSz_ = idx;
    }

    return ret;
}


void SSL_CTX::IncrementStats(StatsField fd)
{

    Lock guard(mutex_);
    
    switch (fd) {

	case Accept:
        ++stats_.accept_;
        break;

    case Connect:
        ++stats_.connect_;
        break;

    case AcceptGood:
        ++stats_.acceptGood_;
        break;

    case ConnectGood:
        ++stats_.connectGood_;
        break;

    case AcceptRenegotiate:
        ++stats_.acceptRenegotiate_;
        break;

    case ConnectRenegotiate:
        ++stats_.connectRenegotiate_;
        break;

    case Hits:
        ++stats_.hits_;
        break;

    case CbHits:
        ++stats_.cbHits_;
        break;

    case CacheFull:
        ++stats_.cacheFull_;
        break;

    case Misses:
        ++stats_.misses_;
        break;

    case Timeouts:
        ++stats_.timeouts_;
        break;

    case Number:
        ++stats_.number_;
        break;

    case GetCacheSize:
        ++stats_.getCacheSize_;
        break;

    case VerifyMode:
        ++stats_.verifyMode_;
        break;

    case VerifyDepth:
        ++stats_.verifyDepth_;
        break;

    default:
        break;
    }
}


Crypto::Crypto() 
    : digest_(0), cipher_(0), dh_(0) 
{}


Crypto::~Crypto()
{
    delete dh_;
    delete cipher_;
    delete digest_;
}


const Digest& Crypto::get_digest() const
{
    return *digest_;
}


const BulkCipher& Crypto::get_cipher() const
{
    return *cipher_;
}


const DiffieHellman& Crypto::get_dh() const
{
    return *dh_;
}


const RandomPool& Crypto::get_random() const
{
    return random_;
}


const CertManager& Crypto::get_certManager() const
{
    return cert_;
}


      
Digest& Crypto::use_digest()
{
    return *digest_;
}


BulkCipher& Crypto::use_cipher()
{
    return *cipher_;
}


DiffieHellman& Crypto::use_dh()
{
    return *dh_;
}


RandomPool& Crypto::use_random()
{
    return random_;
}


CertManager& Crypto::use_certManager()
{
    return cert_;
}



void Crypto::SetDH(DiffieHellman* dh)
{
    dh_ = dh;
}


void Crypto::SetDH(const DH_Parms& dh)
{
    if (dh.set_)
unknown's avatar
unknown committed
1746
        dh_ = new DiffieHellman(dh.p_, dh.g_, random_);
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
}


bool Crypto::DhSet()
{
    return dh_ != 0;
}


void Crypto::setDigest(Digest* digest)
{
    digest_ = digest;
}


void Crypto::setCipher(BulkCipher* c)
{
    cipher_ = c;
}


const MD5& sslHashes::get_MD5() const
{
    return md5HandShake_;
}


const SHA& sslHashes::get_SHA() const
{
    return shaHandShake_;
}


const Finished& sslHashes::get_verify() const
{
    return verify_;
}


const Hashes& sslHashes::get_certVerify() const
{
    return certVerify_;
}


MD5& sslHashes::use_MD5(){
    return md5HandShake_;
}


SHA& sslHashes::use_SHA()
{
    return shaHandShake_;
}


Finished& sslHashes::use_verify()
{
    return verify_;
}


Hashes& sslHashes::use_certVerify()
{
    return certVerify_;
}


Buffers::~Buffers()
{
    mySTL::for_each(handShakeList_.begin(), handShakeList_.end(),
                  del_ptr_zero()) ;
    mySTL::for_each(dataList_.begin(), dataList_.end(),
                  del_ptr_zero()) ;
}


const Buffers::inputList& Buffers::getData() const
{
    return dataList_;
}


const Buffers::outputList& Buffers::getHandShake() const
{
    return handShakeList_;
}


Buffers::inputList& Buffers::useData()
{
    return dataList_;
}


Buffers::outputList& Buffers::useHandShake()
{
    return handShakeList_;
}


Security::Security(ProtocolVersion pv, RandomPool& ran, ConnectionEnd ce,
                   const Ciphers& ciphers, SSL_CTX* ctx)
   : conn_(pv, ran), parms_(ce, ciphers, pv), resumeSession_(ran), ctx_(ctx),
     resuming_(false)
{}


const Connection& Security::get_connection() const
{
    return conn_;
}


const SSL_CTX* Security::GetContext() const
{
    return ctx_;
}


const Parameters& Security::get_parms() const
{
    return parms_;
}


const SSL_SESSION& Security::get_resume() const
{
    return resumeSession_;
}


bool Security::get_resuming() const
{
    return resuming_;
}


Connection& Security::use_connection()
{
    return conn_;
}


Parameters& Security::use_parms()
{
    return parms_;
}


SSL_SESSION& Security::use_resume()
{
    return resumeSession_;
}


void Security::set_resuming(bool b)
{
    resuming_ = b;
}


X509_NAME::X509_NAME(const char* n, size_t sz)
    : name_(0)
{
    if (sz) {
unknown's avatar
unknown committed
1913
        name_ = new char[sz];
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
        memcpy(name_, n, sz);
    }
}


X509_NAME::~X509_NAME()
{
    delete[] name_;
}


char* X509_NAME::GetName()
{
    return name_;
}


X509::X509(const char* i, size_t iSz, const char* s, size_t sSz)
    : issuer_(i, iSz), subject_(s, sSz)
{}
unknown's avatar
unknown committed
1934
   
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947

X509_NAME* X509::GetIssuer()
{
    return &issuer_;
}


X509_NAME* X509::GetSubject()
{
    return &subject_;
}

} // namespace
unknown's avatar
unknown committed
1948 1949

#ifdef __GNUC__
unknown's avatar
unknown committed
1950
namespace mySTL {
unknown's avatar
unknown committed
1951 1952 1953
template yaSSL::yassl_int_cpp_local1::SumData mySTL::for_each<mySTL::list<yaSSL::input_buffer*>::iterator, yaSSL::yassl_int_cpp_local1::SumData>(mySTL::list<yaSSL::input_buffer*>::iterator, mySTL::list<yaSSL::input_buffer*>::iterator, yaSSL::yassl_int_cpp_local1::SumData);
template yaSSL::yassl_int_cpp_local1::SumBuffer mySTL::for_each<mySTL::list<yaSSL::output_buffer*>::iterator, yaSSL::yassl_int_cpp_local1::SumBuffer>(mySTL::list<yaSSL::output_buffer*>::iterator, mySTL::list<yaSSL::output_buffer*>::iterator, yaSSL::yassl_int_cpp_local1::SumBuffer);
template mySTL::list<yaSSL::SSL_SESSION*>::iterator mySTL::find_if<mySTL::list<yaSSL::SSL_SESSION*>::iterator, yaSSL::yassl_int_cpp_local2::sess_match>(mySTL::list<yaSSL::SSL_SESSION*>::iterator, mySTL::list<yaSSL::SSL_SESSION*>::iterator, yaSSL::yassl_int_cpp_local2::sess_match);
unknown's avatar
unknown committed
1954
}
unknown's avatar
unknown committed
1955
#endif