~ubuntu-branches/ubuntu/trusty/mariadb-5.5/trusty-proposed

« back to all changes in this revision

Viewing changes to extra/yassl/taocrypt/src/asn.cpp

  • Committer: Package Import Robot
  • Author(s): Otto Kekäläinen
  • Date: 2013-12-22 10:27:05 UTC
  • Revision ID: package-import@ubuntu.com-20131222102705-mndw7s12mz0szrcn
Tags: upstream-5.5.32
Import upstream version 5.5.32

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
   Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
 
3
   Use is subject to license terms.
 
4
 
 
5
   This program is free software; you can redistribute it and/or modify
 
6
   it under the terms of the GNU General Public License as published by
 
7
   the Free Software Foundation; version 2 of the License.
 
8
 
 
9
   This program is distributed in the hope that it will be useful,
 
10
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
   GNU General Public License for more details.
 
13
 
 
14
   You should have received a copy of the GNU General Public License
 
15
   along with this program; see the file COPYING. If not, write to the
 
16
   Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 
17
   MA  02110-1301  USA.
 
18
*/
 
19
 
 
20
/* asn.cpp implements ASN1 BER, PublicKey, and x509v3 decoding 
 
21
*/
 
22
 
 
23
#include "runtime.hpp"
 
24
#include "asn.hpp"
 
25
#include "file.hpp"
 
26
#include "integer.hpp"
 
27
#include "rsa.hpp"
 
28
#include "dsa.hpp"
 
29
#include "dh.hpp"
 
30
#include "md5.hpp"
 
31
#include "md2.hpp"
 
32
#include "sha.hpp"
 
33
#include "coding.hpp"
 
34
#include <time.h>     // gmtime();
 
35
#include "memory.hpp" // some auto_ptr don't have reset, also need auto_array
 
36
 
 
37
 
 
38
namespace TaoCrypt {
 
39
 
 
40
namespace { // locals
 
41
 
 
42
 
 
43
// to the minute
 
44
bool operator>(tm& a, tm& b)
 
45
{
 
46
    if (a.tm_year > b.tm_year)
 
47
        return true;
 
48
 
 
49
    if (a.tm_year == b.tm_year && a.tm_mon > b.tm_mon)
 
50
        return true;
 
51
    
 
52
    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon && a.tm_mday >b.tm_mday)
 
53
        return true;
 
54
 
 
55
    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon &&
 
56
        a.tm_mday == b.tm_mday && a.tm_hour > b.tm_hour)
 
57
        return true;
 
58
 
 
59
    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon &&
 
60
        a.tm_mday == b.tm_mday && a.tm_hour == b.tm_hour &&
 
61
        a.tm_min > b.tm_min)
 
62
        return true;
 
63
 
 
64
    return false;
 
65
}
 
66
 
 
67
 
 
68
bool operator<(tm& a, tm&b)
 
69
{
 
70
    return !(a>b);
 
71
}
 
72
 
 
73
 
 
74
// like atoi but only use first byte
 
75
word32 btoi(byte b)
 
76
{
 
77
    return b - 0x30;
 
78
}
 
79
 
 
80
 
 
81
// two byte date/time, add to value
 
82
void GetTime(int& value, const byte* date, int& i)
 
83
{
 
84
    value += btoi(date[i++]) * 10;
 
85
    value += btoi(date[i++]);
 
86
}
 
87
 
 
88
 
 
89
// Make sure before and after dates are valid
 
90
bool ValidateDate(const byte* date, byte format, CertDecoder::DateType dt)
 
91
{
 
92
    tm certTime;
 
93
    memset(&certTime, 0, sizeof(certTime));
 
94
    int i = 0;
 
95
 
 
96
    if (format == UTC_TIME) {
 
97
        if (btoi(date[0]) >= 5)
 
98
            certTime.tm_year = 1900;
 
99
        else
 
100
            certTime.tm_year = 2000;
 
101
    }
 
102
    else  { // format == GENERALIZED_TIME
 
103
        certTime.tm_year += btoi(date[i++]) * 1000;
 
104
        certTime.tm_year += btoi(date[i++]) * 100;
 
105
    }
 
106
 
 
107
    GetTime(certTime.tm_year, date, i);     certTime.tm_year -= 1900; // adjust
 
108
    GetTime(certTime.tm_mon,  date, i);     certTime.tm_mon  -= 1;    // adjust
 
109
    GetTime(certTime.tm_mday, date, i);
 
110
    GetTime(certTime.tm_hour, date, i); 
 
111
    GetTime(certTime.tm_min,  date, i); 
 
112
    GetTime(certTime.tm_sec,  date, i); 
 
113
 
 
114
    if (date[i] != 'Z')     // only Zulu supported for this profile
 
115
        return false;
 
116
 
 
117
    time_t ltime = time(0);
 
118
    tm* localTime = gmtime(&ltime);
 
119
 
 
120
    if (dt == CertDecoder::BEFORE) {
 
121
        if (*localTime < certTime)
 
122
            return false;
 
123
    }
 
124
    else
 
125
        if (*localTime > certTime)
 
126
            return false;
 
127
 
 
128
    return true;
 
129
}
 
130
 
 
131
 
 
132
class BadCertificate {};
 
133
 
 
134
} // local namespace
 
135
 
 
136
 
 
137
 
 
138
// used by Integer as well
 
139
word32 GetLength(Source& source)
 
140
{
 
141
    word32 length = 0;
 
142
 
 
143
    byte b = source.next();
 
144
    if (b >= LONG_LENGTH) {        
 
145
        word32 bytes = b & 0x7F;
 
146
 
 
147
        if (source.IsLeft(bytes) == false) return 0;
 
148
 
 
149
        while (bytes--) {
 
150
            b = source.next();
 
151
            length = (length << 8) | b;
 
152
        }
 
153
    }
 
154
    else
 
155
        length = b;
 
156
 
 
157
    if (source.IsLeft(length) == false) return 0;
 
158
 
 
159
    return length;
 
160
}
 
