Security.cpp 8.4 KB

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