-- | libp2p TLS 1.3 secure channel with mutual peer authentication.
module LibP2P.Security.TLS (
  TLSRole (..),
  TLSHandshakeResult (..),
  performTLSHandshake,
  performTLSHandshakeWithMuxers,
  tlsProtocolId,
  yamuxProtocolId,
  libp2pALPN,
) where

import Control.Exception (IOException, SomeException, catch)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Lazy qualified as LBS
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.List (find)
import Data.Text.Encoding qualified as TE
import Data.X509 (CertificateChain)
import Data.X509.Validation (FailedReason (..), SignatureFailure (..))
import LibP2P.Crypto.Key (KeyPair)
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.MultistreamSelect.Negotiation (ProtocolId, StreamIO (..))
import LibP2P.Security.TLS.Certificate (
  newIdentityCredential,
  verifyIdentityCertificate,
 )
import Network.TLS (
  Backend (..),
  CertificateRejectReason (..),
  CertificateUsage (..),
  ClientHooks (..),
  ClientParams (..),
  Context,
  Credential,
  Credentials (..),
  ServerHooks (..),
  ServerParams (..),
  Shared (..),
  Supported (..),
  Version (TLS13),
  bye,
  contextNew,
  defaultParamsClient,
  defaultParamsServer,
  getNegotiatedProtocol,
  handshake,
  recvData,
  sendData,
 )
import Network.TLS.Extra.Cipher (ciphersuite_default)

-- | TLS endpoint role on a libp2p byte stream.
data TLSRole = TLSClient | TLSServer
  deriving (Int -> TLSRole -> ShowS
[TLSRole] -> ShowS
TLSRole -> String
(Int -> TLSRole -> ShowS)
-> (TLSRole -> String) -> ([TLSRole] -> ShowS) -> Show TLSRole
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TLSRole -> ShowS
showsPrec :: Int -> TLSRole -> ShowS
$cshow :: TLSRole -> String
show :: TLSRole -> String
$cshowList :: [TLSRole] -> ShowS
showList :: [TLSRole] -> ShowS
Show, TLSRole -> TLSRole -> Bool
(TLSRole -> TLSRole -> Bool)
-> (TLSRole -> TLSRole -> Bool) -> Eq TLSRole
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: TLSRole -> TLSRole -> Bool
== :: TLSRole -> TLSRole -> Bool
$c/= :: TLSRole -> TLSRole -> Bool
/= :: TLSRole -> TLSRole -> Bool
Eq)

-- | Authenticated TLS channel and the ALPN result selected by the peer.
data TLSHandshakeResult = TLSHandshakeResult
  { TLSHandshakeResult -> PeerId
tlsRemotePeerId :: !PeerId
  , TLSHandshakeResult -> Maybe ByteString
tlsNegotiatedALPN :: !(Maybe ByteString)
  , TLSHandshakeResult -> StreamIO
tlsStream :: !StreamIO
  , TLSHandshakeResult -> IO ()
tlsClose :: !(IO ())
  }

-- | multistream-select protocol ID for the libp2p TLS handshake.
tlsProtocolId :: ProtocolId
tlsProtocolId :: ProtocolId
tlsProtocolId = ProtocolId
"/tls/1.0.0"

-- | Yamux protocol ID, also used as its inlined TLS ALPN value.
yamuxProtocolId :: ProtocolId
yamuxProtocolId :: ProtocolId
yamuxProtocolId = ProtocolId
"/yamux/1.0.0"

libp2pALPN :: ByteString
libp2pALPN :: ByteString
libp2pALPN = ByteString
"libp2p"

-- | Perform a TLS 1.3 handshake with Yamux offered for inlined negotiation.
performTLSHandshake :: KeyPair -> TLSRole -> StreamIO -> IO TLSHandshakeResult
performTLSHandshake :: KeyPair -> TLSRole -> StreamIO -> IO TLSHandshakeResult
performTLSHandshake = [ProtocolId]
-> KeyPair -> TLSRole -> StreamIO -> IO TLSHandshakeResult
performTLSHandshakeWithMuxers [ProtocolId
yamuxProtocolId]

