yassl_imp.cpp 61.9 KB
Newer Older
1
/*
2
   Copyright (c) 2005, 2017, Oracle and/or its affiliates.
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

   This program 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; version 2 of the License.

   This program 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; see the file COPYING. If not, write to the
   Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
   MA  02110-1301  USA.
*/

/*  yaSSL source implements all SSL.v3 secification structures.
 */

#include "runtime.hpp"
#include "yassl_int.hpp"
#include "handshake.hpp"

#include "asn.hpp"  // provide crypto wrapper??



namespace yaSSL {


namespace { // locals

bool isTLS(ProtocolVersion pv)
{
    if (pv.major_ >= 3 && pv.minor_ >= 1)
        return true;

    return false;
}


}  // namespace (locals)


void hashHandShake(SSL&, const input_buffer&, uint);


ProtocolVersion::ProtocolVersion(uint8 maj, uint8 min) 
    : major_(maj), minor_(min) 
{}


// construct key exchange with known ssl parms
void ClientKeyExchange::createKey(SSL& ssl)
{
    const ClientKeyFactory& ckf = ssl.getFactory().getClientKey();
    client_key_ = ckf.CreateObject(ssl.getSecurity().get_parms().kea_);

    if (!client_key_)
        ssl.SetError(factory_error);
}


// construct key exchange with known ssl parms
void ServerKeyExchange::createKey(SSL& ssl)
{
    const ServerKeyFactory& skf = ssl.getFactory().getServerKey();
    server_key_ = skf.CreateObject(ssl.getSecurity().get_parms().kea_);

    if (!server_key_)
        ssl.SetError(factory_error);
}


// build/set PreMaster secret and encrypt, client side
void EncryptedPreMasterSecret::build(SSL& ssl)
{
    opaque tmp[SECRET_LEN];
    memset(tmp, 0, sizeof(tmp));
    ssl.getCrypto().get_random().Fill(tmp, SECRET_LEN);
    ProtocolVersion pv = ssl.getSecurity().get_connection().chVersion_;
    tmp[0] = pv.major_;
    tmp[1] = pv.minor_;
    ssl.set_preMaster(tmp, SECRET_LEN);

    const CertManager& cert = ssl.getCrypto().get_certManager();
    RSA rsa(cert.get_peerKey(), cert.get_peerKeyLength());
    bool tls = ssl.isTLS();     // if TLS, put length for encrypted data
    alloc(rsa.get_cipherLength() + (tls ? 2 : 0));
    byte* holder = secret_;
    if (tls) {
        byte len[2];
        c16toa(rsa.get_cipherLength(), len);
        memcpy(secret_, len, sizeof(len));
        holder += 2;
    }
    rsa.encrypt(holder, tmp, SECRET_LEN, ssl.getCrypto().get_random());
}


// build/set premaster and Client Public key, client side
void ClientDiffieHellmanPublic::build(SSL& ssl)
{
    DiffieHellman& dhServer = ssl.useCrypto().use_dh();
    DiffieHellman  dhClient(dhServer);

    uint keyLength = dhClient.get_agreedKeyLength(); // pub and agree same

    alloc(keyLength, true);
112
113
    dhClient.makeAgreement(dhServer.get_publicKey(),
                           dhServer.get_publicKeyLength());
114
115
116
    c16toa(keyLength, Yc_);
    memcpy(Yc_ + KEY_OFFSET, dhClient.get_publicKey(), keyLength);

117
    ssl.set_preMaster(dhClient.get_agreedKey(), keyLength);
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
}


// build server exhange, server side
void DH_Server::build(SSL& ssl)
{
    DiffieHellman& dhServer = ssl.useCrypto().use_dh();

    int pSz, gSz, pubSz;
    dhServer.set_sizes(pSz, gSz, pubSz);
    dhServer.get_parms(parms_.alloc_p(pSz), parms_.alloc_g(gSz),
                       parms_.alloc_pub(pubSz));

    short sigSz = 0;
    mySTL::auto_ptr<Auth> auth;
    const CertManager& cert = ssl.getCrypto().get_certManager();
    
    if (ssl.getSecurity().get_parms().sig_algo_ == rsa_sa_algo) {
        if (cert.get_keyType() != rsa_sa_algo) {
            ssl.SetError(privateKey_error);
            return;
        }
        auth.reset(NEW_YS RSA(cert.get_privateKey(),
                   cert.get_privateKeyLength(), false));
    }
    else {
        if (cert.get_keyType() != dsa_sa_algo) {
            ssl.SetError(privateKey_error);
            return;
        }
        auth.reset(NEW_YS DSS(cert.get_privateKey(),
                   cert.get_privateKeyLength(), false));
        sigSz += DSS_ENCODED_EXTRA;
    }
    
    sigSz += auth->get_signatureLength();
    if (!sigSz) {
        ssl.SetError(privateKey_error);
        return;
    }

    length_ = 8; // pLen + gLen + YsLen + SigLen
    length_ += pSz + gSz + pubSz + sigSz;

    output_buffer tmp(length_);
    byte len[2];
    // P
    c16toa(pSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(parms_.get_p(), pSz);
    // G
    c16toa(gSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(parms_.get_g(), gSz);
    // Ys
    c16toa(pubSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(parms_.get_pub(), pubSz);

    // Sig
    byte hash[FINISHED_SZ];
    MD5  md5;
    SHA  sha;
    signature_ = NEW_YS byte[sigSz];

    const Connection& conn = ssl.getSecurity().get_connection();
    // md5
    md5.update(conn.client_random_, RAN_LEN);
    md5.update(conn.server_random_, RAN_LEN);
    md5.update(tmp.get_buffer(), tmp.get_size());
    md5.get_digest(hash);

    // sha
    sha.update(conn.client_random_, RAN_LEN);
    sha.update(conn.server_random_, RAN_LEN);
    sha.update(tmp.get_buffer(), tmp.get_size());
    sha.get_digest(&hash[MD5_LEN]);

196
    if (ssl.getSecurity().get_parms().sig_algo_ == rsa_sa_algo) {
197
198
        auth->sign(signature_, hash, sizeof(hash),
                   ssl.getCrypto().get_random());
199
200
201
202
203
204
205
        // check for rsa signautre fault
        if (!auth->verify(hash, sizeof(hash), signature_,
                                              auth->get_signatureLength())) {
            ssl.SetError(rsaSignFault_error);
            return;
        }
    }
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    else {
        auth->sign(signature_, &hash[MD5_LEN], SHA_LEN,
                   ssl.getCrypto().get_random());
        byte encoded[DSS_SIG_SZ + DSS_ENCODED_EXTRA];
        TaoCrypt::EncodeDSA_Signature(signature_, encoded);
        memcpy(signature_, encoded, sizeof(encoded));
    }

    c16toa(sigSz, len);
    tmp.write(len, sizeof(len));
    tmp.write(signature_, sigSz);

    // key message
    keyMessage_ = NEW_YS opaque[length_];
    memcpy(keyMessage_, tmp.get_buffer(), tmp.get_size());
}


// read PreMaster secret and decrypt, server side
void EncryptedPreMasterSecret::read(SSL& ssl, input_buffer& input)
{
227
228
229
230
231
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }

232
233
234
235
236
    const CertManager& cert = ssl.getCrypto().get_certManager();
    RSA rsa(cert.get_privateKey(), cert.get_privateKeyLength(), false);
    uint16 cipherLen = rsa.get_cipherLength();
    if (ssl.isTLS()) {
        byte len[2];
237
238
        len[0] = input[AUTO];
        len[1] = input[AUTO];
239
240
241
242
        ato16(len, cipherLen);
    }
    alloc(cipherLen);
    input.read(secret_, length_);
243
244
245
246
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }
247
248

    opaque preMasterSecret[SECRET_LEN];
249
    memset(preMasterSecret, 0, sizeof(preMasterSecret));
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
287
288
289
290
291
292
293
294
    rsa.decrypt(preMasterSecret, secret_, length_, 
                ssl.getCrypto().get_random());

    ProtocolVersion pv = ssl.getSecurity().get_connection().chVersion_;
    if (pv.major_ != preMasterSecret[0] || pv.minor_ != preMasterSecret[1])
        ssl.SetError(pms_version_error); // continue deriving for timing attack

    ssl.set_preMaster(preMasterSecret, SECRET_LEN);
    ssl.makeMasterSecret();
}


EncryptedPreMasterSecret::EncryptedPreMasterSecret()
    : secret_(0), length_(0)
{}


EncryptedPreMasterSecret::~EncryptedPreMasterSecret()
{
    ysArrayDelete(secret_);
}


int EncryptedPreMasterSecret::get_length() const
{
    return length_;
}


opaque* EncryptedPreMasterSecret::get_clientKey() const
{
    return secret_;
}


void EncryptedPreMasterSecret::alloc(int sz)
{
    length_ = sz;
    secret_ = NEW_YS opaque[sz];
}


// read client's public key, server side
void ClientDiffieHellmanPublic::read(SSL& ssl, input_buffer& input)
{
295
296
297
298
299
    if (input.get_error() || input.get_remaining() < (uint)LENGTH_SZ) {
        ssl.SetError(bad_input);
        return;
    }

300
301
302
303
304
305
306
307
    DiffieHellman& dh = ssl.useCrypto().use_dh();

    uint16 keyLength;
    byte tmp[2];
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, keyLength);

308
309
310
311
312
    if (keyLength < dh.get_agreedKeyLength()/2) {
        ssl.SetError(bad_input);
        return;
    }

313
314
    alloc(keyLength);
    input.read(Yc_, keyLength);
315
316
317
318
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }
319
320
    dh.makeAgreement(Yc_, keyLength); 

321
    ssl.set_preMaster(dh.get_agreedKey(), dh.get_agreedKeyLength());
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
    ssl.makeMasterSecret();
}


