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