summaryrefslogtreecommitdiff
path: root/mysql/extra/yassl/taocrypt/src/asn.cpp
blob: e0aef45fc276c7e3db99921c82ce29048cc50503 (plain)
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
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
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
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
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
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
/*
   Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

   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.
*/

/* asn.cpp implements ASN1 BER, PublicKey, and x509v3 decoding 
*/

#include "runtime.hpp"
#include "asn.hpp"
#include "file.hpp"
#include "integer.hpp"
#include "rsa.hpp"
#include "dsa.hpp"
#include "dh.hpp"
#include "md5.hpp"
#include "md2.hpp"
#include "sha.hpp"
#include "coding.hpp"
#include <time.h>     // gmtime();
#include "memory.hpp" // some auto_ptr don't have reset, also need auto_array


namespace TaoCrypt {

// like atoi but only use first byte
word32 btoi(byte b)
{
    return b - 0x30;
}


// two byte date/time, add to value
void GetTime(int *value, const byte* date, int& i)
{
    *value += btoi(date[i++]) * 10;
    *value += btoi(date[i++]);
}


bool ASN1_TIME_extract(const unsigned char* date, unsigned char format,
                       tm *t)
{
  int i = 0;
  memset(t, 0, sizeof (tm));

  if (format != UTC_TIME && format != GENERALIZED_TIME)
    return false;

  if (format == UTC_TIME) {
    if (btoi(date[0]) >= 5)
      t->tm_year = 1900;
    else
      t->tm_year = 2000;
  }
  else  { // format == GENERALIZED_TIME
    t->tm_year += btoi(date[i++]) * 1000;
    t->tm_year += btoi(date[i++]) * 100;
  }

  GetTime(&t->tm_year, date, i);     t->tm_year -= 1900; // adjust
  GetTime(&t->tm_mon,  date, i);     t->tm_mon  -= 1;    // adjust
  GetTime(&t->tm_mday, date, i);
  GetTime(&t->tm_hour, date, i);
  GetTime(&t->tm_min,  date, i);
  GetTime(&t->tm_sec,  date, i);

  if (date[i] != 'Z')     // only Zulu supported for this profile
    return false;
  return true;
}


namespace { // locals


// to the second
bool operator>(tm& a, tm& b)
{
    if (a.tm_year > b.tm_year)
        return true;

    if (a.tm_year == b.tm_year && a.tm_mon > b.tm_mon)
        return true;
    
    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon && a.tm_mday >b.tm_mday)
        return true;

    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon &&
        a.tm_mday == b.tm_mday && a.tm_hour > b.tm_hour)
        return true;

    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon &&
        a.tm_mday == b.tm_mday && a.tm_hour == b.tm_hour &&
        a.tm_min > b.tm_min)
        return true;

    if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon &&
        a.tm_mday == b.tm_mday && a.tm_hour == b.tm_hour &&
        a.tm_min  == b.tm_min  && a.tm_sec > b.tm_sec)
        return true;

    return false;
}


bool operator<(tm& a, tm&b)
{
    return (b>a);
}


// Make sure before and after dates are valid
bool ValidateDate(const byte* date, byte format, CertDecoder::DateType dt)
{
    tm certTime;

    if (!ASN1_TIME_extract(date, format, &certTime))
        return false;

    time_t ltime = time(0);
    tm* localTime = gmtime(&ltime);

    if (dt == CertDecoder::BEFORE) {
        if (*localTime < certTime)
            return false;
    }
    else
        if (*localTime > certTime)
            return false;

    return true;
}


class BadCertificate {};

} // local namespace



// used by Integer as well
word32 GetLength(Source& source)
{
    word32 length = 0;

    byte b = source.next();
    if (b >= LONG_LENGTH) {        
        word32 bytes = b & 0x7F;

        if (source.IsLeft(bytes) == false) return 0;

        while (bytes--) {
            b = source.next();
            length = (length << 8) | b;
        }
    }
    else
        length = b;

    if (source.IsLeft(length) == false) return 0;

    return length;
}


word32 SetLength(word32 length, byte* output)
{
    word32 i = 0;

    if (length < LONG_LENGTH)
        output[i++] = length;
    else {
        output[i++] = BytePrecision(length) | 0x80;
      
        for (int j = BytePrecision(length); j; --j) {
            output[i] = length >> (j - 1) * 8;
            i++;
        }
    }
    return i;
}