ClientDiffieHellmanPublic::ClientDiffieHellmanPublic()
    : length_(0), Yc_(0)
{}


ClientDiffieHellmanPublic::~ClientDiffieHellmanPublic()
{
    ysArrayDelete(Yc_);
}


int ClientDiffieHellmanPublic::get_length() const
{
    return length_;
}


opaque* ClientDiffieHellmanPublic::get_clientKey() const
{
    return Yc_;
}


void ClientDiffieHellmanPublic::alloc(int sz, bool offset) 
{
    length_ = sz + (offset ? KEY_OFFSET : 0); 
    Yc_ = NEW_YS opaque[length_];
}


// read server's p, g, public key and sig, client side
void DH_Server::read(SSL& ssl, input_buffer& input)
{
359
360
361
362
    if (input.get_error() || input.get_remaining() < (uint)LENGTH_SZ) {
        ssl.SetError(bad_input);
        return;
    }
363
364
365
366
367
368
369
370
371
372
    uint16 length, messageTotal = 6; // pSz + gSz + pubSz
    byte tmp[2];

    // p
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);
    messageTotal += length;

    input.read(parms_.alloc_p(length), length);
373
374
375
376
    if (input.get_error() || input.get_remaining() < (uint)LENGTH_SZ) {
        ssl.SetError(bad_input);
        return;
    }