161
 
 
162
 
 
163
word32 SetLength(word32 length, byte* output)
 
164
{
 
165
    word32 i = 0;
 
166
 
 
167
    if (length < LONG_LENGTH)
 
168
        output[i++] = length;
 
169
    else {
 
170
        output[i++] = BytePrecision(length) | 0x80;
 
171
      
 
172
        for (int j = BytePrecision(length); j; --j) {
 
173
            output[i] = length >> (j - 1) * 8;
 
174
            i++;
 
175
        }
 
176
    }
 
177
    return i;
 
178
}
 
179
 
 
180
 
 
181
PublicKey::PublicKey(const byte* k, word32 s) : key_(0), sz_(0)
 
182
{
 
183
    if (s) {
 
184
        SetSize(s);
 
185
        SetKey(k);
 
186
    }
 
187
}
 
188
 
 
189
 
 
190
void PublicKey::SetSize(word32 s)
 
191
{
 
192
    sz_ = s;
 
193
    key_ = NEW_TC byte[sz_];
 
194
}
 
195
 
 
196
 
 
197
void PublicKey::SetKey(const byte* k)
 
198
{
 
199
    memcpy(key_, k, sz_);
 
200
}
 
201
 
 
202
 
 
203
void PublicKey::AddToEnd(const byte* data, word32 len)
 
204
{
 
205
    mySTL::auto_array<byte> tmp(NEW_TC byte[sz_ + len]);
 
206
 
 
207
    memcpy(tmp.get(), key_, sz_);
 
208
    memcpy(tmp.get() + sz_, data, len);
 
209
 
 
210
    byte* del = 0;
 
211
    STL::swap(del, key_);
 
212
    tcArrayDelete(del);
 
213
 
 
214
    key_ = tmp.release();
 
215
    sz_ += len;
 
216
}
 
217
 
 
218
 
 
219
Signer::Signer(const byte* k, word32 kSz, const char* n, const byte* h)
 
220
    : key_(k, kSz)
 
221
{
 
222
    size_t sz = strlen(n);
 
223
    memcpy(name_, n, sz);
 
224
    name_[sz] = 0;
 
225
 
 
226
    memcpy(hash_, h, SHA::DIGEST_SIZE);
 
227
}
 
228
 
 
229
Signer::~Signer()
 
230
{
 
231
}
 
232
 
 
233
 
 
234
Error BER_Decoder::GetError()
 
235
 
236
    return source_.GetError(); 
 
237
}
 
238
 
 
239
 
 
240
Integer& BER_Decoder::GetInteger(Integer& integer)
 
241
{
 
242
    if (!source_.GetError().What())
 
243
        integer.Decode(source_);
 
244
    return integer;
 
245
}
 
246
 
 
247
  
 
248
// Read a Sequence, return length
 
249
word32 BER_Decoder::GetSequence()
 
250
{
 
251
    if (source_.GetError().What()) return 0;
 
252
 
 
253
    byte b = source_.next();
 
254
    if (b != (SEQUENCE | CONSTRUCTED)) {
 
255
        source_.SetError(SEQUENCE_E);
 
256
        return 0;
 
257
    }
 
258
 
 
259
    return GetLength(source_);
 
260
}
 
261
 
 
262
 
 
263
// Read a Sequence, return length
 
264
word32 BER_Decoder::GetSet()
 
265
{
 
266
    if (source_.GetError().What()) return 0;
 
267
 
 
268
    byte b = source_.next();
 
269
    if (b != (SET | CONSTRUCTED)) {
 
270
        source_.SetError(SET_E);
 
271
        return 0;
 
272
    }
 
273
 
 
274
    return GetLength(source_);
 
275
}
 
276
 
 
277
 
 
278
// Read Version, return it
 
279
word32 BER_Decoder::GetVersion()
 
280
{
 
281
    if (source_.GetError().What()) return 0;
 
282
 
 
283
    byte b = source_.next();
 
284
    if (b != INTEGER) {
 
285
        source_.SetError(INTEGER_E);
 
286
        return 0;
 
287
    }
 
288
 
 
289
    b = source_.next();
 
290
    if (b != 0x01) {
 
291
        source_.SetError(VERSION_E);
 
292
        return 0;
 
293
    }
 
294
 
 
295
    return source_.next();
 
296
}
 
297
 
 
298
 
 
299
// Read ExplicitVersion, return it or 0 if not there (not an error)
 
300
word32 BER_Decoder::GetExplicitVersion()
 
301
{
 
302
    if (source_.GetError().What()) return 0;
 
303
 
 
304
    byte b = source_.next();
 
305
 
 
306
    if (b == (CONTEXT_SPECIFIC | CONSTRUCTED)) { // not an error if not here
 
307
        source_.next();
 
308
        return GetVersion();
 
309
    }
 
310
    else 
 
311
        source_.prev(); // put back
 
312
  
 
313
    return 0;
 
314
}
 
315
 
 
316
 
 
317
// Decode a BER encoded RSA Private Key
 
318
void RSA_Private_Decoder::Decode(RSA_PrivateKey& key)
 
319
{
 
320
    ReadHeader();
 
321
    if (source_.GetError().What()) return;
 
322
    // public
 
323
    key.SetModulus(GetInteger(Integer().Ref()));
 
324
    key.SetPublicExponent(GetInteger(Integer().Ref()));
 
325
 
 
326
    // private
 
327
    key.SetPrivateExponent(GetInteger(Integer().Ref()));
 
328
    key.SetPrime1(GetInteger(Integer().Ref()));
 
329
    key.SetPrime2(GetInteger(Integer().Ref()));
 
330
    key.SetModPrime1PrivateExponent(GetInteger(Integer().Ref()));
 
331
    key.SetModPrime2PrivateExponent(GetInteger(Integer().Ref()));
 
332
    key.SetMultiplicativeInverseOfPrime2ModPrime1(GetInteger(Integer().Ref()));
 
333
}
 