PublicKey::PublicKey(const byte* k, word32 s) : key_(0), sz_(0)
{
    if (s) {
        SetSize(s);
        SetKey(k);
    }
}


void PublicKey::SetSize(word32 s)
{
    sz_ = s;
    key_ = NEW_TC byte[sz_];
}


void PublicKey::SetKey(const byte* k)
{
    memcpy(key_, k, sz_);
}


void PublicKey::AddToEnd(const byte* data, word32 len)
{
    mySTL::auto_array<byte> tmp(NEW_TC byte[sz_ + len]);

    memcpy(tmp.get(), key_, sz_);
    memcpy(tmp.get() + sz_, data, len);

    byte* del = 0;
    STL::swap(del, key_);
    tcArrayDelete(del);

    key_ = tmp.release();
    sz_ += len;
}


Signer::Signer(const byte* k, word32 kSz, const char* n, const byte* h)
    : key_(k, kSz)
{
    size_t sz = strlen(n);
    memcpy(name_, n, sz);
    name_[sz] = 0;

    memcpy(hash_, h, SHA::DIGEST_SIZE);
}

Signer::~Signer()
{
}


Error BER_Decoder::GetError()
{ 
    return source_.GetError(); 
}


Integer& BER_Decoder::GetInteger(Integer& integer)
{
    if (!source_.GetError().What())
        integer.Decode(source_);
    return integer;
}

  
// Read a Sequence, return length
word32 BER_Decoder::GetSequence()
{
    if (source_.GetError().What()) return 0;

    byte b = source_.next();
    if (b != (SEQUENCE | CONSTRUCTED)) {
        source_.SetError(SEQUENCE_E);
        return 0;
    }

    return GetLength(source_);
}


// Read a Sequence, return length
word32 BER_Decoder::GetSet()
{
    if (source_.GetError().What()) return 0;

    byte b = source_.next();
    if (b != (SET | CONSTRUCTED)) {
        source_.SetError(SET_E);
        return 0;
    }

    return GetLength(source_);
}


// Read Version, return it
word32 BER_Decoder::GetVersion()
{
    if (source_.GetError().What()) return 0;

    byte b = source_.next();
    if (b != INTEGER) {
        source_.SetError(INTEGER_E);
        return 0;
    }

    b = source_.next();
    if (b != 0x01) {
        source_.SetError(VERSION_E);
        return 0;
    }

    return source_.next();
}


// Read ExplicitVersion, return it or 0 if not there (not an error)
word32 BER_Decoder::GetExplicitVersion()
{
    if (source_.GetError().What()) return 0;

    byte b = source_.next();

    if (b == (CONTEXT_SPECIFIC | CONSTRUCTED)) { // not an error if not here
        source_.next();
        return GetVersion();
    }
    else 
        source_.prev(); // put back
  
    return 0;
}


// Decode a BER encoded RSA Private Key
void RSA_Private_Decoder::Decode(RSA_PrivateKey& key)
{
    ReadHeader();
    if (source_.GetError().What()) return;
    // public
    key.SetModulus(GetInteger(Integer().Ref()));
    key.SetPublicExponent(GetInteger(Integer().Ref()));

    // private
    key.SetPrivateExponent(GetInteger(Integer().Ref()));
    key.SetPrime1(GetInteger(Integer().Ref()));
    key.SetPrime2(GetInteger(Integer().Ref()));
    key.SetModPrime1PrivateExponent(GetInteger(Integer().Ref()));
    key.SetModPrime2PrivateExponent(GetInteger(Integer().Ref()));
    key.SetMultiplicativeInverseOfPrime2ModPrime1(GetInteger(Integer().Ref()));
}


void RSA_Private_Decoder::ReadHeader()
{
    GetSequence();
    GetVersion();
}


// Decode a BER encoded DSA Private Key
void DSA_Private_Decoder::Decode(DSA_PrivateKey& key)
{
    ReadHeader();
    if (source_.GetError().What()) return;
    // group parameters
    key.SetModulus(GetInteger(Integer().Ref()));
    key.SetSubGroupOrder(GetInteger(Integer().Ref()));
    key.SetSubGroupGenerator(GetInteger(Integer().Ref()));

    // key
    key.SetPublicPart(GetInteger(Integer().Ref()));
    key.SetPrivatePart(GetInteger(Integer().Ref()));   
}