377
378
379
380
381
382
383
384

    // g
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);
    messageTotal += length;

    input.read(parms_.alloc_g(length), length);
385
386
387
388
    if (input.get_error() || input.get_remaining() < (uint)LENGTH_SZ) {
        ssl.SetError(bad_input);
        return;
    }
389
390
391
392
393
394
395
396

    // pub
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);
    messageTotal += length;

    input.read(parms_.alloc_pub(length), length);
397
398
399
400
    if (input.get_error() || input.get_remaining() < (uint)LENGTH_SZ) {
        ssl.SetError(bad_input);
        return;
    }
401
402
403
404
405
406

    // save message for hash verify
    input_buffer message(messageTotal);
    input.set_current(input.get_current() - messageTotal);
    input.read(message.get_buffer(), messageTotal);
    message.add_size(messageTotal);
407
408
409
410
    if (input.get_error() || input.get_remaining() < (uint)LENGTH_SZ) {
        ssl.SetError(bad_input);
        return;
    }
411
412
413
414
415
416

    // signature
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, length);

417
418
419
420
    if (length == 0) {
        ssl.SetError(bad_input);
        return;
    }
421
422
    signature_ = NEW_YS byte[length];
    input.read(signature_, length);
423
424
425
426
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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

    // verify signature
    byte hash[FINISHED_SZ];
    MD5  md5;
    SHA  sha;

    const Connection& conn = ssl.getSecurity().get_connection();
    // md5
    md5.update(conn.client_random_, RAN_LEN);
    md5.update(conn.server_random_, RAN_LEN);
    md5.update(message.get_buffer(), message.get_size());
    md5.get_digest(hash);

    // sha
    sha.update(conn.client_random_, RAN_LEN);
    sha.update(conn.server_random_, RAN_LEN);
    sha.update(message.get_buffer(), message.get_size());
    sha.get_digest(&hash[MD5_LEN]);

    const CertManager& cert = ssl.getCrypto().get_certManager();
    
    if (ssl.getSecurity().get_parms().sig_algo_ == rsa_sa_algo) {
        RSA rsa(cert.get_peerKey(), cert.get_peerKeyLength());
        if (!rsa.verify(hash, sizeof(hash), signature_, length))
            ssl.SetError(verify_error);
    }
    else {
        byte decodedSig[DSS_SIG_SZ];
        length = TaoCrypt::DecodeDSA_Signature(decodedSig, signature_, length);
        
        DSS dss(cert.get_peerKey(), cert.get_peerKeyLength());
        if (!dss.verify(&hash[MD5_LEN], SHA_LEN, decodedSig, length))
            ssl.SetError(verify_error);
    }

    // save input
    ssl.useCrypto().SetDH(NEW_YS DiffieHellman(parms_.get_p(),
               parms_.get_pSize(), parms_.get_g(), parms_.get_gSize(),
               parms_.get_pub(), parms_.get_pubSize(),
               ssl.getCrypto().get_random()));
}