334
 
 
335
 
 
336
void RSA_Private_Decoder::ReadHeader()
 
337
{
 
338
    GetSequence();
 
339
    GetVersion();
 
340
}
 
341
 
 
342
 
 
343
// Decode a BER encoded DSA Private Key
 
344
void DSA_Private_Decoder::Decode(DSA_PrivateKey& key)
 
345
{
 
346
    ReadHeader();
 
347
    if (source_.GetError().What()) return;
 
348
    // group parameters
 
349
    key.SetModulus(GetInteger(Integer().Ref()));
 
350
    key.SetSubGroupOrder(GetInteger(Integer().Ref()));
 
351
    key.SetSubGroupGenerator(GetInteger(Integer().Ref()));
 
352
 
 
353
    // key
 
354
    key.SetPublicPart(GetInteger(Integer().Ref()));
 
355
    key.SetPrivatePart(GetInteger(Integer().Ref()));   
 
356
}
 
357
 
 
358
 
 
359
void DSA_Private_Decoder::ReadHeader()
 
360
{
 
361
    GetSequence();
 
362
    GetVersion();
 
363
}
 
364
 
 
365
 
 
366
// Decode a BER encoded RSA Public Key
 
367
void RSA_Public_Decoder::Decode(RSA_PublicKey& key)
 
368
{
 
369
    ReadHeader();
 
370
    if (source_.GetError().What()) return;
 
371
 
 
372
    ReadHeaderOpenSSL();   // may or may not be
 
373
    if (source_.GetError().What()) return;
 
374
 
 
375
    // public key
 
376
    key.SetModulus(GetInteger(Integer().Ref()));
 
377
    key.SetPublicExponent(GetInteger(Integer().Ref()));
 
378
}
 
379
 
 
380
 
 
381
// Read OpenSSL format public header
 
382
void RSA_Public_Decoder::ReadHeaderOpenSSL()
 
383
{
 
384
    byte b = source_.next();  // peek
 
385
    source_.prev();
 
386
 
 
387
    if (b != INTEGER) { // have OpenSSL public format
 
388
        GetSequence();
 
389
        b = source_.next();
 
390
        if (b != OBJECT_IDENTIFIER) {
 
391
            source_.SetError(OBJECT_ID_E);
 
392
            return;
 
393
        }
 
394
 
 
395
        word32 len = GetLength(source_);
 
396
        source_.advance(len);
 
397
 
 
398
        b = source_.next();
 
399
        if (b == TAG_NULL) {   // could have NULL tag and 0 terminator, may not 
 
400
            b = source_.next();
 
401
            if (b != 0) {
 
402
                source_.SetError(EXPECT_0_E);
 
403
                return; 
 
404
            }
 
405
        }
 
406
        else
 
407
            source_.prev();   // put back
 
408
 
 
409
        b = source_.next();
 
410
        if (b != BIT_STRING) {   
 
411
            source_.SetError(BIT_STR_E);
 
412
            return; 
 
413
        }
 
414
 
 
415
        len = GetLength(source_); 
 
416
        b = source_.next();
 
417
        if (b != 0)           // could have 0
 
418
            source_.prev();   // put back
 
419
        
 
420
        GetSequence();
 
421
    }
 
422
}
 
423
 
 
424
 
 
425
void RSA_Public_Decoder::ReadHeader()
 
426
{
 
427
    GetSequence();
 
428
}
 
429
 
 
430
 
 
431
// Decode a BER encoded DSA Public Key
 
432
void DSA_Public_Decoder::Decode(DSA_PublicKey& key)
 
433
{
 
434
    ReadHeader();
 
435
    if (source_.GetError().What()) return;
 
436
 
 
437
    // group parameters
 
438
    key.SetModulus(GetInteger(Integer().Ref()));
 
439
    key.SetSubGroupOrder(GetInteger(Integer().Ref()));
 
440
    key.SetSubGroupGenerator(GetInteger(Integer().Ref()));
 
441
 
 
442
    // key
 
443
    key.SetPublicPart(GetInteger(Integer().Ref()));
 
444
}
 
445
 
 
446
 
 
447
void DSA_Public_Decoder::ReadHeader()
 
448
{
 
449
    GetSequence();
 
450
}
 
451
 
 
452
 
 
453
void DH_Decoder::ReadHeader()
 
454
{
 
455
    GetSequence();
 
456
}
 
457
 
 
458
 
 
459
// Decode a BER encoded Diffie-Hellman Key
 
460
void DH_Decoder::Decode(DH& key)
 
461
{
 
462
    ReadHeader();
 
463
    if (source_.GetError().What()) return;
 
464
 
 
465
    // group parms
 
466
    key.SetP(GetInteger(Integer().Ref()));
 
467
    key.SetG(GetInteger(Integer().Ref()));
 
468
}
 
469
 
 
470
 
 
471
CertDecoder::CertDecoder(Source& s, bool decode, SignerList* signers,
 
472
                         bool noVerify, CertType ct)
 
473
    : BER_Decoder(s), certBegin_(0), sigIndex_(0), sigLength_(0),
 
474
      signature_(0), verify_(!noVerify)
 
475
{
 
476
    issuer_[0] = 0;
 
477
    subject_[0] = 0;
 
478
 
 
479
    if (decode)
 
480
        Decode(signers, ct);
 
481
 
 
482
}
 
483
 
 
484
 
 
485
CertDecoder::~CertDecoder()
 
486
{
 
487
    tcArrayDelete(signature_);
 
488
}
 
489
 
 
490
 
 
491
// process certificate header, set signature offset
 
492
void CertDecoder::ReadHeader()
 
493
{
 
494
    if (source_.GetError().What()) return;
 
495
 
 
496
    GetSequence();  // total
 
497
    certBegin_ = source_.get_index();
 
498
 
 
499
    sigIndex_ = GetSequence();  // this cert
 
500
    sigIndex_ += source_.get_index();
 
501
 
 
502
    GetExplicitVersion(); // version
 
503
    GetInteger(Integer().Ref());  // serial number
 
504
}
 