void DSA_Private_Decoder::ReadHeader()
{
    GetSequence();
    GetVersion();
}


// Decode a BER encoded RSA Public Key
void RSA_Public_Decoder::Decode(RSA_PublicKey& key)
{
    ReadHeader();
    if (source_.GetError().What()) return;

    ReadHeaderOpenSSL();   // may or may not be
    if (source_.GetError().What()) return;

    // public key
    key.SetModulus(GetInteger(Integer().Ref()));
    key.SetPublicExponent(GetInteger(Integer().Ref()));
}


// Read OpenSSL format public header
void RSA_Public_Decoder::ReadHeaderOpenSSL()
{
    byte b = source_.next();  // peek
    source_.prev();

    if (b != INTEGER) { // have OpenSSL public format
        GetSequence();
        b = source_.next();
        if (b != OBJECT_IDENTIFIER) {
            source_.SetError(OBJECT_ID_E);
            return;
        }

        word32 len = GetLength(source_);
        source_.advance(len);

        b = source_.next();
        if (b == TAG_NULL) {   // could have NULL tag and 0 terminator, may not 
            b = source_.next();
            if (b != 0) {
                source_.SetError(EXPECT_0_E);
                return; 
            }
        }
        else
            source_.prev();   // put back

        b = source_.next();
        if (b != BIT_STRING) {   
            source_.SetError(BIT_STR_E);
            return; 
        }

        len = GetLength(source_); 
        b = source_.next();
        if (b != 0)           // could have 0
            source_.prev();   // put back
        
        GetSequence();
    }
}


void RSA_Public_Decoder::ReadHeader()
{
    GetSequence();
}


// Decode a BER encoded DSA Public Key
void DSA_Public_Decoder::Decode(DSA_PublicKey& key)
{
    ReadHeader();
    if (source_.GetError().What()) return;

    // group parameters
    key.SetModulus(GetInteger(Integer().Ref()));
    key.SetSubGroupOrder(GetInteger(Integer().Ref()));
    key.SetSubGroupGenerator(GetInteger(Integer().Ref()));

    // key
    key.SetPublicPart(GetInteger(Integer().Ref()));
}


void DSA_Public_Decoder::ReadHeader()
{
    GetSequence();
}


void DH_Decoder::ReadHeader()
{
    GetSequence();
}


// Decode a BER encoded Diffie-Hellman Key
void DH_Decoder::Decode(DH& key)
{
    ReadHeader();
    if (source_.GetError().What()) return;

    // group parms
    key.SetP(GetInteger(Integer().Ref()));
    key.SetG(GetInteger(Integer().Ref()));
}


CertDecoder::CertDecoder(Source& s, bool decode, SignerList* signers,
                         bool noVerify, CertType ct)
    : BER_Decoder(s), certBegin_(0), sigIndex_(0), sigLength_(0), subCnPos_(-1),
      subCnLen_(0), issCnPos_(-1), issCnLen_(0), signature_(0),
      verify_(!noVerify)
{
    issuer_[0] = 0;
    subject_[0] = 0;

    if (decode)
        Decode(signers, ct);

}


CertDecoder::~CertDecoder()
{
    tcArrayDelete(signature_);
}


// process certificate header, set signature offset
void CertDecoder::ReadHeader()
{
    if (source_.GetError().What()) return;

    GetSequence();  // total
    certBegin_ = source_.get_index();

    sigIndex_ = GetSequence();  // this cert
    sigIndex_ += source_.get_index();

    GetExplicitVersion(); // version
    GetInteger(Integer().Ref());  // serial number
}


// Decode a x509v3 Certificate
void CertDecoder::Decode(SignerList* signers, CertType ct)
{
    if (source_.GetError().What()) return;
    DecodeToKey();
    if (source_.GetError().What()) return;

    if (source_.get_index() != sigIndex_)
        source_.set_index(sigIndex_);

    word32 confirmOID = GetAlgoId();
    GetSignature();
    if (source_.GetError().What()) return;

    if ( confirmOID != signatureOID_ ) {
        source_.SetError(SIG_OID_E);
        return;
    }
    
    if (ct != CA && verify_ && !ValidateSignature(signers))
        source_.SetError(SIG_OTHER_E);
}


