user.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package dataprovider
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "math"
  20. "net"
  21. "os"
  22. "path"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/rs/xid"
  27. "github.com/sftpgo/sdk"
  28. "github.com/drakkan/sftpgo/v2/internal/kms"
  29. "github.com/drakkan/sftpgo/v2/internal/logger"
  30. "github.com/drakkan/sftpgo/v2/internal/mfa"
  31. "github.com/drakkan/sftpgo/v2/internal/plugin"
  32. "github.com/drakkan/sftpgo/v2/internal/util"
  33. "github.com/drakkan/sftpgo/v2/internal/vfs"
  34. )
  35. // Available permissions for SFTPGo users
  36. const (
  37. // All permissions are granted
  38. PermAny = "*"
  39. // List items such as files and directories is allowed
  40. PermListItems = "list"
  41. // download files is allowed
  42. PermDownload = "download"
  43. // upload files is allowed
  44. PermUpload = "upload"
  45. // overwrite an existing file, while uploading, is allowed
  46. // upload permission is required to allow file overwrite
  47. PermOverwrite = "overwrite"
  48. // delete files or directories is allowed
  49. PermDelete = "delete"
  50. // delete files is allowed
  51. PermDeleteFiles = "delete_files"
  52. // delete directories is allowed
  53. PermDeleteDirs = "delete_dirs"
  54. // rename files or directories is allowed
  55. PermRename = "rename"
  56. // rename files is allowed
  57. PermRenameFiles = "rename_files"
  58. // rename directories is allowed
  59. PermRenameDirs = "rename_dirs"
  60. // create directories is allowed
  61. PermCreateDirs = "create_dirs"
  62. // create symbolic links is allowed
  63. PermCreateSymlinks = "create_symlinks"
  64. // changing file or directory permissions is allowed
  65. PermChmod = "chmod"
  66. // changing file or directory owner and group is allowed
  67. PermChown = "chown"
  68. // changing file or directory access and modification time is allowed
  69. PermChtimes = "chtimes"
  70. )
  71. // Available login methods
  72. const (
  73. LoginMethodNoAuthTried = "no_auth_tried"
  74. LoginMethodPassword = "password"
  75. SSHLoginMethodPassword = "password-over-SSH"
  76. SSHLoginMethodPublicKey = "publickey"
  77. SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
  78. SSHLoginMethodKeyAndPassword = "publickey+password"
  79. SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive"
  80. LoginMethodTLSCertificate = "TLSCertificate"
  81. LoginMethodTLSCertificateAndPwd = "TLSCertificate+password"
  82. LoginMethodIDP = "IDP"
  83. )
  84. var (
  85. errNoMatchingVirtualFolder = errors.New("no matching virtual folder found")
  86. permsRenameAny = []string{PermRename, PermRenameDirs, PermRenameFiles}
  87. permsDeleteAny = []string{PermDelete, PermDeleteDirs, PermDeleteFiles}
  88. )
  89. // RecoveryCode defines a 2FA recovery code
  90. type RecoveryCode struct {
  91. Secret *kms.Secret `json:"secret"`
  92. Used bool `json:"used,omitempty"`
  93. }
  94. // UserTOTPConfig defines the time-based one time password configuration
  95. type UserTOTPConfig struct {
  96. Enabled bool `json:"enabled,omitempty"`
  97. ConfigName string `json:"config_name,omitempty"`
  98. Secret *kms.Secret `json:"secret,omitempty"`
  99. // TOTP will be required for the specified protocols.
  100. // SSH protocol (SFTP/SCP/SSH commands) will ask for the TOTP passcode if the client uses keyboard interactive
  101. // authentication.
  102. // FTP have no standard way to support two factor authentication, if you
  103. // enable the support for this protocol you have to add the TOTP passcode after the password.
  104. // For example if your password is "password" and your one time passcode is
  105. // "123456" you have to use "password123456" as password.
  106. Protocols []string `json:"protocols,omitempty"`
  107. }
  108. // UserFilters defines additional restrictions for a user
  109. // TODO: rename to UserOptions in v3
  110. type UserFilters struct {
  111. sdk.BaseUserFilters
  112. // User must change password from WebClient/REST API at next login.
  113. RequirePasswordChange bool `json:"require_password_change,omitempty"`
  114. // Time-based one time passwords configuration
  115. TOTPConfig UserTOTPConfig `json:"totp_config,omitempty"`
  116. // Recovery codes to use if the user loses access to their second factor auth device.
  117. // Each code can only be used once, you should use these codes to login and disable or
  118. // reset 2FA for your account
  119. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  120. }
  121. // User defines a SFTPGo user
  122. type User struct {
  123. sdk.BaseUser
  124. // Additional restrictions
  125. Filters UserFilters `json:"filters"`
  126. // Mapping between virtual paths and virtual folders
  127. VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
  128. // Filesystem configuration details
  129. FsConfig vfs.Filesystem `json:"filesystem"`
  130. // groups associated with this user
  131. Groups []sdk.GroupMapping `json:"groups,omitempty"`
  132. // we store the filesystem here using the base path as key.
  133. fsCache map[string]vfs.Fs `json:"-"`
  134. // true if group settings are already applied for this user
  135. groupSettingsApplied bool `json:"-"`
  136. // in multi node setups we mark the user as deleted to be able to update the webdav cache
  137. DeletedAt int64 `json:"-"`
  138. }
  139. // GetFilesystem returns the base filesystem for this user
  140. func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error) {
  141. return u.GetFilesystemForPath("/", connectionID)
  142. }
  143. func (u *User) getRootFs(connectionID string) (fs vfs.Fs, err error) {
  144. switch u.FsConfig.Provider {
  145. case sdk.S3FilesystemProvider:
  146. return vfs.NewS3Fs(connectionID, u.GetHomeDir(), "", u.FsConfig.S3Config)
  147. case sdk.GCSFilesystemProvider:
  148. return vfs.NewGCSFs(connectionID, u.GetHomeDir(), "", u.FsConfig.GCSConfig)
  149. case sdk.AzureBlobFilesystemProvider:
  150. return vfs.NewAzBlobFs(connectionID, u.GetHomeDir(), "", u.FsConfig.AzBlobConfig)
  151. case sdk.CryptedFilesystemProvider:
  152. return vfs.NewCryptFs(connectionID, u.GetHomeDir(), "", u.FsConfig.CryptConfig)
  153. case sdk.SFTPFilesystemProvider:
  154. forbiddenSelfUsers, err := u.getForbiddenSFTPSelfUsers(u.FsConfig.SFTPConfig.Username)
  155. if err != nil {
  156. return nil, err
  157. }
  158. forbiddenSelfUsers = append(forbiddenSelfUsers, u.Username)
  159. return vfs.NewSFTPFs(connectionID, "", u.GetHomeDir(), forbiddenSelfUsers, u.FsConfig.SFTPConfig)
  160. case sdk.HTTPFilesystemProvider:
  161. return vfs.NewHTTPFs(connectionID, u.GetHomeDir(), "", u.FsConfig.HTTPConfig)
  162. default:
  163. return vfs.NewOsFs(connectionID, u.GetHomeDir(), "", &u.FsConfig.OSConfig), nil
  164. }
  165. }
  166. func (u *User) checkDirWithParents(virtualDirPath, connectionID string) error {
  167. dirs := util.GetDirsForVirtualPath(virtualDirPath)
  168. for idx := len(dirs) - 1; idx >= 0; idx-- {
  169. vPath := dirs[idx]
  170. if vPath == "/" {
  171. continue
  172. }
  173. fs, err := u.GetFilesystemForPath(vPath, connectionID)
  174. if err != nil {
  175. return fmt.Errorf("unable to get fs for path %q: %w", vPath, err)
  176. }
  177. if fs.HasVirtualFolders() {
  178. continue
  179. }
  180. fsPath, err := fs.ResolvePath(vPath)
  181. if err != nil {
  182. return fmt.Errorf("unable to resolve path %q: %w", vPath, err)
  183. }
  184. _, err = fs.Stat(fsPath)
  185. if err == nil {
  186. continue
  187. }
  188. if fs.IsNotExist(err) {
  189. err = fs.Mkdir(fsPath)
  190. if err != nil {
  191. return err
  192. }
  193. vfs.SetPathPermissions(fs, fsPath, u.GetUID(), u.GetGID())
  194. } else {
  195. return fmt.Errorf("unable to stat path %q: %w", vPath, err)
  196. }
  197. }
  198. return nil
  199. }
  200. func (u *User) checkLocalHomeDir(connectionID string) {
  201. switch u.FsConfig.Provider {
  202. case sdk.LocalFilesystemProvider, sdk.CryptedFilesystemProvider:
  203. return
  204. default:
  205. osFs := vfs.NewOsFs(connectionID, u.GetHomeDir(), "", nil)
  206. osFs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  207. }
  208. }
  209. func (u *User) checkRootPath(connectionID string) error {
  210. fs, err := u.GetFilesystemForPath("/", connectionID)
  211. if err != nil {
  212. logger.Warn(logSender, connectionID, "could not create main filesystem for user %q err: %v", u.Username, err)
  213. return fmt.Errorf("could not create root filesystem: %w", err)
  214. }
  215. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  216. return nil
  217. }
  218. // CheckFsRoot check the root directory for the main fs and the virtual folders.
  219. // It returns an error if the main filesystem cannot be created
  220. func (u *User) CheckFsRoot(connectionID string) error {
  221. if u.Filters.DisableFsChecks {
  222. return nil
  223. }
  224. delay := lastLoginMinDelay
  225. if u.Filters.ExternalAuthCacheTime > 0 {
  226. cacheTime := time.Duration(u.Filters.ExternalAuthCacheTime) * time.Second
  227. if cacheTime > delay {
  228. delay = cacheTime
  229. }
  230. }
  231. if isLastActivityRecent(u.LastLogin, delay) {
  232. if u.LastLogin > u.UpdatedAt {
  233. if config.IsShared == 1 {
  234. u.checkLocalHomeDir(connectionID)
  235. }
  236. return nil
  237. }
  238. }
  239. err := u.checkRootPath(connectionID)
  240. if err != nil {
  241. return err
  242. }
  243. if u.Filters.StartDirectory != "" {
  244. err = u.checkDirWithParents(u.Filters.StartDirectory, connectionID)
  245. if err != nil {
  246. logger.Warn(logSender, connectionID, "could not create start directory %q, err: %v",
  247. u.Filters.StartDirectory, err)
  248. }
  249. }
  250. for idx := range u.VirtualFolders {
  251. v := &u.VirtualFolders[idx]
  252. fs, err := u.GetFilesystemForPath(v.VirtualPath, connectionID)
  253. if err == nil {
  254. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  255. }
  256. // now check intermediary folders
  257. err = u.checkDirWithParents(path.Dir(v.VirtualPath), connectionID)
  258. if err != nil {
  259. logger.Warn(logSender, connectionID, "could not create intermediary dir to %q, err: %v", v.VirtualPath, err)
  260. }
  261. }
  262. return nil
  263. }
  264. // GetCleanedPath returns a clean POSIX absolute path using the user start directory as base
  265. // if the provided rawVirtualPath is relative
  266. func (u *User) GetCleanedPath(rawVirtualPath string) string {
  267. if u.Filters.StartDirectory != "" {
  268. if !path.IsAbs(rawVirtualPath) {
  269. var b strings.Builder
  270. b.Grow(len(u.Filters.StartDirectory) + 1 + len(rawVirtualPath))
  271. b.WriteString(u.Filters.StartDirectory)
  272. b.WriteString("/")
  273. b.WriteString(rawVirtualPath)
  274. return util.CleanPath(b.String())
  275. }
  276. }
  277. return util.CleanPath(rawVirtualPath)
  278. }
  279. // isFsEqual returns true if the filesystem configurations are the same
  280. func (u *User) isFsEqual(other *User) bool {
  281. if u.FsConfig.Provider == sdk.LocalFilesystemProvider && u.GetHomeDir() != other.GetHomeDir() {
  282. return false
  283. }
  284. if !u.FsConfig.IsEqual(other.FsConfig) {
  285. return false
  286. }
  287. if u.Filters.StartDirectory != other.Filters.StartDirectory {
  288. return false
  289. }
  290. if len(u.VirtualFolders) != len(other.VirtualFolders) {
  291. return false
  292. }
  293. for idx := range u.VirtualFolders {
  294. f := &u.VirtualFolders[idx]
  295. found := false
  296. for idx1 := range other.VirtualFolders {
  297. f1 := &other.VirtualFolders[idx1]
  298. if f.VirtualPath == f1.VirtualPath {
  299. found = true
  300. if f.FsConfig.Provider == sdk.LocalFilesystemProvider && f.MappedPath != f1.MappedPath {
  301. return false
  302. }
  303. if !f.FsConfig.IsEqual(f1.FsConfig) {
  304. return false
  305. }
  306. }
  307. }
  308. if !found {
  309. return false
  310. }
  311. }
  312. return true
  313. }
  314. // CheckLoginConditions checks if the user is active and not expired
  315. func (u *User) CheckLoginConditions() error {
  316. if u.Status < 1 {
  317. return fmt.Errorf("user %q is disabled", u.Username)
  318. }
  319. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  320. return fmt.Errorf("user %q is expired, expiration timestamp: %v current timestamp: %v", u.Username,
  321. u.ExpirationDate, util.GetTimeAsMsSinceEpoch(time.Now()))
  322. }
  323. return nil
  324. }
  325. // hideConfidentialData hides user confidential data
  326. func (u *User) hideConfidentialData() {
  327. u.Password = ""
  328. u.FsConfig.HideConfidentialData()
  329. if u.Filters.TOTPConfig.Secret != nil {
  330. u.Filters.TOTPConfig.Secret.Hide()
  331. }
  332. for _, code := range u.Filters.RecoveryCodes {
  333. if code.Secret != nil {
  334. code.Secret.Hide()
  335. }
  336. }
  337. }
  338. // CheckMaxShareExpiration returns an error if the share expiration exceed the
  339. // maximum allowed date.
  340. func (u *User) CheckMaxShareExpiration(expiresAt time.Time) error {
  341. if u.Filters.MaxSharesExpiration == 0 {
  342. return nil
  343. }
  344. maxAllowedExpiration := time.Now().Add(24 * time.Hour * time.Duration(u.Filters.MaxSharesExpiration+1))
  345. maxAllowedExpiration = time.Date(maxAllowedExpiration.Year(), maxAllowedExpiration.Month(),
  346. maxAllowedExpiration.Day(), 0, 0, 0, 0, maxAllowedExpiration.Location())
  347. if util.GetTimeAsMsSinceEpoch(expiresAt) == 0 || expiresAt.After(maxAllowedExpiration) {
  348. return util.NewValidationError(fmt.Sprintf("the share must expire before %s", maxAllowedExpiration.Format(time.DateOnly)))
  349. }
  350. return nil
  351. }
  352. // GetSubDirPermissions returns permissions for sub directories
  353. func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions {
  354. var result []sdk.DirectoryPermissions
  355. for k, v := range u.Permissions {
  356. if k == "/" {
  357. continue
  358. }
  359. dirPerms := sdk.DirectoryPermissions{
  360. Path: k,
  361. Permissions: v,
  362. }
  363. result = append(result, dirPerms)
  364. }
  365. return result
  366. }
  367. func (u *User) setAnonymousSettings() {
  368. for k := range u.Permissions {
  369. u.Permissions[k] = []string{PermListItems, PermDownload}
  370. }
  371. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, protocolSSH, protocolHTTP)
  372. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  373. for _, method := range ValidLoginMethods {
  374. if method != LoginMethodPassword {
  375. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, method)
  376. }
  377. }
  378. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  379. }
  380. // RenderAsJSON implements the renderer interface used within plugins
  381. func (u *User) RenderAsJSON(reload bool) ([]byte, error) {
  382. if reload {
  383. user, err := provider.userExists(u.Username, "")
  384. if err != nil {
  385. providerLog(logger.LevelError, "unable to reload user before rendering as json: %v", err)
  386. return nil, err
  387. }
  388. user.PrepareForRendering()
  389. return json.Marshal(user)
  390. }
  391. u.PrepareForRendering()
  392. return json.Marshal(u)
  393. }
  394. // PrepareForRendering prepares a user for rendering.
  395. // It hides confidential data and set to nil the empty secrets
  396. // so they are not serialized
  397. func (u *User) PrepareForRendering() {
  398. u.hideConfidentialData()
  399. u.FsConfig.SetNilSecretsIfEmpty()
  400. for idx := range u.VirtualFolders {
  401. folder := &u.VirtualFolders[idx]
  402. folder.PrepareForRendering()
  403. }
  404. }
  405. // HasRedactedSecret returns true if the user has a redacted secret
  406. func (u *User) hasRedactedSecret() bool {
  407. if u.FsConfig.HasRedactedSecret() {
  408. return true
  409. }
  410. for idx := range u.VirtualFolders {
  411. folder := &u.VirtualFolders[idx]
  412. if folder.HasRedactedSecret() {
  413. return true
  414. }
  415. }
  416. return u.Filters.TOTPConfig.Secret.IsRedacted()
  417. }
  418. // CloseFs closes the underlying filesystems
  419. func (u *User) CloseFs() error {
  420. if u.fsCache == nil {
  421. return nil
  422. }
  423. var err error
  424. for _, fs := range u.fsCache {
  425. errClose := fs.Close()
  426. if err == nil {
  427. err = errClose
  428. }
  429. }
  430. return err
  431. }
  432. // IsPasswordHashed returns true if the password is hashed
  433. func (u *User) IsPasswordHashed() bool {
  434. return util.IsStringPrefixInSlice(u.Password, hashPwdPrefixes)
  435. }
  436. // IsTLSVerificationEnabled returns true if we need to check the TLS authentication
  437. func (u *User) IsTLSVerificationEnabled() bool {
  438. if len(u.Filters.TLSCerts) > 0 {
  439. return true
  440. }
  441. if u.Filters.TLSUsername != "" {
  442. return u.Filters.TLSUsername != sdk.TLSUsernameNone
  443. }
  444. return false
  445. }
  446. // SetEmptySecrets sets to empty any user secret
  447. func (u *User) SetEmptySecrets() {
  448. u.FsConfig.SetEmptySecrets()
  449. for idx := range u.VirtualFolders {
  450. folder := &u.VirtualFolders[idx]
  451. folder.FsConfig.SetEmptySecrets()
  452. }
  453. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  454. }
  455. // GetPermissionsForPath returns the permissions for the given path.
  456. // The path must be a SFTPGo virtual path
  457. func (u *User) GetPermissionsForPath(p string) []string {
  458. permissions := []string{}
  459. if perms, ok := u.Permissions["/"]; ok {
  460. // if only root permissions are defined returns them unconditionally
  461. if len(u.Permissions) == 1 {
  462. return perms
  463. }
  464. // fallback permissions
  465. permissions = perms
  466. }
  467. dirsForPath := util.GetDirsForVirtualPath(p)
  468. // dirsForPath contains all the dirs for a given path in reverse order
  469. // for example if the path is: /1/2/3/4 it contains:
  470. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  471. // so the first match is the one we are interested to
  472. for idx := range dirsForPath {
  473. if perms, ok := u.Permissions[dirsForPath[idx]]; ok {
  474. return perms
  475. }
  476. for dir, perms := range u.Permissions {
  477. if match, err := path.Match(dir, dirsForPath[idx]); err == nil && match {
  478. return perms
  479. }
  480. }
  481. }
  482. return permissions
  483. }
  484. func (u *User) getForbiddenSFTPSelfUsers(username string) ([]string, error) {
  485. if allowSelfConnections == 0 {
  486. return nil, nil
  487. }
  488. sftpUser, err := UserExists(username, "")
  489. if err == nil {
  490. err = sftpUser.LoadAndApplyGroupSettings()
  491. }
  492. if err == nil {
  493. // we don't allow local nested SFTP folders
  494. var forbiddens []string
  495. if sftpUser.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  496. forbiddens = append(forbiddens, sftpUser.Username)
  497. return forbiddens, nil
  498. }
  499. for idx := range sftpUser.VirtualFolders {
  500. v := &sftpUser.VirtualFolders[idx]
  501. if v.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  502. forbiddens = append(forbiddens, sftpUser.Username)
  503. return forbiddens, nil
  504. }
  505. }
  506. return forbiddens, nil
  507. }
  508. if !errors.Is(err, util.ErrNotFound) {
  509. return nil, err
  510. }
  511. return nil, nil
  512. }
  513. // GetFsConfigForPath returns the file system configuration for the specified virtual path
  514. func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem {
  515. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  516. folder, err := u.GetVirtualFolderForPath(virtualPath)
  517. if err == nil {
  518. return folder.FsConfig
  519. }
  520. }
  521. return u.FsConfig
  522. }
  523. // GetFilesystemForPath returns the filesystem for the given path
  524. func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error) {
  525. if u.fsCache == nil {
  526. u.fsCache = make(map[string]vfs.Fs)
  527. }
  528. // allow to override the `/` path with a virtual folder
  529. if len(u.VirtualFolders) > 0 {
  530. folder, err := u.GetVirtualFolderForPath(virtualPath)
  531. if err == nil {
  532. if fs, ok := u.fsCache[folder.VirtualPath]; ok {
  533. return fs, nil
  534. }
  535. forbiddenSelfUsers := []string{u.Username}
  536. if folder.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  537. forbiddens, err := u.getForbiddenSFTPSelfUsers(folder.FsConfig.SFTPConfig.Username)
  538. if err != nil {
  539. return nil, err
  540. }
  541. forbiddenSelfUsers = append(forbiddenSelfUsers, forbiddens...)
  542. }
  543. fs, err := folder.GetFilesystem(connectionID, forbiddenSelfUsers)
  544. if err == nil {
  545. u.fsCache[folder.VirtualPath] = fs
  546. }
  547. return fs, err
  548. }
  549. }
  550. if val, ok := u.fsCache["/"]; ok {
  551. return val, nil
  552. }
  553. fs, err := u.getRootFs(connectionID)
  554. if err != nil {
  555. return fs, err
  556. }
  557. u.fsCache["/"] = fs
  558. return fs, err
  559. }
  560. // GetVirtualFolderForPath returns the virtual folder containing the specified virtual path.
  561. // If the path is not inside a virtual folder an error is returned
  562. func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error) {
  563. var folder vfs.VirtualFolder
  564. if len(u.VirtualFolders) == 0 {
  565. return folder, errNoMatchingVirtualFolder
  566. }
  567. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  568. for index := range dirsForPath {
  569. for idx := range u.VirtualFolders {
  570. v := &u.VirtualFolders[idx]
  571. if v.VirtualPath == dirsForPath[index] {
  572. return *v, nil
  573. }
  574. }
  575. }
  576. return folder, errNoMatchingVirtualFolder
  577. }
  578. // ScanQuota scans the user home dir and virtual folders, included in its quota,
  579. // and returns the number of files and their size
  580. func (u *User) ScanQuota() (int, int64, error) {
  581. fs, err := u.getRootFs(xid.New().String())
  582. if err != nil {
  583. return 0, 0, err
  584. }
  585. defer fs.Close()
  586. numFiles, size, err := fs.ScanRootDirContents()
  587. if err != nil {
  588. return numFiles, size, err
  589. }
  590. for idx := range u.VirtualFolders {
  591. v := &u.VirtualFolders[idx]
  592. if !v.IsIncludedInUserQuota() {
  593. continue
  594. }
  595. num, s, err := v.ScanQuota()
  596. if err != nil {
  597. return numFiles, size, err
  598. }
  599. numFiles += num
  600. size += s
  601. }
  602. return numFiles, size, nil
  603. }
  604. // GetVirtualFoldersInPath returns the virtual folders inside virtualPath including
  605. // any parents
  606. func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool {
  607. result := make(map[string]bool)
  608. for idx := range u.VirtualFolders {
  609. dirsForPath := util.GetDirsForVirtualPath(u.VirtualFolders[idx].VirtualPath)
  610. for index := range dirsForPath {
  611. d := dirsForPath[index]
  612. if d == "/" {
  613. continue
  614. }
  615. if path.Dir(d) == virtualPath {
  616. result[d] = true
  617. }
  618. }
  619. }
  620. if u.Filters.StartDirectory != "" {
  621. dirsForPath := util.GetDirsForVirtualPath(u.Filters.StartDirectory)
  622. for index := range dirsForPath {
  623. d := dirsForPath[index]
  624. if d == "/" {
  625. continue
  626. }
  627. if path.Dir(d) == virtualPath {
  628. result[d] = true
  629. }
  630. }
  631. }
  632. return result
  633. }
  634. func (u *User) hasVirtualDirs() bool {
  635. if u.Filters.StartDirectory != "" {
  636. return true
  637. }
  638. numFolders := len(u.VirtualFolders)
  639. if numFolders == 1 {
  640. return u.VirtualFolders[0].VirtualPath != "/"
  641. }
  642. return numFolders > 0
  643. }
  644. // GetVirtualFoldersInfo returns []os.FileInfo for virtual folders
  645. func (u *User) GetVirtualFoldersInfo(virtualPath string) []os.FileInfo {
  646. filter := u.getPatternsFilterForPath(virtualPath)
  647. if !u.hasVirtualDirs() && filter.DenyPolicy != sdk.DenyPolicyHide {
  648. return nil
  649. }
  650. vdirs := u.GetVirtualFoldersInPath(virtualPath)
  651. result := make([]os.FileInfo, 0, len(vdirs))
  652. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  653. dirName := path.Base(dir)
  654. if filter.DenyPolicy == sdk.DenyPolicyHide {
  655. if !filter.CheckAllowed(dirName) {
  656. continue
  657. }
  658. }
  659. result = append(result, vfs.NewFileInfo(dirName, true, 0, time.Unix(0, 0), false))
  660. }
  661. return result
  662. }
  663. // FilterListDir removes hidden items from the given files list
  664. func (u *User) FilterListDir(dirContents []os.FileInfo, virtualPath string) []os.FileInfo {
  665. filter := u.getPatternsFilterForPath(virtualPath)
  666. if !u.hasVirtualDirs() && filter.DenyPolicy != sdk.DenyPolicyHide {
  667. return dirContents
  668. }
  669. vdirs := make(map[string]bool)
  670. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  671. dirName := path.Base(dir)
  672. if filter.DenyPolicy == sdk.DenyPolicyHide {
  673. if !filter.CheckAllowed(dirName) {
  674. continue
  675. }
  676. }
  677. vdirs[dirName] = true
  678. }
  679. validIdx := 0
  680. for idx := range dirContents {
  681. fi := dirContents[idx]
  682. if fi.Name() != "." && fi.Name() != ".." {
  683. if _, ok := vdirs[fi.Name()]; ok {
  684. continue
  685. }
  686. if filter.DenyPolicy == sdk.DenyPolicyHide {
  687. if !filter.CheckAllowed(fi.Name()) {
  688. continue
  689. }
  690. }
  691. }
  692. dirContents[validIdx] = fi
  693. validIdx++
  694. }
  695. return dirContents[:validIdx]
  696. }
  697. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  698. // The filesystem path must be cleaned before calling this method
  699. func (u *User) IsMappedPath(fsPath string) bool {
  700. for idx := range u.VirtualFolders {
  701. v := &u.VirtualFolders[idx]
  702. if fsPath == v.MappedPath {
  703. return true
  704. }
  705. }
  706. return false
  707. }
  708. // IsVirtualFolder returns true if the specified virtual path is a virtual folder
  709. func (u *User) IsVirtualFolder(virtualPath string) bool {
  710. for idx := range u.VirtualFolders {
  711. v := &u.VirtualFolders[idx]
  712. if virtualPath == v.VirtualPath {
  713. return true
  714. }
  715. }
  716. return false
  717. }
  718. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  719. // specified virtual path. We assume that path are cleaned
  720. func (u *User) HasVirtualFoldersInside(virtualPath string) bool {
  721. if virtualPath == "/" && len(u.VirtualFolders) > 0 {
  722. return true
  723. }
  724. for idx := range u.VirtualFolders {
  725. v := &u.VirtualFolders[idx]
  726. if len(v.VirtualPath) > len(virtualPath) {
  727. if strings.HasPrefix(v.VirtualPath, virtualPath+"/") {
  728. return true
  729. }
  730. }
  731. }
  732. return false
  733. }
  734. // HasPermissionsInside returns true if the specified virtualPath has no permissions itself and
  735. // no subdirs with defined permissions
  736. func (u *User) HasPermissionsInside(virtualPath string) bool {
  737. for dir, perms := range u.Permissions {
  738. if len(perms) == 1 && perms[0] == PermAny {
  739. continue
  740. }
  741. if dir == virtualPath {
  742. return true
  743. } else if len(dir) > len(virtualPath) {
  744. if strings.HasPrefix(dir, virtualPath+"/") {
  745. return true
  746. }
  747. }
  748. }
  749. return false
  750. }
  751. // HasPerm returns true if the user has the given permission or any permission
  752. func (u *User) HasPerm(permission, path string) bool {
  753. perms := u.GetPermissionsForPath(path)
  754. if util.Contains(perms, PermAny) {
  755. return true
  756. }
  757. return util.Contains(perms, permission)
  758. }
  759. // HasAnyPerm returns true if the user has at least one of the given permissions
  760. func (u *User) HasAnyPerm(permissions []string, path string) bool {
  761. perms := u.GetPermissionsForPath(path)
  762. if util.Contains(perms, PermAny) {
  763. return true
  764. }
  765. for _, permission := range permissions {
  766. if util.Contains(perms, permission) {
  767. return true
  768. }
  769. }
  770. return false
  771. }
  772. // HasPerms returns true if the user has all the given permissions
  773. func (u *User) HasPerms(permissions []string, path string) bool {
  774. perms := u.GetPermissionsForPath(path)
  775. if util.Contains(perms, PermAny) {
  776. return true
  777. }
  778. for _, permission := range permissions {
  779. if !util.Contains(perms, permission) {
  780. return false
  781. }
  782. }
  783. return true
  784. }
  785. // HasPermsDeleteAll returns true if the user can delete both files and directories
  786. // for the given path
  787. func (u *User) HasPermsDeleteAll(path string) bool {
  788. perms := u.GetPermissionsForPath(path)
  789. canDeleteFiles := false
  790. canDeleteDirs := false
  791. for _, permission := range perms {
  792. if permission == PermAny || permission == PermDelete {
  793. return true
  794. }
  795. if permission == PermDeleteFiles {
  796. canDeleteFiles = true
  797. }
  798. if permission == PermDeleteDirs {
  799. canDeleteDirs = true
  800. }
  801. }
  802. return canDeleteFiles && canDeleteDirs
  803. }
  804. // HasPermsRenameAll returns true if the user can rename both files and directories
  805. // for the given path
  806. func (u *User) HasPermsRenameAll(path string) bool {
  807. perms := u.GetPermissionsForPath(path)
  808. canRenameFiles := false
  809. canRenameDirs := false
  810. for _, permission := range perms {
  811. if permission == PermAny || permission == PermRename {
  812. return true
  813. }
  814. if permission == PermRenameFiles {
  815. canRenameFiles = true
  816. }
  817. if permission == PermRenameDirs {
  818. canRenameDirs = true
  819. }
  820. }
  821. return canRenameFiles && canRenameDirs
  822. }
  823. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  824. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  825. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  826. return true
  827. }
  828. return false
  829. }
  830. // IsLoginMethodAllowed returns true if the specified login method is allowed
  831. func (u *User) IsLoginMethodAllowed(loginMethod, protocol string) bool {
  832. if len(u.Filters.DeniedLoginMethods) == 0 {
  833. return true
  834. }
  835. if util.Contains(u.Filters.DeniedLoginMethods, loginMethod) {
  836. return false
  837. }
  838. if protocol == protocolSSH && loginMethod == LoginMethodPassword {
  839. if util.Contains(u.Filters.DeniedLoginMethods, SSHLoginMethodPassword) {
  840. return false
  841. }
  842. }
  843. return true
  844. }
  845. // GetNextAuthMethods returns the list of authentications methods that can
  846. // continue for multi-step authentication. We call this method after a
  847. // successful public key authentication.
  848. func (u *User) GetNextAuthMethods() []string {
  849. var methods []string
  850. for _, method := range u.GetAllowedLoginMethods() {
  851. if method == SSHLoginMethodKeyAndPassword {
  852. methods = append(methods, LoginMethodPassword)
  853. }
  854. if method == SSHLoginMethodKeyAndKeyboardInt {
  855. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  856. }
  857. }
  858. return methods
  859. }
  860. // IsPartialAuth returns true if the specified login method is a step for
  861. // a multi-step Authentication.
  862. // We support publickey+password and publickey+keyboard-interactive, so
  863. // only publickey can returns partial success.
  864. // We can have partial success if only multi-step Auth methods are enabled
  865. func (u *User) IsPartialAuth() bool {
  866. for _, method := range u.GetAllowedLoginMethods() {
  867. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd ||
  868. method == SSHLoginMethodPassword {
  869. continue
  870. }
  871. if method == LoginMethodPassword && util.Contains(u.Filters.DeniedLoginMethods, SSHLoginMethodPassword) {
  872. continue
  873. }
  874. if !util.Contains(SSHMultiStepsLoginMethods, method) {
  875. return false
  876. }
  877. }
  878. return true
  879. }
  880. // GetAllowedLoginMethods returns the allowed login methods
  881. func (u *User) GetAllowedLoginMethods() []string {
  882. var allowedMethods []string
  883. for _, method := range ValidLoginMethods {
  884. if method == SSHLoginMethodPassword {
  885. continue
  886. }
  887. if !util.Contains(u.Filters.DeniedLoginMethods, method) {
  888. allowedMethods = append(allowedMethods, method)
  889. }
  890. }
  891. return allowedMethods
  892. }
  893. func (u *User) getPatternsFilterForPath(virtualPath string) sdk.PatternsFilter {
  894. var filter sdk.PatternsFilter
  895. if len(u.Filters.FilePatterns) == 0 {
  896. return filter
  897. }
  898. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  899. for idx, dir := range dirsForPath {
  900. for _, f := range u.Filters.FilePatterns {
  901. if f.Path == dir {
  902. if idx > 0 && len(f.AllowedPatterns) > 0 && len(f.DeniedPatterns) > 0 && f.DeniedPatterns[0] == "*" {
  903. if f.CheckAllowed(path.Base(dirsForPath[idx-1])) {
  904. return filter
  905. }
  906. }
  907. filter = f
  908. break
  909. }
  910. }
  911. if filter.Path != "" {
  912. break
  913. }
  914. }
  915. return filter
  916. }
  917. func (u *User) isDirHidden(virtualPath string) bool {
  918. if len(u.Filters.FilePatterns) == 0 {
  919. return false
  920. }
  921. for _, dirPath := range util.GetDirsForVirtualPath(virtualPath) {
  922. if dirPath == "/" {
  923. return false
  924. }
  925. filter := u.getPatternsFilterForPath(dirPath)
  926. if filter.DenyPolicy == sdk.DenyPolicyHide && filter.Path != dirPath {
  927. if !filter.CheckAllowed(path.Base(dirPath)) {
  928. return true
  929. }
  930. }
  931. }
  932. return false
  933. }
  934. func (u *User) getMinPasswordEntropy() float64 {
  935. if u.Filters.PasswordStrength > 0 {
  936. return float64(u.Filters.PasswordStrength)
  937. }
  938. return config.PasswordValidation.Users.MinEntropy
  939. }
  940. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters.
  941. // The second parameter returned is the deny policy
  942. func (u *User) IsFileAllowed(virtualPath string) (bool, int) {
  943. dirPath := path.Dir(virtualPath)
  944. if u.isDirHidden(dirPath) {
  945. return false, sdk.DenyPolicyHide
  946. }
  947. filter := u.getPatternsFilterForPath(dirPath)
  948. return filter.CheckAllowed(path.Base(virtualPath)), filter.DenyPolicy
  949. }
  950. // CanManageMFA returns true if the user can add a multi-factor authentication configuration
  951. func (u *User) CanManageMFA() bool {
  952. if util.Contains(u.Filters.WebClient, sdk.WebClientMFADisabled) {
  953. return false
  954. }
  955. return len(mfa.GetAvailableTOTPConfigs()) > 0
  956. }
  957. func (u *User) skipExternalAuth() bool {
  958. if u.Filters.Hooks.ExternalAuthDisabled {
  959. return true
  960. }
  961. if u.ID <= 0 {
  962. return false
  963. }
  964. if u.Filters.ExternalAuthCacheTime <= 0 {
  965. return false
  966. }
  967. return isLastActivityRecent(u.LastLogin, time.Duration(u.Filters.ExternalAuthCacheTime)*time.Second)
  968. }
  969. // CanManageShares returns true if the user can add, update and list shares
  970. func (u *User) CanManageShares() bool {
  971. return !util.Contains(u.Filters.WebClient, sdk.WebClientSharesDisabled)
  972. }
  973. // CanResetPassword returns true if this user is allowed to reset its password
  974. func (u *User) CanResetPassword() bool {
  975. return !util.Contains(u.Filters.WebClient, sdk.WebClientPasswordResetDisabled)
  976. }
  977. // CanChangePassword returns true if this user is allowed to change its password
  978. func (u *User) CanChangePassword() bool {
  979. return !util.Contains(u.Filters.WebClient, sdk.WebClientPasswordChangeDisabled)
  980. }
  981. // CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
  982. func (u *User) CanChangeAPIKeyAuth() bool {
  983. return !util.Contains(u.Filters.WebClient, sdk.WebClientAPIKeyAuthChangeDisabled)
  984. }
  985. // CanChangeInfo returns true if this user is allowed to change its info such as email and description
  986. func (u *User) CanChangeInfo() bool {
  987. return !util.Contains(u.Filters.WebClient, sdk.WebClientInfoChangeDisabled)
  988. }
  989. // CanManagePublicKeys returns true if this user is allowed to manage public keys
  990. // from the web client. Used in web client UI
  991. func (u *User) CanManagePublicKeys() bool {
  992. return !util.Contains(u.Filters.WebClient, sdk.WebClientPubKeyChangeDisabled)
  993. }
  994. // CanAddFilesFromWeb returns true if the client can add files from the web UI.
  995. // The specified target is the directory where the files must be uploaded
  996. func (u *User) CanAddFilesFromWeb(target string) bool {
  997. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  998. return false
  999. }
  1000. return u.HasPerm(PermUpload, target) || u.HasPerm(PermOverwrite, target)
  1001. }
  1002. // CanAddDirsFromWeb returns true if the client can add directories from the web UI.
  1003. // The specified target is the directory where the new directory must be created
  1004. func (u *User) CanAddDirsFromWeb(target string) bool {
  1005. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1006. return false
  1007. }
  1008. return u.HasPerm(PermCreateDirs, target)
  1009. }
  1010. // CanRenameFromWeb returns true if the client can rename objects from the web UI.
  1011. // The specified src and dest are the source and target directories for the rename.
  1012. func (u *User) CanRenameFromWeb(src, dest string) bool {
  1013. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1014. return false
  1015. }
  1016. return u.HasAnyPerm(permsRenameAny, src) && u.HasAnyPerm(permsRenameAny, dest)
  1017. }
  1018. // CanDeleteFromWeb returns true if the client can delete objects from the web UI.
  1019. // The specified target is the parent directory for the object to delete
  1020. func (u *User) CanDeleteFromWeb(target string) bool {
  1021. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1022. return false
  1023. }
  1024. return u.HasAnyPerm(permsDeleteAny, target)
  1025. }
  1026. // PasswordExpiresIn returns the number of days before the password expires.
  1027. // The returned value is negative if the password is expired.
  1028. // The caller must ensure that a PasswordExpiration is set
  1029. func (u *User) PasswordExpiresIn() int {
  1030. lastPwdChange := util.GetTimeFromMsecSinceEpoch(u.LastPasswordChange)
  1031. pwdExpiration := lastPwdChange.Add(time.Duration(u.Filters.PasswordExpiration) * 24 * time.Hour)
  1032. res := int(math.Round(float64(time.Until(pwdExpiration)) / float64(24*time.Hour)))
  1033. if res == 0 && pwdExpiration.After(time.Now()) {
  1034. res = 1
  1035. }
  1036. return res
  1037. }
  1038. // MustChangePassword returns true if the user must change the password
  1039. func (u *User) MustChangePassword() bool {
  1040. if u.Filters.RequirePasswordChange {
  1041. return true
  1042. }
  1043. if u.Filters.PasswordExpiration == 0 {
  1044. return false
  1045. }
  1046. lastPwdChange := util.GetTimeFromMsecSinceEpoch(u.LastPasswordChange)
  1047. return lastPwdChange.Add(time.Duration(u.Filters.PasswordExpiration) * 24 * time.Hour).Before(time.Now())
  1048. }
  1049. // MustSetSecondFactor returns true if the user must set a second factor authentication
  1050. func (u *User) MustSetSecondFactor() bool {
  1051. if len(u.Filters.TwoFactorAuthProtocols) > 0 {
  1052. if !u.Filters.TOTPConfig.Enabled {
  1053. return true
  1054. }
  1055. for _, p := range u.Filters.TwoFactorAuthProtocols {
  1056. if !util.Contains(u.Filters.TOTPConfig.Protocols, p) {
  1057. return true
  1058. }
  1059. }
  1060. }
  1061. return false
  1062. }
  1063. // MustSetSecondFactorForProtocol returns true if the user must set a second factor authentication
  1064. // for the specified protocol
  1065. func (u *User) MustSetSecondFactorForProtocol(protocol string) bool {
  1066. if util.Contains(u.Filters.TwoFactorAuthProtocols, protocol) {
  1067. if !u.Filters.TOTPConfig.Enabled {
  1068. return true
  1069. }
  1070. if !util.Contains(u.Filters.TOTPConfig.Protocols, protocol) {
  1071. return true
  1072. }
  1073. }
  1074. return false
  1075. }
  1076. // GetSignature returns a signature for this user.
  1077. // It will change after an update
  1078. func (u *User) GetSignature() string {
  1079. return strconv.FormatInt(u.UpdatedAt, 10)
  1080. }
  1081. // GetBandwidthForIP returns the upload and download bandwidth for the specified IP
  1082. func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64) {
  1083. if len(u.Filters.BandwidthLimits) > 0 {
  1084. ip := net.ParseIP(clientIP)
  1085. if ip != nil {
  1086. for _, bwLimit := range u.Filters.BandwidthLimits {
  1087. for _, source := range bwLimit.Sources {
  1088. _, ipNet, err := net.ParseCIDR(source)
  1089. if err == nil {
  1090. if ipNet.Contains(ip) {
  1091. logger.Debug(logSender, connectionID, "override bandwidth limit for ip %q, upload limit: %v KB/s, download limit: %v KB/s",
  1092. clientIP, bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth)
  1093. return bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth
  1094. }
  1095. }
  1096. }
  1097. }
  1098. }
  1099. }
  1100. return u.UploadBandwidth, u.DownloadBandwidth
  1101. }
  1102. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  1103. // If AllowedIP is defined only the specified IP/Mask can login.
  1104. // If DeniedIP is defined the specified IP/Mask cannot login.
  1105. // If an IP is both allowed and denied then login will be allowed
  1106. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  1107. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  1108. return true
  1109. }
  1110. remoteIP := net.ParseIP(util.GetIPFromRemoteAddress(remoteAddr))
  1111. // if remoteIP is invalid we allow login, this should never happen
  1112. if remoteIP == nil {
  1113. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %q", remoteAddr)
  1114. return true
  1115. }
  1116. for _, IPMask := range u.Filters.AllowedIP {
  1117. _, IPNet, err := net.ParseCIDR(IPMask)
  1118. if err != nil {
  1119. return false
  1120. }
  1121. if IPNet.Contains(remoteIP) {
  1122. return true
  1123. }
  1124. }
  1125. for _, IPMask := range u.Filters.DeniedIP {
  1126. _, IPNet, err := net.ParseCIDR(IPMask)
  1127. if err != nil {
  1128. return false
  1129. }
  1130. if IPNet.Contains(remoteIP) {
  1131. return false
  1132. }
  1133. }
  1134. return len(u.Filters.AllowedIP) == 0
  1135. }
  1136. // GetPermissionsAsJSON returns the permissions as json byte array
  1137. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  1138. return json.Marshal(u.Permissions)
  1139. }
  1140. // GetPublicKeysAsJSON returns the public keys as json byte array
  1141. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  1142. return json.Marshal(u.PublicKeys)
  1143. }
  1144. // GetFiltersAsJSON returns the filters as json byte array
  1145. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  1146. return json.Marshal(u.Filters)
  1147. }
  1148. // GetFsConfigAsJSON returns the filesystem config as json byte array
  1149. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  1150. return json.Marshal(u.FsConfig)
  1151. }
  1152. // GetUID returns a validate uid, suitable for use with os.Chown
  1153. func (u *User) GetUID() int {
  1154. if u.UID <= 0 || u.UID > math.MaxInt32 {
  1155. return -1
  1156. }
  1157. return u.UID
  1158. }
  1159. // GetGID returns a validate gid, suitable for use with os.Chown
  1160. func (u *User) GetGID() int {
  1161. if u.GID <= 0 || u.GID > math.MaxInt32 {
  1162. return -1
  1163. }
  1164. return u.GID
  1165. }
  1166. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  1167. func (u *User) GetHomeDir() string {
  1168. return u.HomeDir
  1169. }
  1170. // HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
  1171. func (u *User) HasRecentActivity() bool {
  1172. return isLastActivityRecent(u.LastLogin, lastLoginMinDelay)
  1173. }
  1174. // HasQuotaRestrictions returns true if there are any disk quota restrictions
  1175. func (u *User) HasQuotaRestrictions() bool {
  1176. return u.QuotaFiles > 0 || u.QuotaSize > 0
  1177. }
  1178. // HasTransferQuotaRestrictions returns true if there are any data transfer restrictions
  1179. func (u *User) HasTransferQuotaRestrictions() bool {
  1180. return u.UploadDataTransfer > 0 || u.TotalDataTransfer > 0 || u.DownloadDataTransfer > 0
  1181. }
  1182. // GetDataTransferLimits returns upload, download and total data transfer limits
  1183. func (u *User) GetDataTransferLimits() (int64, int64, int64) {
  1184. var total, ul, dl int64
  1185. if u.TotalDataTransfer > 0 {
  1186. total = u.TotalDataTransfer * 1048576
  1187. }
  1188. if u.DownloadDataTransfer > 0 {
  1189. dl = u.DownloadDataTransfer * 1048576
  1190. }
  1191. if u.UploadDataTransfer > 0 {
  1192. ul = u.UploadDataTransfer * 1048576
  1193. }
  1194. return ul, dl, total
  1195. }
  1196. // GetQuotaSummary returns used quota and limits if defined
  1197. func (u *User) GetQuotaSummary() string {
  1198. var sb strings.Builder
  1199. addSection := func() {
  1200. if sb.Len() > 0 {
  1201. sb.WriteString(". ")
  1202. }
  1203. }
  1204. if u.UsedQuotaFiles > 0 || u.QuotaFiles > 0 {
  1205. sb.WriteString(fmt.Sprintf("Files: %v", u.UsedQuotaFiles))
  1206. if u.QuotaFiles > 0 {
  1207. sb.WriteString(fmt.Sprintf("/%v", u.QuotaFiles))
  1208. }
  1209. }
  1210. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  1211. addSection()
  1212. sb.WriteString(fmt.Sprintf("Size: %v", util.ByteCountIEC(u.UsedQuotaSize)))
  1213. if u.QuotaSize > 0 {
  1214. sb.WriteString(fmt.Sprintf("/%v", util.ByteCountIEC(u.QuotaSize)))
  1215. }
  1216. }
  1217. if u.TotalDataTransfer > 0 {
  1218. addSection()
  1219. total := u.UsedDownloadDataTransfer + u.UsedUploadDataTransfer
  1220. sb.WriteString(fmt.Sprintf("Transfer: %v/%v", util.ByteCountIEC(total),
  1221. util.ByteCountIEC(u.TotalDataTransfer*1048576)))
  1222. }
  1223. if u.UploadDataTransfer > 0 {
  1224. addSection()
  1225. sb.WriteString(fmt.Sprintf("UL: %v/%v", util.ByteCountIEC(u.UsedUploadDataTransfer),
  1226. util.ByteCountIEC(u.UploadDataTransfer*1048576)))
  1227. }
  1228. if u.DownloadDataTransfer > 0 {
  1229. addSection()
  1230. sb.WriteString(fmt.Sprintf("DL: %v/%v", util.ByteCountIEC(u.UsedDownloadDataTransfer),
  1231. util.ByteCountIEC(u.DownloadDataTransfer*1048576)))
  1232. }
  1233. return sb.String()
  1234. }
  1235. // GetPermissionsAsString returns the user's permissions as comma separated string
  1236. func (u *User) GetPermissionsAsString() string {
  1237. result := ""
  1238. for dir, perms := range u.Permissions {
  1239. dirPerms := strings.Join(perms, ", ")
  1240. dp := fmt.Sprintf("%q: %q", dir, dirPerms)
  1241. if dir == "/" {
  1242. if result != "" {
  1243. result = dp + ", " + result
  1244. } else {
  1245. result = dp
  1246. }
  1247. } else {
  1248. if result != "" {
  1249. result += ", "
  1250. }
  1251. result += dp
  1252. }
  1253. }
  1254. return result
  1255. }
  1256. // GetBandwidthAsString returns bandwidth limits if defines
  1257. func (u *User) GetBandwidthAsString() string {
  1258. var sb strings.Builder
  1259. sb.WriteString("DL: ")
  1260. if u.DownloadBandwidth > 0 {
  1261. sb.WriteString(util.ByteCountIEC(u.DownloadBandwidth*1000) + "/s.")
  1262. } else {
  1263. sb.WriteString("unlimited.")
  1264. }
  1265. sb.WriteString(" UL: ")
  1266. if u.UploadBandwidth > 0 {
  1267. sb.WriteString(util.ByteCountIEC(u.UploadBandwidth*1000) + "/s.")
  1268. } else {
  1269. sb.WriteString("unlimited.")
  1270. }
  1271. return sb.String()
  1272. }
  1273. // GetMFAStatusAsString returns MFA status
  1274. func (u *User) GetMFAStatusAsString() string {
  1275. if u.Filters.TOTPConfig.Enabled {
  1276. return strings.Join(u.Filters.TOTPConfig.Protocols, ", ")
  1277. }
  1278. return "Disabled"
  1279. }
  1280. // GetLastLoginAsString returns the last login as string
  1281. func (u *User) GetLastLoginAsString() string {
  1282. if u.LastLogin > 0 {
  1283. return util.GetTimeFromMsecSinceEpoch(u.LastLogin).UTC().Format(iso8601UTCFormat)
  1284. }
  1285. return ""
  1286. }
  1287. // GetLastQuotaUpdateAsString returns the last quota update as string
  1288. func (u *User) GetLastQuotaUpdateAsString() string {
  1289. if u.LastQuotaUpdate > 0 {
  1290. return util.GetTimeFromMsecSinceEpoch(u.LastQuotaUpdate).UTC().Format(iso8601UTCFormat)
  1291. }
  1292. return ""
  1293. }
  1294. // GetStorageDescrition returns the storage description
  1295. func (u *User) GetStorageDescrition() string {
  1296. switch u.FsConfig.Provider {
  1297. case sdk.LocalFilesystemProvider:
  1298. return fmt.Sprintf("Local: %v", u.GetHomeDir())
  1299. case sdk.S3FilesystemProvider:
  1300. return fmt.Sprintf("S3: %v", u.FsConfig.S3Config.Bucket)
  1301. case sdk.GCSFilesystemProvider:
  1302. return fmt.Sprintf("GCS: %v", u.FsConfig.GCSConfig.Bucket)
  1303. case sdk.AzureBlobFilesystemProvider:
  1304. return fmt.Sprintf("AzBlob: %v", u.FsConfig.AzBlobConfig.Container)
  1305. case sdk.CryptedFilesystemProvider:
  1306. return fmt.Sprintf("Encrypted: %v", u.GetHomeDir())
  1307. case sdk.SFTPFilesystemProvider:
  1308. return fmt.Sprintf("SFTP: %v", u.FsConfig.SFTPConfig.Endpoint)
  1309. case sdk.HTTPFilesystemProvider:
  1310. return fmt.Sprintf("HTTP: %v", u.FsConfig.HTTPConfig.Endpoint)
  1311. default:
  1312. return ""
  1313. }
  1314. }
  1315. // GetGroupsAsString returns the user's groups as a string
  1316. func (u *User) GetGroupsAsString() string {
  1317. if len(u.Groups) == 0 {
  1318. return ""
  1319. }
  1320. var groups []string
  1321. for _, g := range u.Groups {
  1322. if g.Type == sdk.GroupTypePrimary {
  1323. groups = append(groups, "")
  1324. copy(groups[1:], groups)
  1325. groups[0] = g.Name
  1326. } else {
  1327. groups = append(groups, g.Name)
  1328. }
  1329. }
  1330. return strings.Join(groups, ",")
  1331. }
  1332. // GetInfoString returns user's info as string.
  1333. // Storage provider, number of public keys, max sessions, uid,
  1334. // gid, denied and allowed IP/Mask are returned
  1335. func (u *User) GetInfoString() string {
  1336. var result strings.Builder
  1337. if len(u.PublicKeys) > 0 {
  1338. result.WriteString(fmt.Sprintf("Public keys: %v. ", len(u.PublicKeys)))
  1339. }
  1340. if u.MaxSessions > 0 {
  1341. result.WriteString(fmt.Sprintf("Max sessions: %v. ", u.MaxSessions))
  1342. }
  1343. if u.UID > 0 {
  1344. result.WriteString(fmt.Sprintf("UID: %v. ", u.UID))
  1345. }
  1346. if u.GID > 0 {
  1347. result.WriteString(fmt.Sprintf("GID: %v. ", u.GID))
  1348. }
  1349. if len(u.Filters.DeniedLoginMethods) > 0 {
  1350. result.WriteString(fmt.Sprintf("Denied login methods: %v. ", strings.Join(u.Filters.DeniedLoginMethods, ",")))
  1351. }
  1352. if len(u.Filters.DeniedProtocols) > 0 {
  1353. result.WriteString(fmt.Sprintf("Denied protocols: %v. ", strings.Join(u.Filters.DeniedProtocols, ",")))
  1354. }
  1355. if len(u.Filters.DeniedIP) > 0 {
  1356. result.WriteString(fmt.Sprintf("Denied IP/Mask: %v. ", len(u.Filters.DeniedIP)))
  1357. }
  1358. if len(u.Filters.AllowedIP) > 0 {
  1359. result.WriteString(fmt.Sprintf("Allowed IP/Mask: %v", len(u.Filters.AllowedIP)))
  1360. }
  1361. return result.String()
  1362. }
  1363. // GetStatusAsString returns the user status as a string
  1364. func (u *User) GetStatusAsString() string {
  1365. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  1366. return "Expired"
  1367. }
  1368. if u.Status == 1 {
  1369. return "Active"
  1370. }
  1371. return "Inactive"
  1372. }
  1373. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  1374. func (u *User) GetExpirationDateAsString() string {
  1375. if u.ExpirationDate > 0 {
  1376. t := util.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  1377. return t.Format("2006-01-02")
  1378. }
  1379. return ""
  1380. }
  1381. // GetAllowedIPAsString returns the allowed IP as comma separated string
  1382. func (u *User) GetAllowedIPAsString() string {
  1383. return strings.Join(u.Filters.AllowedIP, ",")
  1384. }
  1385. // GetDeniedIPAsString returns the denied IP as comma separated string
  1386. func (u *User) GetDeniedIPAsString() string {
  1387. return strings.Join(u.Filters.DeniedIP, ",")
  1388. }
  1389. // HasExternalAuth returns true if the external authentication is globally enabled
  1390. // and it is not disabled for this user
  1391. func (u *User) HasExternalAuth() bool {
  1392. if u.Filters.Hooks.ExternalAuthDisabled {
  1393. return false
  1394. }
  1395. if config.ExternalAuthHook != "" {
  1396. return true
  1397. }
  1398. return plugin.Handler.HasAuthenticators()
  1399. }
  1400. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  1401. func (u *User) CountUnusedRecoveryCodes() int {
  1402. unused := 0
  1403. for _, code := range u.Filters.RecoveryCodes {
  1404. if !code.Used {
  1405. unused++
  1406. }
  1407. }
  1408. return unused
  1409. }
  1410. // SetEmptySecretsIfNil sets the secrets to empty if nil
  1411. func (u *User) SetEmptySecretsIfNil() {
  1412. u.HasPassword = u.Password != ""
  1413. u.FsConfig.SetEmptySecretsIfNil()
  1414. for idx := range u.VirtualFolders {
  1415. vfolder := &u.VirtualFolders[idx]
  1416. vfolder.FsConfig.SetEmptySecretsIfNil()
  1417. }
  1418. if u.Filters.TOTPConfig.Secret == nil {
  1419. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  1420. }
  1421. }
  1422. func (u *User) hasMainDataTransferLimits() bool {
  1423. return u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 || u.TotalDataTransfer > 0
  1424. }
  1425. // HasPrimaryGroup returns true if the user has the specified primary group
  1426. func (u *User) HasPrimaryGroup(name string) bool {
  1427. for _, g := range u.Groups {
  1428. if g.Name == name {
  1429. return g.Type == sdk.GroupTypePrimary
  1430. }
  1431. }
  1432. return false
  1433. }
  1434. // HasSecondaryGroup returns true if the user has the specified secondary group
  1435. func (u *User) HasSecondaryGroup(name string) bool {
  1436. for _, g := range u.Groups {
  1437. if g.Name == name {
  1438. return g.Type == sdk.GroupTypeSecondary
  1439. }
  1440. }
  1441. return false
  1442. }
  1443. // HasMembershipGroup returns true if the user has the specified membership group
  1444. func (u *User) HasMembershipGroup(name string) bool {
  1445. for _, g := range u.Groups {
  1446. if g.Name == name {
  1447. return g.Type == sdk.GroupTypeMembership
  1448. }
  1449. }
  1450. return false
  1451. }
  1452. func (u *User) hasSettingsFromGroups() bool {
  1453. for _, g := range u.Groups {
  1454. if g.Type != sdk.GroupTypeMembership {
  1455. return true
  1456. }
  1457. }
  1458. return false
  1459. }
  1460. func (u *User) applyGroupSettings(groupsMapping map[string]Group) {
  1461. if !u.hasSettingsFromGroups() {
  1462. return
  1463. }
  1464. if u.groupSettingsApplied {
  1465. return
  1466. }
  1467. replacer := u.getGroupPlacehodersReplacer()
  1468. for _, g := range u.Groups {
  1469. if g.Type == sdk.GroupTypePrimary {
  1470. if group, ok := groupsMapping[g.Name]; ok {
  1471. u.mergeWithPrimaryGroup(&group, replacer)
  1472. } else {
  1473. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1474. }
  1475. break
  1476. }
  1477. }
  1478. for _, g := range u.Groups {
  1479. if g.Type == sdk.GroupTypeSecondary {
  1480. if group, ok := groupsMapping[g.Name]; ok {
  1481. u.mergeAdditiveProperties(&group, sdk.GroupTypeSecondary, replacer)
  1482. } else {
  1483. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1484. }
  1485. }
  1486. }
  1487. u.removeDuplicatesAfterGroupMerge()
  1488. }
  1489. // LoadAndApplyGroupSettings update the user by loading and applying the group settings
  1490. func (u *User) LoadAndApplyGroupSettings() error {
  1491. if !u.hasSettingsFromGroups() {
  1492. return nil
  1493. }
  1494. if u.groupSettingsApplied {
  1495. return nil
  1496. }
  1497. names := make([]string, 0, len(u.Groups))
  1498. var primaryGroupName string
  1499. for _, g := range u.Groups {
  1500. if g.Type == sdk.GroupTypePrimary {
  1501. primaryGroupName = g.Name
  1502. }
  1503. if g.Type != sdk.GroupTypeMembership {
  1504. names = append(names, g.Name)
  1505. }
  1506. }
  1507. groups, err := provider.getGroupsWithNames(names)
  1508. if err != nil {
  1509. return fmt.Errorf("unable to get groups: %w", err)
  1510. }
  1511. replacer := u.getGroupPlacehodersReplacer()
  1512. // make sure to always merge with the primary group first
  1513. for idx := range groups {
  1514. g := groups[idx]
  1515. if g.Name == primaryGroupName {
  1516. u.mergeWithPrimaryGroup(&g, replacer)
  1517. lastIdx := len(groups) - 1
  1518. groups[idx] = groups[lastIdx]
  1519. groups = groups[:lastIdx]
  1520. break
  1521. }
  1522. }
  1523. for idx := range groups {
  1524. g := groups[idx]
  1525. u.mergeAdditiveProperties(&g, sdk.GroupTypeSecondary, replacer)
  1526. }
  1527. u.removeDuplicatesAfterGroupMerge()
  1528. return nil
  1529. }
  1530. func (u *User) getGroupPlacehodersReplacer() *strings.Replacer {
  1531. return strings.NewReplacer("%username%", u.Username)
  1532. }
  1533. func (u *User) replacePlaceholder(value string, replacer *strings.Replacer) string {
  1534. if value == "" {
  1535. return value
  1536. }
  1537. return replacer.Replace(value)
  1538. }
  1539. func (u *User) replaceFsConfigPlaceholders(fsConfig vfs.Filesystem, replacer *strings.Replacer) vfs.Filesystem {
  1540. switch fsConfig.Provider {
  1541. case sdk.S3FilesystemProvider:
  1542. fsConfig.S3Config.KeyPrefix = u.replacePlaceholder(fsConfig.S3Config.KeyPrefix, replacer)
  1543. case sdk.GCSFilesystemProvider:
  1544. fsConfig.GCSConfig.KeyPrefix = u.replacePlaceholder(fsConfig.GCSConfig.KeyPrefix, replacer)
  1545. case sdk.AzureBlobFilesystemProvider:
  1546. fsConfig.AzBlobConfig.KeyPrefix = u.replacePlaceholder(fsConfig.AzBlobConfig.KeyPrefix, replacer)
  1547. case sdk.SFTPFilesystemProvider:
  1548. fsConfig.SFTPConfig.Username = u.replacePlaceholder(fsConfig.SFTPConfig.Username, replacer)
  1549. fsConfig.SFTPConfig.Prefix = u.replacePlaceholder(fsConfig.SFTPConfig.Prefix, replacer)
  1550. case sdk.HTTPFilesystemProvider:
  1551. fsConfig.HTTPConfig.Username = u.replacePlaceholder(fsConfig.HTTPConfig.Username, replacer)
  1552. }
  1553. return fsConfig
  1554. }
  1555. func (u *User) mergeCryptFsConfig(group *Group) {
  1556. if group.UserSettings.FsConfig.Provider == sdk.CryptedFilesystemProvider {
  1557. if u.FsConfig.CryptConfig.ReadBufferSize == 0 {
  1558. u.FsConfig.CryptConfig.ReadBufferSize = group.UserSettings.FsConfig.CryptConfig.ReadBufferSize
  1559. }
  1560. if u.FsConfig.CryptConfig.WriteBufferSize == 0 {
  1561. u.FsConfig.CryptConfig.WriteBufferSize = group.UserSettings.FsConfig.CryptConfig.WriteBufferSize
  1562. }
  1563. }
  1564. }
  1565. func (u *User) mergeWithPrimaryGroup(group *Group, replacer *strings.Replacer) {
  1566. if group.UserSettings.HomeDir != "" {
  1567. u.HomeDir = u.replacePlaceholder(group.UserSettings.HomeDir, replacer)
  1568. }
  1569. if group.UserSettings.FsConfig.Provider != 0 {
  1570. u.FsConfig = u.replaceFsConfigPlaceholders(group.UserSettings.FsConfig, replacer)
  1571. u.mergeCryptFsConfig(group)
  1572. } else {
  1573. if u.FsConfig.OSConfig.ReadBufferSize == 0 {
  1574. u.FsConfig.OSConfig.ReadBufferSize = group.UserSettings.FsConfig.OSConfig.ReadBufferSize
  1575. }
  1576. if u.FsConfig.OSConfig.WriteBufferSize == 0 {
  1577. u.FsConfig.OSConfig.WriteBufferSize = group.UserSettings.FsConfig.OSConfig.WriteBufferSize
  1578. }
  1579. }
  1580. if u.MaxSessions == 0 {
  1581. u.MaxSessions = group.UserSettings.MaxSessions
  1582. }
  1583. if u.QuotaSize == 0 {
  1584. u.QuotaSize = group.UserSettings.QuotaSize
  1585. }
  1586. if u.QuotaFiles == 0 {
  1587. u.QuotaFiles = group.UserSettings.QuotaFiles
  1588. }
  1589. if u.UploadBandwidth == 0 {
  1590. u.UploadBandwidth = group.UserSettings.UploadBandwidth
  1591. }
  1592. if u.DownloadBandwidth == 0 {
  1593. u.DownloadBandwidth = group.UserSettings.DownloadBandwidth
  1594. }
  1595. if !u.hasMainDataTransferLimits() {
  1596. u.UploadDataTransfer = group.UserSettings.UploadDataTransfer
  1597. u.DownloadDataTransfer = group.UserSettings.DownloadDataTransfer
  1598. u.TotalDataTransfer = group.UserSettings.TotalDataTransfer
  1599. }
  1600. if u.ExpirationDate == 0 && group.UserSettings.ExpiresIn > 0 {
  1601. u.ExpirationDate = u.CreatedAt + int64(group.UserSettings.ExpiresIn)*86400000
  1602. }
  1603. u.mergePrimaryGroupFilters(&group.UserSettings.Filters, replacer)
  1604. u.mergeAdditiveProperties(group, sdk.GroupTypePrimary, replacer)
  1605. }
  1606. func (u *User) mergePrimaryGroupFilters(filters *sdk.BaseUserFilters, replacer *strings.Replacer) { //nolint:gocyclo
  1607. if u.Filters.MaxUploadFileSize == 0 {
  1608. u.Filters.MaxUploadFileSize = filters.MaxUploadFileSize
  1609. }
  1610. if !u.IsTLSVerificationEnabled() {
  1611. u.Filters.TLSUsername = filters.TLSUsername
  1612. }
  1613. if !u.Filters.Hooks.CheckPasswordDisabled {
  1614. u.Filters.Hooks.CheckPasswordDisabled = filters.Hooks.CheckPasswordDisabled
  1615. }
  1616. if !u.Filters.Hooks.PreLoginDisabled {
  1617. u.Filters.Hooks.PreLoginDisabled = filters.Hooks.PreLoginDisabled
  1618. }
  1619. if !u.Filters.Hooks.ExternalAuthDisabled {
  1620. u.Filters.Hooks.ExternalAuthDisabled = filters.Hooks.ExternalAuthDisabled
  1621. }
  1622. if !u.Filters.DisableFsChecks {
  1623. u.Filters.DisableFsChecks = filters.DisableFsChecks
  1624. }
  1625. if !u.Filters.AllowAPIKeyAuth {
  1626. u.Filters.AllowAPIKeyAuth = filters.AllowAPIKeyAuth
  1627. }
  1628. if !u.Filters.IsAnonymous {
  1629. u.Filters.IsAnonymous = filters.IsAnonymous
  1630. }
  1631. if u.Filters.ExternalAuthCacheTime == 0 {
  1632. u.Filters.ExternalAuthCacheTime = filters.ExternalAuthCacheTime
  1633. }
  1634. if u.Filters.FTPSecurity == 0 {
  1635. u.Filters.FTPSecurity = filters.FTPSecurity
  1636. }
  1637. if u.Filters.StartDirectory == "" {
  1638. u.Filters.StartDirectory = u.replacePlaceholder(filters.StartDirectory, replacer)
  1639. }
  1640. if u.Filters.DefaultSharesExpiration == 0 {
  1641. u.Filters.DefaultSharesExpiration = filters.DefaultSharesExpiration
  1642. }
  1643. if u.Filters.MaxSharesExpiration == 0 {
  1644. u.Filters.MaxSharesExpiration = filters.MaxSharesExpiration
  1645. }
  1646. if u.Filters.PasswordExpiration == 0 {
  1647. u.Filters.PasswordExpiration = filters.PasswordExpiration
  1648. }
  1649. if u.Filters.PasswordStrength == 0 {
  1650. u.Filters.PasswordStrength = filters.PasswordStrength
  1651. }
  1652. }
  1653. func (u *User) mergeAdditiveProperties(group *Group, groupType int, replacer *strings.Replacer) {
  1654. u.mergeVirtualFolders(group, groupType, replacer)
  1655. u.mergePermissions(group, groupType, replacer)
  1656. u.mergeFilePatterns(group, groupType, replacer)
  1657. u.Filters.BandwidthLimits = append(u.Filters.BandwidthLimits, group.UserSettings.Filters.BandwidthLimits...)
  1658. u.Filters.AllowedIP = append(u.Filters.AllowedIP, group.UserSettings.Filters.AllowedIP...)
  1659. u.Filters.DeniedIP = append(u.Filters.DeniedIP, group.UserSettings.Filters.DeniedIP...)
  1660. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, group.UserSettings.Filters.DeniedLoginMethods...)
  1661. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, group.UserSettings.Filters.DeniedProtocols...)
  1662. u.Filters.WebClient = append(u.Filters.WebClient, group.UserSettings.Filters.WebClient...)
  1663. u.Filters.TwoFactorAuthProtocols = append(u.Filters.TwoFactorAuthProtocols, group.UserSettings.Filters.TwoFactorAuthProtocols...)
  1664. }
  1665. func (u *User) mergeVirtualFolders(group *Group, groupType int, replacer *strings.Replacer) {
  1666. if len(group.VirtualFolders) > 0 {
  1667. folderPaths := make(map[string]bool)
  1668. for _, folder := range u.VirtualFolders {
  1669. folderPaths[folder.VirtualPath] = true
  1670. }
  1671. for _, folder := range group.VirtualFolders {
  1672. if folder.VirtualPath == "/" && groupType != sdk.GroupTypePrimary {
  1673. continue
  1674. }
  1675. folder.VirtualPath = u.replacePlaceholder(folder.VirtualPath, replacer)
  1676. if _, ok := folderPaths[folder.VirtualPath]; !ok {
  1677. folder.MappedPath = u.replacePlaceholder(folder.MappedPath, replacer)
  1678. folder.FsConfig = u.replaceFsConfigPlaceholders(folder.FsConfig, replacer)
  1679. u.VirtualFolders = append(u.VirtualFolders, folder)
  1680. }
  1681. }
  1682. }
  1683. }
  1684. func (u *User) mergePermissions(group *Group, groupType int, replacer *strings.Replacer) {
  1685. if u.Permissions == nil {
  1686. u.Permissions = make(map[string][]string)
  1687. }
  1688. for k, v := range group.UserSettings.Permissions {
  1689. if k == "/" {
  1690. if groupType == sdk.GroupTypePrimary {
  1691. u.Permissions[k] = v
  1692. } else {
  1693. continue
  1694. }
  1695. }
  1696. k = u.replacePlaceholder(k, replacer)
  1697. if _, ok := u.Permissions[k]; !ok {
  1698. u.Permissions[k] = v
  1699. }
  1700. }
  1701. }
  1702. func (u *User) mergeFilePatterns(group *Group, groupType int, replacer *strings.Replacer) {
  1703. if len(group.UserSettings.Filters.FilePatterns) > 0 {
  1704. patternPaths := make(map[string]bool)
  1705. for _, pattern := range u.Filters.FilePatterns {
  1706. patternPaths[pattern.Path] = true
  1707. }
  1708. for _, pattern := range group.UserSettings.Filters.FilePatterns {
  1709. if pattern.Path == "/" && groupType != sdk.GroupTypePrimary {
  1710. continue
  1711. }
  1712. pattern.Path = u.replacePlaceholder(pattern.Path, replacer)
  1713. if _, ok := patternPaths[pattern.Path]; !ok {
  1714. u.Filters.FilePatterns = append(u.Filters.FilePatterns, pattern)
  1715. }
  1716. }
  1717. }
  1718. }
  1719. func (u *User) removeDuplicatesAfterGroupMerge() {
  1720. u.Filters.AllowedIP = util.RemoveDuplicates(u.Filters.AllowedIP, false)
  1721. u.Filters.DeniedIP = util.RemoveDuplicates(u.Filters.DeniedIP, false)
  1722. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  1723. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  1724. u.Filters.WebClient = util.RemoveDuplicates(u.Filters.WebClient, false)
  1725. u.Filters.TwoFactorAuthProtocols = util.RemoveDuplicates(u.Filters.TwoFactorAuthProtocols, false)
  1726. u.SetEmptySecretsIfNil()
  1727. u.groupSettingsApplied = true
  1728. }
  1729. func (u *User) hasRole(role string) bool {
  1730. if role == "" {
  1731. return true
  1732. }
  1733. return role == u.Role
  1734. }
  1735. func (u *User) getACopy() User {
  1736. u.SetEmptySecretsIfNil()
  1737. pubKeys := make([]string, len(u.PublicKeys))
  1738. copy(pubKeys, u.PublicKeys)
  1739. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  1740. for idx := range u.VirtualFolders {
  1741. vfolder := u.VirtualFolders[idx].GetACopy()
  1742. virtualFolders = append(virtualFolders, vfolder)
  1743. }
  1744. groups := make([]sdk.GroupMapping, 0, len(u.Groups))
  1745. for _, g := range u.Groups {
  1746. groups = append(groups, sdk.GroupMapping{
  1747. Name: g.Name,
  1748. Type: g.Type,
  1749. })
  1750. }
  1751. permissions := make(map[string][]string)
  1752. for k, v := range u.Permissions {
  1753. perms := make([]string, len(v))
  1754. copy(perms, v)
  1755. permissions[k] = perms
  1756. }
  1757. filters := UserFilters{
  1758. BaseUserFilters: copyBaseUserFilters(u.Filters.BaseUserFilters),
  1759. }
  1760. filters.RequirePasswordChange = u.Filters.RequirePasswordChange
  1761. filters.TOTPConfig.Enabled = u.Filters.TOTPConfig.Enabled
  1762. filters.TOTPConfig.ConfigName = u.Filters.TOTPConfig.ConfigName
  1763. filters.TOTPConfig.Secret = u.Filters.TOTPConfig.Secret.Clone()
  1764. filters.TOTPConfig.Protocols = make([]string, len(u.Filters.TOTPConfig.Protocols))
  1765. copy(filters.TOTPConfig.Protocols, u.Filters.TOTPConfig.Protocols)
  1766. filters.RecoveryCodes = make([]RecoveryCode, 0, len(u.Filters.RecoveryCodes))
  1767. for _, code := range u.Filters.RecoveryCodes {
  1768. if code.Secret == nil {
  1769. code.Secret = kms.NewEmptySecret()
  1770. }
  1771. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  1772. Secret: code.Secret.Clone(),
  1773. Used: code.Used,
  1774. })
  1775. }
  1776. return User{
  1777. BaseUser: sdk.BaseUser{
  1778. ID: u.ID,
  1779. Username: u.Username,
  1780. Email: u.Email,
  1781. Password: u.Password,
  1782. PublicKeys: pubKeys,
  1783. HasPassword: u.HasPassword,
  1784. HomeDir: u.HomeDir,
  1785. UID: u.UID,
  1786. GID: u.GID,
  1787. MaxSessions: u.MaxSessions,
  1788. QuotaSize: u.QuotaSize,
  1789. QuotaFiles: u.QuotaFiles,
  1790. Permissions: permissions,
  1791. UsedQuotaSize: u.UsedQuotaSize,
  1792. UsedQuotaFiles: u.UsedQuotaFiles,
  1793. LastQuotaUpdate: u.LastQuotaUpdate,
  1794. UploadBandwidth: u.UploadBandwidth,
  1795. DownloadBandwidth: u.DownloadBandwidth,
  1796. UploadDataTransfer: u.UploadDataTransfer,
  1797. DownloadDataTransfer: u.DownloadDataTransfer,
  1798. TotalDataTransfer: u.TotalDataTransfer,
  1799. UsedUploadDataTransfer: u.UsedUploadDataTransfer,
  1800. UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
  1801. Status: u.Status,
  1802. ExpirationDate: u.ExpirationDate,
  1803. LastLogin: u.LastLogin,
  1804. FirstDownload: u.FirstDownload,
  1805. FirstUpload: u.FirstUpload,
  1806. LastPasswordChange: u.LastPasswordChange,
  1807. AdditionalInfo: u.AdditionalInfo,
  1808. Description: u.Description,
  1809. CreatedAt: u.CreatedAt,
  1810. UpdatedAt: u.UpdatedAt,
  1811. Role: u.Role,
  1812. },
  1813. Filters: filters,
  1814. VirtualFolders: virtualFolders,
  1815. Groups: groups,
  1816. FsConfig: u.FsConfig.GetACopy(),
  1817. groupSettingsApplied: u.groupSettingsApplied,
  1818. }
  1819. }
  1820. // GetEncryptionAdditionalData returns the additional data to use for AEAD
  1821. func (u *User) GetEncryptionAdditionalData() string {
  1822. return u.Username
  1823. }