505
 
 
506
 
 
507
// Decode a x509v3 Certificate
 
508
void CertDecoder::Decode(SignerList* signers, CertType ct)
 
509
{
 
510
    if (source_.GetError().What()) return;
 
511
    DecodeToKey();
 
512
    if (source_.GetError().What()) return;
 
513
 
 
514
    if (source_.get_index() != sigIndex_)
 
515
        source_.set_index(sigIndex_);
 
516
 
 
517
    word32 confirmOID = GetAlgoId();
 
518
    GetSignature();
 
519
    if (source_.GetError().What()) return;
 
520
 
 
521
    if ( confirmOID != signatureOID_ ) {
 
522
        source_.SetError(SIG_OID_E);
 
523
        return;
 
524
    }
 
525
    
 
526
    if (ct != CA && verify_ && !ValidateSignature(signers))
 
527
        source_.SetError(SIG_OTHER_E);
 
528
}
 
529
 
 
530
 
 
531
void CertDecoder::DecodeToKey()
 
532
{
 
533
    ReadHeader();
 
534
    signatureOID_ = GetAlgoId();
 
535
    GetName(ISSUER);   
 
536
    GetValidity();
 
537
    GetName(SUBJECT);   
 
538
    GetKey();
 
539
}
 
540
 
 
541
 
 
542
// Read public key
 
543
void CertDecoder::GetKey()
 
544
{
 
545
    if (source_.GetError().What()) return;
 
546
 
 
547
    GetSequence();    
 
548
    keyOID_ = GetAlgoId();
 
549
 
 
550
    if (keyOID_ == RSAk) {
 
551
        byte b = source_.next();
 
552
        if (b != BIT_STRING) {
 
553
            source_.SetError(BIT_STR_E);
 
554
            return;
 
555
        }
 
556
        b = source_.next();      // length, future
 
557
        b = source_.next(); 
 
558
        while(b != 0)
 
559
            b = source_.next();
 
560
    }
 
561
    else if (keyOID_ == DSAk)
 
562
        ;   // do nothing
 
563
    else {
 
564
        source_.SetError(UNKNOWN_OID_E);
 
565
        return;
 
566
    }
 
567
 
 
568
    StoreKey();
 
569
    if (keyOID_ == DSAk)
 
570
        AddDSA();
 
571
}
 
572
 
 
573
 
 
574
// Save public key
 
575
void CertDecoder::StoreKey()
 
576
{
 
577
    if (source_.GetError().What()) return;
 
578
 
 
579
    word32 read = source_.get_index();
 
580
    word32 length = GetSequence();
 
581
 
 
582
    read = source_.get_index() - read;
 
583
    length += read;
 
584
 
 
585
    if (source_.GetError().What()) return;
 
586
    while (read--) source_.prev();
 
587
 
 
588
    if (source_.IsLeft(length) == false) return;
 
589
    key_.SetSize(length);
 
590
    key_.SetKey(source_.get_current());
 
591
    source_.advance(length);
 
592
}
 
593
 
 
594
 
 
595
// DSA has public key after group
 
596
void CertDecoder::AddDSA()
 
597
{
 
598
    if (source_.GetError().What()) return;
 
599
 
 
600
    byte b = source_.next();
 
601
    if (b != BIT_STRING) {
 
602
        source_.SetError(BIT_STR_E);
 
603
        return;
 
604
    }
 
605
    b = source_.next();      // length, future
 
606
    b = source_.next(); 
 
607
    while(b != 0)
 
608
        b = source_.next();
 
609
 
 
610
    word32 idx = source_.get_index();
 
611
    b = source_.next();
 
612
    if (b != INTEGER) {
 
613
        source_.SetError(INTEGER_E);
 
614
        return;
 
615
    }
 
616
 
 
617
    word32 length = GetLength(source_);
 
618
    length += source_.get_index() - idx;
 
619
 
 
620
    if (source_.IsLeft(length) == false) return;
 
621
 
 
622
    key_.AddToEnd(source_.get_buffer() + idx, length);    
 
623
}
 
624
 
 
625
 
 
626
// process algo OID by summing, return it
 
627
word32 CertDecoder::GetAlgoId()
 
628
{
 
629
    if (source_.GetError().What()) return 0;
 
630
    word32 length = GetSequence();
 
631
 
 
632
    if (source_.GetError().What()) return 0;
 
633
    
 
634
    byte b = source_.next();
 
635
    if (b != OBJECT_IDENTIFIER) {
 
636
        source_.SetError(OBJECT_ID_E);
 
637
        return 0;
 
638
    }
 
639
 
 
640
    length = GetLength(source_);
 
641
    if (source_.IsLeft(length) == false) return 0;
 
642
 
 
643
    word32 oid = 0;
 
644
    while(length--)
 
645
        oid += source_.next();        // just sum it up for now
 
646
 
 
647
    // could have NULL tag and 0 terminator, but may not
 
648
    b = source_.next();
 
649
    if (b == TAG_NULL) {
 
650
        b = source_.next();
 
651
        if (b != 0) {
 
652
            source_.SetError(EXPECT_0_E);
 
653
            return 0;
 
654
        }
 
655
    }
 
656
    else
 
657
        // go back, didn't have it
 
658
        b = source_.prev();
 
659
 
 
660
    return oid;
 
661
}
 
662
 
 
663
 
 
664
// read cert signature, store in signature_
 
665
word32 CertDecoder::GetSignature()
 