void CertDecoder::DecodeToKey()
{
    ReadHeader();
    signatureOID_ = GetAlgoId();
    GetName(ISSUER);   
    GetValidity();
    GetName(SUBJECT);   
    GetKey();
}


// Read public key
void CertDecoder::GetKey()
{
    if (source_.GetError().What()) return;

    GetSequence();    
    keyOID_ = GetAlgoId();

    if (keyOID_ == RSAk) {
        byte b = source_.next();
        if (b != BIT_STRING) {
            source_.SetError(BIT_STR_E);
            return;
        }
        b = source_.next();      // length, future
        b = source_.next(); 
        while(b != 0)
            b = source_.next();
    }
    else if (keyOID_ == DSAk)
        ;   // do nothing
    else {
        source_.SetError(UNKNOWN_OID_E);
        return;
    }

    StoreKey();
    if (keyOID_ == DSAk)
        AddDSA();
}


// Save public key
void CertDecoder::StoreKey()
{
    if (source_.GetError().What()) return;

    word32 read = source_.get_index();
    word32 length = GetSequence();

    read = source_.get_index() - read;
    length += read;

    if (source_.GetError().What()) return;
    while (read--) source_.prev();

    if (source_.IsLeft(length) == false) return;
    key_.SetSize(length);
    key_.SetKey(source_.get_current());
    source_.advance(length);
}


// DSA has public key after group
void CertDecoder::AddDSA()
{
    if (source_.GetError().What()) return;

    byte b = source_.next();
    if (b != BIT_STRING) {
        source_.SetError(BIT_STR_E);
        return;
    }
    b = source_.next();      // length, future
    b = source_.next(); 
    while(b != 0)
        b = source_.next();

    word32 idx = source_.get_index();
    b = source_.next();
    if (b != INTEGER) {
        source_.SetError(INTEGER_E);
        return;
    }

    word32 length = GetLength(source_);
    length += source_.get_index() - idx;

    if (source_.IsLeft(length) == false) return;

    key_.AddToEnd(source_.get_buffer() + idx, length);    
}


// process algo OID by summing, return it
word32 CertDecoder::GetAlgoId()
{
    if (source_.GetError().What()) return 0;
    word32 length = GetSequence();

    if (source_.GetError().What()) return 0;
    
    byte b = source_.next();
    if (b != OBJECT_IDENTIFIER) {
        source_.SetError(OBJECT_ID_E);
        return 0;
    }

    length = GetLength(source_);
    if (source_.IsLeft(length) == false) return 0;

    word32 oid = 0;
    while(length--)
        oid += source_.next();        // just sum it up for now

    // could have NULL tag and 0 terminator, but may not
    b = source_.next();
    if (b == TAG_NULL) {
        b = source_.next();
        if (b != 0) {
            source_.SetError(EXPECT_0_E);
            return 0;
        }
    }
    else
        // go back, didn't have it
        b = source_.prev();

    return oid;
}


// read cert signature, store in signature_
word32 CertDecoder::GetSignature()
{
    if (source_.GetError().What()) return 0;
    byte b = source_.next();

    if (b != BIT_STRING) {
        source_.SetError(BIT_STR_E);
        return 0;
    }

    sigLength_ = GetLength(source_);
    if (sigLength_ <= 1 || source_.IsLeft(sigLength_) == false) {
        source_.SetError(CONTENT_E);
        return 0;
    }
  
    b = source_.next();
    if (b != 0) {
        source_.SetError(EXPECT_0_E);
        return 0;
    }
    sigLength_--;

    signature_ = NEW_TC byte[sigLength_];
    memcpy(signature_, source_.get_current(), sigLength_);
    source_.advance(sigLength_);

    return sigLength_;
}


// read cert digest, store in signature_
word32 CertDecoder::GetDigest()
{
    if (source_.GetError().What()) return 0;
    byte b = source_.next();

    if (b != OCTET_STRING) {
        source_.SetError(OCTET_STR_E);
        return 0;
    }

    sigLength_ = GetLength(source_);

    signature_ = NEW_TC byte[sigLength_];
    memcpy(signature_, source_.get_current(), sigLength_);
    source_.advance(sigLength_);

    return sigLength_;
}


