Security.cpp 8.5 KB

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