666
{
 
667
    if (source_.GetError().What()) return 0;
 
668
    byte b = source_.next();
 
669
 
 
670
    if (b != BIT_STRING) {
 
671
        source_.SetError(BIT_STR_E);
 
672
        return 0;
 
673
    }
 
674
 
 
675
    sigLength_ = GetLength(source_);
 
676
    if (sigLength_ == 0 || source_.IsLeft(sigLength_) == false) {
 
677
        source_.SetError(CONTENT_E);
 
678
        return 0;
 
679
    }
 
680
  
 
681
    b = source_.next();
 
682
    if (b != 0) {
 
683
        source_.SetError(EXPECT_0_E);
 
684
        return 0;
 
685
    }
 
686
    sigLength_--;
 
687
 
 
688
    signature_ = NEW_TC byte[sigLength_];
 
689
    memcpy(signature_, source_.get_current(), sigLength_);
 
690
    source_.advance(sigLength_);
 
691
 
 
692
    return sigLength_;
 
693
}
 
694
 
 
695
 
 
696
// read cert digest, store in signature_
 
697
word32 CertDecoder::GetDigest()
 
698
{
 
699
    if (source_.GetError().What()) return 0;
 
700
    byte b = source_.next();
 
701
 
 
702
    if (b != OCTET_STRING) {
 
703
        source_.SetError(OCTET_STR_E);
 
704
        return 0;
 
705
    }
 
706
 
 
707
    sigLength_ = GetLength(source_);
 
708
 
 
709
    signature_ = NEW_TC byte[sigLength_];
 
710
    memcpy(signature_, source_.get_current(), sigLength_);
 
711
    source_.advance(sigLength_);
 
712
 
 
713
    return sigLength_;
 
714
}
 
715
 
 
716
 
 
717
// memory length checked add tag to buffer
 
718
char* CertDecoder::AddTag(char* ptr, const char* buf_end, const char* tag_name,
 
719
                          word32 tag_name_length, word32 tag_value_length)
 
720
{
 
721
    if (ptr + tag_name_length + tag_value_length > buf_end) {
 
722
        source_.SetError(CONTENT_E);
 
723
        return 0;
 
724
    }
 
725
 
 
726
    memcpy(ptr, tag_name, tag_name_length);
 
727
    ptr += tag_name_length;
 
728
 
 
729
    memcpy(ptr, source_.get_current(), tag_value_length);
 
730
    ptr += tag_value_length;
 
731
 
 
732
    return ptr;
 
733
}
 
734
 
 
735
 
 
736
// process NAME, either issuer or subject
 
737
void CertDecoder::GetName(NameType nt)
 
738
{
 
739
    if (source_.GetError().What()) return;
 
740
 
 
741
    SHA    sha;
 
742
    word32 length = GetSequence();  // length of all distinguished names
 
743
 
 
744
    if (length >= ASN_NAME_MAX)
 
745
        return;
 
746
    if (source_.IsLeft(length) == false) return;
 
747
    length += source_.get_index();
 
748
    
 
749
    char* ptr;
 
750
    char* buf_end;
 
751
 
 
752
    if (nt == ISSUER) {
 
753
        ptr = issuer_;
 
754
        buf_end = ptr + sizeof(issuer_) - 1;   // 1 byte for trailing 0
 
755
    }
 
756
    else {
 
757
        ptr = subject_;
 
758
        buf_end = ptr + sizeof(subject_) - 1;  // 1 byte for trailing 0
 
759
    }
 
760
 
 
761
    while (source_.get_index() < length) {
 
762
        GetSet();
 
763
        if (source_.GetError().What() == SET_E) {
 
764
            source_.SetError(NO_ERROR_E);  // extensions may only have sequence
 
765
            source_.prev();
 
766
        }
 
767
        GetSequence();
 
768
 
 
769
        byte b = source_.next();
 
770
        if (b != OBJECT_IDENTIFIER) {
 
771
            source_.SetError(OBJECT_ID_E);
 
772
            return;
 
773
        }
 
774
 
 
775
        word32 oidSz = GetLength(source_);
 
776
        if (source_.IsLeft(oidSz) == false) return;
 
777
 
 
778
        byte joint[2];
 
779
        if (source_.IsLeft(sizeof(joint)) == false) return;
 
780
        memcpy(joint, source_.get_current(), sizeof(joint));
 
781
 
 
782
        // v1 name types
 
783
        if (joint[0] == 0x55 && joint[1] == 0x04) {
 
784
            source_.advance(2);
 
785
            byte   id      = source_.next();  
 
786
            b              = source_.next();    // strType
 
787
            word32 strLen  = GetLength(source_);
 
788
 
 
789
            if (source_.IsLeft(strLen) == false) return;
 
790
 
 
791
            switch (id) {
 
792
            case COMMON_NAME:
 
793
                if (!(ptr = AddTag(ptr, buf_end, "/CN=", 4, strLen)))
 
794
                    return;
 
795
                break;
 
796
            case SUR_NAME:
 
797
                if (!(ptr = AddTag(ptr, buf_end, "/SN=", 4, strLen)))
 
798
                    return;
 
799
                break;
 
800
            case COUNTRY_NAME:
 
801
                if (!(ptr = AddTag(ptr, buf_end, "/C=", 3, strLen)))
 
802
                    return;
 
803
                break;
 
804
            case LOCALITY_NAME:
 
805
                if (!(ptr = AddTag(ptr, buf_end, "/L=", 3, strLen)))
 
806
                    return;
 
807
                break;
 
808
            case STATE_NAME:
 
809
                if (!(ptr = AddTag(ptr, buf_end, "/ST=", 4, strLen)))
 
810
                    return;
 
811
                break;
 
812
            case ORG_NAME:
 
813
                if (!(ptr = AddTag(ptr, buf_end, "/O=", 3, strLen)))
 
814
                    return;
 
815
                break;
 
816
            case ORGUNIT_NAME:
 
817
                if (!(ptr = AddTag(ptr, buf_end, "/OU=", 4, strLen)))
 
818
                    return;
 
819
                break;
 
820
            }
 
821
 
 
822
            sha.Update(source_.get_current(), strLen);
 
823
            source_.advance(strLen);
 
824
        }
 
825
        else { 
 
826
            bool email = false;
 
827
            if (joint[0] == 0x2a && joint[1] == 0x86)  // email id hdr
 
828
                email = true;
 
829
 
 
830
            source_.advance(oidSz + 1);
 
831
            word32 length = GetLength(source_);
 
832
            if (source_.IsLeft(length) == false) return;
 
833
 
 
834
            if (email) {
 
835
                if (!(ptr = AddTag(ptr, buf_end, "/emailAddress=", 14, length))) {
 
836
                    source_.SetError(CONTENT_E);
 
837
                    return;
 
838
                }
 
839
            }
 
840
 
 
841
            source_.advance(length);
 
842
        }
 
843
    }
 
844
 
 
845
    *ptr = 0;
 
846
 
 
847
    if (nt == ISSUER)
 
848
        sha.Final(issuerHash_);
 
849
    else
 
850
        sha.Final(subjectHash_);
 
851
}
 
