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
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Concurrent
import qualified Data.ByteString.Base16 as BS16
import qualified Data.ByteString.Char8 as C8
import Data.IORef
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import Data.X509.CertificateStore
import Network.Run.TCP
import Network.Socket
import Network.TLS hiding (is0RTTPossible)
import Network.TLS.Internal (makeCipherShowPretty)
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.X509
import Client
import Common
import Imports
data Options = Options
{ optDebugLog :: Bool
, optShow :: Bool
, optKeyLogFile :: Maybe FilePath
, optGroups :: [Group]
, optValidate :: Bool
, optVerNego :: Bool
, optResumption :: Bool
, opt0RTT :: Bool
, optRetry :: Bool
, optVersions :: [Version]
, optALPN :: String
, optCertFile :: Maybe FilePath
, optKeyFile :: Maybe FilePath
}
deriving (Show)
defaultOptions :: Options
defaultOptions =
Options
{ optDebugLog = False
, optShow = False
, optKeyLogFile = Nothing
, optGroups = supportedGroups defaultSupported
, optValidate = False
, optVerNego = False
, optResumption = False
, opt0RTT = False
, optRetry = False
, optVersions = supportedVersions defaultSupported
, optALPN = "http/1.1"
, optCertFile = Nothing
, optKeyFile = Nothing
}
usage :: String
usage = "Usage: quic-client [OPTION] addr port [path]"
options :: [OptDescr (Options -> Options)]
options =
[ Option
['d']
["debug"]
(NoArg (\o -> o{optDebugLog = True}))
"print debug info"
, Option
['v']
["show-content"]
(NoArg (\o -> o{optShow = True}))
"print downloaded content"
, Option
['l']
["key-log-file"]
(ReqArg (\file o -> o{optKeyLogFile = Just file}) "<file>")
"a file to store negotiated secrets"
, Option
['g']
["groups"]
(ReqArg (\gs o -> o{optGroups = readGroups gs}) "<groups>")
"specify groups"
, Option
['e']
["validate"]
(NoArg (\o -> o{optValidate = True}))
"validate server's certificate"
, Option
['R']
["resumption"]
(NoArg (\o -> o{optResumption = True}))
"try session resumption"
, Option
['Z']
["0rtt"]
(NoArg (\o -> o{opt0RTT = True}))
"try sending early data"
, Option
['S']
["hello-retry"]
(NoArg (\o -> o{optRetry = True}))
"try client hello retry"
, Option
['2']
["tls12"]
(NoArg (\o -> o{optVersions = [TLS12]}))
"use TLS 1.2"
, Option
['3']
["tls13"]
(NoArg (\o -> o{optVersions = [TLS13]}))
"use TLS 1.3"
, Option
['a']
["alpn"]
(ReqArg (\a o -> o{optALPN = a}) "<alpn>")
"set ALPN"
, Option
['c']
["cert"]
(ReqArg (\fl o -> o{optCertFile = Just fl}) "<file>")
"certificate file"
, Option
['k']
["key"]
(ReqArg (\fl o -> o{optKeyFile = Just fl}) "<file>")
"key file"
]
showUsageAndExit :: String -> IO a
showUsageAndExit msg = do
putStrLn msg
putStrLn $ usageInfo usage options
putStrLn $ " <groups> = " ++ intercalate "," (map fst namedGroups)
exitFailure
clientOpts :: [String] -> IO (Options, [String])
clientOpts argv =
case getOpt Permute options argv of
(o, n, []) -> return (foldl (flip id) defaultOptions o, n)
(_, _, errs) -> showUsageAndExit $ concat errs
main :: IO ()
main = do
args <- getArgs
(opts@Options{..}, ips) <- clientOpts args
(host, port, paths) <- case ips of
[] -> showUsageAndExit usage
_ : [] -> showUsageAndExit usage
h : p : [] -> return (h, p, ["/"])
h : p : ps -> return (h, p, C8.pack <$> NE.fromList ps)
when (null optGroups) $ do
putStrLn "Error: unsupported groups"
exitFailure
let onCertReq = \_ -> case optCertFile of
Just certFile -> case optKeyFile of
Just keyFile -> do
Right (!cc, !priv) <- credentialLoadX509 certFile keyFile
return $ Just (cc, priv)
_ -> return Nothing
_ -> return Nothing
ref <- newIORef []
let debug
| optDebugLog = putStrLn
| otherwise = \_ -> return ()
showContent
| optShow = C8.putStr
| otherwise = \_ -> return ()
aux =
Aux
{ auxAuthority = host
, auxPort = port
, auxDebugPrint = debug
, auxShow = showContent
, auxReadResumptionData = readIORef ref
}
mstore <-
if optValidate then Just <$> getSystemCertificateStore else return Nothing
let cparams = getClientParams opts host port (smIORef ref) mstore onCertReq
client
| optALPN == "dot" = clientDNS
| otherwise = clientHTTP11
makeCipherShowPretty
runClient opts client cparams aux paths
runClient
:: Options -> Cli -> ClientParams -> Aux -> NonEmpty ByteString -> IO ()
runClient opts@Options{..} client cparams aux@Aux{..} paths = do
auxDebugPrint "------------------------"
(info1, msd) <- runTLS opts cparams aux $ \ctx -> do
i1 <- getInfo ctx
when optDebugLog $ printHandshakeInfo i1
client aux paths ctx
msd' <- auxReadResumptionData
return (i1, msd')
if
| optResumption ->
if isResumptionPossible msd
then do
let cparams2 = modifyClientParams cparams msd False
info2 <- runClient2 opts client cparams2 aux paths
if infoVersion info1 == TLS12
then do
if infoTLS12Resumption info2
then do
putStrLn "Result: (R) TLS resumption ... OK"
exitSuccess
else do
putStrLn "Result: (R) TLS resumption ... NG"
exitFailure
else do
if infoTLS13HandshakeMode info2 == Just PreSharedKey
then do
putStrLn "Result: (R) TLS resumption ... OK"
exitSuccess
else do
putStrLn "Result: (R) TLS resumption ... NG"
exitFailure
else do
putStrLn "Result: (R) TLS resumption ... NG"
exitFailure
| opt0RTT ->
if is0RTTPossible info1 msd
then do
let cparams2 = modifyClientParams cparams msd True
info2 <- runClient2 opts client cparams2 aux paths
if infoTLS13HandshakeMode info2 == Just RTT0
then do
putStrLn "Result: (Z) 0-RTT ... OK"
exitSuccess
else do
putStrLn "Result: (Z) 0-RTT ... NG"
exitFailure
else do
putStrLn "Result: (Z) 0-RTT ... NG"
exitFailure
| optRetry ->
if infoTLS13HandshakeMode info1 == Just HelloRetryRequest
then do
putStrLn "Result: (S) retry ... OK"
exitSuccess
else do
putStrLn "Result: (S) retry ... NG"
exitFailure
| otherwise -> do
putStrLn "Result: (H) handshake ... OK"
when (optALPN == "http/1.1") $
putStrLn "Result: (1) HTTP/1.1 transaction ... OK"
exitSuccess
runClient2
:: Options
-> Cli
-> ClientParams
-> Aux
-> NonEmpty ByteString
-> IO Information
runClient2 opts@Options{..} client cparams aux@Aux{..} paths = do
threadDelay 100000
auxDebugPrint "<<<< next connection >>>>"
auxDebugPrint "------------------------"
runTLS opts cparams aux $ \ctx -> do
if opt0RTT
then do
void $ client aux paths ctx
i <- getInfo ctx
when optDebugLog $ printHandshakeInfo i
return i
else do
i <- getInfo ctx
when optDebugLog $ printHandshakeInfo i
void $ client aux paths ctx
return i
runTLS
:: Options
-> ClientParams
-> Aux
-> (Context -> IO a)
-> IO a
runTLS Options{..} cparams Aux{..} action =
runTCPClient auxAuthority auxPort $ \sock -> do
ctx <- contextNew sock cparams
when optDebugLog $
contextHookSetLogging
ctx
defaultLogging
{ loggingPacketSent = putStrLn . (">> " ++)
, loggingPacketRecv = putStrLn . ("<< " ++)
}
handshake ctx
r <- action ctx
bye ctx
return r
modifyClientParams
:: ClientParams -> [(SessionID, SessionData)] -> Bool -> ClientParams
modifyClientParams cparams ts early =
cparams
{ clientWantSessionResumeList = ts
, clientUseEarlyData = early
}
getClientParams
:: Options
-> HostName
-> ServiceName
-> SessionManager
-> Maybe CertificateStore
-> OnCertificateRequest
-> ClientParams
getClientParams Options{..} serverName port sm mstore onCertReq =
(defaultParamsClient serverName (C8.pack port))
{ clientSupported = supported
, clientUseServerNameIndication = True
, clientShared = shared
, clientHooks = hooks
, clientDebug = debug
}
where
groups
| optRetry = FFDHE8192 : optGroups
| otherwise = optGroups
shared =
defaultShared
{ sharedSessionManager = sm
, sharedCAStore = case mstore of
Just store -> store
Nothing -> mempty
, sharedValidationCache = validateCache
}
supported =
defaultSupported
{ supportedVersions = optVersions
, supportedGroups = groups
}
hooks =
defaultClientHooks
{ onSuggestALPN = return $ Just [C8.pack optALPN]
, onCertificateRequest = onCertReq
}
validateCache
| isJust mstore = sharedValidationCache defaultShared
| otherwise =
ValidationCache
(\_ _ _ -> return ValidationCachePass)
(\_ _ _ -> return ())
debug =
defaultDebugParams
{ debugKeyLogger = getLogger optKeyLogFile
}
smIORef :: IORef [(SessionID, SessionData)] -> SessionManager
smIORef ref =
noSessionManager
{ sessionEstablish = \sid sdata ->
modifyIORef' ref (\xs -> (sid, sdata) : xs)
>> printTicket sid sdata
>> return Nothing
}
printTicket :: SessionID -> SessionData -> IO ()
printTicket sid sdata = do
C8.putStr $ "Ticket: " <> C8.take 16 (BS16.encode sid) <> "..., "
putStrLn $ "0-RTT: " <> if sessionMaxEarlyDataSize sdata > 0 then "OK" else "NG"
isResumptionPossible :: [(SessionID, SessionData)] -> Bool
isResumptionPossible = not . null
is0RTTPossible :: Information -> [(SessionID, SessionData)] -> Bool
is0RTTPossible _ [] = False
is0RTTPossible info xs =
infoVersion info == TLS13
&& any (\(_, sd) -> sessionMaxEarlyDataSize sd > 0) xs
|