ssl_cryptlib.pas 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. {==============================================================================|
  2. | Project : Ararat Synapse | 001.001.001 |
  3. |==============================================================================|
  4. | Content: SSL/SSH support by Peter Gutmann's CryptLib |
  5. |==============================================================================|
  6. | Copyright (c)1999-2015, Lukas Gebauer |
  7. | All rights reserved. |
  8. | |
  9. | Redistribution and use in source and binary forms, with or without |
  10. | modification, are permitted provided that the following conditions are met: |
  11. | |
  12. | Redistributions of source code must retain the above copyright notice, this |
  13. | list of conditions and the following disclaimer. |
  14. | |
  15. | Redistributions in binary form must reproduce the above copyright notice, |
  16. | this list of conditions and the following disclaimer in the documentation |
  17. | and/or other materials provided with the distribution. |
  18. | |
  19. | Neither the name of Lukas Gebauer nor the names of its contributors may |
  20. | be used to endorse or promote products derived from this software without |
  21. | specific prior written permission. |
  22. | |
  23. | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
  24. | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
  25. | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
  26. | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
  27. | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
  28. | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
  29. | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
  30. | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  31. | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
  32. | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
  33. | DAMAGE. |
  34. |==============================================================================|
  35. | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
  36. | Portions created by Lukas Gebauer are Copyright (c)2005-2015. |
  37. | All Rights Reserved. |
  38. |==============================================================================|
  39. | Contributor(s): |
  40. |==============================================================================|
  41. | History: see HISTORY.HTM from distribution package |
  42. | (Found at URL: http://www.ararat.cz/synapse/) |
  43. |==============================================================================}
  44. {:@abstract(SSL/SSH plugin for CryptLib)
  45. This plugin requires cl32.dll at least version 3.2.0! It can be used on Win32
  46. and Linux. This library is staticly linked - when you compile your application
  47. with this plugin, you MUST distribute it with Cryptib library, otherwise you
  48. cannot run your application!
  49. It can work with keys and certificates stored as PKCS#15 only! It must be stored
  50. as disk file only, you cannot load them from memory! Each file can hold multiple
  51. keys and certificates. You must identify it by 'label' stored in
  52. @link(TSSLCryptLib.PrivateKeyLabel).
  53. If you need to use secure connection and authorize self by certificate
  54. (each SSL/TLS server or client with client authorization), then use
  55. @link(TCustomSSL.PrivateKeyFile), @link(TSSLCryptLib.PrivateKeyLabel) and
  56. @link(TCustomSSL.KeyPassword) properties.
  57. If you need to use server what verifying client certificates, then use
  58. @link(TCustomSSL.CertCAFile) as PKCS#15 file with public keyas of allowed clients. Clients
  59. with non-matching certificates will be rejected by cryptLib.
  60. This plugin is capable to create Ad-Hoc certificates. When you start SSL/TLS
  61. server without explicitly assigned key and certificate, then this plugin create
  62. Ad-Hoc key and certificate for each incomming connection by self. It slowdown
  63. accepting of new connections!
  64. You can use this plugin for SSHv2 connections too! You must explicitly set
  65. @link(TCustomSSL.SSLType) to value LT_SSHv2 and set @link(TCustomSSL.username)
  66. and @link(TCustomSSL.password). You can use special SSH channels too, see
  67. @link(TCustomSSL).
  68. }
  69. {$IFDEF FPC}
  70. {$MODE DELPHI}
  71. {$ENDIF}
  72. {$H+}
  73. unit ssl_cryptlib;
  74. interface
  75. uses
  76. Windows,
  77. SysUtils,
  78. blcksock, synsock, synautil, synacode,
  79. cryptlib;
  80. type
  81. {:@abstract(class implementing CryptLib SSL/SSH plugin.)
  82. Instance of this class will be created for each @link(TTCPBlockSocket).
  83. You not need to create instance of this class, all is done by Synapse itself!}
  84. TSSLCryptLib = class(TCustomSSL)
  85. protected
  86. FCryptSession: CRYPT_SESSION;
  87. FPrivateKeyLabel: string;
  88. FDelCert: Boolean;
  89. FReadBuffer: string;
  90. FTrustedCAs: array of integer;
  91. function SSLCheck(Value: integer): Boolean;
  92. function Init(server:Boolean): Boolean;
  93. function DeInit: Boolean;
  94. function Prepare(server:Boolean): Boolean;
  95. function GetString(const cryptHandle: CRYPT_HANDLE; const attributeType: CRYPT_ATTRIBUTE_TYPE): string;
  96. function CreateSelfSignedCert(Host: string): Boolean; override;
  97. function PopAll: string;
  98. public
  99. {:See @inherited}
  100. constructor Create(const Value: TTCPBlockSocket); override;
  101. destructor Destroy; override;
  102. {:Load trusted CA's in PEM format}
  103. procedure SetCertCAFile(const Value: string); override;
  104. {:See @inherited}
  105. function LibVersion: String; override;
  106. {:See @inherited}
  107. function LibName: String; override;
  108. {:See @inherited}
  109. procedure Assign(const Value: TCustomSSL); override;
  110. {:See @inherited and @link(ssl_cryptlib) for more details.}
  111. function Connect: boolean; override;
  112. {:See @inherited and @link(ssl_cryptlib) for more details.}
  113. function Accept: boolean; override;
  114. {:See @inherited}
  115. function Shutdown: boolean; override;
  116. {:See @inherited}
  117. function BiShutdown: boolean; override;
  118. {:See @inherited}
  119. function SendBuffer(Buffer: TMemory; Len: Integer): Integer; override;
  120. {:See @inherited}
  121. function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; override;
  122. {:See @inherited}
  123. function WaitingData: Integer; override;
  124. {:See @inherited}
  125. function GetSSLVersion: string; override;
  126. {:See @inherited}
  127. function GetPeerSubject: string; override;
  128. {:See @inherited}
  129. function GetPeerIssuer: string; override;
  130. {:See @inherited}
  131. function GetPeerName: string; override;
  132. {:See @inherited}
  133. function GetPeerFingerprint: string; override;
  134. {:See @inherited}
  135. function GetVerifyCert: integer; override;
  136. published
  137. {:name of certificate/key within PKCS#15 file. It can hold more then one
  138. certificate/key and each certificate/key must have unique label within one file.}
  139. property PrivateKeyLabel: string read FPrivateKeyLabel Write FPrivateKeyLabel;
  140. end;
  141. implementation
  142. {==============================================================================}
  143. constructor TSSLCryptLib.Create(const Value: TTCPBlockSocket);
  144. begin
  145. inherited Create(Value);
  146. FcryptSession := CRYPT_SESSION(CRYPT_SESSION_NONE);
  147. FPrivateKeyLabel := 'synapse';
  148. FDelCert := false;
  149. FTrustedCAs := nil;
  150. end;
  151. destructor TSSLCryptLib.Destroy;
  152. begin
  153. SetCertCAFile(''); // destroy certificates
  154. DeInit;
  155. inherited Destroy;
  156. end;
  157. procedure TSSLCryptLib.Assign(const Value: TCustomSSL);
  158. begin
  159. inherited Assign(Value);
  160. if Value is TSSLCryptLib then
  161. begin
  162. FPrivateKeyLabel := TSSLCryptLib(Value).privatekeyLabel;
  163. end;
  164. end;
  165. function TSSLCryptLib.GetString(const cryptHandle: CRYPT_HANDLE; const attributeType: CRYPT_ATTRIBUTE_TYPE): string;
  166. var
  167. l: integer;
  168. begin
  169. l := 0;
  170. cryptGetAttributeString(cryptHandle, attributeType, nil, l);
  171. setlength(Result, l);
  172. cryptGetAttributeString(cryptHandle, attributeType, pointer(Result), l);
  173. setlength(Result, l);
  174. end;
  175. function TSSLCryptLib.LibVersion: String;
  176. var
  177. x: integer;
  178. begin
  179. Result := GetString(CRYPT_UNUSED, CRYPT_OPTION_INFO_DESCRIPTION);
  180. cryptGetAttribute(CRYPT_UNUSED, CRYPT_OPTION_INFO_MAJORVERSION, x);
  181. Result := Result + ' v' + IntToStr(x);
  182. cryptGetAttribute(CRYPT_UNUSED, CRYPT_OPTION_INFO_MINORVERSION, x);
  183. Result := Result + '.' + IntToStr(x);
  184. cryptGetAttribute(CRYPT_UNUSED, CRYPT_OPTION_INFO_STEPPING, x);
  185. Result := Result + '.' + IntToStr(x);
  186. end;
  187. function TSSLCryptLib.LibName: String;
  188. begin
  189. Result := 'ssl_cryptlib';
  190. end;
  191. function TSSLCryptLib.SSLCheck(Value: integer): Boolean;
  192. begin
  193. Result := true;
  194. FLastErrorDesc := '';
  195. if Value = CRYPT_ERROR_COMPLETE then
  196. Value := 0;
  197. FLastError := Value;
  198. if FLastError <> 0 then
  199. begin
  200. Result := False;
  201. {$IF CRYPTLIB_VERSION >= 3400}
  202. FLastErrorDesc := GetString(FCryptSession, CRYPT_ATTRIBUTE_ERRORMESSAGE);
  203. {$ELSE}
  204. FLastErrorDesc := GetString(FCryptSession, CRYPT_ATTRIBUTE_INT_ERRORMESSAGE);
  205. {$IFEND}
  206. end;
  207. end;
  208. function TSSLCryptLib.CreateSelfSignedCert(Host: string): Boolean;
  209. var
  210. privateKey: CRYPT_CONTEXT;
  211. keyset: CRYPT_KEYSET;
  212. cert: CRYPT_CERTIFICATE;
  213. publicKey: CRYPT_CONTEXT;
  214. begin
  215. if FPrivatekeyFile = '' then
  216. FPrivatekeyFile := GetTempFile('', 'key');
  217. cryptCreateContext(privateKey, CRYPT_UNUSED, CRYPT_ALGO_RSA);
  218. cryptSetAttributeString(privateKey, CRYPT_CTXINFO_LABEL, Pointer(FPrivatekeyLabel),
  219. Length(FPrivatekeyLabel));
  220. cryptSetAttribute(privateKey, CRYPT_CTXINFO_KEYSIZE, 1024);
  221. cryptGenerateKey(privateKey);
  222. cryptKeysetOpen(keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, PChar(FPrivatekeyFile), CRYPT_KEYOPT_CREATE);
  223. FDelCert := True;
  224. cryptAddPrivateKey(keyset, privateKey, PChar(FKeyPassword));
  225. cryptCreateCert(cert, CRYPT_UNUSED, CRYPT_CERTTYPE_CERTIFICATE);
  226. cryptSetAttribute(cert, CRYPT_CERTINFO_XYZZY, 1);
  227. cryptGetPublicKey(keyset, publicKey, CRYPT_KEYID_NAME, PChar(FPrivatekeyLabel));
  228. cryptSetAttribute(cert, CRYPT_CERTINFO_SUBJECTPUBLICKEYINFO, publicKey);
  229. cryptSetAttributeString(cert, CRYPT_CERTINFO_COMMONNAME, Pointer(host), Length(host));
  230. cryptSignCert(cert, privateKey);
  231. cryptAddPublicKey(keyset, cert);
  232. cryptKeysetClose(keyset);
  233. cryptDestroyCert(cert);
  234. cryptDestroyContext(privateKey);
  235. cryptDestroyContext(publicKey);
  236. Result := True;
  237. end;
  238. function TSSLCryptLib.PopAll: string;
  239. const
  240. BufferMaxSize = 32768;
  241. var
  242. Outbuffer: string;
  243. WriteLen: integer;
  244. begin
  245. Result := '';
  246. repeat
  247. setlength(outbuffer, BufferMaxSize);
  248. Writelen := 0;
  249. SSLCheck(CryptPopData(FCryptSession, @OutBuffer[1], BufferMaxSize, Writelen));
  250. if FLastError <> 0 then
  251. Break;
  252. if WriteLen > 0 then
  253. begin
  254. setlength(outbuffer, WriteLen);
  255. Result := Result + outbuffer;
  256. end;
  257. until WriteLen = 0;
  258. end;
  259. function TSSLCryptLib.Init(server:Boolean): Boolean;
  260. var
  261. st: CRYPT_SESSION_TYPE;
  262. keysetobj: CRYPT_KEYSET;
  263. cryptContext: CRYPT_CONTEXT;
  264. x: integer;
  265. aUserName : AnsiString;
  266. aPassword: AnsiString;
  267. begin
  268. Result := False;
  269. FLastErrorDesc := '';
  270. FLastError := 0;
  271. FDelCert := false;
  272. FcryptSession := CRYPT_SESSION(CRYPT_SESSION_NONE);
  273. if server then
  274. case FSSLType of
  275. LT_all, LT_SSLv3, LT_TLSv1, LT_TLSv1_1:
  276. st := CRYPT_SESSION_SSL_SERVER;
  277. LT_SSHv2:
  278. st := CRYPT_SESSION_SSH_SERVER;
  279. else
  280. Exit;
  281. end
  282. else
  283. case FSSLType of
  284. LT_all, LT_SSLv3, LT_TLSv1, LT_TLSv1_1:
  285. st := CRYPT_SESSION_SSL;
  286. LT_SSHv2:
  287. st := CRYPT_SESSION_SSH;
  288. else
  289. Exit;
  290. end;
  291. if not SSLCheck(cryptCreateSession(FcryptSession, CRYPT_UNUSED, st)) then
  292. Exit;
  293. x := -1;
  294. case FSSLType of
  295. LT_SSLv3:
  296. x := 0;
  297. LT_TLSv1:
  298. x := 1;
  299. LT_TLSv1_1:
  300. x := 2;
  301. end;
  302. if x >= 0 then
  303. if not SSLCheck(cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_VERSION, x)) then
  304. Exit;
  305. if (FCertComplianceLevel <> -1) then
  306. if not SSLCheck(cryptSetAttribute (CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL,
  307. FCertComplianceLevel)) then
  308. Exit;
  309. if FUsername <> '' then
  310. begin
  311. aUserName := fUserName;
  312. aPassword := fPassword;
  313. cryptSetAttributeString(FcryptSession, CRYPT_SESSINFO_USERNAME,
  314. Pointer(FUsername), Length(FUsername));
  315. cryptSetAttributeString(FcryptSession, CRYPT_SESSINFO_PASSWORD,
  316. Pointer(FPassword), Length(FPassword));
  317. end;
  318. if FSSLType = LT_SSHv2 then
  319. if FSSHChannelType <> '' then
  320. begin
  321. cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_SSH_CHANNEL, CRYPT_UNUSED);
  322. cryptSetAttributeString(FCryptSession, CRYPT_SESSINFO_SSH_CHANNEL_TYPE,
  323. Pointer(FSSHChannelType), Length(FSSHChannelType));
  324. if FSSHChannelArg1 <> '' then
  325. cryptSetAttributeString(FCryptSession, CRYPT_SESSINFO_SSH_CHANNEL_ARG1,
  326. Pointer(FSSHChannelArg1), Length(FSSHChannelArg1));
  327. if FSSHChannelArg2 <> '' then
  328. cryptSetAttributeString(FCryptSession, CRYPT_SESSINFO_SSH_CHANNEL_ARG2,
  329. Pointer(FSSHChannelArg2), Length(FSSHChannelArg2));
  330. end;
  331. if server and (FPrivatekeyFile = '') then
  332. begin
  333. if FPrivatekeyLabel = '' then
  334. FPrivatekeyLabel := 'synapse';
  335. if FkeyPassword = '' then
  336. FkeyPassword := 'synapse';
  337. CreateSelfSignedcert(FSocket.ResolveIPToName(FSocket.GetRemoteSinIP));
  338. end;
  339. if (FPrivatekeyLabel <> '') and (FPrivatekeyFile <> '') then
  340. begin
  341. if not SSLCheck(cryptKeysetOpen(KeySetObj, CRYPT_UNUSED, CRYPT_KEYSET_FILE,
  342. PChar(FPrivatekeyFile), CRYPT_KEYOPT_READONLY)) then
  343. Exit;
  344. try
  345. if not SSLCheck(cryptGetPrivateKey(KeySetObj, cryptcontext, CRYPT_KEYID_NAME,
  346. PChar(FPrivatekeyLabel), PChar(FKeyPassword))) then
  347. Exit;
  348. if not SSLCheck(cryptSetAttribute(FcryptSession, CRYPT_SESSINFO_PRIVATEKEY,
  349. cryptcontext)) then
  350. Exit;
  351. finally
  352. cryptKeysetClose(keySetObj);
  353. cryptDestroyContext(cryptcontext);
  354. end;
  355. end;
  356. if server and FVerifyCert then
  357. begin
  358. if not SSLCheck(cryptKeysetOpen(KeySetObj, CRYPT_UNUSED, CRYPT_KEYSET_FILE,
  359. PChar(FCertCAFile), CRYPT_KEYOPT_READONLY)) then
  360. Exit;
  361. try
  362. if not SSLCheck(cryptSetAttribute(FcryptSession, CRYPT_SESSINFO_KEYSET,
  363. keySetObj)) then
  364. Exit;
  365. finally
  366. cryptKeysetClose(keySetObj);
  367. end;
  368. end;
  369. Result := true;
  370. end;
  371. function TSSLCryptLib.DeInit: Boolean;
  372. begin
  373. Result := True;
  374. if FcryptSession <> CRYPT_SESSION(CRYPT_SESSION_NONE) then
  375. CryptDestroySession(FcryptSession);
  376. FcryptSession := CRYPT_SESSION(CRYPT_SESSION_NONE);
  377. FSSLEnabled := False;
  378. if FDelCert then
  379. SysUtils.DeleteFile(FPrivatekeyFile);
  380. end;
  381. function TSSLCryptLib.Prepare(server:Boolean): Boolean;
  382. begin
  383. Result := false;
  384. DeInit;
  385. if Init(server) then
  386. Result := true
  387. else
  388. DeInit;
  389. end;
  390. function TSSLCryptLib.Connect: boolean;
  391. begin
  392. Result := False;
  393. if FSocket.Socket = INVALID_SOCKET then
  394. Exit;
  395. if Prepare(false) then
  396. begin
  397. if not SSLCheck(cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_NETWORKSOCKET, FSocket.Socket)) then
  398. Exit;
  399. if not SSLCheck(cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_ACTIVE, 1)) then
  400. Exit;
  401. if FverifyCert then
  402. if (GetVerifyCert <> 0) or (not DoVerifyCert) then
  403. Exit;
  404. FSSLEnabled := True;
  405. Result := True;
  406. FReadBuffer := '';
  407. end;
  408. end;
  409. function TSSLCryptLib.Accept: boolean;
  410. begin
  411. Result := False;
  412. if FSocket.Socket = INVALID_SOCKET then
  413. Exit;
  414. if Prepare(true) then
  415. begin
  416. if not SSLCheck(cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_NETWORKSOCKET, FSocket.Socket)) then
  417. Exit;
  418. if not SSLCheck(cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_ACTIVE, 1)) then
  419. Exit;
  420. FSSLEnabled := True;
  421. Result := True;
  422. FReadBuffer := '';
  423. end;
  424. end;
  425. function TSSLCryptLib.Shutdown: boolean;
  426. begin
  427. Result := BiShutdown;
  428. end;
  429. function TSSLCryptLib.BiShutdown: boolean;
  430. begin
  431. if FcryptSession <> CRYPT_SESSION(CRYPT_SESSION_NONE) then
  432. cryptSetAttribute(FCryptSession, CRYPT_SESSINFO_ACTIVE, 0);
  433. DeInit;
  434. FReadBuffer := '';
  435. Result := True;
  436. end;
  437. function TSSLCryptLib.SendBuffer(Buffer: TMemory; Len: Integer): Integer;
  438. var
  439. l: integer;
  440. begin
  441. FLastError := 0;
  442. FLastErrorDesc := '';
  443. SSLCheck(cryptPushData(FCryptSession, Buffer, Len, L));
  444. cryptFlushData(FcryptSession);
  445. Result := l;
  446. end;
  447. function TSSLCryptLib.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
  448. begin
  449. FLastError := 0;
  450. FLastErrorDesc := '';
  451. if Length(FReadBuffer) = 0 then
  452. FReadBuffer := PopAll;
  453. if Len > Length(FReadBuffer) then
  454. Len := Length(FReadBuffer);
  455. Move(Pointer(FReadBuffer)^, buffer^, Len);
  456. Delete(FReadBuffer, 1, Len);
  457. Result := Len;
  458. end;
  459. function TSSLCryptLib.WaitingData: Integer;
  460. begin
  461. Result := Length(FReadBuffer);
  462. end;
  463. function TSSLCryptLib.GetSSLVersion: string;
  464. var
  465. x: integer;
  466. begin
  467. Result := '';
  468. if FcryptSession = CRYPT_SESSION(CRYPT_SESSION_NONE) then
  469. Exit;
  470. cryptGetAttribute(FCryptSession, CRYPT_SESSINFO_VERSION, x);
  471. if FSSLType in [LT_SSLv3, LT_TLSv1, LT_TLSv1_1, LT_all] then
  472. case x of
  473. 0:
  474. Result := 'SSLv3';
  475. 1:
  476. Result := 'TLSv1';
  477. 2:
  478. Result := 'TLSv1.1';
  479. end;
  480. if FSSLType in [LT_SSHv2] then
  481. case x of
  482. 0:
  483. Result := 'SSHv1';
  484. 1:
  485. Result := 'SSHv2';
  486. end;
  487. end;
  488. function TSSLCryptLib.GetPeerSubject: string;
  489. var
  490. cert: CRYPT_CERTIFICATE;
  491. begin
  492. Result := '';
  493. if FcryptSession = CRYPT_SESSION(CRYPT_SESSION_NONE) then
  494. Exit;
  495. cryptGetAttribute(FCryptSession, CRYPT_SESSINFO_RESPONSE, cert);
  496. cryptSetAttribute(cert, CRYPT_ATTRIBUTE_CURRENT, CRYPT_CERTINFO_SUBJECTNAME);
  497. Result := GetString(cert, CRYPT_CERTINFO_DN);
  498. cryptDestroyCert(cert);
  499. end;
  500. function TSSLCryptLib.GetPeerName: string;
  501. var
  502. cert: CRYPT_CERTIFICATE;
  503. begin
  504. Result := '';
  505. if FcryptSession = CRYPT_SESSION(CRYPT_SESSION_NONE) then
  506. Exit;
  507. cryptGetAttribute(FCryptSession, CRYPT_SESSINFO_RESPONSE, cert);
  508. cryptSetAttribute(cert, CRYPT_ATTRIBUTE_CURRENT, CRYPT_CERTINFO_SUBJECTNAME);
  509. Result := GetString(cert, CRYPT_CERTINFO_COMMONNAME);
  510. cryptDestroyCert(cert);
  511. end;
  512. function TSSLCryptLib.GetPeerIssuer: string;
  513. var
  514. cert: CRYPT_CERTIFICATE;
  515. begin
  516. Result := '';
  517. if FcryptSession = CRYPT_SESSION(CRYPT_SESSION_NONE) then
  518. Exit;
  519. cryptGetAttribute(FCryptSession, CRYPT_SESSINFO_RESPONSE, cert);
  520. cryptSetAttribute(cert, CRYPT_ATTRIBUTE_CURRENT, CRYPT_CERTINFO_ISSUERNAME);
  521. Result := GetString(cert, CRYPT_CERTINFO_COMMONNAME);
  522. cryptDestroyCert(cert);
  523. end;
  524. function TSSLCryptLib.GetPeerFingerprint: string;
  525. var
  526. cert: CRYPT_CERTIFICATE;
  527. begin
  528. Result := '';
  529. if FcryptSession = CRYPT_SESSION(CRYPT_SESSION_NONE) then
  530. Exit;
  531. cryptGetAttribute(FCryptSession, CRYPT_SESSINFO_RESPONSE, cert);
  532. Result := GetString(cert, CRYPT_CERTINFO_FINGERPRINT);
  533. cryptDestroyCert(cert);
  534. end;
  535. procedure TSSLCryptLib.SetCertCAFile(const Value: string);
  536. var F:textfile;
  537. bInCert:boolean;
  538. s,sCert:string;
  539. cert: CRYPT_CERTIFICATE;
  540. idx:integer;
  541. begin
  542. if assigned(FTrustedCAs) then
  543. begin
  544. for idx := 0 to High(FTrustedCAs) do
  545. cryptDestroyCert(FTrustedCAs[idx]);
  546. FTrustedCAs:=nil;
  547. end;
  548. if Value<>'' then
  549. begin
  550. AssignFile(F,Value);
  551. reset(F);
  552. bInCert:=false;
  553. idx:=0;
  554. while not eof(F) do
  555. begin
  556. readln(F,s);
  557. if pos('-----END CERTIFICATE-----',s)>0 then
  558. begin
  559. bInCert:=false;
  560. cert:=0;
  561. if (cryptImportCert(PAnsiChar(sCert),length(sCert)-2,CRYPT_UNUSED,cert)=CRYPT_OK) then
  562. begin
  563. cryptSetAttribute( cert, CRYPT_CERTINFO_TRUSTED_IMPLICIT, 1 );
  564. SetLength(FTrustedCAs,idx+1);
  565. FTrustedCAs[idx]:=cert;
  566. idx:=idx+1;
  567. end;
  568. end;
  569. if bInCert then
  570. sCert:=sCert+s+#13#10;
  571. if pos('-----BEGIN CERTIFICATE-----',s)>0 then
  572. begin
  573. bInCert:=true;
  574. sCert:='';
  575. end;
  576. end;
  577. CloseFile(F);
  578. end;
  579. end;
  580. function TSSLCryptLib.GetVerifyCert: integer;
  581. var
  582. cert: CRYPT_CERTIFICATE;
  583. itype,ilocus:integer;
  584. begin
  585. Result := -1;
  586. if FcryptSession = CRYPT_SESSION(CRYPT_SESSION_NONE) then
  587. Exit;
  588. cryptGetAttribute(FCryptSession, CRYPT_SESSINFO_RESPONSE, cert);
  589. result:=cryptCheckCert(cert,CRYPT_UNUSED);
  590. if result<>CRYPT_OK then
  591. begin
  592. //get extended error info if available
  593. cryptGetAttribute(cert,CRYPT_ATTRIBUTE_ERRORtype,itype);
  594. cryptGetAttribute(cert,CRYPT_ATTRIBUTE_ERRORLOCUS,ilocus);
  595. cryptSetAttribute(cert, CRYPT_ATTRIBUTE_CURRENT, CRYPT_CERTINFO_SUBJECTNAME);
  596. FLastError := Result;
  597. FLastErrorDesc := format('SSL/TLS certificate verification failed for "%s"'#13#10'Status: %d. ERRORTYPE: %d. ERRORLOCUS: %d.',
  598. [GetString(cert, CRYPT_CERTINFO_COMMONNAME),result,itype,ilocus]);
  599. end;
  600. cryptDestroyCert(cert);
  601. end;
  602. {==============================================================================}
  603. var imajor,iminor,iver:integer;
  604. // e: ESynapseError;
  605. initialization
  606. if cryptInit = CRYPT_OK then
  607. SSLImplementation := TSSLCryptLib;
  608. cryptAddRandom(nil, CRYPT_RANDOM_SLOWPOLL);
  609. cryptGetAttribute (CRYPT_UNUSED, CRYPT_OPTION_INFO_MAJORVERSION,imajor);
  610. cryptGetAttribute (CRYPT_UNUSED, CRYPT_OPTION_INFO_MINORVERSION,iminor);
  611. // according to the documentation CRYPTLIB version has 3 digits. recent versions use 4 digits
  612. if CRYPTLIB_VERSION >1000 then
  613. iver:=CRYPTLIB_VERSION div 100
  614. else
  615. iver:=CRYPTLIB_VERSION div 10;
  616. if (iver <> imajor*10+iminor) then
  617. begin
  618. SSLImplementation :=TSSLNone;
  619. // e := ESynapseError.Create(format('Error wrong cryptlib version (is %d.%d expected %d.%d). ',
  620. // [imajor,iminor,iver div 10, iver mod 10]));
  621. // e.ErrorCode := 0;
  622. // e.ErrorMessage := format('Error wrong cryptlib version (%d.%d expected %d.%d)',
  623. // [imajor,iminor,iver div 10, iver mod 10]);
  624. // raise e;
  625. end;
  626. finalization
  627. cryptEnd;
  628. end.