// memory length checked add tag to buffer
char* CertDecoder::AddTag(char* ptr, const char* buf_end, const char* tag_name,
                          word32 tag_name_length, word32 tag_value_length)
{
    if (ptr + tag_name_length + tag_value_length > buf_end) {
        source_.SetError(CONTENT_E);
        return 0;
    }

    memcpy(ptr, tag_name, tag_name_length);
    ptr += tag_name_length;

    memcpy(ptr, source_.get_current(), tag_value_length);
    ptr += tag_value_length;

    return ptr;
}


// process NAME, either issuer or subject
void CertDecoder::GetName(NameType nt)
{
    if (source_.GetError().What()) return;

    SHA    sha;
    word32 length = GetSequence();  // length of all distinguished names

    if (length >= ASN_NAME_MAX)
        return;
    if (source_.IsLeft(length) == false) return;
    length += source_.get_index();
    
    char* ptr;
    char* buf_end;

    if (nt == ISSUER) {
        ptr = issuer_;
        buf_end = ptr + sizeof(issuer_) - 1;   // 1 byte for trailing 0
    }
    else {
        ptr = subject_;
        buf_end = ptr + sizeof(subject_) - 1;  // 1 byte for trailing 0
    }

    while (source_.get_index() < length) {
        GetSet();
        if (source_.GetError().What() == SET_E) {
            source_.SetError(NO_ERROR_E);  // extensions may only have sequence 
            source_.prev();
        }
        GetSequence();

        byte b = source_.next();
        if (b != OBJECT_IDENTIFIER) {
            source_.SetError(OBJECT_ID_E);
            return;
        }

        word32 oidSz = GetLength(source_);
        if (source_.IsLeft(oidSz) == false) return;

        byte joint[2];
        if (source_.IsLeft(sizeof(joint)) == false) return;
        memcpy(joint, source_.get_current(), sizeof(joint));

        // v1 name types
        if (joint[0] == 0x55 && joint[1] == 0x04) {
            source_.advance(2);
            byte   id      = source_.next();  
            b              = source_.next();    // strType
            word32 strLen  = GetLength(source_);

            if (source_.IsLeft(strLen) == false) return;

            switch (id) {
            case COMMON_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/CN=", 4, strLen)))
                    return;
                if (nt == ISSUER) {
                    issCnPos_ = (int)(ptr - strLen - issuer_);
                    issCnLen_ = (int)strLen;
                } else {
                    subCnPos_ = (int)(ptr - strLen - subject_);
                    subCnLen_ = (int)strLen;
                }
                break;
            case SUR_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/SN=", 4, strLen)))
                    return;
                break;
            case COUNTRY_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/C=", 3, strLen)))
                    return;
                break;
            case LOCALITY_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/L=", 3, strLen)))
                    return;
                break;
            case STATE_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/ST=", 4, strLen)))
                    return;
                break;
            case ORG_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/O=", 3, strLen)))
                    return;
                break;
            case ORGUNIT_NAME:
                if (!(ptr = AddTag(ptr, buf_end, "/OU=", 4, strLen)))
                    return;
                break;
            }

            sha.Update(source_.get_current(), strLen);
            source_.advance(strLen);
        }
        else { 
            bool email = false;
            if (joint[0] == 0x2a && joint[1] == 0x86)  // email id hdr
                email = true;

            source_.advance(oidSz + 1);
            word32 length = GetLength(source_);
            if (source_.IsLeft(length) == false) return;

            if (email) {
                if (!(ptr = AddTag(ptr, buf_end, "/emailAddress=", 14, length)))
                    return; 
            }

            source_.advance(length);
        }
    }

    *ptr = 0;

    if (nt == ISSUER)
        sha.Final(issuerHash_);
    else
        sha.Final(subjectHash_);
}


