/
Hookup.hs
698 lines (613 loc) · 25.2 KB
/
Hookup.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
{-# Language BlockArguments, LambdaCase #-}
{-|
Module : Hookup
Description : Network connections generalized over TLS and SOCKS
Copyright : (c) Eric Mertens, 2016
License : ISC
Maintainer : emertens@gmail.com
This module provides a uniform interface to network connections
with optional support for TLS and SOCKS.
This library is careful to support both IPv4 and IPv6. It will attempt to
all of the addresses that a domain name resolves to until one the first
successful connection.
Use 'connect' and 'close' to establish and close network connections.
Use 'recv', 'recvLine', and 'send' to receive and transmit data on an
open network connection.
TLS and SOCKS parameters can be provided. When both are provided a connection
will first be established to the SOCKS server and then the TLS connection will
be established through that proxy server. This is most useful when connecting
through a dynamic port forward of an SSH client via the @-D@ flag.
-}
module Hookup
(
-- * Connections
Connection,
connect,
connectWithSocket,
close,
upgradeTls,
-- * Reading and writing data
recv,
recvLine,
send,
putBuf,
-- * Configuration
ConnectionParams(..),
SocksParams(..),
SocksAuthentication(..),
TlsParams(..),
TlsVerify(..),
PEM.PemPasswordSupply(..),
defaultTlsParams,
-- * Errors
ConnectionFailure(..),
CommandReply(..)
-- * SSL Information
, getClientCertificate
, getPeerCertificate
, getPeerCertFingerprintSha1
, getPeerCertFingerprintSha256
, getPeerCertFingerprintSha512
, getPeerPubkeyFingerprintSha1
, getPeerPubkeyFingerprintSha256
, getPeerPubkeyFingerprintSha512
) where
import Control.Concurrent
import Control.Exception
import Control.Monad (when, unless)
import System.IO.Error (isDoesNotExistError, ioeGetErrorString)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Foldable (for_, traverse_)
import Data.List (intercalate, partition)
import Data.Maybe (fromMaybe, mapMaybe)
import Foreign.C.String (withCStringLen)
import Foreign.Ptr (nullPtr)
import Network.Socket (AddrInfo, HostName, PortNumber, SockAddr, Socket, Family)
import qualified Network.Socket as Socket
import qualified Network.Socket.ByteString as SocketB
import OpenSSL.Session (SSL, SSLContext)
import qualified OpenSSL as SSL
import qualified OpenSSL.Session as SSL
import OpenSSL.X509.SystemStore (contextLoadSystemCerts)
import OpenSSL.X509 (X509)
import qualified OpenSSL.X509 as X509
import qualified OpenSSL.PEM as PEM
import qualified OpenSSL.EVP.Digest as Digest
import Data.Attoparsec.ByteString (Parser)
import qualified Data.Attoparsec.ByteString as Parser
import Hookup.Concurrent (concurrentAttempts)
import Hookup.OpenSSL
import Hookup.Socks5
-- | Parameters for 'connect'.
--
-- Common defaults for fields: 'defaultFamily', 'defaultTlsParams'
--
-- When a 'SocksParams' is provided the connection will be established
-- using a SOCKS (version 5) proxy.
--
-- When a 'TlsParams' is provided the connection negotiate TLS at connect
-- time in order to protect the stream.
--
-- The binding hostname can be used to force the connect to use a particular
-- interface or IP protocol version.
data ConnectionParams = ConnectionParams
{ cpHost :: HostName -- ^ Destination host
, cpPort :: PortNumber -- ^ Destination TCP port
, cpSocks :: Maybe SocksParams -- ^ Optional SOCKS parameters
, cpTls :: Maybe TlsParams -- ^ Optional TLS parameters
, cpBind :: Maybe HostName -- ^ Source address to bind
}
deriving Show
-- | SOCKS connection parameters
data SocksParams = SocksParams
{ spHost :: HostName -- ^ SOCKS server host
, spPort :: PortNumber -- ^ SOCKS server port
, spAuth :: SocksAuthentication -- ^ SOCKS authentication method
}
deriving Show
data SocksAuthentication
= NoSocksAuthentication -- ^ no credentials
| UsernamePasswordSocksAuthentication ByteString ByteString -- ^ RFC 1929 username and password
deriving Show
-- | TLS connection parameters. These parameters are passed to
-- OpenSSL when making a secure connection.
data TlsParams = TlsParams
{ tpClientCertificate :: Maybe FilePath -- ^ Path to client certificate
, tpClientPrivateKey :: Maybe FilePath -- ^ Path to client private key
, tpClientPrivateKeyPassword :: Maybe ByteString -- ^ Private key decryption password
, tpServerCertificate :: Maybe FilePath -- ^ Path to CA certificate bundle
, tpCipherSuite :: String -- ^ OpenSSL cipher suite name (e.g. @\"HIGH\"@)
, tpCipherSuiteTls13 :: Maybe String -- ^ OpenSSL cipher suites for TLS 1.3
, tpVerify :: TlsVerify -- ^ Hostname to use when checking certificate validity
}
deriving Show
data TlsVerify
= VerifyDefault -- ^ Use the connection hostname to verify
| VerifyNone -- ^ No verification
| VerifyHostname String -- ^ Use the given hostname to verify
deriving Show
-- | Type for errors that can be thrown by this package.
data ConnectionFailure
-- | Failure during 'getAddrInfo' resolving remote host
= HostnameResolutionFailure HostName String
-- | Failure during 'connect' to remote host
| ConnectionFailure [ConnectError]
-- | Failure during 'recvLine'
| LineTooLong
-- | Incomplete line during 'recvLine'
| LineTruncated
-- | Socks command rejected by server by given reply code
| SocksError CommandReply
-- | Socks authentication method was not accepted
| SocksAuthenticationMethodRejected
-- | Socks authentication method was not accepted
| SocksAuthenticationCredentialsRejected
-- | Username or password were too long
| SocksBadAuthenticationCredentials
-- | Socks server sent an invalid message or no message.
| SocksProtocolError
-- | Domain name was too long for SOCKS protocol
| SocksBadDomainName
deriving Show
-- | 'displayException' implemented for prettier messages
instance Exception ConnectionFailure where
displayException LineTruncated = "connection closed while reading line"
displayException LineTooLong = "line length exceeded maximum"
displayException (ConnectionFailure xs) =
"connection attempt failed due to: " ++
intercalate ", " (map displayException xs)
displayException (HostnameResolutionFailure h s) =
"hostname resolution failed (" ++ h ++ "): " ++ s
displayException SocksAuthenticationMethodRejected =
"SOCKS authentication method rejected"
displayException SocksAuthenticationCredentialsRejected =
"SOCKS authentication credentials rejected"
displayException SocksBadAuthenticationCredentials =
"SOCKS authentication credentials too long"
displayException SocksProtocolError =
"SOCKS server protocol error"
displayException SocksBadDomainName =
"SOCKS domain name length limit exceeded"
displayException (SocksError reply) =
"SOCKS command rejected: " ++
case reply of
Succeeded -> "succeeded"
GeneralFailure -> "general SOCKS server failure"
NotAllowed -> "connection not allowed by ruleset"
NetUnreachable -> "network unreachable"
HostUnreachable -> "host unreachable"
ConnectionRefused -> "connection refused"
TTLExpired -> "TTL expired"
CmdNotSupported -> "command not supported"
AddrNotSupported -> "address type not supported"
CommandReply n -> "unknown reply " ++ show n
data ConnectError = ConnectError SockAddr IOError
deriving Show
instance Exception ConnectError where
displayException (ConnectError addr e) = show addr ++ ": " ++ displayException e
-- | Default values for TLS that use no client certificates, use
-- system CA root, @\"HIGH\"@ cipher suite, and which validate hostnames.
defaultTlsParams :: TlsParams
defaultTlsParams = TlsParams
{ tpClientCertificate = Nothing
, tpClientPrivateKey = Nothing
, tpClientPrivateKeyPassword = Nothing
, tpServerCertificate = Nothing -- use system provided CAs
, tpCipherSuite = "HIGH"
, tpCipherSuiteTls13 = Nothing
, tpVerify = VerifyDefault
}
------------------------------------------------------------------------
-- Opening sockets
------------------------------------------------------------------------
-- | Open a socket using the given parameters either directly or
-- via a SOCKS server.
openSocket :: ConnectionParams -> IO Socket
openSocket params =
case cpSocks params of
Nothing -> openSocket' (cpHost params) (cpPort params) (cpBind params)
Just sp ->
bracketOnError
(openSocket' (spHost sp) (spPort sp) (cpBind params))
Socket.close
\sock ->
sock <$ socksConnect sock (cpHost params) (cpPort params) (spAuth sp)
netParse :: Show a => Socket -> Parser a -> IO a
netParse sock parser =
do -- receiving 1 byte at a time is not efficient, but these messages
-- are very short and we don't want to read any more from the socket
-- than is necessary
result <- Parser.parseWith
(SocketB.recv sock 1)
parser
B.empty
case result of
Parser.Done i x | B.null i -> pure x
_ -> throwIO SocksProtocolError
socksConnect :: Socket -> HostName -> PortNumber -> SocksAuthentication -> IO ()
socksConnect sock host port auth =
do case auth of
NoSocksAuthentication ->
do SocketB.sendAll sock $
buildClientHello ClientHello
{ cHelloMethods = [AuthNoAuthenticationRequired] }
hello <- netParse sock parseServerHello
unless (sHelloMethod hello == AuthNoAuthenticationRequired)
(throwIO SocksAuthenticationMethodRejected)
UsernamePasswordSocksAuthentication u p ->
do unless (B.length u < 256 && B.length p < 256)
(throwIO SocksBadAuthenticationCredentials)
SocketB.sendAll sock $
buildClientHello ClientHello
{ cHelloMethods = [AuthUsernamePassword] }
hello <- netParse sock parseServerHello
unless (sHelloMethod hello == AuthUsernamePassword)
(throwIO SocksAuthenticationMethodRejected)
SocketB.sendAll sock $
buildPlainAuthentication PlainAuthentication
{ plainUsername = u, plainPassword = p }
status <- netParse sock parsePlainAuthenticationReply
unless (0 == plainStatus status)
(throwIO SocksAuthenticationCredentialsRejected)
let dnBytes = B8.pack host
unless (B.length dnBytes < 256)
(throwIO SocksBadDomainName)
SocketB.sendAll sock $
buildRequest Request
{ reqCommand = Connect
, reqAddress = Address (DomainName dnBytes) port
}
response <- netParse sock parseResponse
unless (rspReply response == Succeeded )
(throwIO (SocksError (rspReply response)))
openSocket' ::
HostName {- ^ destination -} ->
PortNumber {- ^ destination port -} ->
Maybe HostName {- ^ source -} ->
IO Socket {- ^ connected socket -}
openSocket' h p mbBind =
do mbSrc <- traverse (resolve Nothing) mbBind
dst <- resolve (Just p) h
let pairs = interleaveAddressFamilies (matchBindAddrs mbSrc dst)
when (null pairs)
(throwIO (HostnameResolutionFailure h "No source/destination address family match"))
res <- concurrentAttempts connAttemptDelay Socket.close (uncurry connectToAddrInfo <$> pairs)
case res of
Left es -> throwIO (ConnectionFailure (mapMaybe fromException es))
Right s -> pure s
hints :: AddrInfo
hints = Socket.defaultHints
{ Socket.addrSocketType = Socket.Stream
, Socket.addrFlags = [Socket.AI_NUMERICSERV]
}
resolve :: Maybe PortNumber -> HostName -> IO [AddrInfo]
resolve mbPort host =
do res <- try (Socket.getAddrInfo (Just hints) (Just host) (show<$>mbPort))
case res of
Right ais -> pure ais
Left ioe
| isDoesNotExistError ioe ->
throwIO (HostnameResolutionFailure host (ioeGetErrorString ioe))
| otherwise -> throwIO ioe -- unexpected
-- | When no bind address is specified return the full list of destination
-- addresses with no bind address specified.
--
-- When bind addresses are specified return a subset of the destination list
-- matched up with the first address from the bind list that has the
-- correct address family.
matchBindAddrs :: Maybe [AddrInfo] -> [AddrInfo] -> [(Maybe SockAddr, AddrInfo)]
matchBindAddrs Nothing dst = [ (Nothing, x) | x <- dst ]
matchBindAddrs (Just src) dst =
[ (Just (Socket.addrAddress s), d)
| d <- dst
, let ss = [s | s <- src, Socket.addrFamily d == Socket.addrFamily s]
, s <- take 1 ss ]
connAttemptDelay :: Int
connAttemptDelay = 150 * 1000 -- 150ms
-- | Alternate list of addresses between IPv6 and other (IPv4) addresses.
interleaveAddressFamilies :: [(Maybe SockAddr, AddrInfo)] -> [(Maybe SockAddr, AddrInfo)]
interleaveAddressFamilies xs = interleave sixes others
where
(sixes, others) = partition is6 xs
is6 x = Socket.AF_INET6 == Socket.addrFamily (snd x)
interleave (x:xs) (y:ys) = x : y : interleave xs ys
interleave [] ys = ys
interleave xs [] = xs
-- | Create a socket and connect to the service identified
-- by the given 'AddrInfo' and return the connected socket.
connectToAddrInfo :: Maybe SockAddr -> AddrInfo -> IO Socket
connectToAddrInfo mbSrc info
= let addr = Socket.addrAddress info in
bracketOnError (socket' info) Socket.close \s ->
do traverse_ (bind' s) mbSrc
Socket.connect s addr
pure s
`catch` (throwIO . ConnectError addr)
-- | A version of 'Socket.bind' that doesn't bother binding on the wildcard
-- address. The effect of binding on a wildcard address in this library
-- is to pick an address family. Because of the matching done earlier this
-- is unnecessary for client connections and causes a local port to be
-- unnecessarily fixed early.
bind' :: Socket -> SockAddr -> IO ()
bind' _ (Socket.SockAddrInet _ 0) = pure ()
bind' _ (Socket.SockAddrInet6 _ _ (0,0,0,0) _) = pure ()
bind' s a = Socket.bind s a
-- | Open a 'Socket' using the parameters from an 'AddrInfo'
socket' :: AddrInfo -> IO Socket
socket' ai =
Socket.socket
(Socket.addrFamily ai)
(Socket.addrSocketType ai)
(Socket.addrProtocol ai)
------------------------------------------------------------------------
-- Generalization of Socket
------------------------------------------------------------------------
data NetworkHandle = SSL (Maybe X509) SSL | Socket Socket
openNetworkHandle ::
ConnectionParams {- ^ parameters -} ->
IO Socket {- ^ socket creation action -} ->
IO NetworkHandle {- ^ open network handle -}
openNetworkHandle params mkSocket =
case cpTls params of
Nothing -> Socket <$> mkSocket
Just tls ->
do (clientCert, ssl) <- startTls tls (cpHost params) mkSocket
pure (SSL clientCert ssl)
closeNetworkHandle :: NetworkHandle -> IO ()
closeNetworkHandle (Socket s) = Socket.close s
closeNetworkHandle (SSL _ s) =
do SSL.shutdown s SSL.Unidirectional
traverse_ Socket.close (SSL.sslSocket s)
networkSend :: NetworkHandle -> ByteString -> IO ()
networkSend (Socket s) = SocketB.sendAll s
networkSend (SSL _ s) = SSL.write s
networkRecv :: NetworkHandle -> Int -> IO ByteString
networkRecv (Socket s) = SocketB.recv s
networkRecv (SSL _ s) = SSL.read s
------------------------------------------------------------------------
-- Sockets with a receive buffer
------------------------------------------------------------------------
-- | A connection to a network service along with its read buffer
-- used for line-oriented protocols. The connection could be a plain
-- network connection, SOCKS connected, or TLS.
data Connection =
Connection
{-# UNPACK #-} !(MVar ByteString)
{-# UNPACK #-} !(MVar NetworkHandle)
-- | Open network connection to TCP service specified by
-- the given parameters.
--
-- The resulting connection MUST be closed with 'close' to avoid leaking
-- resources.
--
-- Throws 'IOError', 'SocksError', 'SSL.ProtocolError', 'ConnectionFailure'
connect ::
ConnectionParams {- ^ parameters -} ->
IO Connection {- ^ open connection -}
connect params =
do h <- openNetworkHandle params (openSocket params)
Connection <$> newMVar B.empty <*> newMVar h
-- | Create a new 'Connection' using an already connected socket.
-- This will attempt to start TLS if configured but will ignore
-- any SOCKS server settings as it is assumed that the socket
-- is already actively connected to the intended service.
--
-- Throws 'SSL.ProtocolError'
connectWithSocket ::
ConnectionParams {- ^ parameters -} ->
Socket {- ^ connected socket -} ->
IO Connection {- ^ open connection -}
connectWithSocket params sock =
do h <- openNetworkHandle params (pure sock)
Connection <$> newMVar B.empty <*> newMVar h
-- | Close network connection.
close ::
Connection {- ^ open connection -} ->
IO ()
close (Connection _ m) = withMVar m \h -> closeNetworkHandle h
-- | Receive the next chunk from the stream. This operation will first
-- return the buffer if it contains a non-empty chunk. Otherwise it will
-- request up to the requested number of bytes from the stream.
--
-- Throws: 'IOError', 'SSL.ConnectionAbruptlyTerminated', 'SSL.ProtocolError'
recv ::
Connection {- ^ open connection -} ->
Int {- ^ maximum underlying recv size -} ->
IO ByteString {- ^ next chunk from stream -}
recv (Connection bufVar hVar) n =
modifyMVar bufVar \bufChunk ->
if B.null bufChunk then
do h <- readMVar hVar
bs <- networkRecv h n
pure (B.empty, bs)
else
pure (B.empty, bufChunk)
-- | Receive a line from the network connection. Both
-- @"\\r\\n"@ and @"\\n"@ are recognized.
--
-- Returning 'Nothing' means that the peer has closed its half of
-- the connection.
--
-- Unterminated lines will raise a 'LineTruncated' exception. This
-- can happen if the peer transmits some data and closes its end
-- without transmitting a line terminator.
--
-- Throws: 'SSL.ConnectionAbruptlyTerminated', 'SSL.ProtocolError', 'ConnectionFailure', 'IOError'
recvLine ::
Connection {- ^ open connection -} ->
Int {- ^ maximum line length -} ->
IO (Maybe ByteString) {- ^ next line or end-of-stream -}
recvLine (Connection bufVar hVar) n =
modifyMVar bufVar \bs ->
do h <- readMVar hVar
go h (B.length bs) bs []
where
-- bsn: cached length of concatenation of (bs:bss)
-- bs : most recent chunk
-- bss: other chunks ordered from most to least recent
go h bsn bs bss =
case B8.elemIndex '\n' bs of
Just i -> pure (B.tail b, -- tail drops newline
Just (cleanEnd (B.concat (reverse (a:bss)))))
where
(a,b) = B.splitAt i bs
Nothing ->
do when (bsn >= n) (throwIO LineTooLong)
more <- networkRecv h n
if B.null more -- connection closed
then if bsn == 0 then pure (B.empty, Nothing)
else throwIO LineTruncated
else go h (bsn + B.length more) more (bs:bss)
-- | Push a 'ByteString' onto the buffer so that it will be the first
-- bytes to be read on the next receive operation. This could perhaps
-- be useful for putting the unused portion of a 'recv' back into the
-- buffer for future 'recvLine' or 'recv' operations.
putBuf ::
Connection {- ^ connection -} ->
ByteString {- ^ new head of buffer -} ->
IO ()
putBuf (Connection bufVar _) bs =
modifyMVar_ bufVar (\old -> pure $! B.append bs old)
-- | Remove the trailing @'\\r'@ if one is found.
cleanEnd :: ByteString -> ByteString
cleanEnd bs
| B.null bs || B8.last bs /= '\r' = bs
| otherwise = B.init bs
-- | Send bytes on the network connection. This ensures the whole chunk is
-- transmitted, which might take multiple underlying sends.
--
-- Throws: 'IOError', 'SSL.ProtocolError'
send ::
Connection {- ^ open connection -} ->
ByteString {- ^ chunk -} ->
IO ()
send (Connection _ hVar) bs =
do h <- readMVar hVar
networkSend h bs
upgradeTls ::
TlsParams {- ^ connection params -} ->
String {- ^ hostname -} ->
Connection ->
IO ()
upgradeTls tp hostname (Connection bufVar hVar) =
modifyMVar_ bufVar \buf ->
modifyMVar hVar \h ->
case h of
SSL{} -> pure (h, buf)
Socket s ->
do (cert, ssl) <- startTls tp hostname (pure s)
pure (SSL cert ssl, B.empty)
------------------------------------------------------------------------
-- | Initiate a TLS session on the given socket destined for
-- the given hostname. When successful an active TLS connection
-- is returned with certificate verification successful when
-- requested. This function requires that the TLSParams component
-- of 'ConnectionParams' is set.
startTls ::
TlsParams {- ^ connection params -} ->
String {- ^ hostname -} ->
IO Socket {- ^ socket creation action -} ->
IO (Maybe X509, SSL) {- ^ (client certificate, connected TLS) -}
startTls tp hostname mkSocket = SSL.withOpenSSL $
do ctx <- SSL.context
-- configure context
SSL.contextSetCiphers ctx (tpCipherSuite tp)
traverse_ (contextSetTls13Ciphers ctx) (tpCipherSuiteTls13 tp)
case tpVerify tp of
VerifyNone -> pure ()
VerifyDefault ->
do installVerification ctx hostname
SSL.contextSetVerificationMode ctx verifyPeer
VerifyHostname h ->
do installVerification ctx h
SSL.contextSetVerificationMode ctx verifyPeer
SSL.contextAddOption ctx SSL.SSL_OP_ALL
SSL.contextRemoveOption ctx SSL.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
-- configure certificates
setupCaCertificates ctx (tpServerCertificate tp)
clientCert <- traverse (setupCertificate ctx) (tpClientCertificate tp)
for_ (tpClientPrivateKey tp) \path ->
withDefaultPassword ctx (tpClientPrivateKeyPassword tp) $
SSL.contextSetPrivateKeyFile ctx path
-- add socket to context
-- creation of the socket is delayed until this point to avoid
-- leaking the file descriptor in the cases of exceptions above.
ssl <- SSL.connection ctx =<< mkSocket
-- configure hostname used for SNI
isip <- isIpAddress hostname
unless isip (SSL.setTlsextHostName ssl hostname)
SSL.connect ssl
pure (clientCert, ssl)
isIpAddress :: HostName -> IO Bool
isIpAddress host =
do res <- try (Socket.getAddrInfo
(Just Socket.defaultHints{Socket.addrFlags=[Socket.AI_NUMERICHOST]})
(Just host) Nothing)
case res :: Either IOError [AddrInfo] of
Right{} -> pure True
Left {} -> pure False
setupCaCertificates :: SSLContext -> Maybe FilePath -> IO ()
setupCaCertificates ctx mbPath =
case mbPath of
Nothing -> contextLoadSystemCerts ctx
Just path -> withDefaultPassword ctx Nothing (SSL.contextSetCAFile ctx path)
setupCertificate :: SSLContext -> FilePath -> IO X509
setupCertificate ctx path =
do x509 <- PEM.readX509 =<< readFile path -- EX
SSL.contextSetCertificate ctx x509
pure x509
verifyPeer :: SSL.VerificationMode
verifyPeer = SSL.VerifyPeer
{ SSL.vpFailIfNoPeerCert = True
, SSL.vpClientOnce = True
, SSL.vpCallback = Nothing
}
-- | Get peer certificate if one exists.
getPeerCertificate :: Connection -> IO (Maybe X509.X509)
getPeerCertificate (Connection _ hVar) =
withMVar hVar \case
Socket{} -> pure Nothing
SSL _ ssl -> SSL.getPeerCertificate ssl
-- | Get peer certificate if one exists.
getClientCertificate :: Connection -> IO (Maybe X509.X509)
getClientCertificate (Connection _ hVar) =
do h <- readMVar hVar
pure case h of
Socket{} -> Nothing
SSL c _ -> c
getPeerCertFingerprintSha1 :: Connection -> IO (Maybe ByteString)
getPeerCertFingerprintSha1 = getPeerCertFingerprint "sha1"
getPeerCertFingerprintSha256 :: Connection -> IO (Maybe ByteString)
getPeerCertFingerprintSha256 = getPeerCertFingerprint "sha256"
getPeerCertFingerprintSha512 :: Connection -> IO (Maybe ByteString)
getPeerCertFingerprintSha512 = getPeerCertFingerprint "sha512"
getPeerCertFingerprint :: String -> Connection -> IO (Maybe ByteString)
getPeerCertFingerprint name h =
do mb <- getPeerCertificate h
case mb of
Nothing -> pure Nothing
Just x509 ->
do der <- X509.writeDerX509 x509
mbdigest <- Digest.getDigestByName name
pure $! case mbdigest of
Nothing -> Nothing
Just digest -> Just $! Digest.digestLBS digest der
getPeerPubkeyFingerprintSha1 :: Connection -> IO (Maybe ByteString)
getPeerPubkeyFingerprintSha1 = getPeerPubkeyFingerprint "sha1"
getPeerPubkeyFingerprintSha256 :: Connection -> IO (Maybe ByteString)
getPeerPubkeyFingerprintSha256 = getPeerPubkeyFingerprint "sha256"
getPeerPubkeyFingerprintSha512 :: Connection -> IO (Maybe ByteString)
getPeerPubkeyFingerprintSha512 = getPeerPubkeyFingerprint "sha512"
getPeerPubkeyFingerprint :: String -> Connection -> IO (Maybe ByteString)
getPeerPubkeyFingerprint name h =
do mb <- getPeerCertificate h
case mb of
Nothing -> pure Nothing
Just x509 ->
do der <- getPubKeyDer x509
mbdigest <- Digest.getDigestByName name
pure $! case mbdigest of
Nothing -> Nothing
Just digest -> Just $! Digest.digestBS digest der