{- | Perform a TLS 1.3 mutual-authentication handshake, advertising the given
muxers through ALPN and retaining @libp2p@ as the required fallback.
-}
performTLSHandshakeWithMuxers ::
  [ProtocolId] -> KeyPair -> TLSRole -> StreamIO -> IO TLSHandshakeResult
performTLSHandshakeWithMuxers :: [ProtocolId]
-> KeyPair -> TLSRole -> StreamIO -> IO TLSHandshakeResult
performTLSHandshakeWithMuxers [ProtocolId]
muxers KeyPair
identity TLSRole
role StreamIO
rawStream = do
  credential <- KeyPair -> IO Credential
newIdentityCredential KeyPair
identity
  remotePeerRef <- newIORef Nothing
  let alpnProtocols = (ProtocolId -> ByteString) -> [ProtocolId] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ProtocolId -> ByteString
TE.encodeUtf8 [ProtocolId]
muxers [ByteString] -> [ByteString] -> [ByteString]
forall a. Semigroup a => a -> a -> a
<> [ByteString
libp2pALPN]
  context <- case role of
    TLSRole
TLSClient ->
      Backend -> ClientParams -> IO Context
forall (m :: * -> *) backend params.
(MonadIO m, HasBackend backend, TLSParams params) =>
backend -> params -> m Context
contextNew (StreamIO -> Backend
streamBackend StreamIO
rawStream) (ClientParams -> IO Context) -> ClientParams -> IO Context
forall a b. (a -> b) -> a -> b
$
        [ByteString] -> Credential -> IORef (Maybe PeerId) -> ClientParams
clientParams [ByteString]
alpnProtocols Credential
credential IORef (Maybe PeerId)
remotePeerRef
    TLSRole
TLSServer ->
      Backend -> ServerParams -> IO Context
forall (m :: * -> *) backend params.
(MonadIO m, HasBackend backend, TLSParams params) =>
backend -> params -> m Context
contextNew (StreamIO -> Backend
streamBackend StreamIO
rawStream) (ServerParams -> IO Context) -> ServerParams -> IO Context
forall a b. (a -> b) -> a -> b
$
        [ByteString] -> Credential -> IORef (Maybe PeerId) -> ServerParams
serverParams [ByteString]
alpnProtocols Credential
credential IORef (Maybe PeerId)
remotePeerRef
  handshake context
  remotePeer <-
    readIORef remotePeerRef
      >>= maybe
        (fail "TLS handshake completed without an authenticated peer")
        pure
  negotiated <- getNegotiatedProtocol context
  secureStream <- contextToStreamIO context
  pure
    TLSHandshakeResult
      { tlsRemotePeerId = remotePeer
      , tlsNegotiatedALPN = negotiated
      , tlsStream = secureStream
      , tlsClose = closeContext context
      }

streamBackend :: StreamIO -> Backend
streamBackend :: StreamIO -> Backend
streamBackend StreamIO
stream =
  Backend
    { backendFlush :: IO ()
backendFlush = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    , backendClose :: IO ()
backendClose = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    , backendSend :: ByteString -> IO ()
backendSend = StreamIO -> ByteString -> IO ()
streamWrite StreamIO
stream
    , backendRecv :: Int -> IO ByteString
backendRecv = StreamIO -> Int -> IO ByteString
recvExact StreamIO
stream
    }

-- | Return exactly @n@ bytes. 'streamReadChunk' may deliver a short TCP
-- segment, but 'Network.TLS.backendRecv' treats a short read as a truncated
-- record. A short result is returned only at EOF.
recvExact :: StreamIO -> Int -> IO ByteString
recvExact :: StreamIO -> Int -> IO ByteString
recvExact StreamIO
stream Int
requested
  | Int
requested Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0 = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty
  | Bool