852
 
 
853
 
 
854
// process a Date, either BEFORE or AFTER
 
855
void CertDecoder::GetDate(DateType dt)
 
856
{
 
857
    if (source_.GetError().What()) return;
 
858
 
 
859
    byte b = source_.next();
 
860
    if (b != UTC_TIME && b != GENERALIZED_TIME) {
 
861
        source_.SetError(TIME_E);
 
862
        return;
 
863
    }
 
864
 
 
865
    word32 length = GetLength(source_);
 
866
    if (source_.IsLeft(length) == false) return;
 
867
 
 
868
    byte date[MAX_DATE_SZ];
 
869
    if (length > MAX_DATE_SZ || length < MIN_DATE_SZ) {
 
870
        source_.SetError(DATE_SZ_E);
 
871
        return;
 
872
    }
 
873
 
 
874
    memcpy(date, source_.get_current(), length);
 
875
    source_.advance(length);
 
876
 
 
877
    if (!ValidateDate(date, b, dt) && verify_) {
 
878
        if (dt == BEFORE)
 
879
            source_.SetError(BEFORE_DATE_E);
 
880
        else
 
881
            source_.SetError(AFTER_DATE_E);
 
882
    }
 
883
 
 
884
    // save for later use
 
885
    if (dt == BEFORE) {
 
886
        memcpy(beforeDate_, date, length);
 
887
        beforeDate_[length] = 0;
 
888
    }
 
889
    else {  // after
 
890
        memcpy(afterDate_, date, length);
 
891
        afterDate_[length] = 0;
 
892
    }       
 
893
}
 
894
 
 
895
 
 
896
void CertDecoder::GetValidity()
 
897
{
 
898
    if (source_.GetError().What()) return;
 
899
 
 
900
    GetSequence();
 
901
    GetDate(BEFORE);
 
902
    GetDate(AFTER);
 
903
}
 
904
 
 
905
 
 
906
bool CertDecoder::ValidateSelfSignature()
 
907
{
 
908
    Source pub(key_.GetKey(), key_.size());
 
909
    return ConfirmSignature(pub);
 
910
}
 
911
 
 
912
 
 
913
// extract compare signature hash from plain and place into digest
 
914
void CertDecoder::GetCompareHash(const byte* plain, word32 sz, byte* digest,
 
915
                                 word32 digSz)
 
916
{
 
917
    if (source_.GetError().What()) return;
 
918
 
 
919
    Source s(plain, sz);
 
920
    CertDecoder dec(s, false);
 
921
 
 
922
    dec.GetSequence();
 
923
    dec.GetAlgoId();
 
924
    dec.GetDigest();
 
925
 
 
926
    if (dec.sigLength_ > digSz) {
 
927
        source_.SetError(SIG_LEN_E);
 
928
        return;
 
929
    }
 
930
 
 
931
    memcpy(digest, dec.signature_, dec.sigLength_);
 
932
}
 
933
 
 
934
 
 
935
// validate signature signed by someone else
 
936
bool CertDecoder::ValidateSignature(SignerList* signers)
 
937
{
 
938
    if (!signers)
 
939
        return false;
 
940
 
 
941
    SignerList::iterator first = signers->begin();
 
942
    SignerList::iterator last  = signers->end();
 
943
 
 
944
    while (first != last) {
 
945
        if ( memcmp(issuerHash_, (*first)->GetHash(), SHA::DIGEST_SIZE) == 0) {
 
946
      
 
947
            const PublicKey& iKey = (*first)->GetPublicKey();
 
948
            Source pub(iKey.GetKey(), iKey.size());
 
949
            return ConfirmSignature(pub);
 
950
        }   
 
951
        ++first;
 
952
    }
 
953
    return false;
 
954
}
 
955
 
 
956
 
 
957
// confirm certificate signature
 
958
bool CertDecoder::ConfirmSignature(Source& pub)
 
959
{
 
960
    HashType ht;
 
961
    mySTL::auto_ptr<HASH> hasher;
 
962
 
 
963
    if (signatureOID_ == MD5wRSA) {
 
964
        hasher.reset(NEW_TC MD5);
 
965
        ht = MD5h;
 
966
    }
 
967
    else if (signatureOID_ == MD2wRSA) {
 
968
        hasher.reset(NEW_TC MD2);
 
969
        ht = MD2h;
 
970
    }
 
971
    else if (signatureOID_ == SHAwRSA || signatureOID_ == SHAwDSA) {
 
972
        hasher.reset(NEW_TC SHA);
 
973
        ht = SHAh;
 
974
    }
 
975
    else {
 
976
        source_.SetError(UNKOWN_SIG_E);
 
977
        return false;
 
978
    }
 
979
 
 
980
    byte digest[SHA::DIGEST_SIZE];      // largest size
 
981
 
 
982
    hasher->Update(source_.get_buffer() + certBegin_, sigIndex_ - certBegin_);
 
983
    hasher->Final(digest);
 
984
 
 
985
    if (keyOID_ == RSAk) {
 
986
        // put in ASN.1 signature format
 
987
        Source build;
 
988
        Signature_Encoder(digest, hasher->getDigestSize(), ht, build);
 
989
 
 
990
        RSA_PublicKey pubKey(pub);
 
991
        RSAES_Encryptor enc(pubKey);
 
992
 
 
993
        return enc.SSL_Verify(build.get_buffer(), build.size(), signature_);
 
994
    }
 
995
    else  { // DSA
 
996
        // extract r and s from sequence
 
997
        byte seqDecoded[DSA_SIG_SZ];
 
998
        DecodeDSA_Signature(seqDecoded, signature_, sigLength_);
 
999
 
 
1000
        DSA_PublicKey pubKey(pub);
 
1001
        DSA_Verifier  ver(pubKey);
 
1002
 
 
1003
        return ver.Verify(digest, seqDecoded);
 
1004
    }
 
1005
}
 