// process a Date, either BEFORE or AFTER
void CertDecoder::GetDate(DateType dt)
{
    if (source_.GetError().What()) return;

    byte b = source_.next();
    if (b != UTC_TIME && b != GENERALIZED_TIME) {
        source_.SetError(TIME_E);
        return;
    }

    word32 length = GetLength(source_);
    if (source_.IsLeft(length) == false) return;

    byte date[MAX_DATE_SZ];
    if (length > MAX_DATE_SZ || length < MIN_DATE_SZ) {
        source_.SetError(DATE_SZ_E);
        return;
    }

    memcpy(date, source_.get_current(), length);
    source_.advance(length);

    if (!ValidateDate(date, b, dt) && verify_) {
        if (dt == BEFORE)
            source_.SetError(BEFORE_DATE_E);
        else
            source_.SetError(AFTER_DATE_E);
    }

    // save for later use
    if (dt == BEFORE) {
        memcpy(beforeDate_, date, length);
        beforeDate_[length] = 0;
        beforeDateType_= b;
    }
    else {  // after
        memcpy(afterDate_, date, length);
        afterDate_[length] = 0;
        afterDateType_= b;
    }       
}


void CertDecoder::GetValidity()
{
    if (source_.GetError().What()) return;

    GetSequence();
    GetDate(BEFORE);
    GetDate(AFTER);
}


bool CertDecoder::ValidateSelfSignature()
{
    Source pub(key_.GetKey(), key_.size());
    return ConfirmSignature(pub);
}


// extract compare signature hash from plain and place into digest
void CertDecoder::GetCompareHash(const byte* plain, word32 sz, byte* digest,
                                 word32 digSz)
{
    if (source_.GetError().What()) return;

    Source s(plain, sz);
    CertDecoder dec(s, false);

    dec.GetSequence();
    dec.GetAlgoId();
    dec.GetDigest();

    if (dec.sigLength_ > digSz) {
        source_.SetError(SIG_LEN_E);
        return;
    }

    memcpy(digest, dec.signature_, dec.sigLength_);
}


// validate signature signed by someone else
bool CertDecoder::ValidateSignature(SignerList* signers)
{
    if (!signers)
        return false;

    SignerList::iterator first = signers->begin();
    SignerList::iterator last  = signers->end();

    while (first != last) {
        if ( memcmp(issuerHash_, (*first)->GetHash(), SHA::DIGEST_SIZE) == 0) {
      
            const PublicKey& iKey = (*first)->GetPublicKey();
            Source pub(iKey.GetKey(), iKey.size());
            return ConfirmSignature(pub);
        }   
        ++first;
    }
    return false;
}


// confirm certificate signature
bool CertDecoder::ConfirmSignature(Source& pub)
{
    HashType ht;
    mySTL::auto_ptr<HASH> hasher;

    if (signatureOID_ == MD5wRSA) {
        hasher.reset(NEW_TC MD5);
        ht = MD5h;
    }
    else if (signatureOID_ == MD2wRSA) {
        hasher.reset(NEW_TC MD2);
        ht = MD2h;
    }
    else if (signatureOID_ == SHAwRSA || signatureOID_ == SHAwDSA) {
        hasher.reset(NEW_TC SHA);
        ht = SHAh;
    }
    else if (signatureOID_ == SHA256wRSA || signatureOID_ == SHA256wDSA) {
        hasher.reset(NEW_TC SHA256);
        ht = SHA256h;
    }
#ifdef WORD64_AVAILABLE
    else if (signatureOID_ == SHA384wRSA) {
        hasher.reset(NEW_TC SHA384);
        ht = SHA384h;
    }
    else if (signatureOID_ == SHA512wRSA) {
        hasher.reset(NEW_TC SHA512);
        ht = SHA512h;
    }
#endif
    else {
        source_.SetError(UNKOWN_SIG_E);
        return false;
    }

    byte digest[MAX_SHA2_DIGEST_SIZE];      // largest size

    hasher->Update(source_.get_buffer() + certBegin_, sigIndex_ - certBegin_);
    hasher->Final(digest);

    if (keyOID_ == RSAk) {
        // put in ASN.1 signature format
        Source build;
        Signature_Encoder(digest, hasher->getDigestSize(), ht, build);

        RSA_PublicKey pubKey(pub);
        RSAES_Encryptor enc(pubKey);

        if (pubKey.FixedCiphertextLength() != sigLength_) {
            source_.SetError(SIG_LEN_E);
            return false;
        }

        return enc.SSL_Verify(build.get_buffer(), build.size(), signature_);
    }
    else  { // DSA
        // extract r and s from sequence
        byte seqDecoded[DSA_SIG_SZ];
        memset(seqDecoded, 0, sizeof(seqDecoded));
        DecodeDSA_Signature(seqDecoded, signature_, sigLength_);

        DSA_PublicKey pubKey(pub);
        DSA_Verifier  ver(pubKey);

        return ver.Verify(digest, seqDecoded);
    }
}