DH_Server::DH_Server()
    : signature_(0), length_(0), keyMessage_(0)
{}


DH_Server::~DH_Server()
{
    ysArrayDelete(keyMessage_);
    ysArrayDelete(signature_);
}


int DH_Server::get_length() const
{
    return length_;
}


opaque* DH_Server::get_serverKey() const
{
    return keyMessage_;
}


// set available suites
Parameters::Parameters(ConnectionEnd ce, const Ciphers& ciphers, 
                       ProtocolVersion pv, bool haveDH) : entity_(ce)
{
    pending_ = true;	// suite not set yet
    strncpy(cipher_name_, "NONE", 5);

    removeDH_ = !haveDH;   // only use on server side for set suites

    if (ciphers.setSuites_) {   // use user set list
        suites_size_ = ciphers.suiteSz_;
        memcpy(suites_, ciphers.suites_, ciphers.suiteSz_);
        SetCipherNames();
    }
    else 
        SetSuites(pv, ce == server_end && removeDH_);  // defaults

}


void Parameters::SetSuites(ProtocolVersion pv, bool removeDH, bool removeRSA,
                           bool removeDSA)
{
    int i = 0;
    // available suites, best first
    // when adding more, make sure cipher_names is updated and
    //      MAX_CIPHERS is big enough

    if (isTLS(pv)) {
        if (!removeDH) {
            if (!removeRSA) {
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_RSA_WITH_AES_256_CBC_SHA;
            }
            if (!removeDSA) {
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_DSS_WITH_AES_256_CBC_SHA;
            }
        }
        if (!removeRSA) {
            suites_[i++] = 0x00;
            suites_[i++] = TLS_RSA_WITH_AES_256_CBC_SHA;
        }
        if (!removeDH) {
            if (!removeRSA) {
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
            }
            if (!removeDSA) {
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_DSS_WITH_AES_128_CBC_SHA;
            }
        }
        if (!removeRSA) {
            suites_[i++] = 0x00;
            suites_[i++] = TLS_RSA_WITH_AES_128_CBC_SHA;
            suites_[i++] = 0x00;
            suites_[i++] = TLS_RSA_WITH_AES_256_CBC_RMD160;
            suites_[i++] = 0x00;
            suites_[i++] = TLS_RSA_WITH_AES_128_CBC_RMD160;
            suites_[i++] = 0x00;
            suites_[i++] = TLS_RSA_WITH_3DES_EDE_CBC_RMD160;
        }
        if (!removeDH) {
            if (!removeRSA) {
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_RSA_WITH_AES_256_CBC_RMD160;
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_RSA_WITH_AES_128_CBC_RMD160;
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD160;
            }
            if (!removeDSA) {
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_DSS_WITH_AES_256_CBC_RMD160;
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_DSS_WITH_AES_128_CBC_RMD160;
                suites_[i++] = 0x00;
                suites_[i++] = TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD160;
            }
        }
    }

    if (!removeRSA) {
        suites_[i++] = 0x00;
        suites_[i++] = SSL_RSA_WITH_RC4_128_SHA;  
        suites_[i++] = 0x00;
        suites_[i++] = SSL_RSA_WITH_RC4_128_MD5;

        suites_[i++] = 0x00;
        suites_[i++] = SSL_RSA_WITH_3DES_EDE_CBC_SHA;
        suites_[i++] = 0x00;
        suites_[i++] = SSL_RSA_WITH_DES_CBC_SHA;
    }
    if (!removeDH) {
        if (!removeRSA) {
            suites_[i++] = 0x00;
            suites_[i++] = SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA;
        }
        if (!removeDSA) {
            suites_[i++] = 0x00;
            suites_[i++] = SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA;
        }
        if (!removeRSA) {
            suites_[i++] = 0x00;
            suites_[i++] = SSL_DHE_RSA_WITH_DES_CBC_SHA;
        }
        if (!removeDSA) {
            suites_[i++] = 0x00;
            suites_[i++] = SSL_DHE_DSS_WITH_DES_CBC_SHA;
        }
    }

    suites_size_ = i;

    SetCipherNames();
}


