Security.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //---------------------------------------------------------------------------
  2. #include <CorePCH.h>
  3. #pragma hdrstop
  4. #include "Security.h"
  5. //---------------------------------------------------------------------------
  6. #pragma package(smart_init)
  7. //---------------------------------------------------------------------------
  8. #define PWALG_SIMPLE_INTERNAL 0x00
  9. #define PWALG_SIMPLE_EXTERNAL 0x01
  10. #define PWALG_SIMPLE_INTERNAL2 0x02
  11. static RawByteString PWALG_SIMPLE_STRING("0123456789ABCDEF");
  12. //---------------------------------------------------------------------------
  13. RawByteString SimpleEncryptChar(unsigned char Ch)
  14. {
  15. Ch = (unsigned char)((~Ch) ^ PWALG_SIMPLE_MAGIC);
  16. RawByteString Result("..");
  17. Result[1] = PWALG_SIMPLE_STRING[((Ch & 0xF0) >> 4) + 1];
  18. Result[2] = PWALG_SIMPLE_STRING[((Ch & 0x0F) >> 0) + 1];
  19. return Result;
  20. }
  21. //---------------------------------------------------------------------------
  22. unsigned char SimpleDecryptNextChar(RawByteString &Str)
  23. {
  24. if (Str.Length() > 0)
  25. {
  26. unsigned char Result = (unsigned char)
  27. ~((((PWALG_SIMPLE_STRING.Pos(Str.c_str()[0])-1) << 4) +
  28. ((PWALG_SIMPLE_STRING.Pos(Str.c_str()[1])-1) << 0)) ^ PWALG_SIMPLE_MAGIC);
  29. Str.Delete(1, 2);
  30. return Result;
  31. }
  32. else return 0x00;
  33. }
  34. //---------------------------------------------------------------------------
  35. RawByteString EncryptPassword(UnicodeString UnicodePassword, UnicodeString UnicodeKey, Integer /* Algorithm */)
  36. {
  37. UTF8String Password = UnicodePassword;
  38. UTF8String Key = UnicodeKey;
  39. RawByteString Result;
  40. if (!RandSeed) Randomize();
  41. Password = Key + Password;
  42. Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_FLAG); // Flag
  43. int Len = Password.Length();
  44. if (Len > std::numeric_limits<unsigned char>::max())
  45. {
  46. Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_INTERNAL2);
  47. Result += SimpleEncryptChar((unsigned char)(Len >> 8));
  48. Result += SimpleEncryptChar((unsigned char)(Len & 0xFF));
  49. }
  50. else
  51. {
  52. Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_INTERNAL);
  53. Result += SimpleEncryptChar((unsigned char)Len);
  54. }
  55. int DataLen =
  56. (Result.Length() / 2) +
  57. 1 + // Shift
  58. Password.Length();
  59. int Shift = (DataLen < PWALG_SIMPLE_MAXLEN) ? random(PWALG_SIMPLE_MAXLEN - DataLen) : 0;
  60. Result += SimpleEncryptChar((unsigned char)Shift);
  61. for (int Index = 0; Index < Shift; Index++)
  62. Result += SimpleEncryptChar((unsigned char)random(256));
  63. for (int Index = 0; Index < Password.Length(); Index++)
  64. Result += SimpleEncryptChar(Password.c_str()[Index]);
  65. while (Result.Length() < PWALG_SIMPLE_MAXLEN * 2)
  66. Result += SimpleEncryptChar((unsigned char)random(256));
  67. return Result;
  68. }
  69. //---------------------------------------------------------------------------
  70. UnicodeString DecryptPassword(RawByteString Password, UnicodeString UnicodeKey, Integer /* Algorithm */)
  71. {
  72. int Length;
  73. unsigned char Flag = SimpleDecryptNextChar(Password);
  74. if (Flag == PWALG_SIMPLE_FLAG)
  75. {
  76. unsigned char Version = SimpleDecryptNextChar(Password);
  77. if (Version == PWALG_SIMPLE_INTERNAL)
  78. {
  79. Length = SimpleDecryptNextChar(Password);
  80. }
  81. else if (Version == PWALG_SIMPLE_INTERNAL2)
  82. {
  83. Length = (int(SimpleDecryptNextChar(Password)) << 8) + SimpleDecryptNextChar(Password);
  84. }
  85. else
  86. {
  87. Length = -1;
  88. }
  89. }
  90. else
  91. {
  92. Length = Flag;
  93. }
  94. UTF8String Result;
  95. if (Length >= 0)
  96. {
  97. Password.Delete(1, ((Integer)SimpleDecryptNextChar(Password))*2);
  98. for (int Index = 0; Index < Length; Index++)
  99. {
  100. Result += (char)SimpleDecryptNextChar(Password);
  101. }
  102. if (Flag == PWALG_SIMPLE_FLAG)
  103. {
  104. UTF8String Key = UnicodeKey;
  105. if (Result.SubString(1, Key.Length()) != Key)
  106. {
  107. Result = UTF8String();
  108. }
  109. else
  110. {
  111. Result.Delete(1, Key.Length());
  112. }
  113. }
  114. }
  115. return UnicodeString(Result);
  116. }
  117. //---------------------------------------------------------------------------
  118. RawByteString SetExternalEncryptedPassword(RawByteString Password)
  119. {
  120. RawByteString Result;
  121. Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_FLAG);
  122. Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_EXTERNAL);
  123. Result += UTF8String(BytesToHex(reinterpret_cast<const unsigned char *>(Password.c_str()), Password.Length()));
  124. return Result;
  125. }
  126. //---------------------------------------------------------------------------
  127. bool GetExternalEncryptedPassword(RawByteString Encrypted, RawByteString & Password)
  128. {
  129. bool Result =
  130. (SimpleDecryptNextChar(Encrypted) == PWALG_SIMPLE_FLAG) &&
  131. (SimpleDecryptNextChar(Encrypted) == PWALG_SIMPLE_EXTERNAL);
  132. if (Result)
  133. {
  134. Password = HexToBytes(UTF8ToString(Encrypted));
  135. }
  136. return Result;
  137. }
  138. //---------------------------------------------------------------------------
  139. bool WindowsValidateCertificate(const unsigned char * Certificate, size_t Len, UnicodeString & Error)
  140. {
  141. bool Result = false;
  142. // Parse the certificate into a context.
  143. const CERT_CONTEXT * CertContext =
  144. CertCreateCertificateContext(
  145. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, Certificate, Len);
  146. if (CertContext == NULL)
  147. {
  148. Error = L"Cannot create certificate context";
  149. }
  150. else
  151. {
  152. CERT_CHAIN_PARA ChainPara;
  153. // Retrieve the certificate chain of the certificate
  154. // (a certificate without a valid root does not have a chain).
  155. memset(&ChainPara, 0, sizeof(ChainPara));
  156. ChainPara.cbSize = sizeof(ChainPara);
  157. CERT_CHAIN_ENGINE_CONFIG ChainConfig;
  158. memset(&ChainConfig, 0, sizeof(ChainConfig));
  159. const size_t ChainConfigSize =
  160. reinterpret_cast<const char *>(&ChainConfig.CycleDetectionModulus) + sizeof(ChainConfig.CycleDetectionModulus) -
  161. reinterpret_cast<const char *>(&ChainConfig);
  162. // The hExclusiveRoot and hExclusiveTrustedPeople were added in Windows 7.
  163. // The CertGetCertificateChain fails with E_INVALIDARG when we include them to ChainConfig.cbSize.
  164. // The dwExclusiveFlags was added in Windows 8
  165. DebugAssert(ChainConfigSize == 40);
  166. DebugAssert(ChainConfigSize == sizeof(CERT_CHAIN_ENGINE_CONFIG) - sizeof(ChainConfig.hExclusiveRoot) - sizeof(ChainConfig.hExclusiveTrustedPeople) - sizeof(ChainConfig.dwExclusiveFlags));
  167. ChainConfig.cbSize = ChainConfigSize;
  168. ChainConfig.hRestrictedRoot = NULL;
  169. ChainConfig.hRestrictedTrust = NULL;
  170. ChainConfig.hRestrictedOther = NULL;
  171. ChainConfig.cAdditionalStore = 0;
  172. ChainConfig.rghAdditionalStore = NULL;
  173. ChainConfig.dwFlags = CERT_CHAIN_CACHE_END_CERT;
  174. ChainConfig.dwUrlRetrievalTimeout = 0;
  175. ChainConfig.MaximumCachedCertificates =0;
  176. ChainConfig.CycleDetectionModulus = 0;
  177. HCERTCHAINENGINE ChainEngine;
  178. bool ChainEngineResult = CertCreateCertificateChainEngine(&ChainConfig, &ChainEngine);
  179. if (!ChainEngineResult)
  180. {
  181. Error = L"Cannot create certificate chain engine";
  182. }
  183. else
  184. {
  185. const CERT_CHAIN_CONTEXT * ChainContext = NULL;
  186. if (!CertGetCertificateChain(ChainEngine, CertContext, NULL, NULL, &ChainPara,
  187. CERT_CHAIN_CACHE_END_CERT |
  188. CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT,
  189. NULL, &ChainContext))
  190. {
  191. Error = L"Cannot get certificate chain";
  192. }
  193. else
  194. {
  195. CERT_CHAIN_POLICY_PARA PolicyPara;
  196. PolicyPara.cbSize = sizeof(PolicyPara);
  197. PolicyPara.dwFlags = 0;
  198. PolicyPara.pvExtraPolicyPara = NULL;
  199. CERT_CHAIN_POLICY_STATUS PolicyStatus;
  200. PolicyStatus.cbSize = sizeof(PolicyStatus);
  201. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, ChainContext, &PolicyPara, &PolicyStatus))
  202. {
  203. Error = L"Cannot verify certificate chain policy";
  204. }
  205. else
  206. {
  207. int PolicyError = PolicyStatus.dwError;
  208. // Windows thinks the certificate is valid.
  209. Result = (PolicyError == S_OK);
  210. if (!Result)
  211. {
  212. UnicodeString ErrorStr = SysErrorMessage(PolicyError);
  213. Error = FORMAT(L"Error: %x (%s), Chain index: %d, Element index: %d", (PolicyError, ErrorStr, PolicyStatus.lChainIndex, PolicyStatus.lElementIndex));
  214. }
  215. }
  216. CertFreeCertificateChain(ChainContext);
  217. }
  218. CertFreeCertificateChainEngine(ChainEngine);
  219. }
  220. CertFreeCertificateContext(CertContext);
  221. }
  222. return Result;
  223. }
  224. //---------------------------------------------------------------------------