otherwise = [ByteString] -> Int -> IO ByteString
collect [] Int
requested
 where
  collect :: [ByteString] -> Int -> IO ByteString
collect [ByteString]
chunks Int
remaining = do
    got <- Int -> IO ByteString
nextChunk Int
remaining
    if BS.null got
      then pure (BS.concat (reverse chunks))
      else
        let unread = Int
remaining Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
BS.length ByteString
got
         in if unread <= 0
              then pure (BS.concat (reverse (got : chunks)))
              else collect (got : chunks) unread
  nextChunk :: Int -> IO ByteString
nextChunk Int
remaining =
    StreamIO -> Int -> IO ByteString
streamReadChunk StreamIO
stream Int
remaining
      IO ByteString -> (IOException -> IO ByteString) -> IO ByteString
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(IOException
_ :: IOException) -> ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
BS.empty

clientParams ::
  [ByteString] -> Credential -> IORef (Maybe PeerId) -> ClientParams
clientParams :: [ByteString] -> Credential -> IORef (Maybe PeerId) -> ClientParams
clientParams [ByteString]
alpnProtocols Credential
credential IORef (Maybe PeerId)
remotePeerRef =
  ClientParams
base
    { clientUseServerNameIndication = False
    , clientShared =
        (clientShared base)
          { sharedCredentials = Credentials [credential]
          }
    , clientHooks =
        (clientHooks base)
          { onCertificateRequest = const (pure (Just credential))
          , onServerCertificate = authenticateServer remotePeerRef
          , onSuggestALPN = pure (Just alpnProtocols)
          }
    , clientSupported = tls13Only (clientSupported base)
    }
 where
  base :: ClientParams
base = String -> ByteString -> ClientParams
defaultParamsClient String
"" ByteString
BS.empty

serverParams ::
  [ByteString] -> Credential -> IORef (Maybe PeerId) -> ServerParams
serverParams :: [ByteString] -> Credential -> IORef (Maybe PeerId) -> ServerParams
serverParams [ByteString]
alpnProtocols Credential
credential IORef (Maybe PeerId)
remotePeerRef =
  ServerParams
base
    { serverWantClientCert = True
    , serverShared =
        (serverShared base)
          { sharedCredentials = Credentials [credential]
          }
    , serverHooks =
        (serverHooks base)
          { onClientCertificate = authenticateClient remotePeerRef
          , onALPNClientSuggest = Just (selectALPN alpnProtocols)
          }
    , serverSupported = tls13Only (serverSupported base)
    }
 where
  base :: ServerParams
base = ServerParams
defaultParamsServer

tls13Only :: Supported -> Supported
tls13Only :: Supported -> Supported
tls13Only Supported
supported =
  Supported
supported
    { supportedVersions = [TLS13]
    , supportedCiphers = ciphersuite_default
    }

authenticateServer ::
  IORef (Maybe PeerId) ->
  certificateStore ->
  validationCache ->
  serviceId ->
  CertificateChain ->
  IO [FailedReason]
authenticateServer :: forall certificateStore validationCache serviceId.
IORef (Maybe PeerId)
-> certificateStore
-> validationCache
-> serviceId
-> CertificateChain
-> IO [FailedReason]
authenticateServer IORef (Maybe PeerId)
remotePeerRef certificateStore
_ validationCache
_ serviceId
_ CertificateChain
chain = do
  result <- IORef (Maybe PeerId) -> CertificateChain -> IO (Either String ())
authenticatePeer IORef (Maybe PeerId)
remotePeerRef CertificateChain
chain
  pure $ case result of
    Right () -> []
    Left String
_ -> [SignatureFailure -> FailedReason
InvalidSignature SignatureFailure
SignatureInvalid]

authenticateClient ::
  IORef (Maybe PeerId) -> CertificateChain -> IO CertificateUsage
