22 #include "runtime.hpp"
25 #include "integer.hpp"
47 void GetTime(
int *value,
const byte* date,
int&
i)
49 *value += btoi(date[i++]) * 10;
50 *value += btoi(date[i++]);
54 bool ASN1_TIME_extract(
const unsigned char* date,
unsigned char format,
58 memset(t, 0,
sizeof (tm));
60 if (format != UTC_TIME && format != GENERALIZED_TIME)
63 if (format == UTC_TIME) {
64 if (btoi(date[0]) >= 5)
70 t->tm_year += btoi(date[i++]) * 1000;
71 t->tm_year += btoi(date[i++]) * 100;
74 GetTime(&t->tm_year, date, i); t->tm_year -= 1900;
75 GetTime(&t->tm_mon, date, i); t->tm_mon -= 1;
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);
91 bool operator>(tm& a, tm& b)
93 if (a.tm_year > b.tm_year)
96 if (a.tm_year == b.tm_year && a.tm_mon > b.tm_mon)
99 if (a.tm_year == b.tm_year && a.tm_mon == b.tm_mon && a.tm_mday >b.tm_mday)
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)
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 &&
115 bool operator<(tm& a, tm&b)
122 bool ValidateDate(
const byte* date, byte format, CertDecoder::DateType dt)
126 if (!ASN1_TIME_extract(date, format, &certTime))
129 time_t ltime = time(0);
130 tm* localTime = gmtime(<ime);
132 if (dt == CertDecoder::BEFORE) {
133 if (*localTime < certTime)
137 if (*localTime > certTime)
144 class BadCertificate {};
151 word32 GetLength(Source& source)
155 byte b = source.next();
156 if (b >= LONG_LENGTH) {
157 word32 bytes = b & 0x7F;
159 if (source.IsLeft(bytes) ==
false)
return 0;
163 length = (length << 8) | b;
169 if (source.IsLeft(length) ==
false)
return 0;
175 word32 SetLength(word32 length, byte* output)
179 if (length < LONG_LENGTH)
180 output[i++] = length;
182 output[i++] = BytePrecision(length) | 0x80;
184 for (
int j = BytePrecision(length); j; --j) {
185 output[
i] = length >> (j - 1) * 8;
193 PublicKey::PublicKey(
const byte* k, word32 s) : key_(0), sz_(0)
202 void PublicKey::SetSize(word32 s)
205 key_ = NEW_TC byte[sz_];
209 void PublicKey::SetKey(
const byte* k)
211 memcpy(key_, k, sz_);
215 void PublicKey::AddToEnd(
const byte* data, word32 len)
219 memcpy(tmp.get(), key_, sz_);
220 memcpy(tmp.get() + sz_, data, len);
223 STL::swap(del, key_);
226 key_ = tmp.release();
231 Signer::Signer(
const byte* k, word32 kSz,
const char*
n,
const byte* h)
234 size_t sz = strlen(n);
235 memcpy(name_, n, sz);
238 memcpy(hash_, h, SHA::DIGEST_SIZE);
246 Error BER_Decoder::GetError()
248 return source_.GetError();
252 Integer& BER_Decoder::GetInteger(Integer& integer)
254 if (!source_.GetError().What())
255 integer.Decode(source_);
261 word32 BER_Decoder::GetSequence()
263 if (source_.GetError().What())
return 0;
265 byte b = source_.next();
266 if (b != (SEQUENCE | CONSTRUCTED)) {
267 source_.SetError(SEQUENCE_E);
271 return GetLength(source_);
276 word32 BER_Decoder::GetSet()
278 if (source_.GetError().What())
return 0;
280 byte b = source_.next();
281 if (b != (SET | CONSTRUCTED)) {
282 source_.SetError(SET_E);
286 return GetLength(source_);
291 word32 BER_Decoder::GetVersion()
293 if (source_.GetError().What())
return 0;
295 byte b = source_.next();
297 source_.SetError(INTEGER_E);
303 source_.SetError(VERSION_E);
307 return source_.next();
312 word32 BER_Decoder::GetExplicitVersion()
314 if (source_.GetError().What())
return 0;
316 byte b = source_.next();
318 if (b == (CONTEXT_SPECIFIC | CONSTRUCTED)) {
330 void RSA_Private_Decoder::Decode(RSA_PrivateKey& key)
333 if (source_.GetError().What())
return;
335 key.SetModulus(GetInteger(Integer().Ref()));
336 key.SetPublicExponent(GetInteger(Integer().Ref()));
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()));
348 void RSA_Private_Decoder::ReadHeader()
356 void DSA_Private_Decoder::Decode(DSA_PrivateKey& key)
359 if (source_.GetError().What())
return;
361 key.SetModulus(GetInteger(Integer().Ref()));
362 key.SetSubGroupOrder(GetInteger(Integer().Ref()));
363 key.SetSubGroupGenerator(GetInteger(Integer().Ref()));
366 key.SetPublicPart(GetInteger(Integer().Ref()));
367 key.SetPrivatePart(GetInteger(Integer().Ref()));
371 void DSA_Private_Decoder::ReadHeader()
379 void RSA_Public_Decoder::Decode(RSA_PublicKey& key)
382 if (source_.GetError().What())
return;
385 if (source_.GetError().What())
return;
388 key.SetModulus(GetInteger(Integer().Ref()));
389 key.SetPublicExponent(GetInteger(Integer().Ref()));
394 void RSA_Public_Decoder::ReadHeaderOpenSSL()
396 byte b = source_.next();
402 if (b != OBJECT_IDENTIFIER) {
403 source_.SetError(OBJECT_ID_E);
407 word32 len = GetLength(source_);
408 source_.advance(len);
414 source_.SetError(EXPECT_0_E);
422 if (b != BIT_STRING) {
423 source_.SetError(BIT_STR_E);
427 len = GetLength(source_);
437 void RSA_Public_Decoder::ReadHeader()
444 void DSA_Public_Decoder::Decode(DSA_PublicKey& key)
447 if (source_.GetError().What())
return;
450 key.SetModulus(GetInteger(Integer().Ref()));
451 key.SetSubGroupOrder(GetInteger(Integer().Ref()));
452 key.SetSubGroupGenerator(GetInteger(Integer().Ref()));
455 key.SetPublicPart(GetInteger(Integer().Ref()));
459 void DSA_Public_Decoder::ReadHeader()
465 void DH_Decoder::ReadHeader()
472 void DH_Decoder::Decode(
DH& key)
475 if (source_.GetError().What())
return;
478 key.SetP(GetInteger(Integer().Ref()));
479 key.SetG(GetInteger(Integer().Ref()));
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)
497 CertDecoder::~CertDecoder()
499 tcArrayDelete(signature_);
504 void CertDecoder::ReadHeader()
506 if (source_.GetError().What())
return;
509 certBegin_ = source_.get_index();
511 sigIndex_ = GetSequence();
512 sigIndex_ += source_.get_index();
514 GetExplicitVersion();
515 GetInteger(Integer().Ref());
520 void CertDecoder::Decode(SignerList* signers, CertType ct)
522 if (source_.GetError().What())
return;
524 if (source_.GetError().What())
return;
526 if (source_.get_index() != sigIndex_)
527 source_.set_index(sigIndex_);
529 word32 confirmOID = GetAlgoId();
531 if (source_.GetError().What())
return;
533 if ( confirmOID != signatureOID_ ) {
534 source_.SetError(SIG_OID_E);
538 if (ct != CA && verify_ && !ValidateSignature(signers))
539 source_.SetError(SIG_OTHER_E);
543 void CertDecoder::DecodeToKey()
546 signatureOID_ = GetAlgoId();
555 void CertDecoder::GetKey()
557 if (source_.GetError().What())
return;
560 keyOID_ = GetAlgoId();
562 if (keyOID_ == RSAk) {
563 byte b = source_.next();
564 if (b != BIT_STRING) {
565 source_.SetError(BIT_STR_E);
573 else if (keyOID_ == DSAk)
576 source_.SetError(UNKNOWN_OID_E);
587 void CertDecoder::StoreKey()
589 if (source_.GetError().What())
return;
591 word32 read = source_.get_index();
592 word32 length = GetSequence();
594 read = source_.get_index() - read;
597 if (source_.GetError().What())
return;
598 while (read--) source_.prev();
600 if (source_.IsLeft(length) ==
false)
return;
601 key_.SetSize(length);
602 key_.SetKey(source_.get_current());
603 source_.advance(length);
608 void CertDecoder::AddDSA()
610 if (source_.GetError().What())
return;
612 byte b = source_.next();
613 if (b != BIT_STRING) {
614 source_.SetError(BIT_STR_E);
622 word32 idx = source_.get_index();
625 source_.SetError(INTEGER_E);
629 word32 length = GetLength(source_);
630 length += source_.get_index() - idx;
632 if (source_.IsLeft(length) ==
false)
return;
634 key_.AddToEnd(source_.get_buffer() + idx, length);
639 word32 CertDecoder::GetAlgoId()
641 if (source_.GetError().What())
return 0;
642 word32 length = GetSequence();
644 if (source_.GetError().What())
return 0;
646 byte b = source_.next();
647 if (b != OBJECT_IDENTIFIER) {
648 source_.SetError(OBJECT_ID_E);
652 length = GetLength(source_);
653 if (source_.IsLeft(length) ==
false)
return 0;
657 oid += source_.next();
664 source_.SetError(EXPECT_0_E);
677 word32 CertDecoder::GetSignature()
679 if (source_.GetError().What())
return 0;
680 byte b = source_.next();
682 if (b != BIT_STRING) {
683 source_.SetError(BIT_STR_E);
687 sigLength_ = GetLength(source_);
688 if (sigLength_ == 0 || source_.IsLeft(sigLength_) ==
false) {
689 source_.SetError(CONTENT_E);
695 source_.SetError(EXPECT_0_E);
700 signature_ = NEW_TC byte[sigLength_];
701 memcpy(signature_, source_.get_current(), sigLength_);
702 source_.advance(sigLength_);
709 word32 CertDecoder::GetDigest()
711 if (source_.GetError().What())
return 0;
712 byte b = source_.next();
714 if (b != OCTET_STRING) {
715 source_.SetError(OCTET_STR_E);
719 sigLength_ = GetLength(source_);
721 signature_ = NEW_TC byte[sigLength_];
722 memcpy(signature_, source_.get_current(), sigLength_);
723 source_.advance(sigLength_);
730 char* CertDecoder::AddTag(
char* ptr,
const char* buf_end,
const char* tag_name,
731 word32 tag_name_length, word32 tag_value_length)
733 if (ptr + tag_name_length + tag_value_length > buf_end) {
734 source_.SetError(CONTENT_E);
738 memcpy(ptr, tag_name, tag_name_length);
739 ptr += tag_name_length;
741 memcpy(ptr, source_.get_current(), tag_value_length);
742 ptr += tag_value_length;
749 void CertDecoder::GetName(NameType nt)
751 if (source_.GetError().What())
return;
754 word32 length = GetSequence();
756 if (length >= ASN_NAME_MAX)
758 if (source_.IsLeft(length) ==
false)
return;
759 length += source_.get_index();
766 buf_end = ptr +
sizeof(issuer_) - 1;
770 buf_end = ptr +
sizeof(subject_) - 1;
773 while (source_.get_index() < length) {
775 if (source_.GetError().What() == SET_E) {
776 source_.SetError(NO_ERROR_E);
781 byte b = source_.next();
782 if (b != OBJECT_IDENTIFIER) {
783 source_.SetError(OBJECT_ID_E);
787 word32 oidSz = GetLength(source_);
788 if (source_.IsLeft(oidSz) ==
false)
return;
791 if (source_.IsLeft(
sizeof(joint)) ==
false)
return;
792 memcpy(joint, source_.get_current(),
sizeof(joint));
795 if (joint[0] == 0x55 && joint[1] == 0x04) {
797 byte
id = source_.next();
799 word32 strLen = GetLength(source_);
801 if (source_.IsLeft(strLen) ==
false)
return;
805 if (!(ptr = AddTag(ptr, buf_end,
"/CN=", 4, strLen)))
809 if (!(ptr = AddTag(ptr, buf_end,
"/SN=", 4, strLen)))
813 if (!(ptr = AddTag(ptr, buf_end,
"/C=", 3, strLen)))
817 if (!(ptr = AddTag(ptr, buf_end,
"/L=", 3, strLen)))
821 if (!(ptr = AddTag(ptr, buf_end,
"/ST=", 4, strLen)))
825 if (!(ptr = AddTag(ptr, buf_end,
"/O=", 3, strLen)))
829 if (!(ptr = AddTag(ptr, buf_end,
"/OU=", 4, strLen)))
834 sha.Update(source_.get_current(), strLen);
835 source_.advance(strLen);
839 if (joint[0] == 0x2a && joint[1] == 0x86)
842 source_.advance(oidSz + 1);
843 word32 length = GetLength(source_);
844 if (source_.IsLeft(length) ==
false)
return;
847 if (!(ptr = AddTag(ptr, buf_end,
"/emailAddress=", 14, length))) {
848 source_.SetError(CONTENT_E);
853 source_.advance(length);
860 sha.Final(issuerHash_);
862 sha.Final(subjectHash_);
867 void CertDecoder::GetDate(DateType dt)
869 if (source_.GetError().What())
return;
871 byte b = source_.next();
872 if (b != UTC_TIME && b != GENERALIZED_TIME) {
873 source_.SetError(TIME_E);
877 word32 length = GetLength(source_);
878 if (source_.IsLeft(length) ==
false)
return;
880 byte date[MAX_DATE_SZ];
881 if (length > MAX_DATE_SZ || length < MIN_DATE_SZ) {
882 source_.SetError(DATE_SZ_E);
886 memcpy(date, source_.get_current(), length);
887 source_.advance(length);
889 if (!ValidateDate(date, b, dt) && verify_) {
891 source_.SetError(BEFORE_DATE_E);
893 source_.SetError(AFTER_DATE_E);
898 memcpy(beforeDate_, date, length);
899 beforeDate_[length] = 0;
903 memcpy(afterDate_, date, length);
904 afterDate_[length] = 0;
910 void CertDecoder::GetValidity()
912 if (source_.GetError().What())
return;
920 bool CertDecoder::ValidateSelfSignature()
922 Source pub(key_.GetKey(), key_.size());
923 return ConfirmSignature(pub);
928 void CertDecoder::GetCompareHash(
const byte* plain, word32 sz, byte* digest,
931 if (source_.GetError().What())
return;
934 CertDecoder dec(s,
false);
940 if (dec.sigLength_ > digSz) {
941 source_.SetError(SIG_LEN_E);
945 memcpy(digest, dec.signature_, dec.sigLength_);
950 bool CertDecoder::ValidateSignature(SignerList* signers)
955 SignerList::iterator first = signers->begin();
956 SignerList::iterator last = signers->end();
958 while (first != last) {
959 if ( memcmp(issuerHash_, (*first)->GetHash(), SHA::DIGEST_SIZE) == 0) {
961 const PublicKey& iKey = (*first)->GetPublicKey();
962 Source pub(iKey.GetKey(), iKey.size());
963 return ConfirmSignature(pub);
972 bool CertDecoder::ConfirmSignature(Source& pub)
977 if (signatureOID_ == MD5wRSA) {
978 hasher.reset(NEW_TC MD5);
981 else if (signatureOID_ == MD2wRSA) {
982 hasher.reset(NEW_TC MD2);
985 else if (signatureOID_ == SHAwRSA || signatureOID_ == SHAwDSA) {
986 hasher.reset(NEW_TC SHA);
989 else if (signatureOID_ == SHA256wRSA || signatureOID_ == SHA256wDSA) {
990 hasher.reset(NEW_TC SHA256);
993 #ifdef WORD64_AVAILABLE
994 else if (signatureOID_ == SHA384wRSA) {
995 hasher.reset(NEW_TC SHA384);
998 else if (signatureOID_ == SHA512wRSA) {
999 hasher.reset(NEW_TC SHA512);
1004 source_.SetError(UNKOWN_SIG_E);
1008 byte digest[MAX_SHA2_DIGEST_SIZE];
1010 hasher->Update(source_.get_buffer() + certBegin_, sigIndex_ - certBegin_);
1011 hasher->Final(digest);
1013 if (keyOID_ == RSAk) {
1016 Signature_Encoder(digest, hasher->getDigestSize(), ht, build);
1018 RSA_PublicKey pubKey(pub);
1019 RSAES_Encryptor enc(pubKey);
1021 return enc.SSL_Verify(build.get_buffer(), build.size(), signature_);
1025 byte seqDecoded[DSA_SIG_SZ];
1026 DecodeDSA_Signature(seqDecoded, signature_, sigLength_);
1028 DSA_PublicKey pubKey(pub);
1029 DSA_Verifier ver(pubKey);
1031 return ver.Verify(digest, seqDecoded);
1036 Signature_Encoder::Signature_Encoder(
const byte* dig, word32 digSz,
1037 HashType digOID, Source& source)
1042 byte digArray[MAX_DIGEST_SZ];
1043 word32 digestSz = SetDigest(dig, digSz, digArray);
1046 byte algoArray[MAX_ALGO_SZ];
1047 word32 algoSz = SetAlgoID(digOID, algoArray);
1050 byte seqArray[MAX_SEQ_SZ];
1051 word32 seqSz = SetSequence(digestSz + algoSz, seqArray);
1053 source.grow(seqSz + algoSz + digestSz);
1054 source.add(seqArray, seqSz);
1055 source.add(algoArray, algoSz);
1056 source.add(digArray, digestSz);
1061 word32 Signature_Encoder::SetDigest(
const byte* d, word32 dSz, byte* output)
1063 output[0] = OCTET_STRING;
1065 memcpy(&output[2], d, dSz);
1072 word32 DER_Encoder::SetAlgoID(HashType aOID, byte* output)
1075 static const byte shaAlgoID[] = { 0x2b, 0x0e, 0x03, 0x02, 0x1a,
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 };
1090 const byte* algoName = 0;
1094 algoSz =
sizeof(shaAlgoID);
1095 algoName = shaAlgoID;
1099 algoSz =
sizeof(sha256AlgoID);
1100 algoName = sha256AlgoID;
1103 #ifdef WORD64_AVAILABLE
1105 algoSz =
sizeof(sha384AlgoID);
1106 algoName = sha384AlgoID;
1110 algoSz =
sizeof(sha512AlgoID);
1111 algoName = sha512AlgoID;
1116 algoSz =
sizeof(md2AlgoID);
1117 algoName = md2AlgoID;
1121 algoSz =
sizeof(md5AlgoID);
1122 algoName = md5AlgoID;
1126 error_.SetError(UNKOWN_HASH_E);
1131 byte ID_Length[MAX_LENGTH_SZ];
1132 word32 idSz = SetLength(algoSz - 2, ID_Length);
1134 byte seqArray[MAX_SEQ_SZ + 1];
1135 word32 seqSz = SetSequence(idSz + algoSz + 1, seqArray);
1136 seqArray[seqSz++] = OBJECT_IDENTIFIER;
1138 memcpy(output, seqArray, seqSz);
1139 memcpy(output + seqSz, ID_Length, idSz);
1140 memcpy(output + seqSz + idSz, algoName, algoSz);
1142 return seqSz + idSz + algoSz;
1146 word32 SetSequence(word32 len, byte* output)
1149 output[0] = SEQUENCE | CONSTRUCTED;
1150 return SetLength(len, output + 1) + 1;
1154 word32 EncodeDSA_Signature(
const byte* signature, byte* output)
1156 Integer r(signature, 20);
1157 Integer s(signature + 20, 20);
1159 return EncodeDSA_Signature(r, s, output);
1163 word32 EncodeDSA_Signature(
const Integer& r,
const Integer& s, byte* output)
1165 word32 rSz = r.ByteCount();
1166 word32 sSz = s.ByteCount();
1168 byte rLen[MAX_LENGTH_SZ + 1];
1169 byte sLen[MAX_LENGTH_SZ + 1];
1174 word32 rLenSz = SetLength(rSz, &rLen[1]) + 1;
1175 word32 sLenSz = SetLength(sSz, &sLen[1]) + 1;
1177 byte seqArray[MAX_SEQ_SZ];
1179 word32 seqSz = SetSequence(rLenSz + rSz + sLenSz + sSz, seqArray);
1182 memcpy(output, seqArray, seqSz);
1184 memcpy(output + seqSz, rLen, rLenSz);
1185 r.Encode(output + seqSz + rLenSz, rSz);
1187 memcpy(output + seqSz + rLenSz + rSz, sLen, sLenSz);
1188 s.Encode(output + seqSz + rLenSz + rSz + sLenSz, sSz);
1190 return seqSz + rLenSz + rSz + sLenSz + sSz;
1195 word32 DecodeDSA_Signature(byte* decoded,
const byte* encoded, word32 sz)
1197 Source source(encoded, sz);
1199 if (source.next() != (SEQUENCE | CONSTRUCTED)) {
1200 source.SetError(SEQUENCE_E);
1207 if (source.next() != INTEGER) {
1208 source.SetError(INTEGER_E);
1211 word32 rLen = GetLength(source);
1217 else if (rLen == 19) {
1222 source.SetError(DSA_SZ_E);
1226 memcpy(decoded, source.get_buffer() + source.get_index(), rLen);
1227 source.advance(rLen);
1230 if (source.next() != INTEGER) {
1231 source.SetError(INTEGER_E);
1234 word32 sLen = GetLength(source);
1240 else if (sLen == 19) {
1245 source.SetError(DSA_SZ_E);
1249 memcpy(decoded + rLen, source.get_buffer() + source.get_index(), sLen);
1250 source.advance(sLen);