user.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. package dataprovider
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "golang.org/x/net/webdav"
  14. "github.com/drakkan/sftpgo/kms"
  15. "github.com/drakkan/sftpgo/logger"
  16. "github.com/drakkan/sftpgo/utils"
  17. "github.com/drakkan/sftpgo/vfs"
  18. )
  19. // Available permissions for SFTPGo users
  20. const (
  21. // All permissions are granted
  22. PermAny = "*"
  23. // List items such as files and directories is allowed
  24. PermListItems = "list"
  25. // download files is allowed
  26. PermDownload = "download"
  27. // upload files is allowed
  28. PermUpload = "upload"
  29. // overwrite an existing file, while uploading, is allowed
  30. // upload permission is required to allow file overwrite
  31. PermOverwrite = "overwrite"
  32. // delete files or directories is allowed
  33. PermDelete = "delete"
  34. // rename files or directories is allowed
  35. PermRename = "rename"
  36. // create directories is allowed
  37. PermCreateDirs = "create_dirs"
  38. // create symbolic links is allowed
  39. PermCreateSymlinks = "create_symlinks"
  40. // changing file or directory permissions is allowed
  41. PermChmod = "chmod"
  42. // changing file or directory owner and group is allowed
  43. PermChown = "chown"
  44. // changing file or directory access and modification time is allowed
  45. PermChtimes = "chtimes"
  46. )
  47. // Available login methods
  48. const (
  49. LoginMethodNoAuthTryed = "no_auth_tryed"
  50. LoginMethodPassword = "password"
  51. SSHLoginMethodPublicKey = "publickey"
  52. SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
  53. SSHLoginMethodKeyAndPassword = "publickey+password"
  54. SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive"
  55. LoginMethodTLSCertificate = "TLSCertificate"
  56. LoginMethodTLSCertificateAndPwd = "TLSCertificate+password"
  57. )
  58. // TLSUsername defines the TLS certificate attribute to use as username
  59. type TLSUsername string
  60. // Supported certificate attributes to use as username
  61. const (
  62. TLSUsernameNone TLSUsername = "None"
  63. TLSUsernameCN TLSUsername = "CommonName"
  64. )
  65. var (
  66. errNoMatchingVirtualFolder = errors.New("no matching virtual folder found")
  67. )
  68. // CachedUser adds fields useful for caching to a SFTPGo user
  69. type CachedUser struct {
  70. User User
  71. Expiration time.Time
  72. Password string
  73. LockSystem webdav.LockSystem
  74. }
  75. // IsExpired returns true if the cached user is expired
  76. func (c *CachedUser) IsExpired() bool {
  77. if c.Expiration.IsZero() {
  78. return false
  79. }
  80. return c.Expiration.Before(time.Now())
  81. }
  82. // ExtensionsFilter defines filters based on file extensions.
  83. // These restrictions do not apply to files listing for performance reasons, so
  84. // a denied file cannot be downloaded/overwritten/renamed but will still be
  85. // in the list of files.
  86. // System commands such as Git and rsync interacts with the filesystem directly
  87. // and they are not aware about these restrictions so they are not allowed
  88. // inside paths with extensions filters
  89. type ExtensionsFilter struct {
  90. // Virtual path, if no other specific filter is defined, the filter apply for
  91. // sub directories too.
  92. // For example if filters are defined for the paths "/" and "/sub" then the
  93. // filters for "/" are applied for any file outside the "/sub" directory
  94. Path string `json:"path"`
  95. // only files with these, case insensitive, extensions are allowed.
  96. // Shell like expansion is not supported so you have to specify ".jpg" and
  97. // not "*.jpg". If you want shell like patterns use pattern filters
  98. AllowedExtensions []string `json:"allowed_extensions,omitempty"`
  99. // files with these, case insensitive, extensions are not allowed.
  100. // Denied file extensions are evaluated before the allowed ones
  101. DeniedExtensions []string `json:"denied_extensions,omitempty"`
  102. }
  103. // PatternsFilter defines filters based on shell like patterns.
  104. // These restrictions do not apply to files listing for performance reasons, so
  105. // a denied file cannot be downloaded/overwritten/renamed but will still be
  106. // in the list of files.
  107. // System commands such as Git and rsync interacts with the filesystem directly
  108. // and they are not aware about these restrictions so they are not allowed
  109. // inside paths with extensions filters
  110. type PatternsFilter struct {
  111. // Virtual path, if no other specific filter is defined, the filter apply for
  112. // sub directories too.
  113. // For example if filters are defined for the paths "/" and "/sub" then the
  114. // filters for "/" are applied for any file outside the "/sub" directory
  115. Path string `json:"path"`
  116. // files with these, case insensitive, patterns are allowed.
  117. // Denied file patterns are evaluated before the allowed ones
  118. AllowedPatterns []string `json:"allowed_patterns,omitempty"`
  119. // files with these, case insensitive, patterns are not allowed.
  120. // Denied file patterns are evaluated before the allowed ones
  121. DeniedPatterns []string `json:"denied_patterns,omitempty"`
  122. }
  123. // UserFilters defines additional restrictions for a user
  124. type UserFilters struct {
  125. // only clients connecting from these IP/Mask are allowed.
  126. // IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291
  127. // for example "192.0.2.0/24" or "2001:db8::/32"
  128. AllowedIP []string `json:"allowed_ip,omitempty"`
  129. // clients connecting from these IP/Mask are not allowed.
  130. // Denied rules will be evaluated before allowed ones
  131. DeniedIP []string `json:"denied_ip,omitempty"`
  132. // these login methods are not allowed.
  133. // If null or empty any available login method is allowed
  134. DeniedLoginMethods []string `json:"denied_login_methods,omitempty"`
  135. // these protocols are not allowed.
  136. // If null or empty any available protocol is allowed
  137. DeniedProtocols []string `json:"denied_protocols,omitempty"`
  138. // filters based on file extensions.
  139. // Please note that these restrictions can be easily bypassed.
  140. FileExtensions []ExtensionsFilter `json:"file_extensions,omitempty"`
  141. // filter based on shell patterns
  142. FilePatterns []PatternsFilter `json:"file_patterns,omitempty"`
  143. // max size allowed for a single upload, 0 means unlimited
  144. MaxUploadFileSize int64 `json:"max_upload_file_size,omitempty"`
  145. // TLS certificate attribute to use as username.
  146. // For FTP clients it must match the name provided using the
  147. // "USER" command
  148. TLSUsername TLSUsername `json:"tls_username,omitempty"`
  149. }
  150. // User defines a SFTPGo user
  151. type User struct {
  152. // Database unique identifier
  153. ID int64 `json:"id"`
  154. // 1 enabled, 0 disabled (login is not allowed)
  155. Status int `json:"status"`
  156. // Username
  157. Username string `json:"username"`
  158. // Account expiration date as unix timestamp in milliseconds. An expired account cannot login.
  159. // 0 means no expiration
  160. ExpirationDate int64 `json:"expiration_date"`
  161. // Password used for password authentication.
  162. // For users created using SFTPGo REST API the password is be stored using argon2id hashing algo.
  163. // Checking passwords stored with bcrypt, pbkdf2, md5crypt and sha512crypt is supported too.
  164. Password string `json:"password,omitempty"`
  165. // PublicKeys used for public key authentication. At least one between password and a public key is mandatory
  166. PublicKeys []string `json:"public_keys,omitempty"`
  167. // The user cannot upload or download files outside this directory. Must be an absolute path
  168. HomeDir string `json:"home_dir"`
  169. // Mapping between virtual paths and virtual folders
  170. VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
  171. // If sftpgo runs as root system user then the created files and directories will be assigned to this system UID
  172. UID int `json:"uid"`
  173. // If sftpgo runs as root system user then the created files and directories will be assigned to this system GID
  174. GID int `json:"gid"`
  175. // Maximum concurrent sessions. 0 means unlimited
  176. MaxSessions int `json:"max_sessions"`
  177. // Maximum size allowed as bytes. 0 means unlimited
  178. QuotaSize int64 `json:"quota_size"`
  179. // Maximum number of files allowed. 0 means unlimited
  180. QuotaFiles int `json:"quota_files"`
  181. // List of the granted permissions
  182. Permissions map[string][]string `json:"permissions"`
  183. // Used quota as bytes
  184. UsedQuotaSize int64 `json:"used_quota_size"`
  185. // Used quota as number of files
  186. UsedQuotaFiles int `json:"used_quota_files"`
  187. // Last quota update as unix timestamp in milliseconds
  188. LastQuotaUpdate int64 `json:"last_quota_update"`
  189. // Maximum upload bandwidth as KB/s, 0 means unlimited
  190. UploadBandwidth int64 `json:"upload_bandwidth"`
  191. // Maximum download bandwidth as KB/s, 0 means unlimited
  192. DownloadBandwidth int64 `json:"download_bandwidth"`
  193. // Last login as unix timestamp in milliseconds
  194. LastLogin int64 `json:"last_login"`
  195. // Additional restrictions
  196. Filters UserFilters `json:"filters"`
  197. // Filesystem configuration details
  198. FsConfig vfs.Filesystem `json:"filesystem"`
  199. // optional description, for example full name
  200. Description string `json:"description,omitempty"`
  201. // free form text field for external systems
  202. AdditionalInfo string `json:"additional_info,omitempty"`
  203. // we store the filesystem here using the base path as key.
  204. fsCache map[string]vfs.Fs `json:"-"`
  205. }
  206. // GetFilesystem returns the base filesystem for this user
  207. func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error) {
  208. fs, err = u.getRootFs(connectionID)
  209. if err != nil {
  210. return fs, err
  211. }
  212. u.fsCache = make(map[string]vfs.Fs)
  213. u.fsCache["/"] = fs
  214. return fs, err
  215. }
  216. func (u *User) getRootFs(connectionID string) (fs vfs.Fs, err error) {
  217. switch u.FsConfig.Provider {
  218. case vfs.S3FilesystemProvider:
  219. return vfs.NewS3Fs(connectionID, u.GetHomeDir(), "", u.FsConfig.S3Config)
  220. case vfs.GCSFilesystemProvider:
  221. config := u.FsConfig.GCSConfig
  222. config.CredentialFile = u.GetGCSCredentialsFilePath()
  223. return vfs.NewGCSFs(connectionID, u.GetHomeDir(), "", config)
  224. case vfs.AzureBlobFilesystemProvider:
  225. return vfs.NewAzBlobFs(connectionID, u.GetHomeDir(), "", u.FsConfig.AzBlobConfig)
  226. case vfs.CryptedFilesystemProvider:
  227. return vfs.NewCryptFs(connectionID, u.GetHomeDir(), "", u.FsConfig.CryptConfig)
  228. case vfs.SFTPFilesystemProvider:
  229. return vfs.NewSFTPFs(connectionID, "", u.FsConfig.SFTPConfig)
  230. default:
  231. return vfs.NewOsFs(connectionID, u.GetHomeDir(), ""), nil
  232. }
  233. }
  234. // CheckFsRoot check the root directory for the main fs and the virtual folders.
  235. // It returns an error if the main filesystem cannot be created
  236. func (u *User) CheckFsRoot(connectionID string) error {
  237. fs, err := u.GetFilesystemForPath("/", connectionID)
  238. if err != nil {
  239. logger.Warn(logSender, connectionID, "could not create main filesystem for user %#v err: %v", u.Username, err)
  240. return err
  241. }
  242. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  243. for idx := range u.VirtualFolders {
  244. v := &u.VirtualFolders[idx]
  245. fs, err = u.GetFilesystemForPath(v.VirtualPath, connectionID)
  246. if err == nil {
  247. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  248. }
  249. // now check intermediary folders
  250. fs, err = u.GetFilesystemForPath(path.Dir(v.VirtualPath), connectionID)
  251. if err == nil && !fs.HasVirtualFolders() {
  252. fsPath, err := fs.ResolvePath(v.VirtualPath)
  253. if err != nil {
  254. continue
  255. }
  256. err = fs.MkdirAll(fsPath, u.GetUID(), u.GetGID())
  257. logger.Debug(logSender, connectionID, "create intermediary dir to %#v, path %#v, err: %v",
  258. v.VirtualPath, fsPath, err)
  259. }
  260. }
  261. return nil
  262. }
  263. // hideConfidentialData hides user confidential data
  264. func (u *User) hideConfidentialData() {
  265. u.Password = ""
  266. switch u.FsConfig.Provider {
  267. case vfs.S3FilesystemProvider:
  268. u.FsConfig.S3Config.AccessSecret.Hide()
  269. case vfs.GCSFilesystemProvider:
  270. u.FsConfig.GCSConfig.Credentials.Hide()
  271. case vfs.AzureBlobFilesystemProvider:
  272. u.FsConfig.AzBlobConfig.AccountKey.Hide()
  273. case vfs.CryptedFilesystemProvider:
  274. u.FsConfig.CryptConfig.Passphrase.Hide()
  275. case vfs.SFTPFilesystemProvider:
  276. u.FsConfig.SFTPConfig.Password.Hide()
  277. u.FsConfig.SFTPConfig.PrivateKey.Hide()
  278. }
  279. }
  280. // PrepareForRendering prepares a user for rendering.
  281. // It hides confidential data and set to nil the empty secrets
  282. // so they are not serialized
  283. func (u *User) PrepareForRendering() {
  284. u.hideConfidentialData()
  285. u.FsConfig.SetNilSecretsIfEmpty()
  286. for idx := range u.VirtualFolders {
  287. folder := &u.VirtualFolders[idx]
  288. folder.PrepareForRendering()
  289. }
  290. }
  291. func (u *User) hasRedactedSecret() bool {
  292. switch u.FsConfig.Provider {
  293. case vfs.S3FilesystemProvider:
  294. if u.FsConfig.S3Config.AccessSecret.IsRedacted() {
  295. return true
  296. }
  297. case vfs.GCSFilesystemProvider:
  298. if u.FsConfig.GCSConfig.Credentials.IsRedacted() {
  299. return true
  300. }
  301. case vfs.AzureBlobFilesystemProvider:
  302. if u.FsConfig.AzBlobConfig.AccountKey.IsRedacted() {
  303. return true
  304. }
  305. case vfs.CryptedFilesystemProvider:
  306. if u.FsConfig.CryptConfig.Passphrase.IsRedacted() {
  307. return true
  308. }
  309. case vfs.SFTPFilesystemProvider:
  310. if u.FsConfig.SFTPConfig.Password.IsRedacted() {
  311. return true
  312. }
  313. if u.FsConfig.SFTPConfig.PrivateKey.IsRedacted() {
  314. return true
  315. }
  316. }
  317. for idx := range u.VirtualFolders {
  318. folder := &u.VirtualFolders[idx]
  319. if folder.HasRedactedSecret() {
  320. return true
  321. }
  322. }
  323. return false
  324. }
  325. // CloseFs closes the underlying filesystems
  326. func (u *User) CloseFs() error {
  327. if u.fsCache == nil {
  328. return nil
  329. }
  330. var err error
  331. for _, fs := range u.fsCache {
  332. errClose := fs.Close()
  333. if err == nil {
  334. err = errClose
  335. }
  336. }
  337. return err
  338. }
  339. // IsPasswordHashed returns true if the password is hashed
  340. func (u *User) IsPasswordHashed() bool {
  341. return utils.IsStringPrefixInSlice(u.Password, hashPwdPrefixes)
  342. }
  343. // IsTLSUsernameVerificationEnabled returns true if we need to extract the username
  344. // from the client TLS certificate
  345. func (u *User) IsTLSUsernameVerificationEnabled() bool {
  346. if u.Filters.TLSUsername != "" {
  347. return u.Filters.TLSUsername != TLSUsernameNone
  348. }
  349. return false
  350. }
  351. // SetEmptySecrets sets to empty any user secret
  352. func (u *User) SetEmptySecrets() {
  353. u.FsConfig.S3Config.AccessSecret = kms.NewEmptySecret()
  354. u.FsConfig.GCSConfig.Credentials = kms.NewEmptySecret()
  355. u.FsConfig.AzBlobConfig.AccountKey = kms.NewEmptySecret()
  356. u.FsConfig.CryptConfig.Passphrase = kms.NewEmptySecret()
  357. u.FsConfig.SFTPConfig.Password = kms.NewEmptySecret()
  358. u.FsConfig.SFTPConfig.PrivateKey = kms.NewEmptySecret()
  359. for idx := range u.VirtualFolders {
  360. folder := &u.VirtualFolders[idx]
  361. folder.FsConfig.SetEmptySecretsIfNil()
  362. }
  363. }
  364. // GetPermissionsForPath returns the permissions for the given path.
  365. // The path must be a SFTPGo exposed path
  366. func (u *User) GetPermissionsForPath(p string) []string {
  367. permissions := []string{}
  368. if perms, ok := u.Permissions["/"]; ok {
  369. // if only root permissions are defined returns them unconditionally
  370. if len(u.Permissions) == 1 {
  371. return perms
  372. }
  373. // fallback permissions
  374. permissions = perms
  375. }
  376. dirsForPath := utils.GetDirsForVirtualPath(p)
  377. // dirsForPath contains all the dirs for a given path in reverse order
  378. // for example if the path is: /1/2/3/4 it contains:
  379. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  380. // so the first match is the one we are interested to
  381. for idx := range dirsForPath {
  382. if perms, ok := u.Permissions[dirsForPath[idx]]; ok {
  383. permissions = perms
  384. break
  385. }
  386. }
  387. return permissions
  388. }
  389. // GetFilesystemForPath returns the filesystem for the given path
  390. func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error) {
  391. if u.fsCache == nil {
  392. u.fsCache = make(map[string]vfs.Fs)
  393. }
  394. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  395. folder, err := u.GetVirtualFolderForPath(virtualPath)
  396. if err == nil {
  397. if fs, ok := u.fsCache[folder.VirtualPath]; ok {
  398. return fs, nil
  399. }
  400. fs, err := folder.GetFilesystem(connectionID)
  401. if err == nil {
  402. u.fsCache[folder.VirtualPath] = fs
  403. }
  404. return fs, err
  405. }
  406. }
  407. if val, ok := u.fsCache["/"]; ok {
  408. return val, nil
  409. }
  410. return u.GetFilesystem(connectionID)
  411. }
  412. // GetVirtualFolderForPath returns the virtual folder containing the specified virtual path.
  413. // If the path is not inside a virtual folder an error is returned
  414. func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error) {
  415. var folder vfs.VirtualFolder
  416. if len(u.VirtualFolders) == 0 {
  417. return folder, errNoMatchingVirtualFolder
  418. }
  419. dirsForPath := utils.GetDirsForVirtualPath(virtualPath)
  420. for index := range dirsForPath {
  421. for idx := range u.VirtualFolders {
  422. v := &u.VirtualFolders[idx]
  423. if v.VirtualPath == dirsForPath[index] {
  424. return *v, nil
  425. }
  426. }
  427. }
  428. return folder, errNoMatchingVirtualFolder
  429. }
  430. // ScanQuota scans the user home dir and virtual folders, included in its quota,
  431. // and returns the number of files and their size
  432. func (u *User) ScanQuota() (int, int64, error) {
  433. fs, err := u.getRootFs("")
  434. if err != nil {
  435. return 0, 0, err
  436. }
  437. defer fs.Close()
  438. numFiles, size, err := fs.ScanRootDirContents()
  439. if err != nil {
  440. return numFiles, size, err
  441. }
  442. for idx := range u.VirtualFolders {
  443. v := &u.VirtualFolders[idx]
  444. if !v.IsIncludedInUserQuota() {
  445. continue
  446. }
  447. num, s, err := v.ScanQuota()
  448. if err != nil {
  449. return numFiles, size, err
  450. }
  451. numFiles += num
  452. size += s
  453. }
  454. return numFiles, size, nil
  455. }
  456. // GetVirtualFoldersInPath returns the virtual folders inside virtualPath including
  457. // any parents
  458. func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool {
  459. result := make(map[string]bool)
  460. for idx := range u.VirtualFolders {
  461. v := &u.VirtualFolders[idx]
  462. dirsForPath := utils.GetDirsForVirtualPath(v.VirtualPath)
  463. for index := range dirsForPath {
  464. d := dirsForPath[index]
  465. if d == "/" {
  466. continue
  467. }
  468. if path.Dir(d) == virtualPath {
  469. result[d] = true
  470. }
  471. }
  472. }
  473. return result
  474. }
  475. // AddVirtualDirs adds virtual folders, if defined, to the given files list
  476. func (u *User) AddVirtualDirs(list []os.FileInfo, virtualPath string) []os.FileInfo {
  477. if len(u.VirtualFolders) == 0 {
  478. return list
  479. }
  480. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  481. fi := vfs.NewFileInfo(dir, true, 0, time.Now(), false)
  482. found := false
  483. for index := range list {
  484. if list[index].Name() == fi.Name() {
  485. list[index] = fi
  486. found = true
  487. break
  488. }
  489. }
  490. if !found {
  491. list = append(list, fi)
  492. }
  493. }
  494. return list
  495. }
  496. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  497. // The filesystem path must be cleaned before calling this method
  498. func (u *User) IsMappedPath(fsPath string) bool {
  499. for idx := range u.VirtualFolders {
  500. v := &u.VirtualFolders[idx]
  501. if fsPath == v.MappedPath {
  502. return true
  503. }
  504. }
  505. return false
  506. }
  507. // IsVirtualFolder returns true if the specified virtual path is a virtual folder
  508. func (u *User) IsVirtualFolder(virtualPath string) bool {
  509. for idx := range u.VirtualFolders {
  510. v := &u.VirtualFolders[idx]
  511. if virtualPath == v.VirtualPath {
  512. return true
  513. }
  514. }
  515. return false
  516. }
  517. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  518. // specified virtual path. We assume that path are cleaned
  519. func (u *User) HasVirtualFoldersInside(virtualPath string) bool {
  520. if virtualPath == "/" && len(u.VirtualFolders) > 0 {
  521. return true
  522. }
  523. for idx := range u.VirtualFolders {
  524. v := &u.VirtualFolders[idx]
  525. if len(v.VirtualPath) > len(virtualPath) {
  526. if strings.HasPrefix(v.VirtualPath, virtualPath+"/") {
  527. return true
  528. }
  529. }
  530. }
  531. return false
  532. }
  533. // HasPermissionsInside returns true if the specified virtualPath has no permissions itself and
  534. // no subdirs with defined permissions
  535. func (u *User) HasPermissionsInside(virtualPath string) bool {
  536. for dir := range u.Permissions {
  537. if dir == virtualPath {
  538. return true
  539. } else if len(dir) > len(virtualPath) {
  540. if strings.HasPrefix(dir, virtualPath+"/") {
  541. return true
  542. }
  543. }
  544. }
  545. return false
  546. }
  547. // HasPerm returns true if the user has the given permission or any permission
  548. func (u *User) HasPerm(permission, path string) bool {
  549. perms := u.GetPermissionsForPath(path)
  550. if utils.IsStringInSlice(PermAny, perms) {
  551. return true
  552. }
  553. return utils.IsStringInSlice(permission, perms)
  554. }
  555. // HasPerms return true if the user has all the given permissions
  556. func (u *User) HasPerms(permissions []string, path string) bool {
  557. perms := u.GetPermissionsForPath(path)
  558. if utils.IsStringInSlice(PermAny, perms) {
  559. return true
  560. }
  561. for _, permission := range permissions {
  562. if !utils.IsStringInSlice(permission, perms) {
  563. return false
  564. }
  565. }
  566. return true
  567. }
  568. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  569. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  570. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  571. return true
  572. }
  573. return false
  574. }
  575. // IsLoginMethodAllowed returns true if the specified login method is allowed
  576. func (u *User) IsLoginMethodAllowed(loginMethod string, partialSuccessMethods []string) bool {
  577. if len(u.Filters.DeniedLoginMethods) == 0 {
  578. return true
  579. }
  580. if len(partialSuccessMethods) == 1 {
  581. for _, method := range u.GetNextAuthMethods(partialSuccessMethods, true) {
  582. if method == loginMethod {
  583. return true
  584. }
  585. }
  586. }
  587. if utils.IsStringInSlice(loginMethod, u.Filters.DeniedLoginMethods) {
  588. return false
  589. }
  590. return true
  591. }
  592. // GetNextAuthMethods returns the list of authentications methods that
  593. // can continue for multi-step authentication
  594. func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string {
  595. var methods []string
  596. if len(partialSuccessMethods) != 1 {
  597. return methods
  598. }
  599. if partialSuccessMethods[0] != SSHLoginMethodPublicKey {
  600. return methods
  601. }
  602. for _, method := range u.GetAllowedLoginMethods() {
  603. if method == SSHLoginMethodKeyAndPassword && isPasswordAuthEnabled {
  604. methods = append(methods, LoginMethodPassword)
  605. }
  606. if method == SSHLoginMethodKeyAndKeyboardInt {
  607. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  608. }
  609. }
  610. return methods
  611. }
  612. // IsPartialAuth returns true if the specified login method is a step for
  613. // a multi-step Authentication.
  614. // We support publickey+password and publickey+keyboard-interactive, so
  615. // only publickey can returns partial success.
  616. // We can have partial success if only multi-step Auth methods are enabled
  617. func (u *User) IsPartialAuth(loginMethod string) bool {
  618. if loginMethod != SSHLoginMethodPublicKey {
  619. return false
  620. }
  621. for _, method := range u.GetAllowedLoginMethods() {
  622. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd {
  623. continue
  624. }
  625. if !utils.IsStringInSlice(method, SSHMultiStepsLoginMethods) {
  626. return false
  627. }
  628. }
  629. return true
  630. }
  631. // GetAllowedLoginMethods returns the allowed login methods
  632. func (u *User) GetAllowedLoginMethods() []string {
  633. var allowedMethods []string
  634. for _, method := range ValidLoginMethods {
  635. if !utils.IsStringInSlice(method, u.Filters.DeniedLoginMethods) {
  636. allowedMethods = append(allowedMethods, method)
  637. }
  638. }
  639. return allowedMethods
  640. }
  641. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters
  642. func (u *User) IsFileAllowed(virtualPath string) bool {
  643. return u.isFilePatternAllowed(virtualPath) && u.isFileExtensionAllowed(virtualPath)
  644. }
  645. func (u *User) isFileExtensionAllowed(virtualPath string) bool {
  646. if len(u.Filters.FileExtensions) == 0 {
  647. return true
  648. }
  649. dirsForPath := utils.GetDirsForVirtualPath(path.Dir(virtualPath))
  650. var filter ExtensionsFilter
  651. for _, dir := range dirsForPath {
  652. for _, f := range u.Filters.FileExtensions {
  653. if f.Path == dir {
  654. filter = f
  655. break
  656. }
  657. }
  658. if filter.Path != "" {
  659. break
  660. }
  661. }
  662. if filter.Path != "" {
  663. toMatch := strings.ToLower(virtualPath)
  664. for _, denied := range filter.DeniedExtensions {
  665. if strings.HasSuffix(toMatch, denied) {
  666. return false
  667. }
  668. }
  669. for _, allowed := range filter.AllowedExtensions {
  670. if strings.HasSuffix(toMatch, allowed) {
  671. return true
  672. }
  673. }
  674. return len(filter.AllowedExtensions) == 0
  675. }
  676. return true
  677. }
  678. func (u *User) isFilePatternAllowed(virtualPath string) bool {
  679. if len(u.Filters.FilePatterns) == 0 {
  680. return true
  681. }
  682. dirsForPath := utils.GetDirsForVirtualPath(path.Dir(virtualPath))
  683. var filter PatternsFilter
  684. for _, dir := range dirsForPath {
  685. for _, f := range u.Filters.FilePatterns {
  686. if f.Path == dir {
  687. filter = f
  688. break
  689. }
  690. }
  691. if filter.Path != "" {
  692. break
  693. }
  694. }
  695. if filter.Path != "" {
  696. toMatch := strings.ToLower(path.Base(virtualPath))
  697. for _, denied := range filter.DeniedPatterns {
  698. matched, err := path.Match(denied, toMatch)
  699. if err != nil || matched {
  700. return false
  701. }
  702. }
  703. for _, allowed := range filter.AllowedPatterns {
  704. matched, err := path.Match(allowed, toMatch)
  705. if err == nil && matched {
  706. return true
  707. }
  708. }
  709. return len(filter.AllowedPatterns) == 0
  710. }
  711. return true
  712. }
  713. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  714. // If AllowedIP is defined only the specified IP/Mask can login.
  715. // If DeniedIP is defined the specified IP/Mask cannot login.
  716. // If an IP is both allowed and denied then login will be denied
  717. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  718. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  719. return true
  720. }
  721. remoteIP := net.ParseIP(utils.GetIPFromRemoteAddress(remoteAddr))
  722. // if remoteIP is invalid we allow login, this should never happen
  723. if remoteIP == nil {
  724. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %#v", remoteAddr)
  725. return true
  726. }
  727. for _, IPMask := range u.Filters.DeniedIP {
  728. _, IPNet, err := net.ParseCIDR(IPMask)
  729. if err != nil {
  730. return false
  731. }
  732. if IPNet.Contains(remoteIP) {
  733. return false
  734. }
  735. }
  736. for _, IPMask := range u.Filters.AllowedIP {
  737. _, IPNet, err := net.ParseCIDR(IPMask)
  738. if err != nil {
  739. return false
  740. }
  741. if IPNet.Contains(remoteIP) {
  742. return true
  743. }
  744. }
  745. return len(u.Filters.AllowedIP) == 0
  746. }
  747. // GetPermissionsAsJSON returns the permissions as json byte array
  748. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  749. return json.Marshal(u.Permissions)
  750. }
  751. // GetPublicKeysAsJSON returns the public keys as json byte array
  752. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  753. return json.Marshal(u.PublicKeys)
  754. }
  755. // GetFiltersAsJSON returns the filters as json byte array
  756. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  757. return json.Marshal(u.Filters)
  758. }
  759. // GetFsConfigAsJSON returns the filesystem config as json byte array
  760. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  761. return json.Marshal(u.FsConfig)
  762. }
  763. // GetUID returns a validate uid, suitable for use with os.Chown
  764. func (u *User) GetUID() int {
  765. if u.UID <= 0 || u.UID > 65535 {
  766. return -1
  767. }
  768. return u.UID
  769. }
  770. // GetGID returns a validate gid, suitable for use with os.Chown
  771. func (u *User) GetGID() int {
  772. if u.GID <= 0 || u.GID > 65535 {
  773. return -1
  774. }
  775. return u.GID
  776. }
  777. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  778. func (u *User) GetHomeDir() string {
  779. return filepath.Clean(u.HomeDir)
  780. }
  781. // HasQuotaRestrictions returns true if there is a quota restriction on number of files or size or both
  782. func (u *User) HasQuotaRestrictions() bool {
  783. return u.QuotaFiles > 0 || u.QuotaSize > 0
  784. }
  785. // GetQuotaSummary returns used quota and limits if defined
  786. func (u *User) GetQuotaSummary() string {
  787. var result string
  788. result = "Files: " + strconv.Itoa(u.UsedQuotaFiles)
  789. if u.QuotaFiles > 0 {
  790. result += "/" + strconv.Itoa(u.QuotaFiles)
  791. }
  792. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  793. result += ". Size: " + utils.ByteCountIEC(u.UsedQuotaSize)
  794. if u.QuotaSize > 0 {
  795. result += "/" + utils.ByteCountIEC(u.QuotaSize)
  796. }
  797. }
  798. return result
  799. }
  800. // GetPermissionsAsString returns the user's permissions as comma separated string
  801. func (u *User) GetPermissionsAsString() string {
  802. result := ""
  803. for dir, perms := range u.Permissions {
  804. dirPerms := strings.Join(perms, ", ")
  805. dp := fmt.Sprintf("%#v: %#v", dir, dirPerms)
  806. if dir == "/" {
  807. if result != "" {
  808. result = dp + ", " + result
  809. } else {
  810. result = dp
  811. }
  812. } else {
  813. if result != "" {
  814. result += ", "
  815. }
  816. result += dp
  817. }
  818. }
  819. return result
  820. }
  821. // GetBandwidthAsString returns bandwidth limits if defines
  822. func (u *User) GetBandwidthAsString() string {
  823. result := "Download: "
  824. if u.DownloadBandwidth > 0 {
  825. result += utils.ByteCountIEC(u.DownloadBandwidth*1000) + "/s."
  826. } else {
  827. result += "unlimited."
  828. }
  829. result += " Upload: "
  830. if u.UploadBandwidth > 0 {
  831. result += utils.ByteCountIEC(u.UploadBandwidth*1000) + "/s."
  832. } else {
  833. result += "unlimited."
  834. }
  835. return result
  836. }
  837. // GetInfoString returns user's info as string.
  838. // Storage provider, number of public keys, max sessions, uid,
  839. // gid, denied and allowed IP/Mask are returned
  840. func (u *User) GetInfoString() string {
  841. var result string
  842. if u.LastLogin > 0 {
  843. t := utils.GetTimeFromMsecSinceEpoch(u.LastLogin)
  844. result += fmt.Sprintf("Last login: %v ", t.Format("2006-01-02 15:04:05")) // YYYY-MM-DD HH:MM:SS
  845. }
  846. switch u.FsConfig.Provider {
  847. case vfs.S3FilesystemProvider:
  848. result += "Storage: S3 "
  849. case vfs.GCSFilesystemProvider:
  850. result += "Storage: GCS "
  851. case vfs.AzureBlobFilesystemProvider:
  852. result += "Storage: Azure "
  853. case vfs.CryptedFilesystemProvider:
  854. result += "Storage: Encrypted "
  855. case vfs.SFTPFilesystemProvider:
  856. result += "Storage: SFTP "
  857. }
  858. if len(u.PublicKeys) > 0 {
  859. result += fmt.Sprintf("Public keys: %v ", len(u.PublicKeys))
  860. }
  861. if u.MaxSessions > 0 {
  862. result += fmt.Sprintf("Max sessions: %v ", u.MaxSessions)
  863. }
  864. if u.UID > 0 {
  865. result += fmt.Sprintf("UID: %v ", u.UID)
  866. }
  867. if u.GID > 0 {
  868. result += fmt.Sprintf("GID: %v ", u.GID)
  869. }
  870. if len(u.Filters.DeniedIP) > 0 {
  871. result += fmt.Sprintf("Denied IP/Mask: %v ", len(u.Filters.DeniedIP))
  872. }
  873. if len(u.Filters.AllowedIP) > 0 {
  874. result += fmt.Sprintf("Allowed IP/Mask: %v ", len(u.Filters.AllowedIP))
  875. }
  876. return result
  877. }
  878. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  879. func (u *User) GetExpirationDateAsString() string {
  880. if u.ExpirationDate > 0 {
  881. t := utils.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  882. return t.Format("2006-01-02")
  883. }
  884. return ""
  885. }
  886. // GetAllowedIPAsString returns the allowed IP as comma separated string
  887. func (u *User) GetAllowedIPAsString() string {
  888. return strings.Join(u.Filters.AllowedIP, ",")
  889. }
  890. // GetDeniedIPAsString returns the denied IP as comma separated string
  891. func (u *User) GetDeniedIPAsString() string {
  892. return strings.Join(u.Filters.DeniedIP, ",")
  893. }
  894. // SetEmptySecretsIfNil sets the secrets to empty if nil
  895. func (u *User) SetEmptySecretsIfNil() {
  896. u.FsConfig.SetEmptySecretsIfNil()
  897. for idx := range u.VirtualFolders {
  898. vfolder := &u.VirtualFolders[idx]
  899. vfolder.FsConfig.SetEmptySecretsIfNil()
  900. }
  901. }
  902. func (u *User) getACopy() User {
  903. u.SetEmptySecretsIfNil()
  904. pubKeys := make([]string, len(u.PublicKeys))
  905. copy(pubKeys, u.PublicKeys)
  906. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  907. for idx := range u.VirtualFolders {
  908. vfolder := u.VirtualFolders[idx].GetACopy()
  909. virtualFolders = append(virtualFolders, vfolder)
  910. }
  911. permissions := make(map[string][]string)
  912. for k, v := range u.Permissions {
  913. perms := make([]string, len(v))
  914. copy(perms, v)
  915. permissions[k] = perms
  916. }
  917. filters := UserFilters{}
  918. filters.MaxUploadFileSize = u.Filters.MaxUploadFileSize
  919. filters.TLSUsername = u.Filters.TLSUsername
  920. filters.AllowedIP = make([]string, len(u.Filters.AllowedIP))
  921. copy(filters.AllowedIP, u.Filters.AllowedIP)
  922. filters.DeniedIP = make([]string, len(u.Filters.DeniedIP))
  923. copy(filters.DeniedIP, u.Filters.DeniedIP)
  924. filters.DeniedLoginMethods = make([]string, len(u.Filters.DeniedLoginMethods))
  925. copy(filters.DeniedLoginMethods, u.Filters.DeniedLoginMethods)
  926. filters.FileExtensions = make([]ExtensionsFilter, len(u.Filters.FileExtensions))
  927. copy(filters.FileExtensions, u.Filters.FileExtensions)
  928. filters.FilePatterns = make([]PatternsFilter, len(u.Filters.FilePatterns))
  929. copy(filters.FilePatterns, u.Filters.FilePatterns)
  930. filters.DeniedProtocols = make([]string, len(u.Filters.DeniedProtocols))
  931. copy(filters.DeniedProtocols, u.Filters.DeniedProtocols)
  932. return User{
  933. ID: u.ID,
  934. Username: u.Username,
  935. Password: u.Password,
  936. PublicKeys: pubKeys,
  937. HomeDir: u.HomeDir,
  938. VirtualFolders: virtualFolders,
  939. UID: u.UID,
  940. GID: u.GID,
  941. MaxSessions: u.MaxSessions,
  942. QuotaSize: u.QuotaSize,
  943. QuotaFiles: u.QuotaFiles,
  944. Permissions: permissions,
  945. UsedQuotaSize: u.UsedQuotaSize,
  946. UsedQuotaFiles: u.UsedQuotaFiles,
  947. LastQuotaUpdate: u.LastQuotaUpdate,
  948. UploadBandwidth: u.UploadBandwidth,
  949. DownloadBandwidth: u.DownloadBandwidth,
  950. Status: u.Status,
  951. ExpirationDate: u.ExpirationDate,
  952. LastLogin: u.LastLogin,
  953. Filters: filters,
  954. FsConfig: u.FsConfig.GetACopy(),
  955. AdditionalInfo: u.AdditionalInfo,
  956. Description: u.Description,
  957. }
  958. }
  959. func (u *User) getNotificationFieldsAsSlice(action string) []string {
  960. return []string{action, u.Username,
  961. strconv.FormatInt(u.ID, 10),
  962. strconv.FormatInt(int64(u.Status), 10),
  963. strconv.FormatInt(u.ExpirationDate, 10),
  964. u.HomeDir,
  965. strconv.FormatInt(int64(u.UID), 10),
  966. strconv.FormatInt(int64(u.GID), 10),
  967. }
  968. }
  969. // GetEncrytionAdditionalData returns the additional data to use for AEAD
  970. func (u *User) GetEncrytionAdditionalData() string {
  971. return u.Username
  972. }
  973. // GetGCSCredentialsFilePath returns the path for GCS credentials
  974. func (u *User) GetGCSCredentialsFilePath() string {
  975. return filepath.Join(credentialsDirPath, fmt.Sprintf("%v_gcs_credentials.json", u.Username))
  976. }