Signature_Encoder::Signature_Encoder(const byte* dig, word32 digSz,
                                     HashType digOID, Source& source)
{
    // build bottom up

    // Digest
    byte digArray[MAX_DIGEST_SZ];
    word32 digestSz = SetDigest(dig, digSz, digArray);

    // AlgoID
    byte algoArray[MAX_ALGO_SZ];
    word32 algoSz = SetAlgoID(digOID, algoArray);

    // Sequence
    byte seqArray[MAX_SEQ_SZ];
    word32 seqSz = SetSequence(digestSz + algoSz, seqArray);

    source.grow(seqSz + algoSz + digestSz);  // make sure enough room
    source.add(seqArray,  seqSz);
    source.add(algoArray, algoSz);
    source.add(digArray,  digestSz);
}



word32 Signature_Encoder::SetDigest(const byte* d, word32 dSz, byte* output)
{
    output[0] = OCTET_STRING;
    output[1] = dSz;
    memcpy(&output[2], d, dSz);
    
    return dSz + 2;
}



word32 DER_Encoder::SetAlgoID(HashType aOID, byte* output)
{
    // adding TAG_NULL and 0 to end
    static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
                                      0x05, 0x00 };
    static const byte md5AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
                                      0x02, 0x05, 0x05, 0x00  };
    static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
                                      0x02, 0x02, 0x05, 0x00};
    static const byte sha256AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
                                         0x04, 0x02, 0x01, 0x05, 0x00 };
    static const byte sha384AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
                                         0x04, 0x02, 0x02, 0x05, 0x00 };
    static const byte sha512AlgoID[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
                                         0x04, 0x02, 0x03, 0x05, 0x00 };
    int algoSz = 0;
    const byte* algoName = 0;

    switch (aOID) {
    case SHAh:
        algoSz = sizeof(shaAlgoID);
        algoName = shaAlgoID;
        break;

    case SHA256h:
        algoSz = sizeof(sha256AlgoID);
        algoName = sha256AlgoID;
        break;

    case SHA384h:
        algoSz = sizeof(sha384AlgoID);
        algoName = sha384AlgoID;
        break;

    case SHA512h:
        algoSz = sizeof(sha512AlgoID);
        algoName = sha512AlgoID;
        break;

    case MD2h:
        algoSz = sizeof(md2AlgoID);
        algoName = md2AlgoID;
        break;

    case MD5h:
        algoSz = sizeof(md5AlgoID);
        algoName = md5AlgoID;
        break;

    default:
        error_.SetError(UNKOWN_HASH_E);
        return 0;
    }


    byte ID_Length[MAX_LENGTH_SZ];
    word32 idSz = SetLength(algoSz - 2, ID_Length); // don't include TAG_NULL/0

    byte seqArray[MAX_SEQ_SZ + 1];  // add object_id to end
    word32 seqSz = SetSequence(idSz + algoSz + 1, seqArray);
    seqArray[seqSz++] = OBJECT_IDENTIFIER;

    memcpy(output, seqArray, seqSz);
    memcpy(output + seqSz, ID_Length, idSz);
    memcpy(output + seqSz + idSz, algoName, algoSz);

    return seqSz + idSz + algoSz;
}


word32 SetSequence(word32 len, byte* output)
{
  
    output[0] = SEQUENCE | CONSTRUCTED;
    return SetLength(len, output + 1) + 1;
}


word32 EncodeDSA_Signature(const byte* signature, byte* output)
{
    Integer r(signature, 20);
    Integer s(signature + 20, 20);

    return EncodeDSA_Signature(r, s, output);
}


