dataprovider.go 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949
  1. // Package dataprovider provides data access.
  2. // It abstracts different data providers and exposes a common API.
  3. package dataprovider
  4. import (
  5. "bufio"
  6. "bytes"
  7. "context"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "crypto/sha512"
  11. "crypto/subtle"
  12. "crypto/x509"
  13. "encoding/base64"
  14. "encoding/json"
  15. "errors"
  16. "fmt"
  17. "hash"
  18. "io"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "os/exec"
  24. "path"
  25. "path/filepath"
  26. "regexp"
  27. "runtime"
  28. "strconv"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/GehirnInc/crypt"
  34. "github.com/GehirnInc/crypt/apr1_crypt"
  35. "github.com/GehirnInc/crypt/md5_crypt"
  36. "github.com/GehirnInc/crypt/sha512_crypt"
  37. "github.com/alexedwards/argon2id"
  38. "github.com/go-chi/render"
  39. "github.com/rs/xid"
  40. passwordvalidator "github.com/wagslane/go-password-validator"
  41. "golang.org/x/crypto/bcrypt"
  42. "golang.org/x/crypto/pbkdf2"
  43. "golang.org/x/crypto/ssh"
  44. "github.com/drakkan/sftpgo/v2/httpclient"
  45. "github.com/drakkan/sftpgo/v2/kms"
  46. "github.com/drakkan/sftpgo/v2/logger"
  47. "github.com/drakkan/sftpgo/v2/metric"
  48. "github.com/drakkan/sftpgo/v2/mfa"
  49. "github.com/drakkan/sftpgo/v2/sdk"
  50. "github.com/drakkan/sftpgo/v2/sdk/plugin"
  51. "github.com/drakkan/sftpgo/v2/util"
  52. "github.com/drakkan/sftpgo/v2/vfs"
  53. )
  54. const (
  55. // SQLiteDataProviderName defines the name for SQLite database provider
  56. SQLiteDataProviderName = "sqlite"
  57. // PGSQLDataProviderName defines the name for PostgreSQL database provider
  58. PGSQLDataProviderName = "postgresql"
  59. // MySQLDataProviderName defines the name for MySQL database provider
  60. MySQLDataProviderName = "mysql"
  61. // BoltDataProviderName defines the name for bbolt key/value store provider
  62. BoltDataProviderName = "bolt"
  63. // MemoryDataProviderName defines the name for memory provider
  64. MemoryDataProviderName = "memory"
  65. // CockroachDataProviderName defines the for CockroachDB provider
  66. CockroachDataProviderName = "cockroachdb"
  67. // DumpVersion defines the version for the dump.
  68. // For restore/load we support the current version and the previous one
  69. DumpVersion = 10
  70. argonPwdPrefix = "$argon2id$"
  71. bcryptPwdPrefix = "$2a$"
  72. pbkdf2SHA1Prefix = "$pbkdf2-sha1$"
  73. pbkdf2SHA256Prefix = "$pbkdf2-sha256$"
  74. pbkdf2SHA512Prefix = "$pbkdf2-sha512$"
  75. pbkdf2SHA256B64SaltPrefix = "$pbkdf2-b64salt-sha256$"
  76. md5cryptPwdPrefix = "$1$"
  77. md5cryptApr1PwdPrefix = "$apr1$"
  78. sha512cryptPwdPrefix = "$6$"
  79. trackQuotaDisabledError = "please enable track_quota in your configuration to use this method"
  80. operationAdd = "add"
  81. operationUpdate = "update"
  82. operationDelete = "delete"
  83. sqlPrefixValidChars = "abcdefghijklmnopqrstuvwxyz_0123456789"
  84. maxHookResponseSize = 1048576 // 1MB
  85. )
  86. // Supported algorithms for hashing passwords.
  87. // These algorithms can be used when SFTPGo hashes a plain text password
  88. const (
  89. HashingAlgoBcrypt = "bcrypt"
  90. HashingAlgoArgon2ID = "argon2id"
  91. )
  92. // ordering constants
  93. const (
  94. OrderASC = "ASC"
  95. OrderDESC = "DESC"
  96. )
  97. const (
  98. protocolSSH = "SSH"
  99. protocolFTP = "FTP"
  100. protocolWebDAV = "DAV"
  101. protocolHTTP = "HTTP"
  102. )
  103. var (
  104. // SupportedProviders defines the supported data providers
  105. SupportedProviders = []string{SQLiteDataProviderName, PGSQLDataProviderName, MySQLDataProviderName,
  106. BoltDataProviderName, MemoryDataProviderName, CockroachDataProviderName}
  107. // ValidPerms defines all the valid permissions for a user
  108. ValidPerms = []string{PermAny, PermListItems, PermDownload, PermUpload, PermOverwrite, PermCreateDirs, PermRename,
  109. PermRenameFiles, PermRenameDirs, PermDelete, PermDeleteFiles, PermDeleteDirs, PermCreateSymlinks, PermChmod,
  110. PermChown, PermChtimes}
  111. // ValidLoginMethods defines all the valid login methods
  112. ValidLoginMethods = []string{SSHLoginMethodPublicKey, LoginMethodPassword, SSHLoginMethodKeyboardInteractive,
  113. SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt, LoginMethodTLSCertificate,
  114. LoginMethodTLSCertificateAndPwd}
  115. // SSHMultiStepsLoginMethods defines the supported Multi-Step Authentications
  116. SSHMultiStepsLoginMethods = []string{SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt}
  117. // ErrNoAuthTryed defines the error for connection closed before authentication
  118. ErrNoAuthTryed = errors.New("no auth tryed")
  119. // ValidProtocols defines all the valid protcols
  120. ValidProtocols = []string{protocolSSH, protocolFTP, protocolWebDAV, protocolHTTP}
  121. // MFAProtocols defines the supported protocols for multi-factor authentication
  122. MFAProtocols = []string{protocolHTTP, protocolSSH, protocolFTP}
  123. // ErrNoInitRequired defines the error returned by InitProvider if no inizialization/update is required
  124. ErrNoInitRequired = errors.New("the data provider is up to date")
  125. // ErrInvalidCredentials defines the error to return if the supplied credentials are invalid
  126. ErrInvalidCredentials = errors.New("invalid credentials")
  127. // ErrLoginNotAllowedFromIP defines the error to return if login is denied from the current IP
  128. ErrLoginNotAllowedFromIP = errors.New("login is not allowed from this IP")
  129. isAdminCreated = int32(0)
  130. validTLSUsernames = []string{string(sdk.TLSUsernameNone), string(sdk.TLSUsernameCN)}
  131. config Config
  132. provider Provider
  133. sqlPlaceholders []string
  134. internalHashPwdPrefixes = []string{argonPwdPrefix, bcryptPwdPrefix}
  135. hashPwdPrefixes = []string{argonPwdPrefix, bcryptPwdPrefix, pbkdf2SHA1Prefix, pbkdf2SHA256Prefix,
  136. pbkdf2SHA512Prefix, pbkdf2SHA256B64SaltPrefix, md5cryptPwdPrefix, md5cryptApr1PwdPrefix, sha512cryptPwdPrefix}
  137. pbkdfPwdPrefixes = []string{pbkdf2SHA1Prefix, pbkdf2SHA256Prefix, pbkdf2SHA512Prefix, pbkdf2SHA256B64SaltPrefix}
  138. pbkdfPwdB64SaltPrefixes = []string{pbkdf2SHA256B64SaltPrefix}
  139. unixPwdPrefixes = []string{md5cryptPwdPrefix, md5cryptApr1PwdPrefix, sha512cryptPwdPrefix}
  140. sharedProviders = []string{PGSQLDataProviderName, MySQLDataProviderName, CockroachDataProviderName}
  141. logSender = "dataProvider"
  142. availabilityTicker *time.Ticker
  143. availabilityTickerDone chan bool
  144. updateCachesTicker *time.Ticker
  145. updateCachesTickerDone chan bool
  146. lastCachesUpdate int64
  147. credentialsDirPath string
  148. sqlTableUsers = "users"
  149. sqlTableFolders = "folders"
  150. sqlTableFoldersMapping = "folders_mapping"
  151. sqlTableAdmins = "admins"
  152. sqlTableAPIKeys = "api_keys"
  153. sqlTableShares = "shares"
  154. sqlTableSchemaVersion = "schema_version"
  155. argon2Params *argon2id.Params
  156. lastLoginMinDelay = 10 * time.Minute
  157. usernameRegex = regexp.MustCompile("^[a-zA-Z0-9-_.~]+$")
  158. tempPath string
  159. )
  160. type schemaVersion struct {
  161. Version int
  162. }
  163. // BcryptOptions defines the options for bcrypt password hashing
  164. type BcryptOptions struct {
  165. Cost int `json:"cost" mapstructure:"cost"`
  166. }
  167. // Argon2Options defines the options for argon2 password hashing
  168. type Argon2Options struct {
  169. Memory uint32 `json:"memory" mapstructure:"memory"`
  170. Iterations uint32 `json:"iterations" mapstructure:"iterations"`
  171. Parallelism uint8 `json:"parallelism" mapstructure:"parallelism"`
  172. }
  173. // PasswordHashing defines the configuration for password hashing
  174. type PasswordHashing struct {
  175. BcryptOptions BcryptOptions `json:"bcrypt_options" mapstructure:"bcrypt_options"`
  176. Argon2Options Argon2Options `json:"argon2_options" mapstructure:"argon2_options"`
  177. // Algorithm to use for hashing passwords. Available algorithms: argon2id, bcrypt. Default: bcrypt
  178. Algo string `json:"algo" mapstructure:"algo"`
  179. }
  180. // PasswordValidationRules defines the password validation rules
  181. type PasswordValidationRules struct {
  182. // MinEntropy defines the minimum password entropy.
  183. // 0 means disabled, any password will be accepted.
  184. // Take a look at the following link for more details
  185. // https://github.com/wagslane/go-password-validator#what-entropy-value-should-i-use
  186. MinEntropy float64 `json:"min_entropy" mapstructure:"min_entropy"`
  187. }
  188. // PasswordValidation defines the password validation rules for admins and protocol users
  189. type PasswordValidation struct {
  190. // Password validation rules for SFTPGo admin users
  191. Admins PasswordValidationRules `json:"admins" mapstructure:"admins"`
  192. // Password validation rules for SFTPGo protocol users
  193. Users PasswordValidationRules `json:"users" mapstructure:"users"`
  194. }
  195. // ObjectsActions defines the action to execute on user create, update, delete for the specified objects
  196. type ObjectsActions struct {
  197. // Valid values are add, update, delete. Empty slice to disable
  198. ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
  199. // Valid values are user, admin, api_key
  200. ExecuteFor []string `json:"execute_for" mapstructure:"execute_for"`
  201. // Absolute path to an external program or an HTTP URL
  202. Hook string `json:"hook" mapstructure:"hook"`
  203. }
  204. // ProviderStatus defines the provider status
  205. type ProviderStatus struct {
  206. Driver string `json:"driver"`
  207. IsActive bool `json:"is_active"`
  208. Error string `json:"error"`
  209. }
  210. // Config provider configuration
  211. type Config struct {
  212. // Driver name, must be one of the SupportedProviders
  213. Driver string `json:"driver" mapstructure:"driver"`
  214. // Database name. For driver sqlite this can be the database name relative to the config dir
  215. // or the absolute path to the SQLite database.
  216. Name string `json:"name" mapstructure:"name"`
  217. // Database host
  218. Host string `json:"host" mapstructure:"host"`
  219. // Database port
  220. Port int `json:"port" mapstructure:"port"`
  221. // Database username
  222. Username string `json:"username" mapstructure:"username"`
  223. // Database password
  224. Password string `json:"password" mapstructure:"password"`
  225. // Used for drivers mysql and postgresql.
  226. // 0 disable SSL/TLS connections.
  227. // 1 require ssl.
  228. // 2 set ssl mode to verify-ca for driver postgresql and skip-verify for driver mysql.
  229. // 3 set ssl mode to verify-full for driver postgresql and preferred for driver mysql.
  230. SSLMode int `json:"sslmode" mapstructure:"sslmode"`
  231. // Custom database connection string.
  232. // If not empty this connection string will be used instead of build one using the previous parameters
  233. ConnectionString string `json:"connection_string" mapstructure:"connection_string"`
  234. // prefix for SQL tables
  235. SQLTablesPrefix string `json:"sql_tables_prefix" mapstructure:"sql_tables_prefix"`
  236. // Set the preferred way to track users quota between the following choices:
  237. // 0, disable quota tracking. REST API to scan user dir and update quota will do nothing
  238. // 1, quota is updated each time a user upload or delete a file even if the user has no quota restrictions
  239. // 2, quota is updated each time a user upload or delete a file but only for users with quota restrictions
  240. // and for virtual folders.
  241. // With this configuration the "quota scan" REST API can still be used to periodically update space usage
  242. // for users without quota restrictions
  243. TrackQuota int `json:"track_quota" mapstructure:"track_quota"`
  244. // Sets the maximum number of open connections for mysql and postgresql driver.
  245. // Default 0 (unlimited)
  246. PoolSize int `json:"pool_size" mapstructure:"pool_size"`
  247. // Users default base directory.
  248. // If no home dir is defined while adding a new user, and this value is
  249. // a valid absolute path, then the user home dir will be automatically
  250. // defined as the path obtained joining the base dir and the username
  251. UsersBaseDir string `json:"users_base_dir" mapstructure:"users_base_dir"`
  252. // Actions to execute on objects add, update, delete.
  253. // The supported objects are user, admin, api_key.
  254. // Update action will not be fired for internal updates such as the last login or the user quota fields.
  255. Actions ObjectsActions `json:"actions" mapstructure:"actions"`
  256. // Absolute path to an external program or an HTTP URL to invoke for users authentication.
  257. // Leave empty to use builtin authentication.
  258. // If the authentication succeed the user will be automatically added/updated inside the defined data provider.
  259. // Actions defined for user added/updated will not be executed in this case.
  260. // This method is slower than built-in authentication methods, but it's very flexible as anyone can
  261. // easily write his own authentication hooks.
  262. ExternalAuthHook string `json:"external_auth_hook" mapstructure:"external_auth_hook"`
  263. // ExternalAuthScope defines the scope for the external authentication hook.
  264. // - 0 means all supported authentication scopes, the external hook will be executed for password,
  265. // public key, keyboard interactive authentication and TLS certificates
  266. // - 1 means passwords only
  267. // - 2 means public keys only
  268. // - 4 means keyboard interactive only
  269. // - 8 means TLS certificates only
  270. // you can combine the scopes, for example 3 means password and public key, 5 password and keyboard
  271. // interactive and so on
  272. ExternalAuthScope int `json:"external_auth_scope" mapstructure:"external_auth_scope"`
  273. // CredentialsPath defines the directory for storing user provided credential files such as
  274. // Google Cloud Storage credentials. It can be a path relative to the config dir or an
  275. // absolute path
  276. CredentialsPath string `json:"credentials_path" mapstructure:"credentials_path"`
  277. // Absolute path to an external program or an HTTP URL to invoke just before the user login.
  278. // This program/URL allows to modify or create the user trying to login.
  279. // It is useful if you have users with dynamic fields to update just before the login.
  280. // Please note that if you want to create a new user, the pre-login hook response must
  281. // include all the mandatory user fields.
  282. //
  283. // The pre-login hook must finish within 30 seconds.
  284. //
  285. // If an error happens while executing the "PreLoginHook" then login will be denied.
  286. // PreLoginHook and ExternalAuthHook are mutally exclusive.
  287. // Leave empty to disable.
  288. PreLoginHook string `json:"pre_login_hook" mapstructure:"pre_login_hook"`
  289. // Absolute path to an external program or an HTTP URL to invoke after the user login.
  290. // Based on the configured scope you can choose if notify failed or successful logins
  291. // or both
  292. PostLoginHook string `json:"post_login_hook" mapstructure:"post_login_hook"`
  293. // PostLoginScope defines the scope for the post-login hook.
  294. // - 0 means notify both failed and successful logins
  295. // - 1 means notify failed logins
  296. // - 2 means notify successful logins
  297. PostLoginScope int `json:"post_login_scope" mapstructure:"post_login_scope"`
  298. // Absolute path to an external program or an HTTP URL to invoke just before password
  299. // authentication. This hook allows you to externally check the provided password,
  300. // its main use case is to allow to easily support things like password+OTP for protocols
  301. // without keyboard interactive support such as FTP and WebDAV. You can ask your users
  302. // to login using a string consisting of a fixed password and a One Time Token, you
  303. // can verify the token inside the hook and ask to SFTPGo to verify the fixed part.
  304. CheckPasswordHook string `json:"check_password_hook" mapstructure:"check_password_hook"`
  305. // CheckPasswordScope defines the scope for the check password hook.
  306. // - 0 means all protocols
  307. // - 1 means SSH
  308. // - 2 means FTP
  309. // - 4 means WebDAV
  310. // you can combine the scopes, for example 6 means FTP and WebDAV
  311. CheckPasswordScope int `json:"check_password_scope" mapstructure:"check_password_scope"`
  312. // Defines how the database will be initialized/updated:
  313. // - 0 means automatically
  314. // - 1 means manually using the initprovider sub-command
  315. UpdateMode int `json:"update_mode" mapstructure:"update_mode"`
  316. // PasswordHashing defines the configuration for password hashing
  317. PasswordHashing PasswordHashing `json:"password_hashing" mapstructure:"password_hashing"`
  318. // PreferDatabaseCredentials indicates whether credential files (currently used for Google
  319. // Cloud Storage) should be stored in the database instead of in the directory specified by
  320. // CredentialsPath.
  321. PreferDatabaseCredentials bool `json:"prefer_database_credentials" mapstructure:"prefer_database_credentials"`
  322. // SkipNaturalKeysValidation allows to use any UTF-8 character for natural keys as username, admin name,
  323. // folder name. These keys are used in URIs for REST API and Web admin. By default only unreserved URI
  324. // characters are allowed: ALPHA / DIGIT / "-" / "." / "_" / "~".
  325. SkipNaturalKeysValidation bool `json:"skip_natural_keys_validation" mapstructure:"skip_natural_keys_validation"`
  326. // PasswordValidation defines the password validation rules
  327. PasswordValidation PasswordValidation `json:"password_validation" mapstructure:"password_validation"`
  328. // Verifying argon2 passwords has a high memory and computational cost,
  329. // by enabling, in memory, password caching you reduce this cost.
  330. PasswordCaching bool `json:"password_caching" mapstructure:"password_caching"`
  331. // DelayedQuotaUpdate defines the number of seconds to accumulate quota updates.
  332. // If there are a lot of close uploads, accumulating quota updates can save you many
  333. // queries to the data provider.
  334. // If you want to track quotas, a scheduled quota update is recommended in any case, the stored
  335. // quota size may be incorrect for several reasons, such as an unexpected shutdown, temporary provider
  336. // failures, file copied outside of SFTPGo, and so on.
  337. // 0 means immediate quota update.
  338. DelayedQuotaUpdate int `json:"delayed_quota_update" mapstructure:"delayed_quota_update"`
  339. // If enabled, a default admin user with username "admin" and password "password" will be created
  340. // on first start.
  341. // You can also create the first admin user by using the web interface or by loading initial data.
  342. CreateDefaultAdmin bool `json:"create_default_admin" mapstructure:"create_default_admin"`
  343. // If the data provider is shared across multiple SFTPGo instances, set this parameter to 1.
  344. // MySQL, PostgreSQL and CockroachDB can be shared, this setting is ignored for other data
  345. // providers. For shared data providers, SFTPGo periodically reloads the latest updated users,
  346. // based on the "updated_at" field, and updates its internal caches if users are updated from
  347. // a different instance. This check, if enabled, is executed every 10 minutes
  348. IsShared int `json:"is_shared" mapstructure:"is_shared"`
  349. }
  350. // BackupData defines the structure for the backup/restore files
  351. type BackupData struct {
  352. Users []User `json:"users"`
  353. Folders []vfs.BaseVirtualFolder `json:"folders"`
  354. Admins []Admin `json:"admins"`
  355. APIKeys []APIKey `json:"api_keys"`
  356. Shares []Share `json:"shares"`
  357. Version int `json:"version"`
  358. }
  359. // HasFolder returns true if the folder with the given name is included
  360. func (d *BackupData) HasFolder(name string) bool {
  361. for _, folder := range d.Folders {
  362. if folder.Name == name {
  363. return true
  364. }
  365. }
  366. return false
  367. }
  368. type checkPasswordRequest struct {
  369. Username string `json:"username"`
  370. IP string `json:"ip"`
  371. Password string `json:"password"`
  372. Protocol string `json:"protocol"`
  373. }
  374. type checkPasswordResponse struct {
  375. // 0 KO, 1 OK, 2 partial success, -1 not executed
  376. Status int `json:"status"`
  377. // for status = 2 this is the password to check against the one stored
  378. // inside the SFTPGo data provider
  379. ToVerify string `json:"to_verify"`
  380. }
  381. // GetQuotaTracking returns the configured mode for user's quota tracking
  382. func GetQuotaTracking() int {
  383. return config.TrackQuota
  384. }
  385. // Provider defines the interface that data providers must implement.
  386. type Provider interface {
  387. validateUserAndPass(username, password, ip, protocol string) (User, error)
  388. validateUserAndPubKey(username string, pubKey []byte) (User, string, error)
  389. validateUserAndTLSCert(username, protocol string, tlsCert *x509.Certificate) (User, error)
  390. updateQuota(username string, filesAdd int, sizeAdd int64, reset bool) error
  391. getUsedQuota(username string) (int, int64, error)
  392. userExists(username string) (User, error)
  393. addUser(user *User) error
  394. updateUser(user *User) error
  395. deleteUser(user *User) error
  396. getUsers(limit int, offset int, order string) ([]User, error)
  397. dumpUsers() ([]User, error)
  398. getRecentlyUpdatedUsers(after int64) ([]User, error)
  399. updateLastLogin(username string) error
  400. updateAdminLastLogin(username string) error
  401. setUpdatedAt(username string)
  402. getFolders(limit, offset int, order string) ([]vfs.BaseVirtualFolder, error)
  403. getFolderByName(name string) (vfs.BaseVirtualFolder, error)
  404. addFolder(folder *vfs.BaseVirtualFolder) error
  405. updateFolder(folder *vfs.BaseVirtualFolder) error
  406. deleteFolder(folder *vfs.BaseVirtualFolder) error
  407. updateFolderQuota(name string, filesAdd int, sizeAdd int64, reset bool) error
  408. getUsedFolderQuota(name string) (int, int64, error)
  409. dumpFolders() ([]vfs.BaseVirtualFolder, error)
  410. adminExists(username string) (Admin, error)
  411. addAdmin(admin *Admin) error
  412. updateAdmin(admin *Admin) error
  413. deleteAdmin(admin *Admin) error
  414. getAdmins(limit int, offset int, order string) ([]Admin, error)
  415. dumpAdmins() ([]Admin, error)
  416. validateAdminAndPass(username, password, ip string) (Admin, error)
  417. apiKeyExists(keyID string) (APIKey, error)
  418. addAPIKey(apiKey *APIKey) error
  419. updateAPIKey(apiKey *APIKey) error
  420. deleteAPIKey(apiKey *APIKey) error
  421. getAPIKeys(limit int, offset int, order string) ([]APIKey, error)
  422. dumpAPIKeys() ([]APIKey, error)
  423. updateAPIKeyLastUse(keyID string) error
  424. shareExists(shareID, username string) (Share, error)
  425. addShare(share *Share) error
  426. updateShare(share *Share) error
  427. deleteShare(share *Share) error
  428. getShares(limit int, offset int, order, username string) ([]Share, error)
  429. dumpShares() ([]Share, error)
  430. updateShareLastUse(shareID string, numTokens int) error
  431. checkAvailability() error
  432. close() error
  433. reloadConfig() error
  434. initializeDatabase() error
  435. migrateDatabase() error
  436. revertDatabase(targetVersion int) error
  437. resetDatabase() error
  438. }
  439. // SetTempPath sets the path for temporary files
  440. func SetTempPath(fsPath string) {
  441. tempPath = fsPath
  442. }
  443. // Initialize the data provider.
  444. // An error is returned if the configured driver is invalid or if the data provider cannot be initialized
  445. func Initialize(cnf Config, basePath string, checkAdmins bool) error {
  446. var err error
  447. config = cnf
  448. if filepath.IsAbs(config.CredentialsPath) {
  449. credentialsDirPath = config.CredentialsPath
  450. } else {
  451. credentialsDirPath = filepath.Join(basePath, config.CredentialsPath)
  452. }
  453. vfs.SetCredentialsDirPath(credentialsDirPath)
  454. if err = initializeHashingAlgo(&cnf); err != nil {
  455. return err
  456. }
  457. if err = validateHooks(); err != nil {
  458. return err
  459. }
  460. err = createProvider(basePath)
  461. if err != nil {
  462. return err
  463. }
  464. if cnf.UpdateMode == 0 {
  465. err = provider.initializeDatabase()
  466. if err != nil && err != ErrNoInitRequired {
  467. logger.WarnToConsole("Unable to initialize data provider: %v", err)
  468. providerLog(logger.LevelWarn, "Unable to initialize data provider: %v", err)
  469. return err
  470. }
  471. if err == nil {
  472. logger.DebugToConsole("Data provider successfully initialized")
  473. }
  474. err = provider.migrateDatabase()
  475. if err != nil && err != ErrNoInitRequired {
  476. providerLog(logger.LevelWarn, "database migration error: %v", err)
  477. return err
  478. }
  479. if checkAdmins && cnf.CreateDefaultAdmin {
  480. err = checkDefaultAdmin()
  481. if err != nil {
  482. providerLog(logger.LevelWarn, "check default admin error: %v", err)
  483. return err
  484. }
  485. }
  486. } else {
  487. providerLog(logger.LevelInfo, "database initialization/migration skipped, manual mode is configured")
  488. }
  489. admins, err := provider.getAdmins(1, 0, OrderASC)
  490. if err != nil {
  491. return err
  492. }
  493. atomic.StoreInt32(&isAdminCreated, int32(len(admins)))
  494. startAvailabilityTimer()
  495. startUpdateCachesTimer()
  496. delayedQuotaUpdater.start()
  497. return nil
  498. }
  499. func validateHooks() error {
  500. var hooks []string
  501. if config.PreLoginHook != "" && !strings.HasPrefix(config.PreLoginHook, "http") {
  502. hooks = append(hooks, config.PreLoginHook)
  503. }
  504. if config.ExternalAuthHook != "" && !strings.HasPrefix(config.ExternalAuthHook, "http") {
  505. hooks = append(hooks, config.ExternalAuthHook)
  506. }
  507. if config.PostLoginHook != "" && !strings.HasPrefix(config.PostLoginHook, "http") {
  508. hooks = append(hooks, config.PostLoginHook)
  509. }
  510. if config.CheckPasswordHook != "" && !strings.HasPrefix(config.CheckPasswordHook, "http") {
  511. hooks = append(hooks, config.CheckPasswordHook)
  512. }
  513. for _, hook := range hooks {
  514. if !filepath.IsAbs(hook) {
  515. return fmt.Errorf("invalid hook: %#v must be an absolute path", hook)
  516. }
  517. _, err := os.Stat(hook)
  518. if err != nil {
  519. providerLog(logger.LevelWarn, "invalid hook: %v", err)
  520. return err
  521. }
  522. }
  523. return nil
  524. }
  525. func initializeHashingAlgo(cnf *Config) error {
  526. argon2Params = &argon2id.Params{
  527. Memory: cnf.PasswordHashing.Argon2Options.Memory,
  528. Iterations: cnf.PasswordHashing.Argon2Options.Iterations,
  529. Parallelism: cnf.PasswordHashing.Argon2Options.Parallelism,
  530. SaltLength: 16,
  531. KeyLength: 32,
  532. }
  533. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  534. if config.PasswordHashing.BcryptOptions.Cost > bcrypt.MaxCost {
  535. err := fmt.Errorf("invalid bcrypt cost %v, max allowed %v", config.PasswordHashing.BcryptOptions.Cost, bcrypt.MaxCost)
  536. logger.WarnToConsole("Unable to initialize data provider: %v", err)
  537. providerLog(logger.LevelWarn, "Unable to initialize data provider: %v", err)
  538. return err
  539. }
  540. }
  541. return nil
  542. }
  543. func validateSQLTablesPrefix() error {
  544. if config.SQLTablesPrefix != "" {
  545. for _, char := range config.SQLTablesPrefix {
  546. if !strings.Contains(sqlPrefixValidChars, strings.ToLower(string(char))) {
  547. return errors.New("invalid sql_tables_prefix only chars in range 'a..z', 'A..Z', '0-9' and '_' are allowed")
  548. }
  549. }
  550. sqlTableUsers = config.SQLTablesPrefix + sqlTableUsers
  551. sqlTableFolders = config.SQLTablesPrefix + sqlTableFolders
  552. sqlTableFoldersMapping = config.SQLTablesPrefix + sqlTableFoldersMapping
  553. sqlTableAdmins = config.SQLTablesPrefix + sqlTableAdmins
  554. sqlTableAPIKeys = config.SQLTablesPrefix + sqlTableAPIKeys
  555. sqlTableShares = config.SQLTablesPrefix + sqlTableShares
  556. sqlTableSchemaVersion = config.SQLTablesPrefix + sqlTableSchemaVersion
  557. providerLog(logger.LevelDebug, "sql table for users %#v, folders %#v folders mapping %#v admins %#v "+
  558. "api keys %#v shares %#v schema version %#v", sqlTableUsers, sqlTableFolders, sqlTableFoldersMapping,
  559. sqlTableAdmins, sqlTableAPIKeys, sqlTableShares, sqlTableSchemaVersion)
  560. }
  561. return nil
  562. }
  563. func checkDefaultAdmin() error {
  564. admins, err := provider.getAdmins(1, 0, OrderASC)
  565. if err != nil {
  566. return err
  567. }
  568. if len(admins) > 0 {
  569. return nil
  570. }
  571. logger.Debug(logSender, "", "no admins found, try to create the default one")
  572. // we need to create the default admin
  573. admin := &Admin{}
  574. if err := admin.setFromEnv(); err != nil {
  575. return err
  576. }
  577. return provider.addAdmin(admin)
  578. }
  579. // InitializeDatabase creates the initial database structure
  580. func InitializeDatabase(cnf Config, basePath string) error {
  581. config = cnf
  582. if filepath.IsAbs(config.CredentialsPath) {
  583. credentialsDirPath = config.CredentialsPath
  584. } else {
  585. credentialsDirPath = filepath.Join(basePath, config.CredentialsPath)
  586. }
  587. err := createProvider(basePath)
  588. if err != nil {
  589. return err
  590. }
  591. err = provider.initializeDatabase()
  592. if err != nil && err != ErrNoInitRequired {
  593. return err
  594. }
  595. return provider.migrateDatabase()
  596. }
  597. // RevertDatabase restores schema and/or data to a previous version
  598. func RevertDatabase(cnf Config, basePath string, targetVersion int) error {
  599. config = cnf
  600. if filepath.IsAbs(config.CredentialsPath) {
  601. credentialsDirPath = config.CredentialsPath
  602. } else {
  603. credentialsDirPath = filepath.Join(basePath, config.CredentialsPath)
  604. }
  605. err := createProvider(basePath)
  606. if err != nil {
  607. return err
  608. }
  609. err = provider.initializeDatabase()
  610. if err != nil && err != ErrNoInitRequired {
  611. return err
  612. }
  613. return provider.revertDatabase(targetVersion)
  614. }
  615. // ResetDatabase restores schema and/or data to a previous version
  616. func ResetDatabase(cnf Config, basePath string) error {
  617. config = cnf
  618. if filepath.IsAbs(config.CredentialsPath) {
  619. credentialsDirPath = config.CredentialsPath
  620. } else {
  621. credentialsDirPath = filepath.Join(basePath, config.CredentialsPath)
  622. }
  623. if err := createProvider(basePath); err != nil {
  624. return err
  625. }
  626. return provider.resetDatabase()
  627. }
  628. // CheckAdminAndPass validates the given admin and password connecting from ip
  629. func CheckAdminAndPass(username, password, ip string) (Admin, error) {
  630. return provider.validateAdminAndPass(username, password, ip)
  631. }
  632. // CheckCachedUserCredentials checks the credentials for a cached user
  633. func CheckCachedUserCredentials(user *CachedUser, password, loginMethod, protocol string, tlsCert *x509.Certificate) error {
  634. if loginMethod != LoginMethodPassword {
  635. _, err := checkUserAndTLSCertificate(&user.User, protocol, tlsCert)
  636. if err != nil {
  637. return err
  638. }
  639. if loginMethod == LoginMethodTLSCertificate {
  640. if !user.User.IsLoginMethodAllowed(LoginMethodTLSCertificate, nil) {
  641. return fmt.Errorf("certificate login method is not allowed for user %#v", user.User.Username)
  642. }
  643. return nil
  644. }
  645. }
  646. if err := user.User.CheckLoginConditions(); err != nil {
  647. return err
  648. }
  649. if password == "" {
  650. return ErrInvalidCredentials
  651. }
  652. if user.Password != "" {
  653. if password == user.Password {
  654. return nil
  655. }
  656. } else {
  657. if ok, _ := isPasswordOK(&user.User, password); ok {
  658. return nil
  659. }
  660. }
  661. return ErrInvalidCredentials
  662. }
  663. // CheckCompositeCredentials checks multiple credentials.
  664. // WebDAV users can send both a password and a TLS certificate within the same request
  665. func CheckCompositeCredentials(username, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (User, string, error) {
  666. if loginMethod == LoginMethodPassword {
  667. user, err := CheckUserAndPass(username, password, ip, protocol)
  668. return user, loginMethod, err
  669. }
  670. user, err := CheckUserBeforeTLSAuth(username, ip, protocol, tlsCert)
  671. if err != nil {
  672. return user, loginMethod, err
  673. }
  674. if !user.IsTLSUsernameVerificationEnabled() {
  675. // for backward compatibility with 2.0.x we only check the password and change the login method here
  676. // in future updates we have to return an error
  677. user, err := CheckUserAndPass(username, password, ip, protocol)
  678. return user, LoginMethodPassword, err
  679. }
  680. user, err = checkUserAndTLSCertificate(&user, protocol, tlsCert)
  681. if err != nil {
  682. return user, loginMethod, err
  683. }
  684. if loginMethod == LoginMethodTLSCertificate && !user.IsLoginMethodAllowed(LoginMethodTLSCertificate, nil) {
  685. return user, loginMethod, fmt.Errorf("certificate login method is not allowed for user %#v", user.Username)
  686. }
  687. if loginMethod == LoginMethodTLSCertificateAndPwd {
  688. if plugin.Handler.HasAuthScope(plugin.AuthScopePassword) {
  689. user, err = doPluginAuth(username, password, nil, ip, protocol, nil, plugin.AuthScopePassword)
  690. } else if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&1 != 0) {
  691. user, err = doExternalAuth(username, password, nil, "", ip, protocol, nil)
  692. } else if config.PreLoginHook != "" {
  693. user, err = executePreLoginHook(username, LoginMethodPassword, ip, protocol)
  694. }
  695. if err != nil {
  696. return user, loginMethod, err
  697. }
  698. user, err = checkUserAndPass(&user, password, ip, protocol)
  699. }
  700. return user, loginMethod, err
  701. }
  702. // CheckUserBeforeTLSAuth checks if a user exits before trying mutual TLS
  703. func CheckUserBeforeTLSAuth(username, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
  704. if plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate) {
  705. return doPluginAuth(username, "", nil, ip, protocol, tlsCert, plugin.AuthScopeTLSCertificate)
  706. }
  707. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&8 != 0) {
  708. return doExternalAuth(username, "", nil, "", ip, protocol, tlsCert)
  709. }
  710. if config.PreLoginHook != "" {
  711. return executePreLoginHook(username, LoginMethodTLSCertificate, ip, protocol)
  712. }
  713. return UserExists(username)
  714. }
  715. // CheckUserAndTLSCert returns the SFTPGo user with the given username and check if the
  716. // given TLS certificate allow authentication without password
  717. func CheckUserAndTLSCert(username, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
  718. if plugin.Handler.HasAuthScope(plugin.AuthScopeTLSCertificate) {
  719. user, err := doPluginAuth(username, "", nil, ip, protocol, tlsCert, plugin.AuthScopeTLSCertificate)
  720. if err != nil {
  721. return user, err
  722. }
  723. return checkUserAndTLSCertificate(&user, protocol, tlsCert)
  724. }
  725. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&8 != 0) {
  726. user, err := doExternalAuth(username, "", nil, "", ip, protocol, tlsCert)
  727. if err != nil {
  728. return user, err
  729. }
  730. return checkUserAndTLSCertificate(&user, protocol, tlsCert)
  731. }
  732. if config.PreLoginHook != "" {
  733. user, err := executePreLoginHook(username, LoginMethodTLSCertificate, ip, protocol)
  734. if err != nil {
  735. return user, err
  736. }
  737. return checkUserAndTLSCertificate(&user, protocol, tlsCert)
  738. }
  739. return provider.validateUserAndTLSCert(username, protocol, tlsCert)
  740. }
  741. // CheckUserAndPass retrieves the SFTPGo user with the given username and password if a match is found or an error
  742. func CheckUserAndPass(username, password, ip, protocol string) (User, error) {
  743. if plugin.Handler.HasAuthScope(plugin.AuthScopePassword) {
  744. user, err := doPluginAuth(username, password, nil, ip, protocol, nil, plugin.AuthScopePassword)
  745. if err != nil {
  746. return user, err
  747. }
  748. return checkUserAndPass(&user, password, ip, protocol)
  749. }
  750. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&1 != 0) {
  751. user, err := doExternalAuth(username, password, nil, "", ip, protocol, nil)
  752. if err != nil {
  753. return user, err
  754. }
  755. return checkUserAndPass(&user, password, ip, protocol)
  756. }
  757. if config.PreLoginHook != "" {
  758. user, err := executePreLoginHook(username, LoginMethodPassword, ip, protocol)
  759. if err != nil {
  760. return user, err
  761. }
  762. return checkUserAndPass(&user, password, ip, protocol)
  763. }
  764. return provider.validateUserAndPass(username, password, ip, protocol)
  765. }
  766. // CheckUserAndPubKey retrieves the SFTP user with the given username and public key if a match is found or an error
  767. func CheckUserAndPubKey(username string, pubKey []byte, ip, protocol string) (User, string, error) {
  768. if plugin.Handler.HasAuthScope(plugin.AuthScopePublicKey) {
  769. user, err := doPluginAuth(username, "", pubKey, ip, protocol, nil, plugin.AuthScopePublicKey)
  770. if err != nil {
  771. return user, "", err
  772. }
  773. return checkUserAndPubKey(&user, pubKey)
  774. }
  775. if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&2 != 0) {
  776. user, err := doExternalAuth(username, "", pubKey, "", ip, protocol, nil)
  777. if err != nil {
  778. return user, "", err
  779. }
  780. return checkUserAndPubKey(&user, pubKey)
  781. }
  782. if config.PreLoginHook != "" {
  783. user, err := executePreLoginHook(username, SSHLoginMethodPublicKey, ip, protocol)
  784. if err != nil {
  785. return user, "", err
  786. }
  787. return checkUserAndPubKey(&user, pubKey)
  788. }
  789. return provider.validateUserAndPubKey(username, pubKey)
  790. }
  791. // CheckKeyboardInteractiveAuth checks the keyboard interactive authentication and returns
  792. // the authenticated user or an error
  793. func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (User, error) {
  794. var user User
  795. var err error
  796. if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
  797. user, err = doPluginAuth(username, "", nil, ip, protocol, nil, plugin.AuthScopeKeyboardInteractive)
  798. } else if config.ExternalAuthHook != "" && (config.ExternalAuthScope == 0 || config.ExternalAuthScope&4 != 0) {
  799. user, err = doExternalAuth(username, "", nil, "1", ip, protocol, nil)
  800. } else if config.PreLoginHook != "" {
  801. user, err = executePreLoginHook(username, SSHLoginMethodKeyboardInteractive, ip, protocol)
  802. } else {
  803. user, err = provider.userExists(username)
  804. }
  805. if err != nil {
  806. return user, err
  807. }
  808. return doKeyboardInteractiveAuth(&user, authHook, client, ip, protocol)
  809. }
  810. // UpdateShareLastUse updates the LastUseAt and UsedTokens for the given share
  811. func UpdateShareLastUse(share *Share, numTokens int) error {
  812. return provider.updateShareLastUse(share.ShareID, numTokens)
  813. }
  814. // UpdateAPIKeyLastUse updates the LastUseAt field for the given API key
  815. func UpdateAPIKeyLastUse(apiKey *APIKey) error {
  816. lastUse := util.GetTimeFromMsecSinceEpoch(apiKey.LastUseAt)
  817. diff := -time.Until(lastUse)
  818. if diff < 0 || diff > lastLoginMinDelay {
  819. return provider.updateAPIKeyLastUse(apiKey.KeyID)
  820. }
  821. return nil
  822. }
  823. // UpdateLastLogin updates the last login field for the given SFTPGo user
  824. func UpdateLastLogin(user *User) {
  825. lastLogin := util.GetTimeFromMsecSinceEpoch(user.LastLogin)
  826. diff := -time.Until(lastLogin)
  827. if diff < 0 || diff > lastLoginMinDelay {
  828. err := provider.updateLastLogin(user.Username)
  829. if err == nil {
  830. webDAVUsersCache.updateLastLogin(user.Username)
  831. }
  832. }
  833. }
  834. // UpdateAdminLastLogin updates the last login field for the given SFTPGo admin
  835. func UpdateAdminLastLogin(admin *Admin) {
  836. lastLogin := util.GetTimeFromMsecSinceEpoch(admin.LastLogin)
  837. diff := -time.Until(lastLogin)
  838. if diff < 0 || diff > lastLoginMinDelay {
  839. provider.updateAdminLastLogin(admin.Username) //nolint:errcheck
  840. }
  841. }
  842. // UpdateUserQuota updates the quota for the given SFTP user adding filesAdd and sizeAdd.
  843. // If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
  844. func UpdateUserQuota(user *User, filesAdd int, sizeAdd int64, reset bool) error {
  845. if config.TrackQuota == 0 {
  846. return util.NewMethodDisabledError(trackQuotaDisabledError)
  847. } else if config.TrackQuota == 2 && !reset && !user.HasQuotaRestrictions() {
  848. return nil
  849. }
  850. if filesAdd == 0 && sizeAdd == 0 && !reset {
  851. return nil
  852. }
  853. if config.DelayedQuotaUpdate == 0 || reset {
  854. if reset {
  855. delayedQuotaUpdater.resetUserQuota(user.Username)
  856. }
  857. return provider.updateQuota(user.Username, filesAdd, sizeAdd, reset)
  858. }
  859. delayedQuotaUpdater.updateUserQuota(user.Username, filesAdd, sizeAdd)
  860. return nil
  861. }
  862. // UpdateVirtualFolderQuota updates the quota for the given virtual folder adding filesAdd and sizeAdd.
  863. // If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
  864. func UpdateVirtualFolderQuota(vfolder *vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error {
  865. if config.TrackQuota == 0 {
  866. return util.NewMethodDisabledError(trackQuotaDisabledError)
  867. }
  868. if filesAdd == 0 && sizeAdd == 0 && !reset {
  869. return nil
  870. }
  871. if config.DelayedQuotaUpdate == 0 || reset {
  872. if reset {
  873. delayedQuotaUpdater.resetFolderQuota(vfolder.Name)
  874. }
  875. return provider.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd, reset)
  876. }
  877. delayedQuotaUpdater.updateFolderQuota(vfolder.Name, filesAdd, sizeAdd)
  878. return nil
  879. }
  880. // GetUsedQuota returns the used quota for the given SFTP user.
  881. func GetUsedQuota(username string) (int, int64, error) {
  882. if config.TrackQuota == 0 {
  883. return 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
  884. }
  885. files, size, err := provider.getUsedQuota(username)
  886. if err != nil {
  887. return files, size, err
  888. }
  889. delayedFiles, delayedSize := delayedQuotaUpdater.getUserPendingQuota(username)
  890. return files + delayedFiles, size + delayedSize, err
  891. }
  892. // GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.
  893. func GetUsedVirtualFolderQuota(name string) (int, int64, error) {
  894. if config.TrackQuota == 0 {
  895. return 0, 0, util.NewMethodDisabledError(trackQuotaDisabledError)
  896. }
  897. files, size, err := provider.getUsedFolderQuota(name)
  898. if err != nil {
  899. return files, size, err
  900. }
  901. delayedFiles, delayedSize := delayedQuotaUpdater.getFolderPendingQuota(name)
  902. return files + delayedFiles, size + delayedSize, err
  903. }
  904. // AddShare adds a new share
  905. func AddShare(share *Share, executor, ipAddress string) error {
  906. err := provider.addShare(share)
  907. if err == nil {
  908. executeAction(operationAdd, executor, ipAddress, actionObjectShare, share.ShareID, share)
  909. }
  910. return err
  911. }
  912. // UpdateShare updates an existing share
  913. func UpdateShare(share *Share, executor, ipAddress string) error {
  914. err := provider.updateShare(share)
  915. if err == nil {
  916. executeAction(operationUpdate, executor, ipAddress, actionObjectShare, share.ShareID, share)
  917. }
  918. return err
  919. }
  920. // DeleteShare deletes an existing share
  921. func DeleteShare(shareID string, executor, ipAddress string) error {
  922. share, err := provider.shareExists(shareID, executor)
  923. if err != nil {
  924. return err
  925. }
  926. err = provider.deleteShare(&share)
  927. if err == nil {
  928. executeAction(operationDelete, executor, ipAddress, actionObjectShare, shareID, &share)
  929. }
  930. return err
  931. }
  932. // ShareExists returns the share with the given ID if it exists
  933. func ShareExists(shareID, username string) (Share, error) {
  934. if shareID == "" {
  935. return Share{}, util.NewRecordNotFoundError(fmt.Sprintf("Share %#v does not exist", shareID))
  936. }
  937. return provider.shareExists(shareID, username)
  938. }
  939. // AddAPIKey adds a new API key
  940. func AddAPIKey(apiKey *APIKey, executor, ipAddress string) error {
  941. err := provider.addAPIKey(apiKey)
  942. if err == nil {
  943. executeAction(operationAdd, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, apiKey)
  944. }
  945. return err
  946. }
  947. // UpdateAPIKey updates an existing API key
  948. func UpdateAPIKey(apiKey *APIKey, executor, ipAddress string) error {
  949. err := provider.updateAPIKey(apiKey)
  950. if err == nil {
  951. executeAction(operationUpdate, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, apiKey)
  952. }
  953. return err
  954. }
  955. // DeleteAPIKey deletes an existing API key
  956. func DeleteAPIKey(keyID string, executor, ipAddress string) error {
  957. apiKey, err := provider.apiKeyExists(keyID)
  958. if err != nil {
  959. return err
  960. }
  961. err = provider.deleteAPIKey(&apiKey)
  962. if err == nil {
  963. executeAction(operationDelete, executor, ipAddress, actionObjectAPIKey, apiKey.KeyID, &apiKey)
  964. }
  965. return err
  966. }
  967. // APIKeyExists returns the API key with the given ID if it exists
  968. func APIKeyExists(keyID string) (APIKey, error) {
  969. if keyID == "" {
  970. return APIKey{}, util.NewRecordNotFoundError(fmt.Sprintf("API key %#v does not exist", keyID))
  971. }
  972. return provider.apiKeyExists(keyID)
  973. }
  974. // HasAdmin returns true if the first admin has been created
  975. // and so SFTPGo is ready to be used
  976. func HasAdmin() bool {
  977. return atomic.LoadInt32(&isAdminCreated) > 0
  978. }
  979. // AddAdmin adds a new SFTPGo admin
  980. func AddAdmin(admin *Admin, executor, ipAddress string) error {
  981. admin.Filters.RecoveryCodes = nil
  982. admin.Filters.TOTPConfig = TOTPConfig{
  983. Enabled: false,
  984. }
  985. err := provider.addAdmin(admin)
  986. if err == nil {
  987. atomic.StoreInt32(&isAdminCreated, 1)
  988. executeAction(operationAdd, executor, ipAddress, actionObjectAdmin, admin.Username, admin)
  989. }
  990. return err
  991. }
  992. // UpdateAdmin updates an existing SFTPGo admin
  993. func UpdateAdmin(admin *Admin, executor, ipAddress string) error {
  994. err := provider.updateAdmin(admin)
  995. if err == nil {
  996. executeAction(operationUpdate, executor, ipAddress, actionObjectAdmin, admin.Username, admin)
  997. }
  998. return err
  999. }
  1000. // DeleteAdmin deletes an existing SFTPGo admin
  1001. func DeleteAdmin(username, executor, ipAddress string) error {
  1002. admin, err := provider.adminExists(username)
  1003. if err != nil {
  1004. return err
  1005. }
  1006. err = provider.deleteAdmin(&admin)
  1007. if err == nil {
  1008. executeAction(operationDelete, executor, ipAddress, actionObjectAdmin, admin.Username, &admin)
  1009. }
  1010. return err
  1011. }
  1012. // AdminExists returns the admin with the given username if it exists
  1013. func AdminExists(username string) (Admin, error) {
  1014. return provider.adminExists(username)
  1015. }
  1016. // UserExists checks if the given SFTPGo username exists, returns an error if no match is found
  1017. func UserExists(username string) (User, error) {
  1018. return provider.userExists(username)
  1019. }
  1020. // AddUser adds a new SFTPGo user.
  1021. func AddUser(user *User, executor, ipAddress string) error {
  1022. user.Filters.RecoveryCodes = nil
  1023. user.Filters.TOTPConfig = sdk.TOTPConfig{
  1024. Enabled: false,
  1025. }
  1026. err := provider.addUser(user)
  1027. if err == nil {
  1028. executeAction(operationAdd, executor, ipAddress, actionObjectUser, user.Username, user)
  1029. }
  1030. return err
  1031. }
  1032. // UpdateUser updates an existing SFTPGo user.
  1033. func UpdateUser(user *User, executor, ipAddress string) error {
  1034. err := provider.updateUser(user)
  1035. if err == nil {
  1036. webDAVUsersCache.swap(user)
  1037. cachedPasswords.Remove(user.Username)
  1038. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, user.Username, user)
  1039. }
  1040. return err
  1041. }
  1042. // DeleteUser deletes an existing SFTPGo user.
  1043. func DeleteUser(username, executor, ipAddress string) error {
  1044. user, err := provider.userExists(username)
  1045. if err != nil {
  1046. return err
  1047. }
  1048. err = provider.deleteUser(&user)
  1049. if err == nil {
  1050. RemoveCachedWebDAVUser(user.Username)
  1051. delayedQuotaUpdater.resetUserQuota(username)
  1052. cachedPasswords.Remove(username)
  1053. executeAction(operationDelete, executor, ipAddress, actionObjectUser, user.Username, &user)
  1054. }
  1055. return err
  1056. }
  1057. // ReloadConfig reloads provider configuration.
  1058. // Currently only implemented for memory provider, allows to reload the users
  1059. // from the configured file, if defined
  1060. func ReloadConfig() error {
  1061. return provider.reloadConfig()
  1062. }
  1063. // GetShares returns an array of shares respecting limit and offset
  1064. func GetShares(limit, offset int, order, username string) ([]Share, error) {
  1065. return provider.getShares(limit, offset, order, username)
  1066. }
  1067. // GetAPIKeys returns an array of API keys respecting limit and offset
  1068. func GetAPIKeys(limit, offset int, order string) ([]APIKey, error) {
  1069. return provider.getAPIKeys(limit, offset, order)
  1070. }
  1071. // GetAdmins returns an array of admins respecting limit and offset
  1072. func GetAdmins(limit, offset int, order string) ([]Admin, error) {
  1073. return provider.getAdmins(limit, offset, order)
  1074. }
  1075. // GetUsers returns an array of users respecting limit and offset and filtered by username exact match if not empty
  1076. func GetUsers(limit, offset int, order string) ([]User, error) {
  1077. return provider.getUsers(limit, offset, order)
  1078. }
  1079. // AddFolder adds a new virtual folder.
  1080. func AddFolder(folder *vfs.BaseVirtualFolder) error {
  1081. return provider.addFolder(folder)
  1082. }
  1083. // UpdateFolder updates the specified virtual folder
  1084. func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, executor, ipAddress string) error {
  1085. err := provider.updateFolder(folder)
  1086. if err == nil {
  1087. for _, user := range users {
  1088. provider.setUpdatedAt(user)
  1089. u, err := provider.userExists(user)
  1090. if err == nil {
  1091. webDAVUsersCache.swap(&u)
  1092. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, &u)
  1093. } else {
  1094. RemoveCachedWebDAVUser(user)
  1095. }
  1096. }
  1097. }
  1098. return err
  1099. }
  1100. // DeleteFolder deletes an existing folder.
  1101. func DeleteFolder(folderName, executor, ipAddress string) error {
  1102. folder, err := provider.getFolderByName(folderName)
  1103. if err != nil {
  1104. return err
  1105. }
  1106. err = provider.deleteFolder(&folder)
  1107. if err == nil {
  1108. for _, user := range folder.Users {
  1109. provider.setUpdatedAt(user)
  1110. u, err := provider.userExists(user)
  1111. if err == nil {
  1112. executeAction(operationUpdate, executor, ipAddress, actionObjectUser, u.Username, &u)
  1113. }
  1114. RemoveCachedWebDAVUser(user)
  1115. }
  1116. delayedQuotaUpdater.resetFolderQuota(folderName)
  1117. }
  1118. return err
  1119. }
  1120. // GetFolderByName returns the folder with the specified name if any
  1121. func GetFolderByName(name string) (vfs.BaseVirtualFolder, error) {
  1122. return provider.getFolderByName(name)
  1123. }
  1124. // GetFolders returns an array of folders respecting limit and offset
  1125. func GetFolders(limit, offset int, order string) ([]vfs.BaseVirtualFolder, error) {
  1126. return provider.getFolders(limit, offset, order)
  1127. }
  1128. // DumpData returns all users and folders
  1129. func DumpData() (BackupData, error) {
  1130. var data BackupData
  1131. users, err := provider.dumpUsers()
  1132. if err != nil {
  1133. return data, err
  1134. }
  1135. folders, err := provider.dumpFolders()
  1136. if err != nil {
  1137. return data, err
  1138. }
  1139. admins, err := provider.dumpAdmins()
  1140. if err != nil {
  1141. return data, err
  1142. }
  1143. apiKeys, err := provider.dumpAPIKeys()
  1144. if err != nil {
  1145. return data, err
  1146. }
  1147. shares, err := provider.dumpShares()
  1148. if err != nil {
  1149. return data, err
  1150. }
  1151. data.Users = users
  1152. data.Folders = folders
  1153. data.Admins = admins
  1154. data.APIKeys = apiKeys
  1155. data.Shares = shares
  1156. data.Version = DumpVersion
  1157. return data, err
  1158. }
  1159. // ParseDumpData tries to parse data as BackupData
  1160. func ParseDumpData(data []byte) (BackupData, error) {
  1161. var dump BackupData
  1162. err := json.Unmarshal(data, &dump)
  1163. return dump, err
  1164. }
  1165. // GetProviderStatus returns an error if the provider is not available
  1166. func GetProviderStatus() ProviderStatus {
  1167. err := provider.checkAvailability()
  1168. status := ProviderStatus{
  1169. Driver: config.Driver,
  1170. }
  1171. if err == nil {
  1172. status.IsActive = true
  1173. } else {
  1174. status.IsActive = false
  1175. status.Error = err.Error()
  1176. }
  1177. return status
  1178. }
  1179. // Close releases all provider resources.
  1180. // This method is used in test cases.
  1181. // Closing an uninitialized provider is not supported
  1182. func Close() error {
  1183. if availabilityTicker != nil {
  1184. availabilityTicker.Stop()
  1185. availabilityTickerDone <- true
  1186. availabilityTicker = nil
  1187. }
  1188. if updateCachesTicker != nil {
  1189. updateCachesTicker.Stop()
  1190. updateCachesTickerDone <- true
  1191. updateCachesTicker = nil
  1192. }
  1193. return provider.close()
  1194. }
  1195. func createProvider(basePath string) error {
  1196. var err error
  1197. sqlPlaceholders = getSQLPlaceholders()
  1198. if err = validateSQLTablesPrefix(); err != nil {
  1199. return err
  1200. }
  1201. logSender = fmt.Sprintf("dataprovider_%v", config.Driver)
  1202. switch config.Driver {
  1203. case SQLiteDataProviderName:
  1204. return initializeSQLiteProvider(basePath)
  1205. case PGSQLDataProviderName, CockroachDataProviderName:
  1206. return initializePGSQLProvider()
  1207. case MySQLDataProviderName:
  1208. return initializeMySQLProvider()
  1209. case BoltDataProviderName:
  1210. return initializeBoltProvider(basePath)
  1211. case MemoryDataProviderName:
  1212. initializeMemoryProvider(basePath)
  1213. return nil
  1214. default:
  1215. return fmt.Errorf("unsupported data provider: %v", config.Driver)
  1216. }
  1217. }
  1218. func buildUserHomeDir(user *User) {
  1219. if user.HomeDir == "" {
  1220. if config.UsersBaseDir != "" {
  1221. user.HomeDir = filepath.Join(config.UsersBaseDir, user.Username)
  1222. return
  1223. }
  1224. switch user.FsConfig.Provider {
  1225. case sdk.SFTPFilesystemProvider, sdk.S3FilesystemProvider, sdk.AzureBlobFilesystemProvider, sdk.GCSFilesystemProvider:
  1226. if tempPath != "" {
  1227. user.HomeDir = filepath.Join(tempPath, user.Username)
  1228. } else {
  1229. user.HomeDir = filepath.Join(os.TempDir(), user.Username)
  1230. }
  1231. }
  1232. }
  1233. }
  1234. func isVirtualDirOverlapped(dir1, dir2 string, fullCheck bool) bool {
  1235. if dir1 == dir2 {
  1236. return true
  1237. }
  1238. if fullCheck {
  1239. if len(dir1) > len(dir2) {
  1240. if strings.HasPrefix(dir1, dir2+"/") {
  1241. return true
  1242. }
  1243. }
  1244. if len(dir2) > len(dir1) {
  1245. if strings.HasPrefix(dir2, dir1+"/") {
  1246. return true
  1247. }
  1248. }
  1249. }
  1250. return false
  1251. }
  1252. func isMappedDirOverlapped(dir1, dir2 string, fullCheck bool) bool {
  1253. if dir1 == dir2 {
  1254. return true
  1255. }
  1256. if fullCheck {
  1257. if len(dir1) > len(dir2) {
  1258. if strings.HasPrefix(dir1, dir2+string(os.PathSeparator)) {
  1259. return true
  1260. }
  1261. }
  1262. if len(dir2) > len(dir1) {
  1263. if strings.HasPrefix(dir2, dir1+string(os.PathSeparator)) {
  1264. return true
  1265. }
  1266. }
  1267. }
  1268. return false
  1269. }
  1270. func validateFolderQuotaLimits(folder vfs.VirtualFolder) error {
  1271. if folder.QuotaSize < -1 {
  1272. return util.NewValidationError(fmt.Sprintf("invalid quota_size: %v folder path %#v", folder.QuotaSize, folder.MappedPath))
  1273. }
  1274. if folder.QuotaFiles < -1 {
  1275. return util.NewValidationError(fmt.Sprintf("invalid quota_file: %v folder path %#v", folder.QuotaFiles, folder.MappedPath))
  1276. }
  1277. if (folder.QuotaSize == -1 && folder.QuotaFiles != -1) || (folder.QuotaFiles == -1 && folder.QuotaSize != -1) {
  1278. return util.NewValidationError(fmt.Sprintf("virtual folder quota_size and quota_files must be both -1 or >= 0, quota_size: %v quota_files: %v",
  1279. folder.QuotaFiles, folder.QuotaSize))
  1280. }
  1281. return nil
  1282. }
  1283. func getVirtualFolderIfInvalid(folder *vfs.BaseVirtualFolder) *vfs.BaseVirtualFolder {
  1284. if err := ValidateFolder(folder); err == nil {
  1285. return folder
  1286. }
  1287. // we try to get the folder from the data provider if only the Name is populated
  1288. if folder.MappedPath != "" {
  1289. return folder
  1290. }
  1291. if folder.Name == "" {
  1292. return folder
  1293. }
  1294. if folder.FsConfig.Provider != sdk.LocalFilesystemProvider {
  1295. return folder
  1296. }
  1297. if f, err := GetFolderByName(folder.Name); err == nil {
  1298. return &f
  1299. }
  1300. return folder
  1301. }
  1302. func validateUserVirtualFolders(user *User) error {
  1303. if len(user.VirtualFolders) == 0 {
  1304. user.VirtualFolders = []vfs.VirtualFolder{}
  1305. return nil
  1306. }
  1307. var virtualFolders []vfs.VirtualFolder
  1308. mappedPaths := make(map[string]bool)
  1309. virtualPaths := make(map[string]bool)
  1310. for _, v := range user.VirtualFolders {
  1311. cleanedVPath := filepath.ToSlash(path.Clean(v.VirtualPath))
  1312. if !path.IsAbs(cleanedVPath) || cleanedVPath == "/" {
  1313. return util.NewValidationError(fmt.Sprintf("invalid virtual folder %#v", v.VirtualPath))
  1314. }
  1315. if err := validateFolderQuotaLimits(v); err != nil {
  1316. return err
  1317. }
  1318. folder := getVirtualFolderIfInvalid(&v.BaseVirtualFolder)
  1319. if err := ValidateFolder(folder); err != nil {
  1320. return err
  1321. }
  1322. cleanedMPath := folder.MappedPath
  1323. if folder.IsLocalOrLocalCrypted() {
  1324. if isMappedDirOverlapped(cleanedMPath, user.GetHomeDir(), true) {
  1325. return util.NewValidationError(fmt.Sprintf("invalid mapped folder %#v cannot be inside or contain the user home dir %#v",
  1326. folder.MappedPath, user.GetHomeDir()))
  1327. }
  1328. for mPath := range mappedPaths {
  1329. if folder.IsLocalOrLocalCrypted() && isMappedDirOverlapped(mPath, cleanedMPath, false) {
  1330. return util.NewValidationError(fmt.Sprintf("invalid mapped folder %#v overlaps with mapped folder %#v",
  1331. v.MappedPath, mPath))
  1332. }
  1333. }
  1334. mappedPaths[cleanedMPath] = true
  1335. }
  1336. for vPath := range virtualPaths {
  1337. if isVirtualDirOverlapped(vPath, cleanedVPath, false) {
  1338. return util.NewValidationError(fmt.Sprintf("invalid virtual folder %#v overlaps with virtual folder %#v",
  1339. v.VirtualPath, vPath))
  1340. }
  1341. }
  1342. virtualPaths[cleanedVPath] = true
  1343. virtualFolders = append(virtualFolders, vfs.VirtualFolder{
  1344. BaseVirtualFolder: *folder,
  1345. VirtualPath: cleanedVPath,
  1346. QuotaSize: v.QuotaSize,
  1347. QuotaFiles: v.QuotaFiles,
  1348. })
  1349. }
  1350. user.VirtualFolders = virtualFolders
  1351. return nil
  1352. }
  1353. func validateUserTOTPConfig(c *sdk.TOTPConfig, username string) error {
  1354. if !c.Enabled {
  1355. c.ConfigName = ""
  1356. c.Secret = kms.NewEmptySecret()
  1357. c.Protocols = nil
  1358. return nil
  1359. }
  1360. if c.ConfigName == "" {
  1361. return util.NewValidationError("totp: config name is mandatory")
  1362. }
  1363. if !util.IsStringInSlice(c.ConfigName, mfa.GetAvailableTOTPConfigNames()) {
  1364. return util.NewValidationError(fmt.Sprintf("totp: config name %#v not found", c.ConfigName))
  1365. }
  1366. if c.Secret.IsEmpty() {
  1367. return util.NewValidationError("totp: secret is mandatory")
  1368. }
  1369. if c.Secret.IsPlain() {
  1370. c.Secret.SetAdditionalData(username)
  1371. if err := c.Secret.Encrypt(); err != nil {
  1372. return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
  1373. }
  1374. }
  1375. c.Protocols = util.RemoveDuplicates(c.Protocols)
  1376. if len(c.Protocols) == 0 {
  1377. return util.NewValidationError("totp: specify at least one protocol")
  1378. }
  1379. for _, protocol := range c.Protocols {
  1380. if !util.IsStringInSlice(protocol, MFAProtocols) {
  1381. return util.NewValidationError(fmt.Sprintf("totp: invalid protocol %#v", protocol))
  1382. }
  1383. }
  1384. return nil
  1385. }
  1386. func validateUserRecoveryCodes(user *User) error {
  1387. for i := 0; i < len(user.Filters.RecoveryCodes); i++ {
  1388. code := &user.Filters.RecoveryCodes[i]
  1389. if code.Secret.IsEmpty() {
  1390. return util.NewValidationError("mfa: recovery code cannot be empty")
  1391. }
  1392. if code.Secret.IsPlain() {
  1393. code.Secret.SetAdditionalData(user.Username)
  1394. if err := code.Secret.Encrypt(); err != nil {
  1395. return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
  1396. }
  1397. }
  1398. }
  1399. return nil
  1400. }
  1401. func validatePermissions(user *User) error {
  1402. if len(user.Permissions) == 0 {
  1403. return util.NewValidationError("please grant some permissions to this user")
  1404. }
  1405. permissions := make(map[string][]string)
  1406. if _, ok := user.Permissions["/"]; !ok {
  1407. return util.NewValidationError("permissions for the root dir \"/\" must be set")
  1408. }
  1409. for dir, perms := range user.Permissions {
  1410. if len(perms) == 0 && dir == "/" {
  1411. return util.NewValidationError(fmt.Sprintf("no permissions granted for the directory: %#v", dir))
  1412. }
  1413. if len(perms) > len(ValidPerms) {
  1414. return util.NewValidationError("invalid permissions")
  1415. }
  1416. for _, p := range perms {
  1417. if !util.IsStringInSlice(p, ValidPerms) {
  1418. return util.NewValidationError(fmt.Sprintf("invalid permission: %#v", p))
  1419. }
  1420. }
  1421. cleanedDir := filepath.ToSlash(path.Clean(dir))
  1422. if cleanedDir != "/" {
  1423. cleanedDir = strings.TrimSuffix(cleanedDir, "/")
  1424. }
  1425. if !path.IsAbs(cleanedDir) {
  1426. return util.NewValidationError(fmt.Sprintf("cannot set permissions for non absolute path: %#v", dir))
  1427. }
  1428. if dir != cleanedDir && cleanedDir == "/" {
  1429. return util.NewValidationError(fmt.Sprintf("cannot set permissions for invalid subdirectory: %#v is an alias for \"/\"", dir))
  1430. }
  1431. if util.IsStringInSlice(PermAny, perms) {
  1432. permissions[cleanedDir] = []string{PermAny}
  1433. } else {
  1434. permissions[cleanedDir] = util.RemoveDuplicates(perms)
  1435. }
  1436. }
  1437. user.Permissions = permissions
  1438. return nil
  1439. }
  1440. func validatePublicKeys(user *User) error {
  1441. if len(user.PublicKeys) == 0 {
  1442. user.PublicKeys = []string{}
  1443. }
  1444. var validatedKeys []string
  1445. for i, k := range user.PublicKeys {
  1446. if k == "" {
  1447. continue
  1448. }
  1449. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(k))
  1450. if err != nil {
  1451. return util.NewValidationError(fmt.Sprintf("could not parse key nr. %d: %s", i+1, err))
  1452. }
  1453. validatedKeys = append(validatedKeys, k)
  1454. }
  1455. user.PublicKeys = util.RemoveDuplicates(validatedKeys)
  1456. return nil
  1457. }
  1458. func validateFiltersPatternExtensions(user *User) error {
  1459. if len(user.Filters.FilePatterns) == 0 {
  1460. user.Filters.FilePatterns = []sdk.PatternsFilter{}
  1461. return nil
  1462. }
  1463. filteredPaths := []string{}
  1464. var filters []sdk.PatternsFilter
  1465. for _, f := range user.Filters.FilePatterns {
  1466. cleanedPath := filepath.ToSlash(path.Clean(f.Path))
  1467. if !path.IsAbs(cleanedPath) {
  1468. return util.NewValidationError(fmt.Sprintf("invalid path %#v for file patterns filter", f.Path))
  1469. }
  1470. if util.IsStringInSlice(cleanedPath, filteredPaths) {
  1471. return util.NewValidationError(fmt.Sprintf("duplicate file patterns filter for path %#v", f.Path))
  1472. }
  1473. if len(f.AllowedPatterns) == 0 && len(f.DeniedPatterns) == 0 {
  1474. return util.NewValidationError(fmt.Sprintf("empty file patterns filter for path %#v", f.Path))
  1475. }
  1476. f.Path = cleanedPath
  1477. allowed := make([]string, 0, len(f.AllowedPatterns))
  1478. denied := make([]string, 0, len(f.DeniedPatterns))
  1479. for _, pattern := range f.AllowedPatterns {
  1480. _, err := path.Match(pattern, "abc")
  1481. if err != nil {
  1482. return util.NewValidationError(fmt.Sprintf("invalid file pattern filter %#v", pattern))
  1483. }
  1484. allowed = append(allowed, strings.ToLower(pattern))
  1485. }
  1486. for _, pattern := range f.DeniedPatterns {
  1487. _, err := path.Match(pattern, "abc")
  1488. if err != nil {
  1489. return util.NewValidationError(fmt.Sprintf("invalid file pattern filter %#v", pattern))
  1490. }
  1491. denied = append(denied, strings.ToLower(pattern))
  1492. }
  1493. f.AllowedPatterns = allowed
  1494. f.DeniedPatterns = denied
  1495. filters = append(filters, f)
  1496. filteredPaths = append(filteredPaths, cleanedPath)
  1497. }
  1498. user.Filters.FilePatterns = filters
  1499. return nil
  1500. }
  1501. func checkEmptyFiltersStruct(user *User) {
  1502. if len(user.Filters.AllowedIP) == 0 {
  1503. user.Filters.AllowedIP = []string{}
  1504. }
  1505. if len(user.Filters.DeniedIP) == 0 {
  1506. user.Filters.DeniedIP = []string{}
  1507. }
  1508. if len(user.Filters.DeniedLoginMethods) == 0 {
  1509. user.Filters.DeniedLoginMethods = []string{}
  1510. }
  1511. if len(user.Filters.DeniedProtocols) == 0 {
  1512. user.Filters.DeniedProtocols = []string{}
  1513. }
  1514. }
  1515. func validateFilters(user *User) error {
  1516. checkEmptyFiltersStruct(user)
  1517. user.Filters.DeniedIP = util.RemoveDuplicates(user.Filters.DeniedIP)
  1518. for _, IPMask := range user.Filters.DeniedIP {
  1519. _, _, err := net.ParseCIDR(IPMask)
  1520. if err != nil {
  1521. return util.NewValidationError(fmt.Sprintf("could not parse denied IP/Mask %#v : %v", IPMask, err))
  1522. }
  1523. }
  1524. user.Filters.AllowedIP = util.RemoveDuplicates(user.Filters.AllowedIP)
  1525. for _, IPMask := range user.Filters.AllowedIP {
  1526. _, _, err := net.ParseCIDR(IPMask)
  1527. if err != nil {
  1528. return util.NewValidationError(fmt.Sprintf("could not parse allowed IP/Mask %#v : %v", IPMask, err))
  1529. }
  1530. }
  1531. user.Filters.DeniedLoginMethods = util.RemoveDuplicates(user.Filters.DeniedLoginMethods)
  1532. if len(user.Filters.DeniedLoginMethods) >= len(ValidLoginMethods) {
  1533. return util.NewValidationError("invalid denied_login_methods")
  1534. }
  1535. for _, loginMethod := range user.Filters.DeniedLoginMethods {
  1536. if !util.IsStringInSlice(loginMethod, ValidLoginMethods) {
  1537. return util.NewValidationError(fmt.Sprintf("invalid login method: %#v", loginMethod))
  1538. }
  1539. }
  1540. user.Filters.DeniedProtocols = util.RemoveDuplicates(user.Filters.DeniedProtocols)
  1541. if len(user.Filters.DeniedProtocols) >= len(ValidProtocols) {
  1542. return util.NewValidationError("invalid denied_protocols")
  1543. }
  1544. for _, p := range user.Filters.DeniedProtocols {
  1545. if !util.IsStringInSlice(p, ValidProtocols) {
  1546. return util.NewValidationError(fmt.Sprintf("invalid protocol: %#v", p))
  1547. }
  1548. }
  1549. if user.Filters.TLSUsername != "" {
  1550. if !util.IsStringInSlice(string(user.Filters.TLSUsername), validTLSUsernames) {
  1551. return util.NewValidationError(fmt.Sprintf("invalid TLS username: %#v", user.Filters.TLSUsername))
  1552. }
  1553. }
  1554. user.Filters.WebClient = util.RemoveDuplicates(user.Filters.WebClient)
  1555. for _, opts := range user.Filters.WebClient {
  1556. if !util.IsStringInSlice(opts, sdk.WebClientOptions) {
  1557. return util.NewValidationError(fmt.Sprintf("invalid web client options %#v", opts))
  1558. }
  1559. }
  1560. return validateFiltersPatternExtensions(user)
  1561. }
  1562. func saveGCSCredentials(fsConfig *vfs.Filesystem, helper vfs.ValidatorHelper) error {
  1563. if fsConfig.Provider != sdk.GCSFilesystemProvider {
  1564. return nil
  1565. }
  1566. if fsConfig.GCSConfig.Credentials.GetPayload() == "" {
  1567. return nil
  1568. }
  1569. if config.PreferDatabaseCredentials {
  1570. if fsConfig.GCSConfig.Credentials.IsPlain() {
  1571. fsConfig.GCSConfig.Credentials.SetAdditionalData(helper.GetEncryptionAdditionalData())
  1572. err := fsConfig.GCSConfig.Credentials.Encrypt()
  1573. if err != nil {
  1574. return err
  1575. }
  1576. }
  1577. return nil
  1578. }
  1579. if fsConfig.GCSConfig.Credentials.IsPlain() {
  1580. fsConfig.GCSConfig.Credentials.SetAdditionalData(helper.GetEncryptionAdditionalData())
  1581. err := fsConfig.GCSConfig.Credentials.Encrypt()
  1582. if err != nil {
  1583. return util.NewValidationError(fmt.Sprintf("could not encrypt GCS credentials: %v", err))
  1584. }
  1585. }
  1586. creds, err := json.Marshal(fsConfig.GCSConfig.Credentials)
  1587. if err != nil {
  1588. return util.NewValidationError(fmt.Sprintf("could not marshal GCS credentials: %v", err))
  1589. }
  1590. credentialsFilePath := helper.GetGCSCredentialsFilePath()
  1591. err = os.MkdirAll(filepath.Dir(credentialsFilePath), 0700)
  1592. if err != nil {
  1593. return util.NewValidationError(fmt.Sprintf("could not create GCS credentials dir: %v", err))
  1594. }
  1595. err = os.WriteFile(credentialsFilePath, creds, 0600)
  1596. if err != nil {
  1597. return util.NewValidationError(fmt.Sprintf("could not save GCS credentials: %v", err))
  1598. }
  1599. fsConfig.GCSConfig.Credentials = kms.NewEmptySecret()
  1600. return nil
  1601. }
  1602. func validateBaseParams(user *User) error {
  1603. if user.Username == "" {
  1604. return util.NewValidationError("username is mandatory")
  1605. }
  1606. if user.Email != "" && !emailRegex.MatchString(user.Email) {
  1607. return util.NewValidationError(fmt.Sprintf("email %#v is not valid", user.Email))
  1608. }
  1609. if !config.SkipNaturalKeysValidation && !usernameRegex.MatchString(user.Username) {
  1610. return util.NewValidationError(fmt.Sprintf("username %#v is not valid, the following characters are allowed: a-zA-Z0-9-_.~",
  1611. user.Username))
  1612. }
  1613. if user.HomeDir == "" {
  1614. return util.NewValidationError("home_dir is mandatory")
  1615. }
  1616. if user.Password == "" && len(user.PublicKeys) == 0 {
  1617. return util.NewValidationError("please set a password or at least a public_key")
  1618. }
  1619. if !filepath.IsAbs(user.HomeDir) {
  1620. return util.NewValidationError(fmt.Sprintf("home_dir must be an absolute path, actual value: %v", user.HomeDir))
  1621. }
  1622. return nil
  1623. }
  1624. func createUserPasswordHash(user *User) error {
  1625. if user.Password != "" && !user.IsPasswordHashed() {
  1626. if config.PasswordValidation.Users.MinEntropy > 0 {
  1627. if err := passwordvalidator.Validate(user.Password, config.PasswordValidation.Users.MinEntropy); err != nil {
  1628. return util.NewValidationError(err.Error())
  1629. }
  1630. }
  1631. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  1632. pwd, err := bcrypt.GenerateFromPassword([]byte(user.Password), config.PasswordHashing.BcryptOptions.Cost)
  1633. if err != nil {
  1634. return err
  1635. }
  1636. user.Password = string(pwd)
  1637. } else {
  1638. pwd, err := argon2id.CreateHash(user.Password, argon2Params)
  1639. if err != nil {
  1640. return err
  1641. }
  1642. user.Password = pwd
  1643. }
  1644. }
  1645. return nil
  1646. }
  1647. // ValidateFolder returns an error if the folder is not valid
  1648. // FIXME: this should be defined as Folder struct method
  1649. func ValidateFolder(folder *vfs.BaseVirtualFolder) error {
  1650. folder.FsConfig.SetEmptySecretsIfNil()
  1651. if folder.Name == "" {
  1652. return util.NewValidationError("folder name is mandatory")
  1653. }
  1654. if !config.SkipNaturalKeysValidation && !usernameRegex.MatchString(folder.Name) {
  1655. return util.NewValidationError(fmt.Sprintf("folder name %#v is not valid, the following characters are allowed: a-zA-Z0-9-_.~",
  1656. folder.Name))
  1657. }
  1658. if folder.FsConfig.Provider == sdk.LocalFilesystemProvider || folder.FsConfig.Provider == sdk.CryptedFilesystemProvider ||
  1659. folder.MappedPath != "" {
  1660. cleanedMPath := filepath.Clean(folder.MappedPath)
  1661. if !filepath.IsAbs(cleanedMPath) {
  1662. return util.NewValidationError(fmt.Sprintf("invalid folder mapped path %#v", folder.MappedPath))
  1663. }
  1664. folder.MappedPath = cleanedMPath
  1665. }
  1666. if folder.HasRedactedSecret() {
  1667. return errors.New("cannot save a folder with a redacted secret")
  1668. }
  1669. if err := folder.FsConfig.Validate(folder); err != nil {
  1670. return err
  1671. }
  1672. return saveGCSCredentials(&folder.FsConfig, folder)
  1673. }
  1674. // ValidateUser returns an error if the user is not valid
  1675. // FIXME: this should be defined as User struct method
  1676. func ValidateUser(user *User) error {
  1677. user.SetEmptySecretsIfNil()
  1678. buildUserHomeDir(user)
  1679. if err := validateBaseParams(user); err != nil {
  1680. return err
  1681. }
  1682. if err := validatePermissions(user); err != nil {
  1683. return err
  1684. }
  1685. if user.hasRedactedSecret() {
  1686. return util.NewValidationError("cannot save a user with a redacted secret")
  1687. }
  1688. if err := validateUserTOTPConfig(&user.Filters.TOTPConfig, user.Username); err != nil {
  1689. return err
  1690. }
  1691. if err := validateUserRecoveryCodes(user); err != nil {
  1692. return err
  1693. }
  1694. if err := user.FsConfig.Validate(user); err != nil {
  1695. return err
  1696. }
  1697. if err := validateUserVirtualFolders(user); err != nil {
  1698. return err
  1699. }
  1700. if user.Status < 0 || user.Status > 1 {
  1701. return util.NewValidationError(fmt.Sprintf("invalid user status: %v", user.Status))
  1702. }
  1703. if err := createUserPasswordHash(user); err != nil {
  1704. return err
  1705. }
  1706. if err := validatePublicKeys(user); err != nil {
  1707. return err
  1708. }
  1709. if err := validateFilters(user); err != nil {
  1710. return err
  1711. }
  1712. if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(sdk.WebClientMFADisabled, user.Filters.WebClient) {
  1713. return util.NewValidationError("multi-factor authentication cannot be disabled for a user with an active configuration")
  1714. }
  1715. return saveGCSCredentials(&user.FsConfig, user)
  1716. }
  1717. func isPasswordOK(user *User, password string) (bool, error) {
  1718. if config.PasswordCaching {
  1719. found, match := cachedPasswords.Check(user.Username, password)
  1720. if found {
  1721. return match, nil
  1722. }
  1723. }
  1724. match := false
  1725. var err error
  1726. if strings.HasPrefix(user.Password, bcryptPwdPrefix) {
  1727. if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
  1728. return match, ErrInvalidCredentials
  1729. }
  1730. match = true
  1731. } else if strings.HasPrefix(user.Password, argonPwdPrefix) {
  1732. match, err = argon2id.ComparePasswordAndHash(password, user.Password)
  1733. if err != nil {
  1734. providerLog(logger.LevelWarn, "error comparing password with argon hash: %v", err)
  1735. return match, err
  1736. }
  1737. } else if util.IsStringPrefixInSlice(user.Password, pbkdfPwdPrefixes) {
  1738. match, err = comparePbkdf2PasswordAndHash(password, user.Password)
  1739. if err != nil {
  1740. return match, err
  1741. }
  1742. } else if util.IsStringPrefixInSlice(user.Password, unixPwdPrefixes) {
  1743. match, err = compareUnixPasswordAndHash(user, password)
  1744. if err != nil {
  1745. return match, err
  1746. }
  1747. }
  1748. if err == nil && match {
  1749. cachedPasswords.Add(user.Username, password)
  1750. }
  1751. return match, err
  1752. }
  1753. func checkUserAndTLSCertificate(user *User, protocol string, tlsCert *x509.Certificate) (User, error) {
  1754. err := user.CheckLoginConditions()
  1755. if err != nil {
  1756. return *user, err
  1757. }
  1758. switch protocol {
  1759. case protocolFTP, protocolWebDAV:
  1760. if user.Filters.TLSUsername == sdk.TLSUsernameCN {
  1761. if user.Username == tlsCert.Subject.CommonName {
  1762. return *user, nil
  1763. }
  1764. return *user, fmt.Errorf("CN %#v does not match username %#v", tlsCert.Subject.CommonName, user.Username)
  1765. }
  1766. return *user, errors.New("TLS certificate is not valid")
  1767. default:
  1768. return *user, fmt.Errorf("certificate authentication is not supported for protocol %v", protocol)
  1769. }
  1770. }
  1771. func checkUserAndPass(user *User, password, ip, protocol string) (User, error) {
  1772. err := user.CheckLoginConditions()
  1773. if err != nil {
  1774. return *user, err
  1775. }
  1776. password, err = checkUserPasscode(user, password, protocol)
  1777. if err != nil {
  1778. return *user, ErrInvalidCredentials
  1779. }
  1780. if user.Password == "" {
  1781. return *user, errors.New("credentials cannot be null or empty")
  1782. }
  1783. if !user.Filters.Hooks.CheckPasswordDisabled {
  1784. hookResponse, err := executeCheckPasswordHook(user.Username, password, ip, protocol)
  1785. if err != nil {
  1786. providerLog(logger.LevelDebug, "error executing check password hook for user %#v, ip %v, protocol %v: %v",
  1787. user.Username, ip, protocol, err)
  1788. return *user, errors.New("unable to check credentials")
  1789. }
  1790. switch hookResponse.Status {
  1791. case -1:
  1792. // no hook configured
  1793. case 1:
  1794. providerLog(logger.LevelDebug, "password accepted by check password hook for user %#v, ip %v, protocol %v",
  1795. user.Username, ip, protocol)
  1796. return *user, nil
  1797. case 2:
  1798. providerLog(logger.LevelDebug, "partial success from check password hook for user %#v, ip %v, protocol %v",
  1799. user.Username, ip, protocol)
  1800. password = hookResponse.ToVerify
  1801. default:
  1802. providerLog(logger.LevelDebug, "password rejected by check password hook for user %#v, ip %v, protocol %v, status: %v",
  1803. user.Username, ip, protocol, hookResponse.Status)
  1804. return *user, ErrInvalidCredentials
  1805. }
  1806. }
  1807. match, err := isPasswordOK(user, password)
  1808. if !match {
  1809. err = ErrInvalidCredentials
  1810. }
  1811. return *user, err
  1812. }
  1813. func checkUserPasscode(user *User, password, protocol string) (string, error) {
  1814. if user.Filters.TOTPConfig.Enabled {
  1815. switch protocol {
  1816. case protocolFTP:
  1817. if util.IsStringInSlice(protocol, user.Filters.TOTPConfig.Protocols) {
  1818. // the TOTP passcode has six digits
  1819. pwdLen := len(password)
  1820. if pwdLen < 7 {
  1821. providerLog(logger.LevelDebug, "password len %v is too short to contain a passcode, user %#v, protocol %v",
  1822. pwdLen, user.Username, protocol)
  1823. return "", util.NewValidationError("password too short, cannot contain the passcode")
  1824. }
  1825. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  1826. if err != nil {
  1827. providerLog(logger.LevelWarn, "unable to decrypt TOTP secret for user %#v, protocol %v, err: %v",
  1828. user.Username, protocol, err)
  1829. return "", err
  1830. }
  1831. pwd := password[0:(pwdLen - 6)]
  1832. passcode := password[(pwdLen - 6):]
  1833. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  1834. user.Filters.TOTPConfig.Secret.GetPayload())
  1835. if !match || err != nil {
  1836. providerLog(logger.LevelWarn, "invalid passcode for user %#v, protocol %v, err: %v",
  1837. user.Username, protocol, err)
  1838. return "", util.NewValidationError("invalid passcode")
  1839. }
  1840. return pwd, nil
  1841. }
  1842. }
  1843. }
  1844. return password, nil
  1845. }
  1846. func checkUserAndPubKey(user *User, pubKey []byte) (User, string, error) {
  1847. err := user.CheckLoginConditions()
  1848. if err != nil {
  1849. return *user, "", err
  1850. }
  1851. if len(user.PublicKeys) == 0 {
  1852. return *user, "", ErrInvalidCredentials
  1853. }
  1854. for i, k := range user.PublicKeys {
  1855. storedPubKey, comment, _, _, err := ssh.ParseAuthorizedKey([]byte(k))
  1856. if err != nil {
  1857. providerLog(logger.LevelWarn, "error parsing stored public key %d for user %v: %v", i, user.Username, err)
  1858. return *user, "", err
  1859. }
  1860. if bytes.Equal(storedPubKey.Marshal(), pubKey) {
  1861. certInfo := ""
  1862. cert, ok := storedPubKey.(*ssh.Certificate)
  1863. if ok {
  1864. certInfo = fmt.Sprintf(" %v ID: %v Serial: %v CA: %v", cert.Type(), cert.KeyId, cert.Serial,
  1865. ssh.FingerprintSHA256(cert.SignatureKey))
  1866. }
  1867. return *user, fmt.Sprintf("%v:%v%v", ssh.FingerprintSHA256(storedPubKey), comment, certInfo), nil
  1868. }
  1869. }
  1870. return *user, "", ErrInvalidCredentials
  1871. }
  1872. func compareUnixPasswordAndHash(user *User, password string) (bool, error) {
  1873. var crypter crypt.Crypter
  1874. if strings.HasPrefix(user.Password, sha512cryptPwdPrefix) {
  1875. crypter = sha512_crypt.New()
  1876. } else if strings.HasPrefix(user.Password, md5cryptPwdPrefix) {
  1877. crypter = md5_crypt.New()
  1878. } else if strings.HasPrefix(user.Password, md5cryptApr1PwdPrefix) {
  1879. crypter = apr1_crypt.New()
  1880. } else {
  1881. return false, errors.New("unix crypt: invalid or unsupported hash format")
  1882. }
  1883. if err := crypter.Verify(user.Password, []byte(password)); err != nil {
  1884. return false, err
  1885. }
  1886. return true, nil
  1887. }
  1888. func comparePbkdf2PasswordAndHash(password, hashedPassword string) (bool, error) {
  1889. vals := strings.Split(hashedPassword, "$")
  1890. if len(vals) != 5 {
  1891. return false, fmt.Errorf("pbkdf2: hash is not in the correct format")
  1892. }
  1893. iterations, err := strconv.Atoi(vals[2])
  1894. if err != nil {
  1895. return false, err
  1896. }
  1897. expected, err := base64.StdEncoding.DecodeString(vals[4])
  1898. if err != nil {
  1899. return false, err
  1900. }
  1901. var salt []byte
  1902. if util.IsStringPrefixInSlice(hashedPassword, pbkdfPwdB64SaltPrefixes) {
  1903. salt, err = base64.StdEncoding.DecodeString(vals[3])
  1904. if err != nil {
  1905. return false, err
  1906. }
  1907. } else {
  1908. salt = []byte(vals[3])
  1909. }
  1910. var hashFunc func() hash.Hash
  1911. if strings.HasPrefix(hashedPassword, pbkdf2SHA256Prefix) || strings.HasPrefix(hashedPassword, pbkdf2SHA256B64SaltPrefix) {
  1912. hashFunc = sha256.New
  1913. } else if strings.HasPrefix(hashedPassword, pbkdf2SHA512Prefix) {
  1914. hashFunc = sha512.New
  1915. } else if strings.HasPrefix(hashedPassword, pbkdf2SHA1Prefix) {
  1916. hashFunc = sha1.New
  1917. } else {
  1918. return false, fmt.Errorf("pbkdf2: invalid or unsupported hash format %v", vals[1])
  1919. }
  1920. df := pbkdf2.Key([]byte(password), salt, iterations, len(expected), hashFunc)
  1921. return subtle.ConstantTimeCompare(df, expected) == 1, nil
  1922. }
  1923. func addCredentialsToUser(user *User) error {
  1924. if err := addFolderCredentialsToUser(user); err != nil {
  1925. return err
  1926. }
  1927. if user.FsConfig.Provider != sdk.GCSFilesystemProvider {
  1928. return nil
  1929. }
  1930. if user.FsConfig.GCSConfig.AutomaticCredentials > 0 {
  1931. return nil
  1932. }
  1933. // Don't read from file if credentials have already been set
  1934. if user.FsConfig.GCSConfig.Credentials.IsValid() {
  1935. return nil
  1936. }
  1937. cred, err := os.ReadFile(user.GetGCSCredentialsFilePath())
  1938. if err != nil {
  1939. return err
  1940. }
  1941. return json.Unmarshal(cred, &user.FsConfig.GCSConfig.Credentials)
  1942. }
  1943. func addFolderCredentialsToUser(user *User) error {
  1944. for idx := range user.VirtualFolders {
  1945. f := &user.VirtualFolders[idx]
  1946. if f.FsConfig.Provider != sdk.GCSFilesystemProvider {
  1947. continue
  1948. }
  1949. if f.FsConfig.GCSConfig.AutomaticCredentials > 0 {
  1950. continue
  1951. }
  1952. // Don't read from file if credentials have already been set
  1953. if f.FsConfig.GCSConfig.Credentials.IsValid() {
  1954. continue
  1955. }
  1956. cred, err := os.ReadFile(f.GetGCSCredentialsFilePath())
  1957. if err != nil {
  1958. return err
  1959. }
  1960. err = json.Unmarshal(cred, f.FsConfig.GCSConfig.Credentials)
  1961. if err != nil {
  1962. return err
  1963. }
  1964. }
  1965. return nil
  1966. }
  1967. func getSSLMode() string {
  1968. if config.Driver == PGSQLDataProviderName || config.Driver == CockroachDataProviderName {
  1969. if config.SSLMode == 0 {
  1970. return "disable"
  1971. } else if config.SSLMode == 1 {
  1972. return "require"
  1973. } else if config.SSLMode == 2 {
  1974. return "verify-ca"
  1975. } else if config.SSLMode == 3 {
  1976. return "verify-full"
  1977. }
  1978. } else if config.Driver == MySQLDataProviderName {
  1979. if config.SSLMode == 0 {
  1980. return "false"
  1981. } else if config.SSLMode == 1 {
  1982. return "true"
  1983. } else if config.SSLMode == 2 {
  1984. return "skip-verify"
  1985. } else if config.SSLMode == 3 {
  1986. return "preferred"
  1987. }
  1988. }
  1989. return ""
  1990. }
  1991. func checkCacheUpdates() {
  1992. providerLog(logger.LevelDebug, "start caches check, update time %v", util.GetTimeFromMsecSinceEpoch(lastCachesUpdate))
  1993. checkTime := util.GetTimeAsMsSinceEpoch(time.Now())
  1994. users, err := provider.getRecentlyUpdatedUsers(lastCachesUpdate)
  1995. if err != nil {
  1996. providerLog(logger.LevelWarn, "unable to get recently updated users: %v", err)
  1997. return
  1998. }
  1999. for _, user := range users {
  2000. providerLog(logger.LevelDebug, "invalidate caches for user %#v", user.Username)
  2001. webDAVUsersCache.swap(&user)
  2002. cachedPasswords.Remove(user.Username)
  2003. }
  2004. lastCachesUpdate = checkTime
  2005. providerLog(logger.LevelDebug, "end caches check, new update time %v", util.GetTimeFromMsecSinceEpoch(lastCachesUpdate))
  2006. }
  2007. func startUpdateCachesTimer() {
  2008. if config.IsShared == 0 {
  2009. return
  2010. }
  2011. if !util.IsStringInSlice(config.Driver, sharedProviders) {
  2012. providerLog(logger.LevelWarn, "update caches not supported for provider %v", config.Driver)
  2013. return
  2014. }
  2015. lastCachesUpdate = util.GetTimeAsMsSinceEpoch(time.Now())
  2016. providerLog(logger.LevelDebug, "update caches check started for provider %v", config.Driver)
  2017. updateCachesTicker = time.NewTicker(10 * time.Minute)
  2018. updateCachesTickerDone = make(chan bool)
  2019. go func() {
  2020. for {
  2021. select {
  2022. case <-updateCachesTickerDone:
  2023. return
  2024. case <-updateCachesTicker.C:
  2025. checkCacheUpdates()
  2026. }
  2027. }
  2028. }()
  2029. }
  2030. func startAvailabilityTimer() {
  2031. availabilityTicker = time.NewTicker(30 * time.Second)
  2032. availabilityTickerDone = make(chan bool)
  2033. checkDataprovider()
  2034. go func() {
  2035. for {
  2036. select {
  2037. case <-availabilityTickerDone:
  2038. return
  2039. case <-availabilityTicker.C:
  2040. checkDataprovider()
  2041. }
  2042. }
  2043. }()
  2044. }
  2045. func checkDataprovider() {
  2046. err := provider.checkAvailability()
  2047. if err != nil {
  2048. providerLog(logger.LevelWarn, "check availability error: %v", err)
  2049. }
  2050. metric.UpdateDataProviderAvailability(err)
  2051. }
  2052. func terminateInteractiveAuthProgram(cmd *exec.Cmd, isFinished bool) {
  2053. if isFinished {
  2054. return
  2055. }
  2056. providerLog(logger.LevelInfo, "kill interactive auth program after an unexpected error")
  2057. err := cmd.Process.Kill()
  2058. if err != nil {
  2059. providerLog(logger.LevelDebug, "error killing interactive auth program: %v", err)
  2060. }
  2061. }
  2062. func sendKeyboardAuthHTTPReq(url string, request *plugin.KeyboardAuthRequest) (*plugin.KeyboardAuthResponse, error) {
  2063. reqAsJSON, err := json.Marshal(request)
  2064. if err != nil {
  2065. providerLog(logger.LevelWarn, "error serializing keyboard interactive auth request: %v", err)
  2066. return nil, err
  2067. }
  2068. resp, err := httpclient.Post(url, "application/json", bytes.NewBuffer(reqAsJSON))
  2069. if err != nil {
  2070. providerLog(logger.LevelWarn, "error getting keyboard interactive auth hook HTTP response: %v", err)
  2071. return nil, err
  2072. }
  2073. defer resp.Body.Close()
  2074. if resp.StatusCode != http.StatusOK {
  2075. return nil, fmt.Errorf("wrong keyboard interactive auth http status code: %v, expected 200", resp.StatusCode)
  2076. }
  2077. var response plugin.KeyboardAuthResponse
  2078. err = render.DecodeJSON(resp.Body, &response)
  2079. return &response, err
  2080. }
  2081. func doBuiltinKeyboardInteractiveAuth(user *User, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  2082. answers, err := client(user.Username, "", []string{"Password: "}, []bool{false})
  2083. if err != nil {
  2084. return 0, err
  2085. }
  2086. if len(answers) != 1 {
  2087. return 0, fmt.Errorf("unexpected number of answers: %v", len(answers))
  2088. }
  2089. _, err = checkUserAndPass(user, answers[0], ip, protocol)
  2090. if err != nil {
  2091. return 0, err
  2092. }
  2093. if !user.Filters.TOTPConfig.Enabled || !util.IsStringInSlice(protocolSSH, user.Filters.TOTPConfig.Protocols) {
  2094. return 1, nil
  2095. }
  2096. err = user.Filters.TOTPConfig.Secret.TryDecrypt()
  2097. if err != nil {
  2098. providerLog(logger.LevelWarn, "unable to decrypt TOTP secret for user %#v, protocol %v, err: %v",
  2099. user.Username, protocol, err)
  2100. return 0, err
  2101. }
  2102. answers, err = client(user.Username, "", []string{"Authentication code: "}, []bool{false})
  2103. if err != nil {
  2104. return 0, err
  2105. }
  2106. if len(answers) != 1 {
  2107. return 0, fmt.Errorf("unexpected number of answers: %v", len(answers))
  2108. }
  2109. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
  2110. user.Filters.TOTPConfig.Secret.GetPayload())
  2111. if !match || err != nil {
  2112. providerLog(logger.LevelWarn, "invalid passcode for user %#v, protocol %v, err: %v",
  2113. user.Username, protocol, err)
  2114. return 0, util.NewValidationError("invalid passcode")
  2115. }
  2116. return 1, nil
  2117. }
  2118. func executeKeyboardInteractivePlugin(user *User, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  2119. authResult := 0
  2120. requestID := xid.New().String()
  2121. authStep := 1
  2122. req := &plugin.KeyboardAuthRequest{
  2123. Username: user.Username,
  2124. IP: ip,
  2125. Password: user.Password,
  2126. RequestID: requestID,
  2127. Step: authStep,
  2128. }
  2129. var response *plugin.KeyboardAuthResponse
  2130. var err error
  2131. for {
  2132. response, err = plugin.Handler.ExecuteKeyboardInteractiveStep(req)
  2133. if err != nil {
  2134. return authResult, err
  2135. }
  2136. if response.AuthResult != 0 {
  2137. return response.AuthResult, err
  2138. }
  2139. if err = response.Validate(); err != nil {
  2140. providerLog(logger.LevelInfo, "invalid response from keyboard interactive plugin: %v", err)
  2141. return authResult, err
  2142. }
  2143. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  2144. if err != nil {
  2145. return authResult, err
  2146. }
  2147. authStep++
  2148. req = &plugin.KeyboardAuthRequest{
  2149. RequestID: requestID,
  2150. Step: authStep,
  2151. Username: user.Username,
  2152. Password: user.Password,
  2153. Answers: answers,
  2154. Questions: response.Questions,
  2155. }
  2156. }
  2157. }
  2158. func executeKeyboardInteractiveHTTPHook(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  2159. authResult := 0
  2160. requestID := xid.New().String()
  2161. authStep := 1
  2162. req := &plugin.KeyboardAuthRequest{
  2163. Username: user.Username,
  2164. IP: ip,
  2165. Password: user.Password,
  2166. RequestID: requestID,
  2167. Step: authStep,
  2168. }
  2169. var response *plugin.KeyboardAuthResponse
  2170. var err error
  2171. for {
  2172. response, err = sendKeyboardAuthHTTPReq(authHook, req)
  2173. if err != nil {
  2174. return authResult, err
  2175. }
  2176. if response.AuthResult != 0 {
  2177. return response.AuthResult, err
  2178. }
  2179. if err = response.Validate(); err != nil {
  2180. providerLog(logger.LevelInfo, "invalid response from keyboard interactive http hook: %v", err)
  2181. return authResult, err
  2182. }
  2183. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  2184. if err != nil {
  2185. return authResult, err
  2186. }
  2187. authStep++
  2188. req = &plugin.KeyboardAuthRequest{
  2189. RequestID: requestID,
  2190. Step: authStep,
  2191. Username: user.Username,
  2192. Password: user.Password,
  2193. Answers: answers,
  2194. Questions: response.Questions,
  2195. }
  2196. }
  2197. }
  2198. func getKeyboardInteractiveAnswers(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
  2199. user *User, ip, protocol string,
  2200. ) ([]string, error) {
  2201. questions := response.Questions
  2202. answers, err := client(user.Username, response.Instruction, questions, response.Echos)
  2203. if err != nil {
  2204. providerLog(logger.LevelInfo, "error getting interactive auth client response: %v", err)
  2205. return answers, err
  2206. }
  2207. if len(answers) != len(questions) {
  2208. err = fmt.Errorf("client answers does not match questions, expected: %v actual: %v", questions, answers)
  2209. providerLog(logger.LevelInfo, "keyboard interactive auth error: %v", err)
  2210. return answers, err
  2211. }
  2212. if len(answers) == 1 && response.CheckPwd > 0 {
  2213. if response.CheckPwd == 2 {
  2214. if !user.Filters.TOTPConfig.Enabled || !util.IsStringInSlice(protocolSSH, user.Filters.TOTPConfig.Protocols) {
  2215. providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to check TOTP passcode, TOTP is not enabled for user %#v",
  2216. user.Username)
  2217. return answers, errors.New("TOTP not enabled for SSH protocol")
  2218. }
  2219. err := user.Filters.TOTPConfig.Secret.TryDecrypt()
  2220. if err != nil {
  2221. providerLog(logger.LevelWarn, "unable to decrypt TOTP secret for user %#v, protocol %v, err: %v",
  2222. user.Username, protocol, err)
  2223. return answers, fmt.Errorf("unable to decrypt TOTP secret: %w", err)
  2224. }
  2225. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, answers[0],
  2226. user.Filters.TOTPConfig.Secret.GetPayload())
  2227. if !match || err != nil {
  2228. providerLog(logger.LevelInfo, "keyboard interactive auth error: unable to validate passcode for user %#v, match? %v, err: %v",
  2229. user.Username, match, err)
  2230. return answers, errors.New("unable to validate TOTP passcode")
  2231. }
  2232. } else {
  2233. _, err = checkUserAndPass(user, answers[0], ip, protocol)
  2234. providerLog(logger.LevelInfo, "interactive auth hook requested password validation for user %#v, validation error: %v",
  2235. user.Username, err)
  2236. if err != nil {
  2237. return answers, err
  2238. }
  2239. }
  2240. answers[0] = "OK"
  2241. }
  2242. return answers, err
  2243. }
  2244. func handleProgramInteractiveQuestions(client ssh.KeyboardInteractiveChallenge, response *plugin.KeyboardAuthResponse,
  2245. user *User, stdin io.WriteCloser, ip, protocol string,
  2246. ) error {
  2247. answers, err := getKeyboardInteractiveAnswers(client, response, user, ip, protocol)
  2248. if err != nil {
  2249. return err
  2250. }
  2251. for _, answer := range answers {
  2252. if runtime.GOOS == "windows" {
  2253. answer += "\r"
  2254. }
  2255. answer += "\n"
  2256. _, err = stdin.Write([]byte(answer))
  2257. if err != nil {
  2258. providerLog(logger.LevelError, "unable to write client answer to keyboard interactive program: %v", err)
  2259. return err
  2260. }
  2261. }
  2262. return nil
  2263. }
  2264. func executeKeyboardInteractiveProgram(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (int, error) {
  2265. authResult := 0
  2266. ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  2267. defer cancel()
  2268. cmd := exec.CommandContext(ctx, authHook)
  2269. cmd.Env = append(os.Environ(),
  2270. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%v", user.Username),
  2271. fmt.Sprintf("SFTPGO_AUTHD_IP=%v", ip),
  2272. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%v", user.Password))
  2273. stdout, err := cmd.StdoutPipe()
  2274. if err != nil {
  2275. return authResult, err
  2276. }
  2277. stdin, err := cmd.StdinPipe()
  2278. if err != nil {
  2279. return authResult, err
  2280. }
  2281. err = cmd.Start()
  2282. if err != nil {
  2283. return authResult, err
  2284. }
  2285. var once sync.Once
  2286. scanner := bufio.NewScanner(stdout)
  2287. for scanner.Scan() {
  2288. var response plugin.KeyboardAuthResponse
  2289. err = json.Unmarshal(scanner.Bytes(), &response)
  2290. if err != nil {
  2291. providerLog(logger.LevelInfo, "interactive auth error parsing response: %v", err)
  2292. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  2293. break
  2294. }
  2295. if response.AuthResult != 0 {
  2296. authResult = response.AuthResult
  2297. break
  2298. }
  2299. if err = response.Validate(); err != nil {
  2300. providerLog(logger.LevelInfo, "invalid response from keyboard interactive program: %v", err)
  2301. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  2302. break
  2303. }
  2304. go func() {
  2305. err := handleProgramInteractiveQuestions(client, &response, user, stdin, ip, protocol)
  2306. if err != nil {
  2307. once.Do(func() { terminateInteractiveAuthProgram(cmd, false) })
  2308. }
  2309. }()
  2310. }
  2311. stdin.Close()
  2312. once.Do(func() { terminateInteractiveAuthProgram(cmd, true) })
  2313. go func() {
  2314. _, err := cmd.Process.Wait()
  2315. if err != nil {
  2316. providerLog(logger.LevelWarn, "error waiting for #%v process to exit: %v", authHook, err)
  2317. }
  2318. }()
  2319. return authResult, err
  2320. }
  2321. func doKeyboardInteractiveAuth(user *User, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (User, error) {
  2322. var authResult int
  2323. var err error
  2324. if plugin.Handler.HasAuthScope(plugin.AuthScopeKeyboardInteractive) {
  2325. authResult, err = executeKeyboardInteractivePlugin(user, client, ip, protocol)
  2326. } else if authHook != "" {
  2327. if strings.HasPrefix(authHook, "http") {
  2328. authResult, err = executeKeyboardInteractiveHTTPHook(user, authHook, client, ip, protocol)
  2329. } else {
  2330. authResult, err = executeKeyboardInteractiveProgram(user, authHook, client, ip, protocol)
  2331. }
  2332. } else {
  2333. authResult, err = doBuiltinKeyboardInteractiveAuth(user, client, ip, protocol)
  2334. }
  2335. if err != nil {
  2336. return *user, err
  2337. }
  2338. if authResult != 1 {
  2339. return *user, fmt.Errorf("keyboard interactive auth failed, result: %v", authResult)
  2340. }
  2341. err = user.CheckLoginConditions()
  2342. if err != nil {
  2343. return *user, err
  2344. }
  2345. return *user, nil
  2346. }
  2347. func isCheckPasswordHookDefined(protocol string) bool {
  2348. if config.CheckPasswordHook == "" {
  2349. return false
  2350. }
  2351. if config.CheckPasswordScope == 0 {
  2352. return true
  2353. }
  2354. switch protocol {
  2355. case protocolSSH:
  2356. return config.CheckPasswordScope&1 != 0
  2357. case protocolFTP:
  2358. return config.CheckPasswordScope&2 != 0
  2359. case protocolWebDAV:
  2360. return config.CheckPasswordScope&4 != 0
  2361. default:
  2362. return false
  2363. }
  2364. }
  2365. func getPasswordHookResponse(username, password, ip, protocol string) ([]byte, error) {
  2366. if strings.HasPrefix(config.CheckPasswordHook, "http") {
  2367. var result []byte
  2368. req := checkPasswordRequest{
  2369. Username: username,
  2370. Password: password,
  2371. IP: ip,
  2372. Protocol: protocol,
  2373. }
  2374. reqAsJSON, err := json.Marshal(req)
  2375. if err != nil {
  2376. return result, err
  2377. }
  2378. resp, err := httpclient.Post(config.CheckPasswordHook, "application/json", bytes.NewBuffer(reqAsJSON))
  2379. if err != nil {
  2380. providerLog(logger.LevelWarn, "error getting check password hook response: %v", err)
  2381. return result, err
  2382. }
  2383. defer resp.Body.Close()
  2384. if resp.StatusCode != http.StatusOK {
  2385. return result, fmt.Errorf("wrong http status code from chek password hook: %v, expected 200", resp.StatusCode)
  2386. }
  2387. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  2388. }
  2389. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  2390. defer cancel()
  2391. cmd := exec.CommandContext(ctx, config.CheckPasswordHook)
  2392. cmd.Env = append(os.Environ(),
  2393. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%v", username),
  2394. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%v", password),
  2395. fmt.Sprintf("SFTPGO_AUTHD_IP=%v", ip),
  2396. fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%v", protocol),
  2397. )
  2398. return cmd.Output()
  2399. }
  2400. func executeCheckPasswordHook(username, password, ip, protocol string) (checkPasswordResponse, error) {
  2401. var response checkPasswordResponse
  2402. if !isCheckPasswordHookDefined(protocol) {
  2403. response.Status = -1
  2404. return response, nil
  2405. }
  2406. startTime := time.Now()
  2407. out, err := getPasswordHookResponse(username, password, ip, protocol)
  2408. providerLog(logger.LevelDebug, "check password hook executed, error: %v, elapsed: %v", err, time.Since(startTime))
  2409. if err != nil {
  2410. return response, err
  2411. }
  2412. err = json.Unmarshal(out, &response)
  2413. return response, err
  2414. }
  2415. func getPreLoginHookResponse(loginMethod, ip, protocol string, userAsJSON []byte) ([]byte, error) {
  2416. if strings.HasPrefix(config.PreLoginHook, "http") {
  2417. var url *url.URL
  2418. var result []byte
  2419. url, err := url.Parse(config.PreLoginHook)
  2420. if err != nil {
  2421. providerLog(logger.LevelWarn, "invalid url for pre-login hook %#v, error: %v", config.PreLoginHook, err)
  2422. return result, err
  2423. }
  2424. q := url.Query()
  2425. q.Add("login_method", loginMethod)
  2426. q.Add("ip", ip)
  2427. q.Add("protocol", protocol)
  2428. url.RawQuery = q.Encode()
  2429. resp, err := httpclient.Post(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
  2430. if err != nil {
  2431. providerLog(logger.LevelWarn, "error getting pre-login hook response: %v", err)
  2432. return result, err
  2433. }
  2434. defer resp.Body.Close()
  2435. if resp.StatusCode == http.StatusNoContent {
  2436. return result, nil
  2437. }
  2438. if resp.StatusCode != http.StatusOK {
  2439. return result, fmt.Errorf("wrong pre-login hook http status code: %v, expected 200", resp.StatusCode)
  2440. }
  2441. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  2442. }
  2443. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  2444. defer cancel()
  2445. cmd := exec.CommandContext(ctx, config.PreLoginHook)
  2446. cmd.Env = append(os.Environ(),
  2447. fmt.Sprintf("SFTPGO_LOGIND_USER=%v", string(userAsJSON)),
  2448. fmt.Sprintf("SFTPGO_LOGIND_METHOD=%v", loginMethod),
  2449. fmt.Sprintf("SFTPGO_LOGIND_IP=%v", ip),
  2450. fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%v", protocol),
  2451. )
  2452. return cmd.Output()
  2453. }
  2454. func executePreLoginHook(username, loginMethod, ip, protocol string) (User, error) {
  2455. u, userAsJSON, err := getUserAndJSONForHook(username)
  2456. if err != nil {
  2457. return u, err
  2458. }
  2459. if u.Filters.Hooks.PreLoginDisabled {
  2460. return u, nil
  2461. }
  2462. startTime := time.Now()
  2463. out, err := getPreLoginHookResponse(loginMethod, ip, protocol, userAsJSON)
  2464. if err != nil {
  2465. return u, fmt.Errorf("pre-login hook error: %v, username %#v, ip %v, protocol %v elapsed %v",
  2466. err, username, ip, protocol, time.Since(startTime))
  2467. }
  2468. providerLog(logger.LevelDebug, "pre-login hook completed, elapsed: %v", time.Since(startTime))
  2469. if util.IsByteArrayEmpty(out) {
  2470. providerLog(logger.LevelDebug, "empty response from pre-login hook, no modification requested for user %#v id: %v",
  2471. username, u.ID)
  2472. if u.ID == 0 {
  2473. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %#v does not exist", username))
  2474. }
  2475. return u, nil
  2476. }
  2477. userID := u.ID
  2478. userPwd := u.Password
  2479. userUsedQuotaSize := u.UsedQuotaSize
  2480. userUsedQuotaFiles := u.UsedQuotaFiles
  2481. userLastQuotaUpdate := u.LastQuotaUpdate
  2482. userLastLogin := u.LastLogin
  2483. userCreatedAt := u.CreatedAt
  2484. err = json.Unmarshal(out, &u)
  2485. if err != nil {
  2486. return u, fmt.Errorf("invalid pre-login hook response %#v, error: %v", string(out), err)
  2487. }
  2488. u.ID = userID
  2489. u.UsedQuotaSize = userUsedQuotaSize
  2490. u.UsedQuotaFiles = userUsedQuotaFiles
  2491. u.LastQuotaUpdate = userLastQuotaUpdate
  2492. u.LastLogin = userLastLogin
  2493. u.CreatedAt = userCreatedAt
  2494. if userID == 0 {
  2495. err = provider.addUser(&u)
  2496. } else {
  2497. u.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  2498. err = provider.updateUser(&u)
  2499. if err == nil {
  2500. webDAVUsersCache.swap(&u)
  2501. if u.Password != userPwd {
  2502. cachedPasswords.Remove(username)
  2503. }
  2504. }
  2505. }
  2506. if err != nil {
  2507. return u, err
  2508. }
  2509. providerLog(logger.LevelDebug, "user %#v added/updated from pre-login hook response, id: %v", username, userID)
  2510. if userID == 0 {
  2511. return provider.userExists(username)
  2512. }
  2513. return u, nil
  2514. }
  2515. // ExecutePostLoginHook executes the post login hook if defined
  2516. func ExecutePostLoginHook(user *User, loginMethod, ip, protocol string, err error) {
  2517. if config.PostLoginHook == "" {
  2518. return
  2519. }
  2520. if config.PostLoginScope == 1 && err == nil {
  2521. return
  2522. }
  2523. if config.PostLoginScope == 2 && err != nil {
  2524. return
  2525. }
  2526. go func() {
  2527. status := "0"
  2528. if err == nil {
  2529. status = "1"
  2530. }
  2531. user.PrepareForRendering()
  2532. userAsJSON, err := json.Marshal(user)
  2533. if err != nil {
  2534. providerLog(logger.LevelWarn, "error serializing user in post login hook: %v", err)
  2535. return
  2536. }
  2537. if strings.HasPrefix(config.PostLoginHook, "http") {
  2538. var url *url.URL
  2539. url, err := url.Parse(config.PostLoginHook)
  2540. if err != nil {
  2541. providerLog(logger.LevelDebug, "Invalid post-login hook %#v", config.PostLoginHook)
  2542. return
  2543. }
  2544. q := url.Query()
  2545. q.Add("login_method", loginMethod)
  2546. q.Add("ip", ip)
  2547. q.Add("protocol", protocol)
  2548. q.Add("status", status)
  2549. url.RawQuery = q.Encode()
  2550. startTime := time.Now()
  2551. respCode := 0
  2552. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(userAsJSON))
  2553. if err == nil {
  2554. respCode = resp.StatusCode
  2555. resp.Body.Close()
  2556. }
  2557. providerLog(logger.LevelDebug, "post login hook executed for user %#v, ip %v, protocol %v, response code: %v, elapsed: %v err: %v",
  2558. user.Username, ip, protocol, respCode, time.Since(startTime), err)
  2559. return
  2560. }
  2561. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  2562. defer cancel()
  2563. cmd := exec.CommandContext(ctx, config.PostLoginHook)
  2564. cmd.Env = append(os.Environ(),
  2565. fmt.Sprintf("SFTPGO_LOGIND_USER=%v", string(userAsJSON)),
  2566. fmt.Sprintf("SFTPGO_LOGIND_IP=%v", ip),
  2567. fmt.Sprintf("SFTPGO_LOGIND_METHOD=%v", loginMethod),
  2568. fmt.Sprintf("SFTPGO_LOGIND_STATUS=%v", status),
  2569. fmt.Sprintf("SFTPGO_LOGIND_PROTOCOL=%v", protocol))
  2570. startTime := time.Now()
  2571. err = cmd.Run()
  2572. providerLog(logger.LevelDebug, "post login hook executed for user %#v, ip %v, protocol %v, elapsed %v err: %v",
  2573. user.Username, ip, protocol, time.Since(startTime), err)
  2574. }()
  2575. }
  2576. func getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol string, cert *x509.Certificate, userAsJSON []byte) ([]byte, error) {
  2577. var tlsCert string
  2578. if cert != nil {
  2579. var err error
  2580. tlsCert, err = util.EncodeTLSCertToPem(cert)
  2581. if err != nil {
  2582. return nil, err
  2583. }
  2584. }
  2585. if strings.HasPrefix(config.ExternalAuthHook, "http") {
  2586. var result []byte
  2587. authRequest := make(map[string]string)
  2588. authRequest["username"] = username
  2589. authRequest["ip"] = ip
  2590. authRequest["password"] = password
  2591. authRequest["public_key"] = pkey
  2592. authRequest["protocol"] = protocol
  2593. authRequest["keyboard_interactive"] = keyboardInteractive
  2594. authRequest["tls_cert"] = tlsCert
  2595. if len(userAsJSON) > 0 {
  2596. authRequest["user"] = string(userAsJSON)
  2597. }
  2598. authRequestAsJSON, err := json.Marshal(authRequest)
  2599. if err != nil {
  2600. providerLog(logger.LevelWarn, "error serializing external auth request: %v", err)
  2601. return result, err
  2602. }
  2603. resp, err := httpclient.Post(config.ExternalAuthHook, "application/json", bytes.NewBuffer(authRequestAsJSON))
  2604. if err != nil {
  2605. providerLog(logger.LevelWarn, "error getting external auth hook HTTP response: %v", err)
  2606. return result, err
  2607. }
  2608. defer resp.Body.Close()
  2609. providerLog(logger.LevelDebug, "external auth hook executed, response code: %v", resp.StatusCode)
  2610. if resp.StatusCode != http.StatusOK {
  2611. return result, fmt.Errorf("wrong external auth http status code: %v, expected 200", resp.StatusCode)
  2612. }
  2613. return io.ReadAll(io.LimitReader(resp.Body, maxHookResponseSize))
  2614. }
  2615. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  2616. defer cancel()
  2617. cmd := exec.CommandContext(ctx, config.ExternalAuthHook)
  2618. cmd.Env = append(os.Environ(),
  2619. fmt.Sprintf("SFTPGO_AUTHD_USERNAME=%v", username),
  2620. fmt.Sprintf("SFTPGO_AUTHD_USER=%v", string(userAsJSON)),
  2621. fmt.Sprintf("SFTPGO_AUTHD_IP=%v", ip),
  2622. fmt.Sprintf("SFTPGO_AUTHD_PASSWORD=%v", password),
  2623. fmt.Sprintf("SFTPGO_AUTHD_PUBLIC_KEY=%v", pkey),
  2624. fmt.Sprintf("SFTPGO_AUTHD_PROTOCOL=%v", protocol),
  2625. fmt.Sprintf("SFTPGO_AUTHD_TLS_CERT=%v", strings.ReplaceAll(tlsCert, "\n", "\\n")),
  2626. fmt.Sprintf("SFTPGO_AUTHD_KEYBOARD_INTERACTIVE=%v", keyboardInteractive))
  2627. return cmd.Output()
  2628. }
  2629. func updateUserFromExtAuthResponse(user *User, password, pkey string) {
  2630. if password != "" {
  2631. user.Password = password
  2632. }
  2633. if pkey != "" && !util.IsStringPrefixInSlice(pkey, user.PublicKeys) {
  2634. user.PublicKeys = append(user.PublicKeys, pkey)
  2635. }
  2636. }
  2637. func doExternalAuth(username, password string, pubKey []byte, keyboardInteractive, ip, protocol string, tlsCert *x509.Certificate) (User, error) {
  2638. var user User
  2639. u, userAsJSON, err := getUserAndJSONForHook(username)
  2640. if err != nil {
  2641. return user, err
  2642. }
  2643. if u.Filters.Hooks.ExternalAuthDisabled {
  2644. return u, nil
  2645. }
  2646. pkey, err := util.GetSSHPublicKeyAsString(pubKey)
  2647. if err != nil {
  2648. return user, err
  2649. }
  2650. startTime := time.Now()
  2651. out, err := getExternalAuthResponse(username, password, pkey, keyboardInteractive, ip, protocol, tlsCert, userAsJSON)
  2652. if err != nil {
  2653. return user, fmt.Errorf("external auth error for user %#v: %v, elapsed: %v", username, err, time.Since(startTime))
  2654. }
  2655. providerLog(logger.LevelDebug, "external auth completed for user %#v, elapsed: %v", username, time.Since(startTime))
  2656. if util.IsByteArrayEmpty(out) {
  2657. providerLog(logger.LevelDebug, "empty response from external hook, no modification requested for user %#v id: %v",
  2658. username, u.ID)
  2659. if u.ID == 0 {
  2660. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %#v does not exist", username))
  2661. }
  2662. return u, nil
  2663. }
  2664. err = json.Unmarshal(out, &user)
  2665. if err != nil {
  2666. return user, fmt.Errorf("invalid external auth response: %v", err)
  2667. }
  2668. // an empty username means authentication failure
  2669. if user.Username == "" {
  2670. return user, ErrInvalidCredentials
  2671. }
  2672. updateUserFromExtAuthResponse(&user, password, pkey)
  2673. // some users want to map multiple login usernames with a single SFTPGo account
  2674. // for example an SFTP user logins using "user1" or "user2" and the external auth
  2675. // returns "user" in both cases, so we use the username returned from
  2676. // external auth and not the one used to login
  2677. if user.Username != username {
  2678. u, err = provider.userExists(user.Username)
  2679. }
  2680. if u.ID > 0 && err == nil {
  2681. user.ID = u.ID
  2682. user.UsedQuotaSize = u.UsedQuotaSize
  2683. user.UsedQuotaFiles = u.UsedQuotaFiles
  2684. user.LastQuotaUpdate = u.LastQuotaUpdate
  2685. user.LastLogin = u.LastLogin
  2686. user.CreatedAt = u.CreatedAt
  2687. user.UpdatedAt = util.GetTimeAsMsSinceEpoch(time.Now())
  2688. err = provider.updateUser(&user)
  2689. if err == nil {
  2690. webDAVUsersCache.swap(&user)
  2691. cachedPasswords.Add(user.Username, password)
  2692. }
  2693. return user, err
  2694. }
  2695. err = provider.addUser(&user)
  2696. if err != nil {
  2697. return user, err
  2698. }
  2699. return provider.userExists(user.Username)
  2700. }
  2701. func doPluginAuth(username, password string, pubKey []byte, ip, protocol string,
  2702. tlsCert *x509.Certificate, authScope int,
  2703. ) (User, error) {
  2704. var user User
  2705. u, userAsJSON, err := getUserAndJSONForHook(username)
  2706. if err != nil {
  2707. return user, err
  2708. }
  2709. if u.Filters.Hooks.ExternalAuthDisabled {
  2710. return u, nil
  2711. }
  2712. pkey, err := util.GetSSHPublicKeyAsString(pubKey)
  2713. if err != nil {
  2714. return user, err
  2715. }
  2716. startTime := time.Now()
  2717. out, err := plugin.Handler.Authenticate(username, password, ip, protocol, pkey, tlsCert, authScope, userAsJSON)
  2718. if err != nil {
  2719. return user, fmt.Errorf("plugin auth error for user %#v: %v, elapsed: %v, auth scope: %v",
  2720. username, err, time.Since(startTime), authScope)
  2721. }
  2722. providerLog(logger.LevelDebug, "plugin auth completed for user %#v, elapsed: %v,auth scope: %v",
  2723. username, time.Since(startTime), authScope)
  2724. if util.IsByteArrayEmpty(out) {
  2725. providerLog(logger.LevelDebug, "empty response from plugin auth, no modification requested for user %#v id: %v",
  2726. username, u.ID)
  2727. if u.ID == 0 {
  2728. return u, util.NewRecordNotFoundError(fmt.Sprintf("username %#v does not exist", username))
  2729. }
  2730. return u, nil
  2731. }
  2732. err = json.Unmarshal(out, &user)
  2733. if err != nil {
  2734. return user, fmt.Errorf("invalid plugin auth response: %v", err)
  2735. }
  2736. updateUserFromExtAuthResponse(&user, password, pkey)
  2737. if u.ID > 0 {
  2738. user.ID = u.ID
  2739. user.UsedQuotaSize = u.UsedQuotaSize
  2740. user.UsedQuotaFiles = u.UsedQuotaFiles
  2741. user.LastQuotaUpdate = u.LastQuotaUpdate
  2742. user.LastLogin = u.LastLogin
  2743. err = provider.updateUser(&user)
  2744. if err == nil {
  2745. webDAVUsersCache.swap(&user)
  2746. cachedPasswords.Add(user.Username, password)
  2747. }
  2748. return user, err
  2749. }
  2750. err = provider.addUser(&user)
  2751. if err != nil {
  2752. return user, err
  2753. }
  2754. return provider.userExists(user.Username)
  2755. }
  2756. func getUserAndJSONForHook(username string) (User, []byte, error) {
  2757. var userAsJSON []byte
  2758. u, err := provider.userExists(username)
  2759. if err != nil {
  2760. if _, ok := err.(*util.RecordNotFoundError); !ok {
  2761. return u, userAsJSON, err
  2762. }
  2763. u = User{
  2764. BaseUser: sdk.BaseUser{
  2765. ID: 0,
  2766. Username: username,
  2767. },
  2768. }
  2769. }
  2770. userAsJSON, err = json.Marshal(u)
  2771. if err != nil {
  2772. return u, userAsJSON, err
  2773. }
  2774. return u, userAsJSON, err
  2775. }
  2776. func providerLog(level logger.LogLevel, format string, v ...interface{}) {
  2777. logger.Log(level, logSender, "", format, v...)
  2778. }