void Parameters::SetCipherNames()
{
    const int suites = suites_size_ / 2;
    int pos = 0;

    for (int j = 0; j < suites; j++) {
        int index = suites_[j*2 + 1];  // every other suite is suite id
        size_t len = strlen(cipher_names[index]) + 1;
        strncpy(cipher_list_[pos++], cipher_names[index], len);
    }
    cipher_list_[pos][0] = 0;
}


// input operator for RecordLayerHeader, adjust stream
input_buffer& operator>>(input_buffer& input, RecordLayerHeader& hdr)
{
    hdr.type_ = ContentType(input[AUTO]);
    hdr.version_.major_ = input[AUTO];
    hdr.version_.minor_ = input[AUTO];

    // length
    byte tmp[2];
    tmp[0] = input[AUTO];
    tmp[1] = input[AUTO];
    ato16(tmp, hdr.length_);

    return input;
}


// output operator for RecordLayerHeader
output_buffer& operator<<(output_buffer& output, const RecordLayerHeader& hdr)
{
    output[AUTO] = hdr.type_;
    output[AUTO] = hdr.version_.major_;
    output[AUTO] = hdr.version_.minor_;
    
    // length
    byte tmp[2];
    c16toa(hdr.length_, tmp);
    output[AUTO] = tmp[0];
    output[AUTO] = tmp[1];

    return output;
}


// virtual input operator for Messages
input_buffer& operator>>(input_buffer& input, Message& msg)
{
    return msg.set(input);
}

// virtual output operator for Messages
output_buffer& operator<<(output_buffer& output, const Message& msg)
{
    return msg.get(output);
}


// input operator for HandShakeHeader
input_buffer& operator>>(input_buffer& input, HandShakeHeader& hs)
{
    hs.type_ = HandShakeType(input[AUTO]);

    hs.length_[0] = input[AUTO];
    hs.length_[1] = input[AUTO];
    hs.length_[2] = input[AUTO];
    
    return input;
}


// output operator for HandShakeHeader
output_buffer& operator<<(output_buffer& output, const HandShakeHeader& hdr)
{
    output[AUTO] = hdr.type_;
    output.write(hdr.length_, sizeof(hdr.length_));
    return output;
}


// HandShake Header Processing function
void HandShakeHeader::Process(input_buffer& input, SSL& ssl)
{
    ssl.verifyState(*this);
    if (ssl.GetError()) return;
701
702
703
704
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }
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
    const HandShakeFactory& hsf = ssl.getFactory().getHandShake();
    mySTL::auto_ptr<HandShakeBase> hs(hsf.CreateObject(type_));
    if (!hs.get()) {
        ssl.SetError(factory_error);
        return;
    }

    uint len = c24to32(length_);
    if (len > input.get_remaining()) {
        ssl.SetError(bad_input);
        return;
    }
    hashHandShake(ssl, input, len);

    hs->set_length(len);
    input >> *hs;
    hs->Process(input, ssl);
}


ContentType HandShakeHeader::get_type() const
{
    return handshake;
}


uint16 HandShakeHeader::get_length() const
{
    return c24to32(length_);
}


HandShakeType HandShakeHeader::get_handshakeType() const
{
    return type_;
}


void HandShakeHeader::set_type(HandShakeType hst)
{
    type_ = hst;
}


void HandShakeHeader::set_length(uint32 u32)
{
    c32to24(u32, length_);
}


input_buffer& HandShakeHeader::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& HandShakeHeader::get(output_buffer& out) const
{
    return out << *this;
}



int HandShakeBase::get_length() const
{
    return length_;
}


void HandShakeBase::set_length(int l)
{
    length_ = l;
}


// for building buffer's type field
HandShakeType HandShakeBase::get_type() const
{
    return no_shake;
}


input_buffer& HandShakeBase::set(input_buffer& in)
{
    return in;
}

 
output_buffer& HandShakeBase::get(output_buffer& out) const
{
    return out;
}


void HandShakeBase::Process(input_buffer&, SSL&) 
{}


input_buffer& HelloRequest::set(input_buffer& in)
{
    return in;
}


output_buffer& HelloRequest::get(output_buffer& out) const
{
    return out;
}


