admin.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // Copyright (C) 2019-2022 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. "crypto/sha256"
  17. "encoding/base64"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "net"
  22. "os"
  23. "strings"
  24. "github.com/alexedwards/argon2id"
  25. passwordvalidator "github.com/wagslane/go-password-validator"
  26. "golang.org/x/crypto/bcrypt"
  27. "github.com/drakkan/sftpgo/v2/kms"
  28. "github.com/drakkan/sftpgo/v2/logger"
  29. "github.com/drakkan/sftpgo/v2/mfa"
  30. "github.com/drakkan/sftpgo/v2/util"
  31. )
  32. // Available permissions for SFTPGo admins
  33. const (
  34. PermAdminAny = "*"
  35. PermAdminAddUsers = "add_users"
  36. PermAdminChangeUsers = "edit_users"
  37. PermAdminDeleteUsers = "del_users"
  38. PermAdminViewUsers = "view_users"
  39. PermAdminViewConnections = "view_conns"
  40. PermAdminCloseConnections = "close_conns"
  41. PermAdminViewServerStatus = "view_status"
  42. PermAdminManageAdmins = "manage_admins"
  43. PermAdminManageGroups = "manage_groups"
  44. PermAdminManageAPIKeys = "manage_apikeys"
  45. PermAdminQuotaScans = "quota_scans"
  46. PermAdminManageSystem = "manage_system"
  47. PermAdminManageDefender = "manage_defender"
  48. PermAdminViewDefender = "view_defender"
  49. PermAdminRetentionChecks = "retention_checks"
  50. PermAdminMetadataChecks = "metadata_checks"
  51. PermAdminViewEvents = "view_events"
  52. PermAdminManageEventRules = "manage_event_rules"
  53. )
  54. var (
  55. validAdminPerms = []string{PermAdminAny, PermAdminAddUsers, PermAdminChangeUsers, PermAdminDeleteUsers,
  56. PermAdminViewUsers, PermAdminManageGroups, PermAdminViewConnections, PermAdminCloseConnections,
  57. PermAdminViewServerStatus, PermAdminManageAdmins, PermAdminManageAPIKeys, PermAdminQuotaScans,
  58. PermAdminManageSystem, PermAdminManageDefender, PermAdminViewDefender, PermAdminRetentionChecks,
  59. PermAdminMetadataChecks, PermAdminViewEvents}
  60. )
  61. // AdminTOTPConfig defines the time-based one time password configuration
  62. type AdminTOTPConfig struct {
  63. Enabled bool `json:"enabled,omitempty"`
  64. ConfigName string `json:"config_name,omitempty"`
  65. Secret *kms.Secret `json:"secret,omitempty"`
  66. }
  67. func (c *AdminTOTPConfig) validate(username string) error {
  68. if !c.Enabled {
  69. c.ConfigName = ""
  70. c.Secret = kms.NewEmptySecret()
  71. return nil
  72. }
  73. if c.ConfigName == "" {
  74. return util.NewValidationError("totp: config name is mandatory")
  75. }
  76. if !util.Contains(mfa.GetAvailableTOTPConfigNames(), c.ConfigName) {
  77. return util.NewValidationError(fmt.Sprintf("totp: config name %#v not found", c.ConfigName))
  78. }
  79. if c.Secret.IsEmpty() {
  80. return util.NewValidationError("totp: secret is mandatory")
  81. }
  82. if c.Secret.IsPlain() {
  83. c.Secret.SetAdditionalData(username)
  84. if err := c.Secret.Encrypt(); err != nil {
  85. return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
  86. }
  87. }
  88. return nil
  89. }
  90. // AdminFilters defines additional restrictions for SFTPGo admins
  91. // TODO: rename to AdminOptions in v3
  92. type AdminFilters struct {
  93. // only clients connecting from these IP/Mask are allowed.
  94. // IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291
  95. // for example "192.0.2.0/24" or "2001:db8::/32"
  96. AllowList []string `json:"allow_list,omitempty"`
  97. // API key auth allows to impersonate this administrator with an API key
  98. AllowAPIKeyAuth bool `json:"allow_api_key_auth,omitempty"`
  99. // Time-based one time passwords configuration
  100. TOTPConfig AdminTOTPConfig `json:"totp_config,omitempty"`
  101. // Recovery codes to use if the user loses access to their second factor auth device.
  102. // Each code can only be used once, you should use these codes to login and disable or
  103. // reset 2FA for your account
  104. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  105. }
  106. // Admin defines a SFTPGo admin
  107. type Admin struct {
  108. // Database unique identifier
  109. ID int64 `json:"id"`
  110. // 1 enabled, 0 disabled (login is not allowed)
  111. Status int `json:"status"`
  112. // Username
  113. Username string `json:"username"`
  114. Password string `json:"password,omitempty"`
  115. Email string `json:"email,omitempty"`
  116. Permissions []string `json:"permissions"`
  117. Filters AdminFilters `json:"filters,omitempty"`
  118. Description string `json:"description,omitempty"`
  119. AdditionalInfo string `json:"additional_info,omitempty"`
  120. // Creation time as unix timestamp in milliseconds. It will be 0 for admins created before v2.2.0
  121. CreatedAt int64 `json:"created_at"`
  122. // last update time as unix timestamp in milliseconds
  123. UpdatedAt int64 `json:"updated_at"`
  124. // Last login as unix timestamp in milliseconds
  125. LastLogin int64 `json:"last_login"`
  126. }
  127. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  128. func (a *Admin) CountUnusedRecoveryCodes() int {
  129. unused := 0
  130. for _, code := range a.Filters.RecoveryCodes {
  131. if !code.Used {
  132. unused++
  133. }
  134. }
  135. return unused
  136. }
  137. func (a *Admin) hashPassword() error {
  138. if a.Password != "" && !util.IsStringPrefixInSlice(a.Password, internalHashPwdPrefixes) {
  139. if config.PasswordValidation.Admins.MinEntropy > 0 {
  140. if err := passwordvalidator.Validate(a.Password, config.PasswordValidation.Admins.MinEntropy); err != nil {
  141. return util.NewValidationError(err.Error())
  142. }
  143. }
  144. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  145. pwd, err := bcrypt.GenerateFromPassword([]byte(a.Password), config.PasswordHashing.BcryptOptions.Cost)
  146. if err != nil {
  147. return err
  148. }
  149. a.Password = string(pwd)
  150. } else {
  151. pwd, err := argon2id.CreateHash(a.Password, argon2Params)
  152. if err != nil {
  153. return err
  154. }
  155. a.Password = pwd
  156. }
  157. }
  158. return nil
  159. }
  160. func (a *Admin) hasRedactedSecret() bool {
  161. return a.Filters.TOTPConfig.Secret.IsRedacted()
  162. }
  163. func (a *Admin) validateRecoveryCodes() error {
  164. for i := 0; i < len(a.Filters.RecoveryCodes); i++ {
  165. code := &a.Filters.RecoveryCodes[i]
  166. if code.Secret.IsEmpty() {
  167. return util.NewValidationError("mfa: recovery code cannot be empty")
  168. }
  169. if code.Secret.IsPlain() {
  170. code.Secret.SetAdditionalData(a.Username)
  171. if err := code.Secret.Encrypt(); err != nil {
  172. return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
  173. }
  174. }
  175. }
  176. return nil
  177. }
  178. func (a *Admin) validatePermissions() error {
  179. a.Permissions = util.RemoveDuplicates(a.Permissions, false)
  180. if len(a.Permissions) == 0 {
  181. return util.NewValidationError("please grant some permissions to this admin")
  182. }
  183. if util.Contains(a.Permissions, PermAdminAny) {
  184. a.Permissions = []string{PermAdminAny}
  185. }
  186. for _, perm := range a.Permissions {
  187. if !util.Contains(validAdminPerms, perm) {
  188. return util.NewValidationError(fmt.Sprintf("invalid permission: %#v", perm))
  189. }
  190. }
  191. return nil
  192. }
  193. func (a *Admin) validate() error {
  194. a.SetEmptySecretsIfNil()
  195. if a.Username == "" {
  196. return util.NewValidationError("username is mandatory")
  197. }
  198. if a.Password == "" {
  199. return util.NewValidationError("please set a password")
  200. }
  201. if a.hasRedactedSecret() {
  202. return util.NewValidationError("cannot save an admin with a redacted secret")
  203. }
  204. if err := a.Filters.TOTPConfig.validate(a.Username); err != nil {
  205. return err
  206. }
  207. if err := a.validateRecoveryCodes(); err != nil {
  208. return err
  209. }
  210. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(a.Username) {
  211. return util.NewValidationError(fmt.Sprintf("username %#v is not valid, the following characters are allowed: a-zA-Z0-9-_.~", a.Username))
  212. }
  213. if err := a.hashPassword(); err != nil {
  214. return err
  215. }
  216. if err := a.validatePermissions(); err != nil {
  217. return err
  218. }
  219. if a.Email != "" && !util.IsEmailValid(a.Email) {
  220. return util.NewValidationError(fmt.Sprintf("email %#v is not valid", a.Email))
  221. }
  222. a.Filters.AllowList = util.RemoveDuplicates(a.Filters.AllowList, false)
  223. for _, IPMask := range a.Filters.AllowList {
  224. _, _, err := net.ParseCIDR(IPMask)
  225. if err != nil {
  226. return util.NewValidationError(fmt.Sprintf("could not parse allow list entry %#v : %v", IPMask, err))
  227. }
  228. }
  229. return nil
  230. }
  231. // CheckPassword verifies the admin password
  232. func (a *Admin) CheckPassword(password string) (bool, error) {
  233. if strings.HasPrefix(a.Password, bcryptPwdPrefix) {
  234. if err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password)); err != nil {
  235. return false, ErrInvalidCredentials
  236. }
  237. return true, nil
  238. }
  239. match, err := argon2id.ComparePasswordAndHash(password, a.Password)
  240. if !match || err != nil {
  241. return false, ErrInvalidCredentials
  242. }
  243. return match, err
  244. }
  245. // CanLoginFromIP returns true if login from the given IP is allowed
  246. func (a *Admin) CanLoginFromIP(ip string) bool {
  247. if len(a.Filters.AllowList) == 0 {
  248. return true
  249. }
  250. parsedIP := net.ParseIP(ip)
  251. if parsedIP == nil {
  252. return len(a.Filters.AllowList) == 0
  253. }
  254. for _, ipMask := range a.Filters.AllowList {
  255. _, network, err := net.ParseCIDR(ipMask)
  256. if err != nil {
  257. continue
  258. }
  259. if network.Contains(parsedIP) {
  260. return true
  261. }
  262. }
  263. return false
  264. }
  265. // CanLogin returns an error if the login is not allowed
  266. func (a *Admin) CanLogin(ip string) error {
  267. if a.Status != 1 {
  268. return fmt.Errorf("admin %#v is disabled", a.Username)
  269. }
  270. if !a.CanLoginFromIP(ip) {
  271. return fmt.Errorf("login from IP %v not allowed", ip)
  272. }
  273. return nil
  274. }
  275. func (a *Admin) checkUserAndPass(password, ip string) error {
  276. if err := a.CanLogin(ip); err != nil {
  277. return err
  278. }
  279. if a.Password == "" || password == "" {
  280. return errors.New("credentials cannot be null or empty")
  281. }
  282. match, err := a.CheckPassword(password)
  283. if err != nil {
  284. return err
  285. }
  286. if !match {
  287. return ErrInvalidCredentials
  288. }
  289. return nil
  290. }
  291. // RenderAsJSON implements the renderer interface used within plugins
  292. func (a *Admin) RenderAsJSON(reload bool) ([]byte, error) {
  293. if reload {
  294. admin, err := provider.adminExists(a.Username)
  295. if err != nil {
  296. providerLog(logger.LevelError, "unable to reload admin before rendering as json: %v", err)
  297. return nil, err
  298. }
  299. admin.HideConfidentialData()
  300. return json.Marshal(admin)
  301. }
  302. a.HideConfidentialData()
  303. return json.Marshal(a)
  304. }
  305. // HideConfidentialData hides admin confidential data
  306. func (a *Admin) HideConfidentialData() {
  307. a.Password = ""
  308. if a.Filters.TOTPConfig.Secret != nil {
  309. a.Filters.TOTPConfig.Secret.Hide()
  310. }
  311. for _, code := range a.Filters.RecoveryCodes {
  312. if code.Secret != nil {
  313. code.Secret.Hide()
  314. }
  315. }
  316. a.SetNilSecretsIfEmpty()
  317. }
  318. // SetEmptySecretsIfNil sets the secrets to empty if nil
  319. func (a *Admin) SetEmptySecretsIfNil() {
  320. if a.Filters.TOTPConfig.Secret == nil {
  321. a.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  322. }
  323. }
  324. // SetNilSecretsIfEmpty set the secrets to nil if empty.
  325. // This is useful before rendering as JSON so the empty fields
  326. // will not be serialized.
  327. func (a *Admin) SetNilSecretsIfEmpty() {
  328. if a.Filters.TOTPConfig.Secret != nil && a.Filters.TOTPConfig.Secret.IsEmpty() {
  329. a.Filters.TOTPConfig.Secret = nil
  330. }
  331. }
  332. // HasPermission returns true if the admin has the specified permission
  333. func (a *Admin) HasPermission(perm string) bool {
  334. if util.Contains(a.Permissions, PermAdminAny) {
  335. return true
  336. }
  337. return util.Contains(a.Permissions, perm)
  338. }
  339. // GetPermissionsAsString returns permission as string
  340. func (a *Admin) GetPermissionsAsString() string {
  341. return strings.Join(a.Permissions, ", ")
  342. }
  343. // GetLastLoginAsString returns the last login as string
  344. func (a *Admin) GetLastLoginAsString() string {
  345. if a.LastLogin > 0 {
  346. return util.GetTimeFromMsecSinceEpoch(a.LastLogin).UTC().Format(iso8601UTCFormat)
  347. }
  348. return ""
  349. }
  350. // GetAllowedIPAsString returns the allowed IP as comma separated string
  351. func (a *Admin) GetAllowedIPAsString() string {
  352. return strings.Join(a.Filters.AllowList, ",")
  353. }
  354. // GetValidPerms returns the allowed admin permissions
  355. func (a *Admin) GetValidPerms() []string {
  356. return validAdminPerms
  357. }
  358. // CanManageMFA returns true if the admin can add a multi-factor authentication configuration
  359. func (a *Admin) CanManageMFA() bool {
  360. return len(mfa.GetAvailableTOTPConfigs()) > 0
  361. }
  362. // GetSignature returns a signature for this admin.
  363. // It could change after an update
  364. func (a *Admin) GetSignature() string {
  365. data := []byte(a.Username)
  366. data = append(data, []byte(a.Password)...)
  367. signature := sha256.Sum256(data)
  368. return base64.StdEncoding.EncodeToString(signature[:])
  369. }
  370. func (a *Admin) getACopy() Admin {
  371. a.SetEmptySecretsIfNil()
  372. permissions := make([]string, len(a.Permissions))
  373. copy(permissions, a.Permissions)
  374. filters := AdminFilters{}
  375. filters.AllowList = make([]string, len(a.Filters.AllowList))
  376. filters.AllowAPIKeyAuth = a.Filters.AllowAPIKeyAuth
  377. filters.TOTPConfig.Enabled = a.Filters.TOTPConfig.Enabled
  378. filters.TOTPConfig.ConfigName = a.Filters.TOTPConfig.ConfigName
  379. filters.TOTPConfig.Secret = a.Filters.TOTPConfig.Secret.Clone()
  380. copy(filters.AllowList, a.Filters.AllowList)
  381. filters.RecoveryCodes = make([]RecoveryCode, 0)
  382. for _, code := range a.Filters.RecoveryCodes {
  383. if code.Secret == nil {
  384. code.Secret = kms.NewEmptySecret()
  385. }
  386. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  387. Secret: code.Secret.Clone(),
  388. Used: code.Used,
  389. })
  390. }
  391. return Admin{
  392. ID: a.ID,
  393. Status: a.Status,
  394. Username: a.Username,
  395. Password: a.Password,
  396. Email: a.Email,
  397. Permissions: permissions,
  398. Filters: filters,
  399. AdditionalInfo: a.AdditionalInfo,
  400. Description: a.Description,
  401. LastLogin: a.LastLogin,
  402. CreatedAt: a.CreatedAt,
  403. UpdatedAt: a.UpdatedAt,
  404. }
  405. }
  406. func (a *Admin) setFromEnv() error {
  407. envUsername := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_USERNAME"))
  408. envPassword := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_PASSWORD"))
  409. if envUsername == "" || envPassword == "" {
  410. return errors.New(`to create the default admin you need to set the env vars "SFTPGO_DEFAULT_ADMIN_USERNAME" and "SFTPGO_DEFAULT_ADMIN_PASSWORD"`)
  411. }
  412. a.Username = envUsername
  413. a.Password = envPassword
  414. a.Status = 1
  415. a.Permissions = []string{PermAdminAny}
  416. return nil
  417. }