word32 EncodeDSA_Signature(const Integer& r, const Integer& s, byte* output)
{
    word32 rSz = r.ByteCount();
    word32 sSz = s.ByteCount();

    byte rLen[MAX_LENGTH_SZ + 1];
    byte sLen[MAX_LENGTH_SZ + 1];

    rLen[0] = INTEGER;
    sLen[0] = INTEGER;

    word32 rLenSz = SetLength(rSz, &rLen[1]) + 1;
    word32 sLenSz = SetLength(sSz, &sLen[1]) + 1;

    byte seqArray[MAX_SEQ_SZ];

    word32 seqSz = SetSequence(rLenSz + rSz + sLenSz + sSz, seqArray);
    
    // seq
    memcpy(output, seqArray, seqSz);
    // r
    memcpy(output + seqSz, rLen, rLenSz);
    r.Encode(output + seqSz + rLenSz, rSz);
    // s
    memcpy(output + seqSz + rLenSz + rSz, sLen, sLenSz);
    s.Encode(output + seqSz + rLenSz + rSz + sLenSz, sSz);

    return seqSz + rLenSz + rSz + sLenSz + sSz;
}


// put sequence encoded dsa signature into decoded in 2 20 byte integers
word32 DecodeDSA_Signature(byte* decoded, const byte* encoded, word32 sz)
{
    Source source(encoded, sz);

    if (source.next() != (SEQUENCE | CONSTRUCTED)) {
        source.SetError(SEQUENCE_E);
        return 0;
    }

    GetLength(source);  // total

    // r
    if (source.next() != INTEGER) {
        source.SetError(INTEGER_E);
        return 0;
    }
    word32 rLen = GetLength(source);
    if (rLen != 20) {
        while (rLen > 20 && source.remaining() > 0) {  // zero's at front, eat
            source.next();
            --rLen;
        }
        if (rLen < 20) { // add zero's to front so 20 bytes
            word32 tmpLen = rLen;
            while (tmpLen < 20) {
            decoded[0] = 0;
            decoded++;
                tmpLen++;
        }
        }
    }
    memcpy(decoded, source.get_buffer() + source.get_index(), rLen);
    source.advance(rLen);

    // s
    if (source.next() != INTEGER) {
        source.SetError(INTEGER_E);
        return 0;
    }
    word32 sLen = GetLength(source);
    if (sLen != 20) {
        while (sLen > 20 && source.remaining() > 0) {
            source.next();          // zero's at front, eat
            --sLen;
        }
        if (sLen < 20) { // add zero's to front so 20 bytes
            word32 tmpLen = sLen;
            while (tmpLen < 20) {
                decoded[rLen] = 0;
            decoded++;
                tmpLen++;
        }
        }
    }
    memcpy(decoded + rLen, source.get_buffer() + source.get_index(), sLen);
    source.advance(sLen);

    return 40;
}


/*
// Get Cert in PEM format from BEGIN to END
int GetCert(Source& source)
{
    char header[] = "-----BEGIN CERTIFICATE-----";
    char footer[] = "-----END CERTIFICATE-----";

    char* begin = strstr((char*)source.get_buffer(), header);
    char* end   = strstr((char*)source.get_buffer(), footer);

    if (!begin || !end || begin >= end) return -1;

    end += strlen(footer); 
    if (*end == '\r') end++;

    Source tmp((byte*)begin, end - begin + 1);
    source.Swap(tmp);

    return 0;
}



// Decode a BER encoded PKCS12 structure
void PKCS12_Decoder::Decode()
{
    ReadHeader();
    if (source_.GetError().What()) return;

    // Get AuthSafe

    GetSequence();
    
        // get object id
    byte obj_id = source_.next();
    if (obj_id != OBJECT_IDENTIFIER) {
        source_.SetError(OBJECT_ID_E);
        return;
    }

    word32 length = GetLength(source_);

    word32 algo_sum = 0;
    while (length--)
        algo_sum += source_.next();

    
       



    // Get MacData optional
    // mac     digestInfo  like certdecoder::getdigest?
    // macsalt octet string
    // iter    integer
    
}


void PKCS12_Decoder::ReadHeader()
{
    // Gets Version
    GetSequence();
    GetVersion();
}


// Get Cert in PEM format from pkcs12 file
int GetPKCS_Cert(const char* password, Source& source)
{
    PKCS12_Decoder pkcs12(source);
    pkcs12.Decode();

    return 0;
}
*/



} // namespace