{-# LANGUAGE LambdaCase #-}-- | Who may connect to a daemon, and whom it trusts, as upstream's daemon-- decides from what the operating system says of a connection's peer:-- its user, matched against @trusted-users@ and @allowed-users@ by name,-- by @*@, or by a group named with @\@@; and its group, a member of the-- build users' group being refused.---- On Windows a peer is an account, read from the token of a named pipe's-- client ('admitAccount'): its user and the groups the token grants by,-- each a SID. An entry names an account as Windows resolves a name-- (@NAME@, an account of this machine, or @DOMAIN\\NAME@ or-- @NAME\@DOMAIN@) or by its SID (@S-1-5-...@), and matches by SID: a bare-- entry the user, and an entry after @\@@ a group the token holds. An-- account whose name holds a space is named by its SID, since the-- settings are lists split at whitespace. A client is refused for the-- build users' group by the groups Windows holds for its account, not by-- those its token shows, which its holder can shape.---- The decision is pure over the account database it is given, a-- t'UserDatabase' or an t'AccountDatabase', so it runs in tests over-- users that do not exist; "Nix.Daemon.Listen" gives it the system's, and-- a peer's identity read from a Unix socket or a named pipe.---- The other way round, a client of a daemon's named pipe on Windows-- decides whether the pipe is the daemon's by the account that owns it-- ('trustsPipeOwner').module Nix.Daemon.Auth ( -- * Peers Peer (..), unknownPeer, -- * The user database UserDatabase (..), GroupEntry (..), -- * Windows accounts AccountPeer (..), AccountKind (..), AccountDatabase (..), -- * Admission AuthSettings (..), Admission (..), admitPeer, admitAccount, acceptedMessage, -- * Trusting a daemon trustsPipeOwner, )whereimport Data.Bifunctor (first)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Char8 as BS8import Data.Either (fromRight)import Data.Maybe (fromMaybe)import Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Word (Word32)import Nix.Builder.BuildUser (peerInBuildUsersGroup)import Nix.Daemon.Protocol (Trust (..))import Nix.Store.Access (Sid, administratorsSid, localSystemSid, novaNixServiceSid, sidFromText, sidText)-- ----------------------------------------------------------------------------- Peers-- ----------------------------------------------------------------------------- | What the operating system says of a connection's peer, as far as it-- says: its process, its user and its group, each by number.data Peer = Peer { peerProcess :: !(Maybe Word32), peerUser :: !(Maybe Word32), peerGroup :: !(Maybe Word32) } deriving (Eq, Show)-- | A peer the daemon knows nothing of, as one whose trust is forced is-- treated: its identity is not read.unknownPeer :: PeerunknownPeer = Peer Nothing Nothing Nothing-- ----------------------------------------------------------------------------- The user database-- ----------------------------------------------------------------------------- | A group as the user database records it: its number and the names-- it lists as members.data GroupEntry = GroupEntry { groupEntryId :: !Word32, groupEntryMembers :: ![ByteString] } deriving (Eq, Show)-- | What the decision asks of the system's users and groups.data UserDatabase m = UserDatabase { -- | A user's name, by number. udUserName :: !(Word32 -> m (Maybe ByteString)), -- | A group's name, by number. udGroupName :: !(Word32 -> m (Maybe ByteString)), -- | A group, by name. udGroup :: !(ByteString -> m (Maybe GroupEntry)), -- | Whether a user is a member of a group, by their numbers, where -- the system answers that apart from a group's member list, as -- macOS's directory does, and 'Nothing' where it does not or the -- question fails. udMembership :: !(Word32 -> Word32 -> m (Maybe Bool)) }-- ----------------------------------------------------------------------------- Windows accounts-- ----------------------------------------------------------------------------- | What Windows says of a named pipe's client, read from its token: its-- process, where known, its user, and the groups it grants by, each by-- SID.data AccountPeer = AccountPeer { accountProcess :: !(Maybe Word32), accountUser :: !Sid, -- | The token's groups that are enabled and not held for deny only, -- as an access check counts them: the ones that trust or admit it. accountGroups :: ![Sid] } deriving (Eq, Show)-- | What an account name is to name.data AccountKind = -- | A user, as a @trusted-users@ or @allowed-users@ entry with no -- @\@@ names one. SYSTEM and a service's virtual account are users -- here, as processes run as them. UserAccount | -- | A group, as an entry after @\@@ or @build-users-group@ names one. GroupAccount deriving (Eq, Show)-- | What the decision asks of Windows' accounts.data AccountDatabase m = AccountDatabase { -- | The SID an account's name names, as Windows resolves one, where -- one of that kind has the name: 'Right' 'Nothing' where none does, -- and 'Left' why where the lookup could not be made, which is not an -- answer. adAccountSid :: !(AccountKind -> ByteString -> m (Either Text (Maybe Sid))), -- | An account's name, @DOMAIN\\NAME@, by its SID, or 'Nothing' where -- it has none. adAccountName :: !(Sid -> m (Maybe ByteString)), -- | Every group an account belongs to, as Windows computes them from -- the account, or why it cannot say. adAccountGroups :: !(Sid -> m (Either Text [Sid])) }-- ----------------------------------------------------------------------------- Admission-- ----------------------------------------------------------------------------- | The daemon's settings that decide admission, as bytes, matched-- against the user database's.data AuthSettings = AuthSettings { -- | @trusted-users@. asTrustedUsers :: ![ByteString], -- | @allowed-users@. asAllowedUsers :: ![ByteString], -- | @build-users-group@, empty for none. asBuildUsersGroup :: !ByteString } deriving (Eq, Show)-- | What becomes of a peer.data Admission = -- | It may connect, trusted or not, and is named so, where it has a -- name. Admitted !Trust !(Maybe ByteString) | -- | It may not, for this reason. Refused !Text deriving (Eq, Show)-- | Decide a peer's admission as upstream's daemon does. The peer is-- named by its user's name, or its user's number where the user has no-- entry, and its group likewise. It is trusted when @trusted-users@-- matches it, and a peer that is not is refused unless @allowed-users@-- matches it; a peer whose group is the build users' is refused either-- way.admitPeer :: (Monad m) => UserDatabase m -> AuthSettings -> Peer -> m AdmissionadmitPeer db settings peer = do user <- traverse (\uid -> fromMaybe (decimal uid) <$> udUserName db uid) (peerUser peer) group <- traverse (\gid -> fromMaybe (decimal gid) <$> udGroupName db gid) (peerGroup peer) let matches = matchUser db peer user group trusted <- matches (asTrustedUsers settings) allowed <- if trusted then pure True else matches (asAllowedUsers settings) pure $ if not allowed || peerInBuildUsersGroup (asBuildUsersGroup settings) group then refusal user else Admitted (if trusted then Trusted else NotTrusted) user-- | Decide a Windows account's admission as 'admitPeer' decides a POSIX-- peer's, by SID: an entry names the user, or after @\@@ a group the-- token grants by, by SID or by a name Windows resolves to one, and @*@-- everyone. The account is named by its name, or its SID where it has-- none. An entry that cannot be looked up names no one, which only-- withholds trust or admission. An account that belongs to the build-- users' group, by the groups Windows holds for it, is refused whatever-- its token shows, and one whose membership cannot be told, or whose group-- cannot be looked up, is refused too, where a mistaken answer would let-- a build account in.admitAccount :: (Monad m) => AccountDatabase m -> AuthSettings -> AccountPeer -> m AdmissionadmitAccount db settings peer = do name <- fromMaybe (TE.encodeUtf8 (sidText user)) <$> adAccountName db user trusted <- matches (asTrustedUsers settings) allowed <- if trusted then pure True else matches (asAllowedUsers settings) building <- inBuildUsersGroup (asBuildUsersGroup settings) pure $ case building of Left reason -> Refused (notAllowed (Just name) <> ": " <> reason) Right member | member || not allowed -> refusal (Just name) | otherwise -> Admitted (if trusted then Trusted else NotTrusted) (Just name) where user = accountUser peer matches = anyM entryMatches entryMatches entry | entry == everyone = pure True | Just group <- BS.stripPrefix groupMark entry = maybe False (`elem` accountGroups peer) . resolved <$> entrySid GroupAccount group | otherwise = (== Just user) . resolved <$> entrySid UserAccount entry resolved = fromRight Nothing inBuildUsersGroup group | BS.null group = pure (Right False) | otherwise = entrySid GroupAccount group >>= \case Left reason -> pure (Left ("cannot look up build-users-group '" <> TE.decodeUtf8Lenient group <> "': " <> reason)) -- A group no account has holds no one. Right Nothing -> pure (Right False) Right (Just built) -> fmap (elem built) . first ("cannot tell the groups of the account: " <>) <$> adAccountGroups db user entrySid kind entry | BS.null entry = pure (Right Nothing) | Right text <- TE.decodeUtf8' entry, Just sid <- sidFromText text = pure (Right (Just sid)) | otherwise = adAccountSid db kind entry-- | Upstream's refusal of a peer, named by its user where it has one.refusal :: Maybe ByteString -> Admissionrefusal = Refused . notAllowed-- | What upstream's daemon says of a peer it will not serve.notAllowed :: Maybe ByteString -> TextnotAllowed user = "user '" <> maybe unknownName TE.decodeUtf8Lenient user <> "' is not allowed to connect to the Nix daemon"-- | Whether a list of users matches the peer: @*@ matches everyone, a-- name the peer's user's name, and @\@GROUP@ a peer whose group is-- named so or whose user the group lists, or, where the system answers-- membership itself, one it says is a member.matchUser :: (Monad m) => UserDatabase m -> Peer -> Maybe ByteString -> Maybe ByteString -> [ByteString] -> m BoolmatchUser db peer user group users | everyone `elem` users = pure True | maybe False (`elem` users) user = pure True | otherwise = anyM groupMatches [name | entry <- users, Just name <- [BS.stripPrefix groupMark entry]] where groupMatches name | group == Just name = pure True | otherwise = udGroup db name >>= \case Nothing -> pure False Just entry -> maybe (pure False) (`listedIn` entry) user listedIn name entry | name `elem` groupEntryMembers entry = pure True | otherwise = maybe (pure False) (\uid -> fromMaybe False <$> udMembership db uid (groupEntryId entry)) (peerUser peer)-- | Whether any of the tests passes, trying them in order until one does.anyM :: (Monad m) => (a -> m Bool) -> [a] -> m BoolanyM test = \case [] -> pure False item : rest -> test item >>= \passed -> if passed then pure True else anyM test rest-- | The entry that matches every user, and the mark of a group.everyone, groupMark :: ByteStringeveryone = "*"groupMark = "@"-- | A number as upstream names a user or group without an entry.decimal :: Word32 -> ByteStringdecimal = BS8.pack . show-- | How a peer with no user is named.unknownName :: TextunknownName = "<unknown>"-- | The line upstream's daemon logs as it accepts a connection, given the-- peer's process, where known.acceptedMessage :: Maybe Word32 -> Admission -> TextacceptedMessage process admission = "accepted connection from pid " <> maybe unknownName (T.pack . show) process <> ", user " <> named where named = case admission of Admitted Trusted user -> userText user <> " (trusted)" Admitted NotTrusted user -> userText user Refused _ -> unknownName userText = maybe unknownName TE.decodeUtf8Lenient-- ----------------------------------------------------------------------------- Trusting a daemon-- ----------------------------------------------------------------------------- | Whether a client trusts a named pipe to be a daemon's, given its own-- account and the account that owns the pipe. The process that makes a-- pipe chooses its owner, and Windows lets it choose only its token's-- user or a group its token holds enabled with the right to own objects-- as it: an elevated administrator's token holds Administrators so, and a-- filtered one, which holds the group for deny only, does not. Only a-- process holding the restore privilege, which an elevated-- administrator's token has, can name another owner. So the owner says-- who made the pipe. A client trusts a pipe owned by its own account, by-- SYSTEM, by Administrators, or by the virtual account-- @NT SERVICE\\nova-nix@ the daemon's Windows service is to run as. Any-- other user owns the pipes it makes as itself, an administrator who is-- not elevated among them, and is not trusted, and neither are the other-- accounts services run as, which other services share.trustsPipeOwner :: Sid -> Sid -> BooltrustsPipeOwner client owner = owner == client || owner `elem` trustedServers where trustedServers = [localSystemSid, administratorsSid, novaNixServiceSid]