1006
 
 
1007
 
 
1008
Signature_Encoder::Signature_Encoder(const byte* dig, word32 digSz,
 
1009
                                     HashType digOID, Source& source)
 
1010
{
 
1011
    // build bottom up
 
1012
 
 
1013
    // Digest
 
1014
    byte digArray[MAX_DIGEST_SZ];
 
1015
    word32 digestSz = SetDigest(dig, digSz, digArray);
 
1016
 
 
1017
    // AlgoID
 
1018
    byte algoArray[MAX_ALGO_SZ];
 
1019
    word32 algoSz = SetAlgoID(digOID, algoArray);
 
1020
 
 
1021
    // Sequence
 
1022
    byte seqArray[MAX_SEQ_SZ];
 
1023
    word32 seqSz = SetSequence(digestSz + algoSz, seqArray);
 
1024
 
 
1025
    source.grow(seqSz + algoSz + digestSz);  // make sure enough room
 
1026
    source.add(seqArray,  seqSz);
 
1027
    source.add(algoArray, algoSz);
 
1028
    source.add(digArray,  digestSz);
 
1029
}
 
1030
 
 
1031
 
 
1032
 
 
1033
word32 Signature_Encoder::SetDigest(const byte* d, word32 dSz, byte* output)
 
1034
{
 
1035
    output[0] = OCTET_STRING;
 
1036
    output[1] = dSz;
 
1037
    memcpy(&output[2], d, dSz);
 
1038
    
 
1039
    return dSz + 2;
 
1040
}
 
1041
 
 
1042
 
 
1043
 
 
1044
word32 DER_Encoder::SetAlgoID(HashType aOID, byte* output)
 
1045
{
 
1046
    // adding TAG_NULL and 0 to end
 
1047
    static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
 
1048
                                      0x05, 0x00 };
 
1049
    static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
 
1050
                                      0x02, 0x05, 0x05, 0x00  };
 
1051
    static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
 
1052
                                      0x02, 0x02, 0x05, 0x00};
 
1053
 
 
1054
    int algoSz = 0;
 
1055
    const byte* algoName = 0;
 
1056
 
 
1057
    switch (aOID) {
 
1058
    case SHAh:
 
1059
        algoSz = sizeof(shaAlgoID);
 
1060
        algoName = shaAlgoID;
 
1061
        break;
 
1062
 
 
1063
    case MD2h:
 
1064
        algoSz = sizeof(md2AlgoID);
 
1065
        algoName = md2AlgoID;
 
1066
        break;
 
1067
 
 
1068
    case MD5h:
 
1069
        algoSz = sizeof(md5AlgoID);
 
1070
        algoName = md5AlgoID;
 
1071
        break;
 
1072
 
 
1073
    default:
 
1074
        error_.SetError(UNKOWN_HASH_E);
 
1075
        return 0;
 
1076
    }
 
1077
 
 
1078
 
 
1079
    byte ID_Length[MAX_LENGTH_SZ];
 
1080
    word32 idSz = SetLength(algoSz - 2, ID_Length); // don't include TAG_NULL/0
 
1081
 
 
1082
    byte seqArray[MAX_SEQ_SZ + 1];  // add object_id to end
 
1083
    word32 seqSz = SetSequence(idSz + algoSz + 1, seqArray);
 
1084
    seqArray[seqSz++] = OBJECT_IDENTIFIER;
 
1085
 
 
1086
    memcpy(output, seqArray, seqSz);
 
1087
    memcpy(output + seqSz, ID_Length, idSz);
 
1088
    memcpy(output + seqSz + idSz, algoName, algoSz);
 
1089
 
 
1090
    return seqSz + idSz + algoSz;
 
1091
}
 
1092
 
 
1093
 
 
1094
word32 SetSequence(word32 len, byte* output)
 
1095
{
 
1096
  
 
1097
    output[0] = SEQUENCE | CONSTRUCTED;
 
1098
    return SetLength(len, output + 1) + 1;
 
1099
}
 
1100
 
 
1101
 
 
1102
word32 EncodeDSA_Signature(const byte* signature, byte* output)
 
1103
{
 
1104
    Integer r(signature, 20);
 
1105
    Integer s(signature + 20, 20);
 
1106
 
 
1107
    return EncodeDSA_Signature(r, s, output);
 
1108
}
 
1109
 
 
1110
 
 
1111
word32 EncodeDSA_Signature(const Integer& r, const Integer& s, byte* output)
 
