dataprovider.go 92 KB

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