void HelloRequest::Process(input_buffer&, SSL&)
{}


HandShakeType HelloRequest::get_type() const
{
    return hello_request;
}


// input operator for CipherSpec
input_buffer& operator>>(input_buffer& input, ChangeCipherSpec& cs)
{
    cs.type_ = CipherChoice(input[AUTO]);
    return input; 
}

// output operator for CipherSpec
output_buffer& operator<<(output_buffer& output, const ChangeCipherSpec& cs)
{
    output[AUTO] = cs.type_;
    return output;
}


ChangeCipherSpec::ChangeCipherSpec() 
    : type_(change_cipher_spec_choice)
{}


input_buffer& ChangeCipherSpec::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& ChangeCipherSpec::get(output_buffer& out) const
{
    return out << *this;
}


ContentType ChangeCipherSpec::get_type() const
{
    return change_cipher_spec;
}


uint16 ChangeCipherSpec::get_length() const
{
    return SIZEOF_ENUM;
}


// CipherSpec processing handler
870
void ChangeCipherSpec::Process(input_buffer& input, SSL& ssl)
871
{
872
873
874
875
876
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }

877
878
879
880
881
882
    // detect duplicate change_cipher
    if (ssl.getSecurity().get_parms().pending_ == false) {
        ssl.order_error();
        return;
    }

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
    ssl.useSecurity().use_parms().pending_ = false;
    if (ssl.getSecurity().get_resuming()) {
        if (ssl.getSecurity().get_parms().entity_ == client_end)
            buildFinished(ssl, ssl.useHashes().use_verify(), server); // server
    }
    else if (ssl.getSecurity().get_parms().entity_ == server_end)
        buildFinished(ssl, ssl.useHashes().use_verify(), client);     // client
}


Alert::Alert(AlertLevel al, AlertDescription ad)
    : level_(al), description_(ad)
{}


ContentType Alert::get_type() const
{
    return alert;
}


uint16 Alert::get_length() const
{
    return SIZEOF_ENUM * 2;
}


input_buffer& Alert::set(input_buffer& in)
{
    return in >> *this;
}


output_buffer& Alert::get(output_buffer& out) const
{
    return out << *this;
}


// input operator for Alert
input_buffer& operator>>(input_buffer& input, Alert& a)
{
    a.level_ = AlertLevel(input[AUTO]);
    a.description_ = AlertDescription(input[AUTO]);
 
    return input;
}


// output operator for Alert
output_buffer& operator<<(output_buffer& output, const Alert& a)
{
    output[AUTO] = a.level_;
    output[AUTO] = a.description_;
    return output;
}


// Alert processing handler
void Alert::Process(input_buffer& input, SSL& ssl)
{
944
945
946
947
948
    if (input.get_error()) {
        ssl.SetError(bad_input);
        return;
    }

949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
    if (ssl.getSecurity().get_parms().pending_ == false)  { // encrypted alert
        int            aSz = get_length();  // alert size already read on input
        opaque         verify[SHA_LEN];
        const  opaque* data = input.get_buffer() + input.get_current() - aSz;

        if (ssl.isTLS())
            TLS_hmac(ssl, verify, data, aSz, alert, true);
        else
            hmac(ssl, verify, data, aSz, alert, true);

        // read mac and skip fill
        int    digestSz = ssl.getCrypto().get_digest().get_digestSize();
        opaque mac[SHA_LEN];
        input.read(mac, digestSz);

        if (ssl.getSecurity().get_parms().cipher_type_ == block) {
            int    ivExtra = 0;
966
            opaque fill;
967
968
969
970
971

            if (ssl.isTLSv1_1())
                ivExtra = ssl.getCrypto().get_cipher().get_blockSize();
            int padSz = ssl.getSecurity().get_parms().encrypt_size_ - ivExtra -
                        aSz - digestSz;
972
973
974
975
976
977
978
            for (int i = 0; i < padSz; i++) 
                fill = input[AUTO];
        }

        if (input.get_error()) {
            ssl.SetError(bad_input);
            return;
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        }

        // verify
        if (memcmp(mac, verify, digestSz)) {
            ssl.SetError(verify_error);
            return;
        }
    }
    if (level_ == fatal) {
        ssl.useStates().useRecord()    = recordNotReady;
        ssl.useStates().useHandShake() = handShakeNotReady;
        ssl.SetError(YasslError(description_));
    }
}


Data::Data()
    : length_(0), buffer_(0), write_buffer_(0)
{}


Data::Data(uint16 len, opaque* b)