authenticateClient :: IORef (Maybe PeerId) -> CertificateChain -> IO CertificateUsage
authenticateClient IORef (Maybe PeerId)
remotePeerRef CertificateChain
chain = do
  result <- IORef (Maybe PeerId) -> CertificateChain -> IO (Either String ())
authenticatePeer IORef (Maybe PeerId)
remotePeerRef CertificateChain
chain
  pure $ case result of
    Right () -> CertificateUsage
CertificateUsageAccept
    Left String
_ ->
      CertificateRejectReason -> CertificateUsage
CertificateUsageReject (CertificateRejectReason -> CertificateUsage)
-> CertificateRejectReason -> CertificateUsage
forall a b. (a -> b) -> a -> b
$
        String -> CertificateRejectReason
CertificateRejectOther String
"libp2p identity certificate rejected"

authenticatePeer ::
  IORef (Maybe PeerId) -> CertificateChain -> IO (Either String ())
authenticatePeer :: IORef (Maybe PeerId) -> CertificateChain -> IO (Either String ())
authenticatePeer IORef (Maybe PeerId)
remotePeerRef CertificateChain
chain = do
  result <- CertificateChain -> IO (Either String PeerId)
verifyIdentityCertificate CertificateChain
chain
  case result of
    Left String
err -> Either String () -> IO (Either String ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (String -> Either String ()
forall a b. a -> Either a b
Left String
err)
    Right PeerId
peerId -> IORef (Maybe PeerId) -> Maybe PeerId -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe PeerId)
remotePeerRef (PeerId -> Maybe PeerId
forall a. a -> Maybe a
Just PeerId
peerId) IO () -> IO (Either String ()) -> IO (Either String ())
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either String () -> IO (Either String ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either String ()
forall a b. b -> Either a b
Right ())

selectALPN :: [ByteString] -> [ByteString] -> IO ByteString
selectALPN :: [ByteString] -> [ByteString] -> IO ByteString
selectALPN [ByteString]
supported [ByteString]
protocols =
  ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> IO ByteString) -> ByteString -> IO ByteString
forall a b. (a -> b) -> a -> b
$
    ByteString
-> (ByteString -> ByteString) -> Maybe ByteString -> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ByteString
BS.empty ByteString -> ByteString
forall a. a -> a
id ((ByteString -> Bool) -> [ByteString] -> Maybe ByteString
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (ByteString -> [ByteString] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ByteString]
supported) [ByteString]
protocols)

contextToStreamIO :: Context -> IO StreamIO
contextToStreamIO :: Context -> IO StreamIO
contextToStreamIO Context
context = do
  readBuffer <- ByteString -> IO (IORef ByteString)
forall a. a -> IO (IORef a)
newIORef ByteString
BS.empty
  pure
    StreamIO
      { streamWrite = sendData context . LBS.fromStrict
      , streamReadByte = BS.head <$> readTLSChunk context readBuffer 1
      , streamReadChunk = readTLSChunk context readBuffer
      , streamClose = closeContext context
      }

readTLSChunk :: Context -> IORef ByteString -> Int -> IO ByteString
readTLSChunk :: Context -> IORef ByteString -> Int -> IO ByteString
readTLSChunk Context
context IORef ByteString
readBuffer Int
requested = do
  buffered <- IORef ByteString -> IO ByteString
forall a. IORef a -> IO a
readIORef IORef ByteString
readBuffer
  available <-
    if BS.null buffered
      then recvData context >>= requireData
      else pure buffered
  let (front, rest) = BS.splitAt requested available
  writeIORef readBuffer rest
  pure front
 where
  requireData :: ByteString -> m ByteString
requireData ByteString
bytes
    | ByteString -> Bool
BS.null ByteString
bytes = String -> m ByteString
forall a. String -> m a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"TLS connection closed"
    | Bool
otherwise = ByteString -> m ByteString
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
bytes

closeContext :: Context -> IO ()
closeContext :: Context -> IO ()
closeContext Context
context = Context -> IO ()
forall (m :: * -> *). MonadIO m => Context -> m ()
bye Context
context IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()