dataprovider.go 99 KB

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