Eventually-decentralized project hosting and management platform
Clone
HTTPS:
darcs clone https://vervis.peers.community/repos/WvWbo
SSH:
darcs clone USERNAME@vervis.peers.community:WvWbo
Tags
TODO
Ssh.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 | {- This file is part of Vervis.
-
- Written in 2016, 2019, 2022 by fr33domlover <fr33domlover@riseup.net>.
-
- ♡ Copying is an act of love. Please copy, reuse and share.
-
- The author(s) have dedicated all copyright and related and neighboring
- rights to this software to the public domain worldwide. This software is
- distributed without any warranty.
-
- You should have received a copy of the CC0 Public Domain Dedication along
- with this software. If not, see
- <http://creativecommons.org/publicdomain/zero/1.0/>.
-}
module Vervis.Ssh
( runSsh
)
where
import Control.Applicative ((<|>), optional)
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT (MaybeT, runMaybeT))
import Control.Monad.Trans.Reader (ReaderT (runReaderT), ask)
import Data.Attoparsec.Text
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (fromStrict)
import Data.Foldable (find)
import Data.Git.Storage (isRepo)
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import Data.String (fromString)
import Data.Text (Text)
import Database.Persist
import Database.Persist.Sql
import Formatting ((%))
import Network.SSH
import Network.SSH.Channel
import Network.SSH.Crypto
import Network.SSH.Session
import System.Directory (doesFileExist, doesDirectoryExist)
import System.Environment
import System.FilePath ((</>))
import System.Process (CreateProcess (..), StdStream (..), createProcess, proc)
import Web.Hashids
import Yesod.Core.Dispatch
import qualified Data.Text as T
import qualified Formatting as F
import Yesod.Hashids
import Vervis.Access
import Vervis.Model
import Vervis.Model.Ident
import Vervis.Model.Role
import Vervis.Path
import Vervis.Settings
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
type ChannelBase = LoggingT (ReaderT ConnectionPool IO)
type SessionBase = LoggingT (ReaderT ConnectionPool IO)
type UserAuthId = PersonId
type Channel = ChannelT UserAuthId ChannelBase
type Session = SessionT SessionBase UserAuthId ChannelBase
type SshChanDB = SqlPersistT Channel
type SshSessDB = SqlPersistT Session
data Action
= DarcsTransferMode (KeyHashid Repo)
| DarcsApply (KeyHashid Repo)
| GitUploadPack (KeyHashid Repo)
| GitReceivePack (KeyHashid Repo)
deriving Show
-- | Result of running an action on the server side as a response to an SSH
-- channel request.
data ActionResult
= ARDone Text -- ^ Action finished successfully with message
| ARProcess -- ^ Action executed process, the rest depends on the process
| ARFail Text -- ^ Action failed with message
-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
src :: Text
src = "SSH"
runChanDB :: SshChanDB a -> Channel a
runChanDB action = do
pool <- lift . lift $ ask
runSqlPool action pool
runSessDB :: SshSessDB a -> Session a
runSessDB action = do
pool <- lift . lift $ ask
runSqlPool action pool
-------------------------------------------------------------------------------
-- Auth
-------------------------------------------------------------------------------
authorize :: Authorize -> Session (AuthResult UserAuthId)
authorize (Password _ _) = return AuthFail
authorize (PublicKey name key) = do
mpk <- runSessDB $ do
mp <- getBy $ UniquePersonLogin $ T.pack name
case mp of
Nothing -> return Nothing
Just (Entity pid _p) -> do
ks <- selectList [SshKeyPerson ==. pid] []
return $ Just (pid, ks)
case mpk of
Nothing -> do
lift $ $logInfoS src "Auth failed: Invalid user"
return AuthFail
Just (pid, keys) -> do
let eValue (Entity _ v) = v
matches =
(== key) . blobToKey . fromStrict . sshKeyContent . eValue
case find matches keys of
Nothing -> do
lift $ $logInfoS src "Auth failed: No matching key found"
return AuthFail
Just match -> do
lift $ $logInfoS src "Auth succeeded"
return $ AuthSuccess pid
-------------------------------------------------------------------------------
-- Actions
-------------------------------------------------------------------------------
toKeyHashid t =
case fromPathPiece t of
Nothing -> fail "Can't parse keyhashid"
Just kh -> return kh
--TOD TODO TODO check paths for safety... no /./ or /../ and so on
darcsRepoSpecP :: Parser (KeyHashid Repo)
darcsRepoSpecP = toKeyHashid =<< (part <* optional (char '/'))
where
part = takeWhile1 $ \ c -> c /= '/' && c /= '\''
gitRepoSpecP :: Parser (KeyHashid Repo)
gitRepoSpecP = toKeyHashid =<< (msh *> part)
where
part = takeWhile1 $ \ c -> c /= '/' && c /= '\''
msh = optional $ satisfy $ \ c -> c == '/' || c == '~'
actionP :: Parser Action
actionP = DarcsTransferMode <$>
("darcs transfer-mode --repodir " *> darcsRepoSpecP)
<|> DarcsApply <$>
("darcs apply --all --repodir '" *> darcsRepoSpecP <* char '\'')
<|> GitUploadPack <$>
("git-upload-pack '" *> gitRepoSpecP <* char '\'')
<|> GitReceivePack <$>
("git-receive-pack '" *> gitRepoSpecP <* char '\'')
parseExec :: Text -> Either String Action
parseExec input = parseOnly (actionP <* endOfInput) input
detectAction :: ChannelRequest -> Either Text Action
detectAction (Execute s) =
case parseExec $ T.pack s of
Left _ -> Left "Unsupported command"
Right action -> Right action
detectAction _ = Left "Unsupported channel request"
execute :: FilePath -> [String] -> Channel ()
execute cmd args = do
lift $ $logDebugS src $
F.sformat ("Executing " % F.string % " " % F.shown) cmd args
let config = (proc cmd args)
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
}
verifyPipe Nothing = error "createProcess didn't create all the pipes"
verifyPipe (Just h) = h
verifyPipes (mIn, mOut, mErr, ph) =
(verifyPipe mIn, verifyPipe mOut, verifyPipe mErr, ph)
spawnProcess $ verifyPipes <$> createProcess config
whenRepoExists
:: Text
-> (FilePath -> IO Bool)
-> Bool
-> FilePath
-> Channel ActionResult
-> Channel ActionResult
whenRepoExists vcs checkFS checkedDB repoPath action = do
looksGood <- liftIO $ checkFS repoPath
if looksGood
then action
else do
when checkedDB $ lift $ $logErrorS src $
T.concat [vcs, " repo not found! ", T.pack repoPath]
return $ ARFail $ T.concat ["No such ", vcs, " repository"]
whenDarcsRepoExists
:: Bool -> FilePath -> Channel ActionResult -> Channel ActionResult
whenDarcsRepoExists =
whenRepoExists "Darcs" $ doesDirectoryExist . (</> "_darcs")
whenGitRepoExists
:: Bool -> FilePath -> Channel ActionResult -> Channel ActionResult
whenGitRepoExists = whenRepoExists "Git" $ isRepo . fromString
canPushTo :: RepoId -> Channel Bool
canPushTo repoID = do
pid <- authId <$> askAuthDetails
oas <- runChanDB $ checkRepoAccess' (Just pid) ProjOpPush repoID
return $
case oas of
ObjectAccessAllowed -> True
_ -> False
runAction
:: (KeyHashid Repo -> Maybe RepoId)
-> FilePath
-> Bool
-> Action
-> Channel ActionResult
runAction decodeRepoHash root _wantReply action =
case action of
DarcsTransferMode repoHash -> do
let repoPath = repoDir root repoHash
whenDarcsRepoExists False repoPath $ do
execute "darcs" ["transfer-mode", "--repodir", repoPath]
return ARProcess
DarcsApply repoHash -> do
let repoPath = repoDir root repoHash
can <-
case decodeRepoHash repoHash of
Nothing -> return False
Just repoID -> canPushTo repoID
if can
then whenDarcsRepoExists True repoPath $ do
pid <- authId <$> askAuthDetails
liftIO $ setEnv "VERVIS_SSH_USER" (show $ fromSqlKey pid)
execute "darcs" ["apply", "--all", "--repodir", repoPath]
return ARProcess
else return $ ARFail "You can't push to this repository"
GitUploadPack repoHash -> do
let repoPath = repoDir root repoHash
whenGitRepoExists False repoPath $ do
execute "git-upload-pack" [repoPath]
return ARProcess
GitReceivePack repoHash -> do
let repoPath = repoDir root repoHash
can <-
case decodeRepoHash repoHash of
Nothing -> return False
Just repoID -> canPushTo repoID
if can
then whenGitRepoExists True repoPath $ do
pid <- authId <$> askAuthDetails
liftIO $ setEnv "VERVIS_SSH_USER" (show $ fromSqlKey pid)
execute "git-receive-pack" [repoPath]
return ARProcess
else return $ ARFail "You can't push to this repository"
handle
:: (KeyHashid Repo -> Maybe RepoId)
-> FilePath
-> Bool
-> ChannelRequest
-> Channel ()
handle decodeRepoHash repoDir wantReply request = do
lift $ $logDebugS src $ T.pack $ show request
case detectAction request of
Left e -> do
lift $ $logDebugS src $ "Invalid action: " <> e
channelError $ T.unpack e
when wantReply channelFail
Right act -> do
lift $ $logDebugS src $ T.pack $ show act
res <- runAction decodeRepoHash repoDir wantReply act
case res of
ARDone msg -> do
lift $ $logDebugS src $ "Action done: " <> msg
channelMessage $ T.unpack msg
when wantReply channelSuccess
channelDone
ARProcess -> do
lift $ $logDebugS src "Action ran process"
when wantReply channelSuccess
ARFail msg -> do
lift $ $logDebugS src $ "Action failed: " <> msg
channelError $ T.unpack msg
when wantReply channelSuccess
channelDone
-------------------------------------------------------------------------------
-- Config and running
-------------------------------------------------------------------------------
ready :: LogFunc -> IO ()
ready = runLoggingT $ $logInfoS src "SSH server component starting"
mkConfig
:: AppSettings
-> HashidsContext
-> ConnectionPool
-> LogFunc
-> IO (Config SessionBase ChannelBase UserAuthId)
mkConfig settings ctx pool logFunc = do
keyPair <- keyPairFromFile $ appSshKeyFile settings
return $ Config
{ cSession = SessionConfig
{ scAuthMethods = ["publickey"]
, scAuthorize = authorize
, scKeyPair = keyPair
, scRunBaseMonad =
flip runReaderT pool . flip runLoggingT logFunc
}
, cChannel = ChannelConfig
{ ccRequestHandler = handle (decodeKeyHashidPure ctx) (appRepoDir settings)
, ccRunBaseMonad =
flip runReaderT pool . flip runLoggingT logFunc
}
, cPort = fromIntegral $ appSshPort settings
, cReadyAction = ready logFunc
}
runSsh :: AppSettings -> HashidsContext -> ConnectionPool -> LogFunc -> IO ()
runSsh settings ctx pool logFunc = do
config <- mkConfig settings ctx pool logFunc
startConfig config
|