1112
{
 
1113
    word32 rSz = r.ByteCount();
 
1114
    word32 sSz = s.ByteCount();
 
1115
 
 
1116
    byte rLen[MAX_LENGTH_SZ + 1];
 
1117
    byte sLen[MAX_LENGTH_SZ + 1];
 
1118
 
 
1119
    rLen[0] = INTEGER;
 
1120
    sLen[0] = INTEGER;
 
1121
 
 
1122
    word32 rLenSz = SetLength(rSz, &rLen[1]) + 1;
 
1123
    word32 sLenSz = SetLength(sSz, &sLen[1]) + 1;
 
1124
 
 
1125
    byte seqArray[MAX_SEQ_SZ];
 
1126
 
 
1127
    word32 seqSz = SetSequence(rLenSz + rSz + sLenSz + sSz, seqArray);
 
1128
    
 
1129
    // seq
 
1130
    memcpy(output, seqArray, seqSz);
 
1131
    // r
 
1132
    memcpy(output + seqSz, rLen, rLenSz);
 
1133
    r.Encode(output + seqSz + rLenSz, rSz);
 
1134
    // s
 
1135
    memcpy(output + seqSz + rLenSz + rSz, sLen, sLenSz);
 
1136
    s.Encode(output + seqSz + rLenSz + rSz + sLenSz, sSz);
 
1137
 
 
1138
    return seqSz + rLenSz + rSz + sLenSz + sSz;
 
1139
}
 
1140
 
 
1141
 
 
1142
// put sequence encoded dsa signature into decoded in 2 20 byte integers
 
1143
word32 DecodeDSA_Signature(byte* decoded, const byte* encoded, word32 sz)
 
1144
{
 
1145
    Source source(encoded, sz);
 
1146
 
 
1147
    if (source.next() != (SEQUENCE | CONSTRUCTED)) {
 
1148
        source.SetError(SEQUENCE_E);
 
1149
        return 0;
 
1150
    }
 
1151
 
 
1152
    GetLength(source);  // total
 
1153
 
 
1154
    // r
 
1155
    if (source.next() != INTEGER) {
 
1156
        source.SetError(INTEGER_E);
 
1157
        return 0;
 
1158
    }
 
1159
    word32 rLen = GetLength(source);
 
1160
    if (rLen != 20) {
 
1161
        if (rLen == 21) {       // zero at front, eat
 
1162
            source.next();
 
1163
            --rLen;
 
1164
        }
 
1165
        else if (rLen == 19) {  // add zero to front so 20 bytes
 
1166
            decoded[0] = 0;
 
1167
            decoded++;
 
1168
        }
 
1169
        else {
 
1170
            source.SetError(DSA_SZ_E);
 
1171
            return 0;
 
1172
        }
 
1173
    }
 
1174
    memcpy(decoded, source.get_buffer() + source.get_index(), rLen);
 
1175
    source.advance(rLen);
 
1176
 
 
1177
    // s
 
1178
    if (source.next() != INTEGER) {
 
1179
        source.SetError(INTEGER_E);
 
1180
        return 0;
 
1181
    }
 
1182
    word32 sLen = GetLength(source);
 
1183
    if (sLen != 20) {
 
1184
        if (sLen == 21) {
 
1185
            source.next();          // zero at front, eat
 
1186
            --sLen;
 
1187
        }
 
1188
        else if (sLen == 19) {
 
1189
            decoded[rLen] = 0;      // add zero to front so 20 bytes
 
1190
            decoded++;
 
1191
        }
 
1192
        else {
 
1193
            source.SetError(DSA_SZ_E);
 
1194
            return 0;
 
1195
        }
 
1196
    }
 
1197
    memcpy(decoded + rLen, source.get_buffer() + source.get_index(), sLen);
 
1198
    source.advance(sLen);
 
1199
 
 
1200
    return 40;
 
1201
}
 
1202
 
 
1203
 
 
1204
/*
 
1205
// Get Cert in PEM format from BEGIN to END
 
1206
int GetCert(Source& source)
 
1207
{
 
1208
    char header[] = "-----BEGIN CERTIFICATE-----";
 
1209
    char footer[] = "-----END CERTIFICATE-----";
 
1210
 
 
1211
    char* begin = strstr((char*)source.get_buffer(), header);
 
1212
    char* end   = strstr((char*)source.get_buffer(), footer);
 
1213
 
 
1214
    if (!begin || !end || begin >= end) return -1;
 
1215
 
 
1216
    end += strlen(footer); 
 
1217
    if (*end == '\r') end++;
 
1218
 
 
1219
    Source tmp((byte*)begin, end - begin + 1);
 
1220
    source.Swap(tmp);
 
1221
 
 
1222
    return 0;
 
1223
}
 
1224
 
 
1225
 
 
1226
 
 
1227
// Decode a BER encoded PKCS12 structure
 
1228
void PKCS12_Decoder::Decode()
 
1229
{
 
1230
    ReadHeader();
 
1231
    if (source_.GetError().What()) return;
 
1232
 
 
1233
    // Get AuthSafe
 
1234
 
 
1235
    GetSequence();
 
1236
    
 
1237
        // get object id
 
1238
    byte obj_id = source_.next();
 
1239
    if (obj_id != OBJECT_IDENTIFIER) {
 
1240
        source_.SetError(OBJECT_ID_E);
 
1241
        return;
 
1242
    }
 
1243
 
 
1244
    word32 length = GetLength(source_);
 
1245
 
 
1246
    word32 algo_sum = 0;
 
1247
    while (length--)
 
1248
        algo_sum += source_.next();
 
1249
 
 
1250
    
 
1251
       
 
1252
 
 
1253
 
 
1254
 
 
1255
    // Get MacData optional
 
1256
    // mac     digestInfo  like certdecoder::getdigest?
 
1257
    // macsalt octet string
 
1258
    // iter    integer
 
1259
    
 
1260
}
 
1261
 
 
1262
 
 
1263
void PKCS12_Decoder::ReadHeader()
 
1264
{
 
1265
    // Gets Version
 
1266
    GetSequence();
 
1267
    GetVersion();
 
1268
}
 
1269
 
 
1270
 
 
1271
// Get Cert in PEM format from pkcs12 file
 
1272
int GetPKCS_Cert(const char* password, Source& source)
 
1273
{
 
1274
    PKCS12_Decoder pkcs12(source);
 
1275
    pkcs12.Decode();
 
1276
 
 
1277
    return 0;
 
1278
}
 
1279
*/
 
1280
 
 
1281
 
 
1282
 
 
1283
} // namespace