dataprovider.go 102 KB

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