{-# LANGUAGE CPP #-}-- | Tests of the daemon on Windows' named pipe ("Nix.Daemon.Pipe") with-- nova-nix's own client ("Nix.Daemon.Client"): the client served a-- handshake, a query and an add over the pipe; named by its account, and-- admitted and trusted as @allowed-users@ and @trusted-users@ name its-- SID, its name and its groups; a client refused for the build users'-- group by its account whatever groups its token shows, and one the-- daemon refuses closed without a byte read from it; a second daemon on-- the pipe refused; who may open, write and add to the pipe, as a process-- of the daemon's own account that is not elevated is held to it; the-- client's check of who made the pipe, which accepts a daemon of its own-- account and refuses a pipe another user owns or a process at Low-- integrity made, with the owners Windows lets a token give a pipe; and a-- quiet client's connection ended as the daemon stops. Elsewhere the-- groups are skipped: there the daemon listens on a Unix socket, which-- "Test.Daemon" tests, and which accounts a client trusts to own a pipe-- is tested there too, as it needs no pipe.---- The daemon's pipe is also used by accounts other than the daemon's-- ('daemonPipeAccounts'), which CI's Windows build runs as an-- administrator, as it makes the local accounts those checks need.module Test.DaemonPipe ( testDaemonPipe, testDaemonPipeIO, daemonPipeAccountsFlag, daemonPipeAccounts, )where#if defined(mingw32_HOST_OS)import Control.Exception (bracket, finally)import Control.Monad (void, when)import Data.Bits ((.&.), (.|.))import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BS8import Data.IORef (atomicModifyIORef', newIORef, readIORef, writeIORef)import Data.Maybe (fromMaybe)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Word (Word32)import DaemonLink (DaemonLink (..), connectDaemon, daemonAddress)import DirDacl (entryOwner, processUserSid)import Foreign.C.String (CString, CWString, peekCString, peekCWString, withCWString)import Foreign.C.Types (CInt (..), CULong (..))import Foreign.Marshal.Alloc (alloca)import Foreign.Marshal.Utils (maybePeek)import Foreign.Ptr (Ptr, nullPtr)import Foreign.Storable (peek)import Nix.Config (NixConfig (..))import Nix.Daemon.Auth (AccountDatabase (..), AccountKind (..))import qualified Nix.Daemon.Client as Clientimport qualified Nix.Daemon.Listen as Listenimport Nix.Daemon.Ops (AddToStoreRequest (..), Repair (..))import qualified Nix.Daemon.Pipe as Pipeimport qualified Nix.Daemon.Protocol as Protoimport Nix.Hash (makeTextPath, sha256Digest)import Nix.Store.Access (sidFromText, sidText)import Nix.Store.Path (defaultStoreDir)import GHC.Clock (getMonotonicTime)import System.Exit (ExitCode (..), exitWith)import System.IO (BufferMode (..), hSetBuffering, stdout)import qualified System.Process as Procimport System.Timeout (timeout)import Test.Daemon (fooPath, helloOver, socketTestMicros, withSocketDaemon)import Test.Harness (TestResult (..), andThen, assertEqual, runTest, runTestM)import Test.WindowsSandbox (SlotAccount (..), accountPrefix, makeAccount, removeAccount, withAccount, withBuildersGroup, withLogon)#elseimport System.Exit (die)#endif-- | The pipe's rules that need no pipe: which paths name one, and what-- the pipe grants Users.testDaemonPipe :: IO [Bool]-- | The daemon on its pipe, with nova-nix's client.testDaemonPipeIO :: IO [Bool]-- | The flag CI's step runs the suite with, as an administrator, to run-- 'daemonPipeAccounts'.daemonPipeAccountsFlag :: StringdaemonPipeAccountsFlag = "--daemon-pipe-accounts"-- | Make two local accounts, one a member of the build users' group-- @nixbld@ and one not, and check what each is to the daemon of the-- administrator who runs this: the one outside the group is admitted-- and not trusted, may not add an instance to the pipe or open it to-- rewrite its DACL, and the one in the group is refused without a byte-- read from it. The accounts and the group are removed however the-- checks end, and the exit status is 0 only when every check passed.daemonPipeAccounts :: [String] -> IO ()#if defined(mingw32_HOST_OS)testDaemonPipe = do putStrLn "daemon/pipe" sequence [ runTest "a pipe's path is \\\\.\\pipe\\ and a name with no separator that is no step, 256 UTF-16 units at most" $ let named = either (const Nothing) (Just . Pipe.pipePathText) . Pipe.pipePath longest = "\\\\.\\pipe\\" <> BS8.replicate (maxPipePathUnits - BS.length "\\\\.\\pipe\\") 'x' in assertEqual "plain" (Just "\\\\.\\pipe\\nova-nix-daemon") (named "\\\\.\\pipe\\nova-nix-daemon") `andThen` assertEqual "upper case" (Just "\\\\.\\PIPE\\x") (named "\\\\.\\PIPE\\x") `andThen` assertEqual "the longest" (Just (TE.decodeUtf8Lenient longest)) (named longest) `andThen` assertEqual "one too long" Nothing (named (longest <> "x")) `andThen` assertEqual "a socket's path" Nothing (named "/nix/var/nix/daemon-socket/socket") `andThen` assertEqual "no name" Nothing (named "\\\\.\\pipe\\") `andThen` assertEqual "a backslash in the name" Nothing (named "\\\\.\\pipe\\a\\b") `andThen` assertEqual "a slash in the name" Nothing (named "\\\\.\\pipe\\a/b") `andThen` assertEqual "a step up" Nothing (named "\\\\.\\pipe\\..") `andThen` assertEqual "another machine's" Nothing (named "\\\\host\\pipe\\x") `andThen` assertEqual "not UTF-8" Nothing (named "\\\\.\\pipe\\\xff"), runTest "Users may read the pipe and write its data, and may not create an instance of it" $ assertEqual "read and write data" (fileReadData + fileWriteData) (Pipe.clientPipeAccess .&. (fileReadData + fileWriteData)) `andThen` assertEqual "create an instance" 0 (Pipe.clientPipeAccess .&. fileCreatePipeInstance), runTest "the daemon's own account may create the pipe's next instance, and has not the rights to rewrite its DACL, take its owner or delete it" $ assertEqual "create an instance" fileCreatePipeInstance (Pipe.daemonPipeAccess .&. fileCreatePipeInstance) `andThen` assertEqual "change the DACL, take the owner, delete" 0 (Pipe.daemonPipeAccess .&. (writeDac .|. writeOwner .|. delete)), runTest "the pipe's descriptor names its owner, and has an entry for the daemon's account only where the account owns the pipe and not Administrators" $ case (sidFromText administratorsSid, sidFromText otherUser) of (Just administrators, Just account) -> assertEqual "an account owns the pipe it makes" (Pipe.OwnedByAccount account) (Pipe.pipeOwnerOf account) `andThen` assertEqual "Administrators owns what an elevated token makes" Pipe.OwnedByAdministrators (Pipe.pipeOwnerOf administrators) `andThen` assertEqual "Administrators" "O:S-1-5-32-544D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x12008b;;;BU)" (Pipe.pipeSddl Pipe.OwnedByAdministrators) `andThen` assertEqual "an account" "O:S-1-5-21-1-2-3-1001D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x12019f;;;S-1-5-21-1-2-3-1001)(A;;0x12008b;;;BU)" (Pipe.pipeSddl (Pipe.OwnedByAccount account)) _ -> Fail "the tests' SIDs do not read as SIDs" ] where -- The most UTF-16 units Windows takes in a pipe's path. maxPipePathUnits = 256 -- winnt.h's FILE_READ_DATA, FILE_WRITE_DATA and -- FILE_CREATE_PIPE_INSTANCE. fileReadData = 0x1 fileWriteData = 0x2 fileCreatePipeInstance = 0x4daemonPipeAccounts _ = do hSetBuffering stdout LineBuffering tag <- T.pack . show <$> Proc.getCurrentPid let member = accountPrefix <> tag <> "m" outsider = accountPrefix <> tag <> "o" results <- withBuildersGroup $ withAccount member $ \inGroup -> bracket (makeAccount outsider) (const (removeAccount outsider)) $ \notInGroup -> withLogon inGroup $ \(_, memberToken) -> withLogon notInGroup $ \(_, outsiderToken) -> sequence (accountChecks (saName notInGroup) memberToken outsiderToken) putStrLn (show (length (filter id results)) <> " of " <> show (length results) <> " checks passed") exitWith (if and results then ExitSuccess else ExitFailure 1)-- | What the daemon makes of the account in the build users' group and of-- the one outside it, given the name of the second and each one's token,-- for a daemon run by the administrator that runs the checks, with-- @trusted-users@ at its default.accountChecks :: Text -> Handle -> Handle -> [IO Bool]accountChecks outsiderName memberToken outsiderToken = [ runTestM "an account outside the build users' group is admitted and not trusted, and one inside it is refused without a byte read from it" $ withSocketDaemon Listen.DefaultTrust (\config -> config {ncBuildUsersGroup = Just "nixbld", ncAllowedUsers = ["*"]}) $ \_ address logged -> do outsider <- connectedAndClosedAs outsiderToken address AllGroups member <- connectedAndClosedAs memberToken address EffectiveOnly messages <- logged let accepted message = "accepted connection from pid " `T.isPrefixOf` message && outsiderName `T.isInfixOf` message && not (" (trusted)" `T.isSuffixOf` message) pure $ assertEqual "the account outside the group is held open" (Right False) outsider `andThen` assertEqual "the account in the group is closed" (Right True) member `andThen` assertEqual "logged" (1, 1) (length (filter accepted messages), length (filter refusalMessage messages)), runTestM "an account of another user may not add an instance to the daemon's pipe or open it to rewrite its DACL" $ withSocketDaemon Listen.DefaultTrust id $ \_ address _ -> do added <- addInstanceAs outsiderToken address rewritten <- openAs outsiderToken address writeDac AllGroups either (const (pure ())) closeHandle added either (const (pure ())) closeHandle rewritten pure $ assertEqual "adding an instance" (Left errorAccessDenied) (() <$ added) `andThen` assertEqual "opening to rewrite the DACL" (Left errorAccessDenied) (() <$ rewritten) ]testDaemonPipeIO = do putStrLn "daemon/pipe-io" processUserSid >>= \process -> case process of Nothing -> (: []) <$> runTest "the process has a user SID" (Fail "it has none") Just user -> do named <- maybe (pure Nothing) (adAccountName Pipe.systemAccounts) (sidFromText user) pipeTests user (maybe user TE.decodeUtf8Lenient named)-- | The tests, given the SID and the name of the account this process-- runs as.pipeTests :: Text -> Text -> IO [Bool]pipeTests user name = sequence [ runTestM "nova-nix's client is served a handshake, a query and an add over the pipe, and the daemon names it by its account" $ case makeTextPath "hello.txt" (sha256Digest helloText) [] of Left err -> pure (Fail (T.pack (show err))) Right expected -> withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address logged -> do pid <- Proc.getCurrentPid source <- chunkSource [helloText] outcome <- withClient address $ do info <- Client.daemonInfo valid <- Client.isValidPath fooPath added <- Proto.vpiPath <$> Client.addToStore (AddToStoreRequest "hello.txt" "text:sha256" Set.empty NoRepair) source validAfter <- Client.isValidPath added pure (info >>= Proto.hiTrust, valid, added, validAfter) messages <- logged pure $ assertEqual "outcome" (Right (Just Proto.Trusted, True, expected, True)) outcome `andThen` assertEqual "logged" [accepted pid " (trusted)"] messages, runTestM "the client is admitted by its SID or its name, and refused where allowed-users names neither, as upstream's daemon refuses a client" $ do pid <- Proc.getCurrentPid bySid <- trustedAs [] [user] $ \outcome messages -> assertEqual "by SID" (Right (Just Proto.NotTrusted), [accepted pid ""]) (outcome, messages) byName <- trustedAs [] [name] $ \outcome messages -> assertEqual "by name" (Right (Just Proto.NotTrusted), [accepted pid ""]) (outcome, messages) neither <- trustedAs [] [otherUser] $ \outcome messages -> assertEqual "neither" (Left (Client.ConnectionLost Client.disconnectedMessage), ["error: while processing connection: user '" <> name <> "' is not allowed to connect to the Nix daemon"]) (outcome, messages) pure (bySid `andThen` byName `andThen` neither), runTestM "trusted-users trusts the client by a group its token holds, named by SID or by name, and not by one it does not hold" $ do usersName <- maybe (pure Nothing) (adAccountName Pipe.systemAccounts) (sidFromText usersSid) bySid <- trustedAs ["@" <> authenticatedUsersSid] ["*"] $ \outcome _ -> assertEqual "by SID" (Right (Just Proto.Trusted)) outcome byName <- case usersName of Nothing -> pure (Fail "Users has no name") Just group -> trustedAs ["@" <> TE.decodeUtf8Lenient group] ["*"] $ \outcome _ -> assertEqual "by name" (Right (Just Proto.Trusted)) outcome notHeld <- trustedAs ["@" <> guestsSid] ["*"] $ \outcome _ -> assertEqual "not held" (Right (Just Proto.NotTrusted)) outcome pure (bySid `andThen` byName `andThen` notHeld), runTestM "a second daemon on the pipe is refused while the first listens" $ withSocketDaemon Listen.DefaultTrust id $ \_ address _ -> Listen.openListener address >>= \opened -> case opened of Left refusal -> pure (assertEqual "refused" ("cannot listen on '" <> TE.decodeUtf8Lenient address <> "': a process already has the pipe open") refusal) Right second -> Fail "a second daemon listened on the pipe" <$ Listen.closeListener second, runTestM "a client of a pipe no daemon has is refused, in Windows' words" $ daemonAddress "" >>= \unused -> case unused of Nothing -> pure (Fail "no pipe's path") Just address -> case Pipe.pipePath address of Left reason -> pure (Fail reason) Right path -> Pipe.connectPipe path >>= \connected -> case connected of Left reason -> pure (assertEqual "refused by CreateFileW" True ("CreateFileW: " `T.isPrefixOf` reason)) Right conn -> Fail "a client connected to a pipe no daemon has" <$ Pipe.closeConnection conn, runTestM "a client trusts the pipe of a daemon run by its own account, which the daemon owns as Administrators where its token holds the group enabled and as its account otherwise" $ do held <- administratorsEnabled withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address _ -> do owner <- entryOwner (BS8.unpack address) served <- withClient address Client.daemonInfo pure $ assertEqual "the pipe's owner" (Just (if held then administratorsSid else user)) owner `andThen` assertEqual "the client connects and is served" True (either (const False) (const True) served), runTestM "a client refuses a pipe another user owns, naming the pipe, and uses it for nothing" $ do path <- freshPipe -- Another user's pipe is stood in for by one an account with the -- restore privilege makes, which can name any owner. made <- makePipeAs nullPtr WithRestore (Pipe.pipePathText path) (ownedBy otherUser) case made of Left code | code == errorNotAllAssigned -> Pass <$ putStrLn " SKIP the process lacks the restore privilege, which a pipe another user owns is made with" | otherwise -> pure (Fail ("making the pipe failed with Win32 error " <> T.pack (show code))) Right pipe -> ( Pipe.connectPipe path >>= \connected -> case connected of Left reason -> pure (assertEqual "refusal" (notTrusted path <> "it belongs to " <> otherUser <> ", not to you, SYSTEM, Administrators or the nova-nix service") reason) Right conn -> Fail "a client connected to a pipe another user owns" <$ Pipe.closeConnection conn ) `finally` closeHandle pipe, runTestM "a token that holds Administrators for deny only owns a pipe as its own account, and Windows lets it give no pipe Administrators as its owner" $ withFilteredToken $ \filtered -> do owner <- tokenPipeOwner filtered path <- freshPipe refused <- makePipeAs filtered Ordinary (Pipe.pipePathText path) (ownedBy administratorsSid) either (\code -> pure (assertEqual "owner of the pipe the daemon makes" user owner `andThen` assertEqual "making a pipe owned by Administrators" errorInvalidOwner code)) (\pipe -> Fail "a token that holds Administrators for deny only made a pipe owned by Administrators" <$ closeHandle pipe) refused, runTestM "a client refuses a pipe a process at Low integrity made, though its own account owns it" $ do path <- freshPipe withIntegrityToken nullPtr lowIntegrity $ \low -> do made <- makePipeAs low Ordinary (Pipe.pipePathText path) (ownedBy user) case made of Left code -> pure (Fail ("making the pipe failed with Win32 error " <> T.pack (show code))) Right pipe -> ( Pipe.connectPipe path >>= \connected -> case connected of Left reason -> pure (assertEqual "refusal" (notTrusted path <> "it was made by a process below Medium integrity (level 0x1000)") reason) Right conn -> Fail "a client connected to a pipe a process at Low integrity made" <$ Pipe.closeConnection conn ) `finally` closeHandle pipe, runTestM "where the daemon owns its pipe as Administrators, a process of its account that is not elevated cannot add an instance to the pipe or open it to rewrite its DACL, and writes it as a client" $ do held <- administratorsEnabled if not held then Pass <$ putStrLn " SKIP the process is not elevated, so its daemon owns its pipe as its account" else withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address _ -> withMediumToken $ \medium -> do added <- addInstanceAs medium address rewritten <- openAs medium address writeDac AllGroups connected <- openAs medium address Pipe.clientPipeAccess AllGroups either (const (pure ())) closeHandle added either (const (pure ())) closeHandle rewritten either (const (pure ())) closeHandle connected pure $ assertEqual "adding an instance" (Left errorAccessDenied) (() <$ added) `andThen` assertEqual "opening to rewrite the DACL" (Left errorAccessDenied) (() <$ rewritten) `andThen` assertEqual "opening as a client" (Right ()) (() <$ connected), runTestM "where the daemon owns its pipe as its account, a process of the account adds the next instance, and cannot open the pipe to take its owner or delete it" $ withFilteredToken $ \filtered -> do owner <- tokenPipeOwner filtered path <- freshPipe case sidFromText owner of Nothing -> pure (Fail "the token's pipe owner is not a SID") Just sid -> makePipeAs filtered Ordinary (Pipe.pipePathText path) (Pipe.pipeSddl (Pipe.pipeOwnerOf sid)) >>= \made -> case made of Left code -> pure (Fail ("making the pipe failed with Win32 error " <> T.pack (show code))) Right first -> do added <- addInstanceAs filtered (TE.encodeUtf8 (Pipe.pipePathText path)) takenOver <- openAs filtered (TE.encodeUtf8 (Pipe.pipePathText path)) writeOwner AllGroups deleted <- openAs filtered (TE.encodeUtf8 (Pipe.pipePathText path)) delete AllGroups either (const (pure ())) closeHandle added either (const (pure ())) closeHandle takenOver either (const (pure ())) closeHandle deleted closeHandle first pure $ assertEqual "adding an instance" (Right ()) (() <$ added) `andThen` assertEqual "opening to take the owner" (Left errorAccessDenied) (() <$ takenOver) `andThen` assertEqual "opening to delete" (Left errorAccessDenied) (() <$ deleted), runTestM "a client the daemon refuses is closed without a byte read from it, again and again, so it holds neither an instance nor a thread" $ withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [], ncAllowedUsers = []}) $ \_ address logged -> do outcomes <- mapM (const (connectedAndClosed address AllGroups)) [1 .. refusedClients] messages <- logged pure $ assertEqual "each is closed" (replicate refusedClients (Right True)) outcomes `andThen` assertEqual "each is told why in the log" (replicate refusedClients True) (map refusalMessage messages), runTestM "a client is refused for the build users' group by its account, whatever groups its token shows, and is served where its account is not in the group" $ withDeniedGroup usersSid $ \shaped -> do let building group = \config -> config {ncBuildUsersGroup = Just group, ncTrustedUsers = ["*"], ncAllowedUsers = ["*"]} refused <- withSocketDaemon Listen.DefaultTrust (building "BUILTIN\\Users") $ \_ address logged -> do outcome <- connectedAndClosedAs shaped address EffectiveOnly messages <- logged pure (assertEqual "closed" (Right True) outcome `andThen` assertEqual "logged" (map refusalMessage messages) [True]) served <- withSocketDaemon Listen.DefaultTrust (building (TE.encodeUtf8 guestsSid)) $ \_ address logged -> do outcome <- connectedAndClosedAs shaped address EffectiveOnly messages <- logged pure (assertEqual "held open" (Right False) outcome `andThen` assertEqual "logged" True (any (T.isPrefixOf "accepted connection from pid ") messages)) pure (refused `andThen` served), runTestM "a name is an account of this machine unless it names a domain, of the kind asked for, and an account's groups are those Windows holds for it" $ do let accounts = Pipe.systemAccounts own <- adAccountName accounts =<< maybe (ioError (userError "the process's SID")) pure (sidFromText user) ownUser <- maybe (pure (Right Nothing)) (adAccountSid accounts UserAccount) own ownAsGroup <- maybe (pure (Right Nothing)) (adAccountSid accounts GroupAccount) own builtin <- adAccountSid accounts GroupAccount "BUILTIN\\Administrators" builtinAsUser <- adAccountSid accounts UserAccount "BUILTIN\\Administrators" system <- adAccountSid accounts UserAccount "NT AUTHORITY\\SYSTEM" bareBuiltinGroup <- adAccountSid accounts GroupAccount "Administrators" bareSystem <- adAccountSid accounts UserAccount "SYSTEM" bareRoot <- adAccountSid accounts UserAccount "root" nobody <- adAccountSid accounts UserAccount "no-such-account-nova-nix" groups <- maybe (ioError (userError "the process's SID")) (adAccountGroups accounts) (sidFromText user) pure $ assertEqual "the process's account, by its own name" (Right (sidFromText user)) ownUser `andThen` assertEqual "a user is no group" (Right Nothing) ownAsGroup `andThen` assertEqual "a group of another domain by name" (Right (sidFromText administratorsSid)) builtin `andThen` assertEqual "a group is no user" (Right Nothing) builtinAsUser `andThen` assertEqual "a well-known user by name" (Right (sidFromText "S-1-5-18")) system `andThen` assertEqual "a bare name is not a built-in group, which is BUILTIN\\NAME" (Right Nothing) bareBuiltinGroup `andThen` assertEqual "a bare name is not a well-known user, which is NT AUTHORITY\\NAME" (Right Nothing) bareSystem `andThen` assertEqual "root, which Windows has no account for" (Right Nothing) bareRoot `andThen` assertEqual "an account that does not exist" (Right Nothing) nobody `andThen` assertEqual "the groups hold Users and Everyone" (Right True) (fmap (\held -> all (`elem` map sidText held) [usersSid, everyoneSid]) groups), runTestM "a client of a pipe whose instances are all busy waits a bounded while, and is told the pipe is busy" $ daemonAddress "" >>= \found -> case found of Nothing -> pure (Fail "no pipe's path") Just address -> case Pipe.pipePath address of Left reason -> pure (Fail reason) Right path -> Listen.openListener address >>= \opened -> case opened of Left refusal -> pure (Fail refusal) Right listener -> do ( Pipe.connectPipe path >>= \first -> case first of Left reason -> pure (Fail ("the first client was refused: " <> reason)) Right taken -> do started <- getMonotonicTime second <- timeout socketTestMicros (Pipe.connectPipe path) waited <- subtract started <$> getMonotonicTime Pipe.closeConnection taken pure $ case second of Nothing -> Fail "the second client waited without end" Just (Right _) -> Fail "a second client connected to a busy pipe" Just (Left reason) -> assertEqual "the pipe is busy" True ("CreateFileW: " `T.isPrefixOf` reason) `andThen` assertEqual "it waited the pipe's default wait" True (waited >= busyWaitSeconds) ) `finally` Listen.closeListener listener, -- No daemon takes clients from the listener, so a check that -- connected to its one instance would leave none for the client -- after it, which would wait for one and give up. runTestM "a daemon's pipe is present while it listens, without the check taking its instance, and absent once it stops" $ daemonAddress "" >>= \found -> case found of Nothing -> pure (Fail "no pipe's path") Just address -> case Pipe.pipePath address of Left reason -> pure (Fail reason) Right path -> do before <- Pipe.pipePresent path Listen.openListener address >>= \opened -> case opened of Left refusal -> pure (Fail refusal) Right listener -> do (during, connects) <- ( do present <- Pipe.pipePresent path taken <- Pipe.connectPipe path either (const (pure ())) Pipe.closeConnection taken pure (present, either (const False) (const True) taken) ) `finally` Listen.closeListener listener after <- Pipe.pipePresent path pure $ assertEqual "before" False before `andThen` assertEqual "while listening" True during `andThen` assertEqual "a client connects after the check" True connects `andThen` assertEqual "after" False after, -- The connection is left open when the daemon is stopped, which a -- daemon that cannot interrupt its read of a quiet client never -- finishes. runTestM "stopping the daemon ends the connection of a client that has gone quiet" $ do held <- newIORef Nothing served <- withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address _ -> do link <- connectDaemon address writeIORef held (Just link) helloOver link Proto.Trusted readIORef held >>= \kept -> case kept of Nothing -> pure served Just link -> do after <- timeout socketTestMicros (linkReceive link 1) `finally` linkClose link pure (served `andThen` assertEqual "after the stop" (Just "") after) ] where accepted pid trusted = "accepted connection from pid " <> T.pack (show pid) <> ", user " <> name <> trusted -- A session that asks only how far the daemon trusts it, given what -- the daemon is told of trusted-users and allowed-users, judged with -- what the daemon logged. trustedAs trusted allowed judge = withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = map TE.encodeUtf8 trusted, ncAllowedUsers = map TE.encodeUtf8 allowed}) $ \_ address logged -> do outcome <- withClient address ((>>= Proto.hiTrust) <$> Client.daemonInfo) judge outcome <$> logged-- | A user's SID no account has, and the SIDs of the well-known groups-- Authenticated Users, which every signed-in account's token holds,-- Users, which holds them, and Guests, which the tests' account is not in.otherUser, authenticatedUsersSid, usersSid, guestsSid :: TextotherUser = "S-1-5-21-1-2-3-1001"authenticatedUsersSid = "S-1-5-11"usersSid = "S-1-5-32-545"guestsSid = "S-1-5-32-546"-- | The SID of Everyone, which every account is in.everyoneSid :: TexteveryoneSid = "S-1-1-0"-- | winnt.h's DELETE, WRITE_DAC and WRITE_OWNER, the rights to remove a-- pipe, rewrite its DACL and take its owner.delete, writeDac, writeOwner :: Word32delete = 0x10000writeDac = 0x40000writeOwner = 0x80000-- | The mandatory label RIDs of Low and Medium integrity (winnt.h's-- @SECURITY_MANDATORY_LOW_RID@ and @SECURITY_MANDATORY_MEDIUM_RID@).lowIntegrity, mediumIntegrity :: Word32lowIntegrity = 0x1000mediumIntegrity = 0x2000-- | The least time, in seconds, a client of a pipe whose instances stay-- busy waits: the pipe's default wait, which is five seconds, less what-- the clock and the wait's start can differ by.busyWaitSeconds :: DoublebusyWaitSeconds = 4-- | How many clients the daemon is to refuse one after the other.refusedClients :: IntrefusedClients = 3-- | How long, in milliseconds, a test waits for the daemon to end a-- connection it has refused, well past what that takes, and how long it-- watches one the daemon admits.closeWaitMillis :: CULongcloseWaitMillis = 3000-- | Whether a line the daemon logged says it refused a client.refusalMessage :: Text -> BoolrefusalMessage message = "error: while processing connection: user '" `T.isPrefixOf` message && "' is not allowed to connect to the Nix daemon" `T.isSuffixOf` message-- | What the daemon sees of the groups a client's token holds.data Visibility = -- | Every group, those held for deny only too. AllGroups | -- | The groups enabled, as an impersonating server sees a client that -- asks for no more. EffectiveOnly-- | What the client says of a pipe no trusted account made, up to the-- reason.notTrusted :: Pipe.PipePath -> TextnotTrusted path = "the pipe '" <> Pipe.pipePathText path <> "' is not served by a trusted account: "-- | Administrators' SID, which the daemon owns its pipe as where its token-- holds the group enabled.administratorsSid :: TextadministratorsSid = "S-1-5-32-544"-- | The SDDL of a security descriptor that gives the owner and lets every-- account do anything, for the pipes the tests stand in a daemon's place-- with.ownedBy :: Text -> TextownedBy owner = "O:" <> owner <> "D:(A;;GA;;;WD)"-- | Win32's @ERROR_INVALID_OWNER@, which a process that names an owner it-- may not give gets, @ERROR_NOT_ALL_ASSIGNED@, which enabling a-- privilege a token does not hold gets, and @ERROR_ACCESS_DENIED@, which a-- pipe's DACL gives (winerror.h).errorInvalidOwner, errorNotAllAssigned, errorAccessDenied :: CULongerrorInvalidOwner = 1307errorNotAllAssigned = 1300errorAccessDenied = 5-- | A pipe's path no other test uses.freshPipe :: IO Pipe.PipePathfreshPipe = daemonAddress "" >>= \address -> case address >>= either (const Nothing) Just . Pipe.pipePath of Just path -> pure path Nothing -> ioError (userError "no pipe's path")-- | The text the add test adds.helloText :: BS.ByteStringhelloText = "hello\n"-- | A chunk source over chunks, giving an empty chunk once they are-- given.chunkSource :: [BS.ByteString] -> IO (IO BS.ByteString)chunkSource chunks = do pending <- newIORef chunks pure (atomicModifyIORef' pending (\left -> case left of [] -> ([], BS.empty); chunk : rest -> (rest, chunk)))-- | Run a session of nova-nix's client with the daemon at the address,-- its messages dropped, and close the connection after.withClient :: BS.ByteString -> Client.ClientT IO a -> IO (Either Client.ClientFailure a)withClient address steps = case Pipe.pipePath address of Left reason -> pure (Left (Client.ConnectionLost reason)) Right path -> Pipe.connectPipe path >>= \connected -> case connected of Left reason -> pure (Left (Client.ConnectionLost reason)) Right conn -> Client.runClient defaultStoreDir Client.offeredVersion (Pipe.connectionTransport conn) (\_ -> pure ()) steps `finally` Pipe.closeConnection conn-- ----------------------------------------------------------------------------- Tokens and pipes-- ----------------------------------------------------------------------------- | A Win32 handle.type Handle = Ptr ()-- | What a pipe made as a token is made with: the privileges it has, or-- the restore privilege enabled as well, which lets it name any owner.data Privilege = Ordinary | WithRestoreforeign import ccall unsafe "nn_test_administrators_enabled" c_nn_test_administrators_enabled :: Ptr CInt -> IO CULongforeign import ccall unsafe "nn_test_filtered_token" c_nn_test_filtered_token :: Ptr Handle -> IO CULongforeign import ccall unsafe "nn_test_integrity_token" c_nn_test_integrity_token :: Handle -> CULong -> Ptr Handle -> IO CULongforeign import ccall unsafe "nn_test_deny_group_token" c_nn_test_deny_group_token :: CWString -> Ptr Handle -> IO CULongforeign import ccall unsafe "nn_test_make_pipe" c_nn_test_make_pipe :: Handle -> CInt -> CWString -> CWString -> Ptr Handle -> IO CULongforeign import ccall unsafe "nn_test_open_as" c_nn_test_open_as :: Handle -> CWString -> CULong -> CInt -> Ptr Handle -> IO CULong-- Safe, as it waits for the daemon, which runs in this process.foreign import ccall safe "nn_test_wait_closed" c_nn_test_wait_closed :: Handle -> CULong -> Ptr CInt -> IO CULongforeign import ccall unsafe "nn_token_pipe_owner" c_nn_token_pipe_owner :: Handle -> Ptr CWString -> Ptr CString -> IO CULongforeign import ccall unsafe "CloseHandle" c_CloseHandle :: Handle -> IO CIntforeign import ccall unsafe "LocalFree" c_LocalFree :: Ptr a -> IO (Ptr a)-- | Close a handle.closeHandle :: Handle -> IO ()closeHandle = void . c_CloseHandle-- | Throw unless a call's Win32 error code is 0.succeeded :: String -> CULong -> IO ()succeeded call code = when (code /= 0) (ioError (userError (call <> " failed with Win32 error " <> show code)))-- | Whether this process's token holds Administrators enabled, which a-- filtered administrator's token does not.administratorsEnabled :: IO BooladministratorsEnabled = alloca $ \heldOut -> do succeeded "nn_test_administrators_enabled" =<< c_nn_test_administrators_enabled heldOut (/= 0) <$> peek heldOut-- | Run an action with a copy of this process's token that holds-- Administrators for deny only.withFilteredToken :: (Handle -> IO a) -> IO awithFilteredToken = bracket make closeHandle where make = alloca $ \tokenOut -> do succeeded "nn_test_filtered_token" =<< c_nn_test_filtered_token tokenOut peek tokenOut-- | Run an action with a copy of a token, the process's where it is null,-- at an integrity level.withIntegrityToken :: Handle -> Word32 -> (Handle -> IO a) -> IO awithIntegrityToken base level = bracket make closeHandle where make = alloca $ \tokenOut -> do succeeded "nn_test_integrity_token" =<< c_nn_test_integrity_token base (fromIntegral level) tokenOut peek tokenOut-- | Run an action with a token as a process of the daemon's account that-- is not elevated holds: Administrators for deny only, no privilege, and-- Medium integrity.withMediumToken :: (Handle -> IO a) -> IO awithMediumToken action = withFilteredToken $ \filtered -> withIntegrityToken filtered mediumIntegrity action-- | Run an action with a copy of this process's token that holds the group-- the SID names for deny only.withDeniedGroup :: Text -> (Handle -> IO a) -> IO awithDeniedGroup group = bracket make closeHandle where make = withCWString (T.unpack group) $ \cGroup -> alloca $ \tokenOut -> do succeeded "nn_test_deny_group_token" =<< c_nn_test_deny_group_token cGroup tokenOut peek tokenOut-- | The SID the daemon would make the owner of its pipe if it ran with the-- token.tokenPipeOwner :: Handle -> IO TexttokenPipeOwner token = alloca $ \sidOut -> alloca $ \failedOut -> do code <- c_nn_token_pipe_owner token sidOut failedOut failed <- maybePeek peekCString =<< peek failedOut succeeded (fromMaybe "nn_token_pipe_owner" failed) code found <- peek sidOut (T.pack <$> peekCWString found) `finally` c_LocalFree found-- | Make a pipe as a token, the process's own where it is null, or give-- the Win32 error code that stopped it. The pipe is for the caller to-- close.makePipeAs :: Handle -> Privilege -> Text -> Text -> IO (Either CULong Handle)makePipeAs token privilege name sddl = withCWString (T.unpack name) $ \cName -> withCWString (T.unpack sddl) $ \cSddl -> alloca $ \pipeOut -> do code <- c_nn_test_make_pipe token restore cName cSddl pipeOut if code == 0 then Right <$> peek pipeOut else pure (Left code) where restore = case privilege of Ordinary -> 0 WithRestore -> 1-- | Add an instance to the pipe at the address as a token, or give the-- Win32 error code that refused it. The instance is for the caller to-- close.addInstanceAs :: Handle -> BS.ByteString -> IO (Either CULong Handle)addInstanceAs token address = withCWString (T.unpack (TE.decodeUtf8Lenient address)) $ \cName -> alloca $ \pipeOut -> do code <- c_nn_test_make_pipe token 0 cName nullPtr pipeOut if code == 0 then Right <$> peek pipeOut else pure (Left code)-- | Open the pipe at the address as a token, the process's where it is-- null, as the library's client does, for the access, or give the Win32-- error code that refused it. The connection is for the caller to close.openAs :: Handle -> BS.ByteString -> Word32 -> Visibility -> IO (Either CULong Handle)openAs token address access visibility = withCWString (T.unpack (TE.decodeUtf8Lenient address)) $ \cName -> alloca $ \pipeOut -> do code <- c_nn_test_open_as token cName (fromIntegral access) effectiveOnly pipeOut if code == 0 then Right <$> peek pipeOut else pure (Left code) where effectiveOnly = case visibility of AllGroups -> 0 EffectiveOnly -> 1-- | Connect to the pipe at the address as a token, the process's where it-- is null, and say whether the daemon ends the connection before the-- client has sent a byte, or give the Win32 error code that stopped it.connectedAndClosedAs :: Handle -> BS.ByteString -> Visibility -> IO (Either CULong Bool)connectedAndClosedAs token address visibility = openAs token address Pipe.clientPipeAccess visibility >>= \opened -> case opened of Left code -> pure (Left code) Right pipe -> (waitClosed pipe `finally` closeHandle pipe) where waitClosed pipe = alloca $ \closedOut -> do code <- c_nn_test_wait_closed pipe closeWaitMillis closedOut if code == 0 then Right . (/= 0) <$> peek closedOut else pure (Left code)-- | 'connectedAndClosedAs' as the process.connectedAndClosed :: BS.ByteString -> Visibility -> IO (Either CULong Bool)connectedAndClosed = connectedAndClosedAs nullPtr#elsetestDaemonPipe = [] <$ putStrLn "daemon/pipe\n SKIP Windows only"testDaemonPipeIO = [] <$ putStrLn "daemon/pipe-io\n SKIP Windows only"daemonPipeAccounts _ = die "the daemon's pipe is Windows only"#endif