dataprovider.go 100 KB

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