ssl_streamsec.pas 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. {==============================================================================|
  2. | Project : Ararat Synapse | 001.000.006 |
  3. |==============================================================================|
  4. | Content: SSL support by StreamSecII |
  5. |==============================================================================|
  6. | Copyright (c)1999-2005, 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. |
  37. | All Rights Reserved. |
  38. |==============================================================================|
  39. | Contributor(s): |
  40. | Henrick Hellström <[email protected]> |
  41. |==============================================================================|
  42. | History: see HISTORY.HTM from distribution package |
  43. | (Found at URL: http://www.ararat.cz/synapse/) |
  44. |==============================================================================}
  45. {:@abstract(SSL plugin for StreamSecII or OpenStreamSecII)
  46. StreamSecII is native pascal library, you not need any external libraries!
  47. You can tune lot of StreamSecII properties by using your GlobalServer. If you not
  48. using your GlobalServer, then this plugin create own TSimpleTLSInternalServer
  49. instance for each TCP connection. Formore information about GlobalServer usage
  50. refer StreamSecII documentation.
  51. If you are not using key and certificate by GlobalServer, then you can use
  52. properties of this plugin instead, but this have limited features and
  53. @link(TCustomSSL.KeyPassword) not working properly yet!
  54. For handling keys and certificates you can use this properties:
  55. @link(TCustomSSL.CertCAFile), @link(TCustomSSL.CertCA),
  56. @link(TCustomSSL.TrustCertificateFile), @link(TCustomSSL.TrustCertificate),
  57. @link(TCustomSSL.PrivateKeyFile), @link(TCustomSSL.PrivateKey),
  58. @link(TCustomSSL.CertificateFile), @link(TCustomSSL.Certificate),
  59. @link(TCustomSSL.PFXFile). For usage of this properties and for possible formats
  60. of keys and certificates refer to StreamSecII documentation.
  61. }
  62. {$IFDEF FPC}
  63. {$MODE DELPHI}
  64. {$ENDIF}
  65. {$H+}
  66. unit ssl_streamsec;
  67. interface
  68. uses
  69. SysUtils, Classes,
  70. blcksock, synsock, synautil, synacode,
  71. TlsInternalServer, TlsSynaSock, TlsConst, StreamSecII, Asn1, X509Base,
  72. SecUtils;
  73. type
  74. {:@exclude}
  75. TMyTLSSynSockSlave = class(TTLSSynSockSlave)
  76. protected
  77. procedure SetMyTLSServer(const Value: TCustomTLSInternalServer);
  78. function GetMyTLSServer: TCustomTLSInternalServer;
  79. published
  80. property MyTLSServer: TCustomTLSInternalServer read GetMyTLSServer write SetMyTLSServer;
  81. end;
  82. {:@abstract(class implementing StreamSecII SSL plugin.)
  83. Instance of this class will be created for each @link(TTCPBlockSocket).
  84. You not need to create instance of this class, all is done by Synapse itself!}
  85. TSSLStreamSec = class(TCustomSSL)
  86. protected
  87. FSlave: TMyTLSSynSockSlave;
  88. FIsServer: Boolean;
  89. FTLSServer: TCustomTLSInternalServer;
  90. FServerCreated: Boolean;
  91. function SSLCheck: Boolean;
  92. function Init(server:Boolean): Boolean;
  93. function DeInit: Boolean;
  94. function Prepare(server:Boolean): Boolean;
  95. procedure NotTrustEvent(Sender: TObject; Cert: TASN1Struct; var ExplicitTrust: Boolean);
  96. function X500StrToStr(const Prefix: string; const Value: TX500String): string;
  97. function X501NameToStr(const Value: TX501Name): string;
  98. function GetCert: PASN1Struct;
  99. public
  100. constructor Create(const Value: TTCPBlockSocket); override;
  101. destructor Destroy; override;
  102. {:See @inherited}
  103. function LibVersion: String; override;
  104. {:See @inherited}
  105. function LibName: String; override;
  106. {:See @inherited and @link(ssl_streamsec) for more details.}
  107. function Connect: boolean; override;
  108. {:See @inherited and @link(ssl_streamsec) for more details.}
  109. function Accept: boolean; override;
  110. {:See @inherited}
  111. function Shutdown: boolean; override;
  112. {:See @inherited}
  113. function BiShutdown: boolean; override;
  114. {:See @inherited}
  115. function SendBuffer(Buffer: TMemory; Len: Integer): Integer; override;
  116. {:See @inherited}
  117. function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; override;
  118. {:See @inherited}
  119. function WaitingData: Integer; override;
  120. {:See @inherited}
  121. function GetSSLVersion: string; override;
  122. {:See @inherited}
  123. function GetPeerSubject: string; override;
  124. {:See @inherited}
  125. function GetPeerIssuer: string; override;
  126. {:See @inherited}
  127. function GetPeerName: string; override;
  128. {:See @inherited}
  129. function GetPeerFingerprint: string; override;
  130. {:See @inherited}
  131. function GetCertInfo: string; override;
  132. published
  133. {:TLS server for tuning of StreamSecII.}
  134. property TLSServer: TCustomTLSInternalServer read FTLSServer write FTLSServer;
  135. end;
  136. implementation
  137. {==============================================================================}
  138. procedure TMyTLSSynSockSlave.SetMyTLSServer(const Value: TCustomTLSInternalServer);
  139. begin
  140. TLSServer := Value;
  141. end;
  142. function TMyTLSSynSockSlave.GetMyTLSServer: TCustomTLSInternalServer;
  143. begin
  144. Result := TLSServer;
  145. end;
  146. {==============================================================================}
  147. constructor TSSLStreamSec.Create(const Value: TTCPBlockSocket);
  148. begin
  149. inherited Create(Value);
  150. FSlave := nil;
  151. FIsServer := False;
  152. FTLSServer := nil;
  153. end;
  154. destructor TSSLStreamSec.Destroy;
  155. begin
  156. DeInit;
  157. inherited Destroy;
  158. end;
  159. function TSSLStreamSec.LibVersion: String;
  160. begin
  161. Result := 'StreamSecII';
  162. end;
  163. function TSSLStreamSec.LibName: String;
  164. begin
  165. Result := 'ssl_streamsec';
  166. end;
  167. function TSSLStreamSec.SSLCheck: Boolean;
  168. begin
  169. Result := true;
  170. FLastErrorDesc := '';
  171. if not Assigned(FSlave) then
  172. Exit;
  173. FLastError := FSlave.ErrorCode;
  174. if FLastError <> 0 then
  175. begin
  176. FLastErrorDesc := TlsConst.AlertMsg(FLastError);
  177. end;
  178. end;
  179. procedure TSSLStreamSec.NotTrustEvent(Sender: TObject; Cert: TASN1Struct; var ExplicitTrust: Boolean);
  180. begin
  181. ExplicitTrust := true;
  182. end;
  183. function TSSLStreamSec.Init(server:Boolean): Boolean;
  184. var
  185. st: TMemoryStream;
  186. pass: ISecretKey;
  187. ws: WideString;
  188. begin
  189. Result := False;
  190. ws := FKeyPassword;
  191. pass := TSecretKey.CreateBmpStr(PWideChar(ws), length(ws));
  192. try
  193. FIsServer := Server;
  194. FSlave := TMyTLSSynSockSlave.CreateSocket(FSocket.Socket);
  195. if Assigned(FTLSServer) then
  196. FSlave.MyTLSServer := FTLSServer
  197. else
  198. if Assigned(TLSInternalServer.GlobalServer) then
  199. FSlave.MyTLSServer := TLSInternalServer.GlobalServer
  200. else begin
  201. FSlave.MyTLSServer := TSimpleTLSInternalServer.Create(nil);
  202. FServerCreated := True;
  203. end;
  204. if server then
  205. FSlave.MyTLSServer.ClientOrServer := cosServerSide
  206. else
  207. FSlave.MyTLSServer.ClientOrServer := cosClientSide;
  208. if not FVerifyCert then
  209. begin
  210. FSlave.MyTLSServer.OnCertNotTrusted := NotTrustEvent;
  211. end;
  212. FSlave.MyTLSServer.Options.VerifyServerName := [];
  213. FSlave.MyTLSServer.Options.Export40Bit := prAllowed;
  214. FSlave.MyTLSServer.Options.Export56Bit := prAllowed;
  215. FSlave.MyTLSServer.Options.RequestClientCertificate := False;
  216. FSlave.MyTLSServer.Options.RequireClientCertificate := False;
  217. if server and FVerifyCert then
  218. begin
  219. FSlave.MyTLSServer.Options.RequestClientCertificate := True;
  220. FSlave.MyTLSServer.Options.RequireClientCertificate := True;
  221. end;
  222. if FCertCAFile <> '' then
  223. FSlave.MyTLSServer.LoadRootCertsFromFile(CertCAFile);
  224. if FCertCA <> '' then
  225. begin
  226. st := TMemoryStream.Create;
  227. try
  228. WriteStrToStream(st, FCertCA);
  229. st.Seek(0, soFromBeginning);
  230. FSlave.MyTLSServer.LoadRootCertsFromStream(st);
  231. finally
  232. st.free;
  233. end;
  234. end;
  235. if FTrustCertificateFile <> '' then
  236. FSlave.MyTLSServer.LoadTrustedCertsFromFile(FTrustCertificateFile);
  237. if FTrustCertificate <> '' then
  238. begin
  239. st := TMemoryStream.Create;
  240. try
  241. WriteStrToStream(st, FTrustCertificate);
  242. st.Seek(0, soFromBeginning);
  243. FSlave.MyTLSServer.LoadTrustedCertsFromStream(st);
  244. finally
  245. st.free;
  246. end;
  247. end;
  248. if FPrivateKeyFile <> '' then
  249. FSlave.MyTLSServer.LoadPrivateKeyRingFromFile(FPrivateKeyFile, pass);
  250. // FSlave.MyTLSServer.PrivateKeyRing.LoadPrivateKeyFromFile(FPrivateKeyFile, pass);
  251. if FPrivateKey <> '' then
  252. begin
  253. st := TMemoryStream.Create;
  254. try
  255. WriteStrToStream(st, FPrivateKey);
  256. st.Seek(0, soFromBeginning);
  257. FSlave.MyTLSServer.LoadPrivateKeyRingFromStream(st, pass);
  258. finally
  259. st.free;
  260. end;
  261. end;
  262. if FCertificateFile <> '' then
  263. FSlave.MyTLSServer.LoadMyCertsFromFile(FCertificateFile);
  264. if FCertificate <> '' then
  265. begin
  266. st := TMemoryStream.Create;
  267. try
  268. WriteStrToStream(st, FCertificate);
  269. st.Seek(0, soFromBeginning);
  270. FSlave.MyTLSServer.LoadMyCertsFromStream(st);
  271. finally
  272. st.free;
  273. end;
  274. end;
  275. if FPFXfile <> '' then
  276. FSlave.MyTLSServer.ImportFromPFX(FPFXfile, pass);
  277. if server and FServerCreated then
  278. begin
  279. FSlave.MyTLSServer.Options.BulkCipherAES128 := prPrefer;
  280. FSlave.MyTLSServer.Options.BulkCipherAES256 := prAllowed;
  281. FSlave.MyTLSServer.Options.EphemeralECDHKeySize := ecs256;
  282. FSlave.MyTLSServer.Options.SignatureRSA := prPrefer;
  283. FSlave.MyTLSServer.Options.KeyAgreementRSA := prAllowed;
  284. FSlave.MyTLSServer.Options.KeyAgreementECDHE := prAllowed;
  285. FSlave.MyTLSServer.Options.KeyAgreementDHE := prPrefer;
  286. FSlave.MyTLSServer.TLSSetupServer;
  287. end;
  288. Result := true;
  289. finally
  290. pass := nil;
  291. end;
  292. end;
  293. function TSSLStreamSec.DeInit: Boolean;
  294. var
  295. obj: TObject;
  296. begin
  297. Result := True;
  298. if assigned(FSlave) then
  299. begin
  300. FSlave.Close;
  301. if FServerCreated then
  302. obj := FSlave.TLSServer
  303. else
  304. obj := nil;
  305. FSlave.Free;
  306. obj.Free;
  307. FSlave := nil;
  308. end;
  309. FSSLEnabled := false;
  310. end;
  311. function TSSLStreamSec.Prepare(server:Boolean): Boolean;
  312. begin
  313. Result := false;
  314. DeInit;
  315. if Init(server) then
  316. Result := true
  317. else
  318. DeInit;
  319. end;
  320. function TSSLStreamSec.Connect: boolean;
  321. begin
  322. Result := False;
  323. if FSocket.Socket = INVALID_SOCKET then
  324. Exit;
  325. if Prepare(false) then
  326. begin
  327. FSlave.Open;
  328. SSLCheck;
  329. if FLastError <> 0 then
  330. Exit;
  331. FSSLEnabled := True;
  332. Result := True;
  333. end;
  334. end;
  335. function TSSLStreamSec.Accept: boolean;
  336. begin
  337. Result := False;
  338. if FSocket.Socket = INVALID_SOCKET then
  339. Exit;
  340. if Prepare(true) then
  341. begin
  342. FSlave.DoConnect;
  343. SSLCheck;
  344. if FLastError <> 0 then
  345. Exit;
  346. FSSLEnabled := True;
  347. Result := True;
  348. end;
  349. end;
  350. function TSSLStreamSec.Shutdown: boolean;
  351. begin
  352. Result := BiShutdown;
  353. end;
  354. function TSSLStreamSec.BiShutdown: boolean;
  355. begin
  356. DeInit;
  357. Result := True;
  358. end;
  359. function TSSLStreamSec.SendBuffer(Buffer: TMemory; Len: Integer): Integer;
  360. var
  361. l: integer;
  362. begin
  363. l := len;
  364. FSlave.SendBuf(Buffer^, l, true);
  365. Result := l;
  366. SSLCheck;
  367. end;
  368. function TSSLStreamSec.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
  369. var
  370. l: integer;
  371. begin
  372. l := Len;
  373. Result := FSlave.ReceiveBuf(Buffer^, l);
  374. SSLCheck;
  375. end;
  376. function TSSLStreamSec.WaitingData: Integer;
  377. begin
  378. Result := 0;
  379. while FSlave.Connected do begin
  380. Result := FSlave.ReceiveLength;
  381. if Result > 0 then
  382. Break;
  383. Sleep(1);
  384. end;
  385. end;
  386. function TSSLStreamSec.GetSSLVersion: string;
  387. begin
  388. Result := 'SSLv3 or TLSv1';
  389. end;
  390. function TSSLStreamSec.GetCert: PASN1Struct;
  391. begin
  392. if FIsServer then
  393. Result := FSlave.GetClientCert
  394. else
  395. Result := FSlave.GetServerCert;
  396. end;
  397. function TSSLStreamSec.GetPeerSubject: string;
  398. var
  399. XName: TX501Name;
  400. Cert: PASN1Struct;
  401. begin
  402. Result := '';
  403. Cert := GetCert;
  404. if Assigned(cert) then
  405. begin
  406. ExtractSubject(Cert^,XName, false);
  407. Result := X501NameToStr(XName);
  408. end;
  409. end;
  410. function TSSLStreamSec.GetPeerName: string;
  411. var
  412. XName: TX501Name;
  413. Cert: PASN1Struct;
  414. begin
  415. Result := '';
  416. Cert := GetCert;
  417. if Assigned(cert) then
  418. begin
  419. ExtractSubject(Cert^,XName, false);
  420. Result := XName.commonName.Str;
  421. end;
  422. end;
  423. function TSSLStreamSec.GetPeerIssuer: string;
  424. var
  425. XName: TX501Name;
  426. Cert: PASN1Struct;
  427. begin
  428. Result := '';
  429. Cert := GetCert;
  430. if Assigned(cert) then
  431. begin
  432. ExtractIssuer(Cert^, XName, false);
  433. Result := X501NameToStr(XName);
  434. end;
  435. end;
  436. function TSSLStreamSec.GetPeerFingerprint: string;
  437. var
  438. Cert: PASN1Struct;
  439. begin
  440. Result := '';
  441. Cert := GetCert;
  442. if Assigned(cert) then
  443. Result := MD5(Cert.ContentAsOctetString);
  444. end;
  445. function TSSLStreamSec.GetCertInfo: string;
  446. var
  447. Cert: PASN1Struct;
  448. l: Tstringlist;
  449. begin
  450. Result := '';
  451. Cert := GetCert;
  452. if Assigned(cert) then
  453. begin
  454. l := TStringList.Create;
  455. try
  456. Asn1.RenderAsText(cert^, l, true, true, true, 2);
  457. Result := l.Text;
  458. finally
  459. l.free;
  460. end;
  461. end;
  462. end;
  463. function TSSLStreamSec.X500StrToStr(const Prefix: string;
  464. const Value: TX500String): string;
  465. begin
  466. if Value.Str = '' then
  467. Result := ''
  468. else
  469. Result := '/' + Prefix + '=' + Value.Str;
  470. end;
  471. function TSSLStreamSec.X501NameToStr(const Value: TX501Name): string;
  472. begin
  473. Result := X500StrToStr('CN',Value.commonName) +
  474. X500StrToStr('C',Value.countryName) +
  475. X500StrToStr('L',Value.localityName) +
  476. X500StrToStr('ST',Value.stateOrProvinceName) +
  477. X500StrToStr('O',Value.organizationName) +
  478. X500StrToStr('OU',Value.organizationalUnitName) +
  479. X500StrToStr('T',Value.title) +
  480. X500StrToStr('N',Value.name) +
  481. X500StrToStr('G',Value.givenName) +
  482. X500StrToStr('I',Value.initials) +
  483. X500StrToStr('SN',Value.surname) +
  484. X500StrToStr('GQ',Value.generationQualifier) +
  485. X500StrToStr('DNQ',Value.dnQualifier) +
  486. X500StrToStr('E',Value.emailAddress);
  487. end;
  488. {==============================================================================}
  489. initialization
  490. SSLImplementation := TSSLStreamSec;
  491. finalization
  492. end.