admin.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. "net"
  20. "os"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "github.com/alexedwards/argon2id"
  25. "github.com/sftpgo/sdk"
  26. passwordvalidator "github.com/wagslane/go-password-validator"
  27. "golang.org/x/crypto/bcrypt"
  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/util"
  32. )
  33. // Available permissions for SFTPGo admins
  34. const (
  35. PermAdminAny = "*"
  36. PermAdminAddUsers = "add_users"
  37. PermAdminChangeUsers = "edit_users"
  38. PermAdminDeleteUsers = "del_users"
  39. PermAdminViewUsers = "view_users"
  40. PermAdminViewConnections = "view_conns"
  41. PermAdminCloseConnections = "close_conns"
  42. PermAdminViewServerStatus = "view_status"
  43. PermAdminManageAdmins = "manage_admins"
  44. PermAdminManageGroups = "manage_groups"
  45. PermAdminManageFolders = "manage_folders"
  46. PermAdminManageAPIKeys = "manage_apikeys"
  47. PermAdminQuotaScans = "quota_scans"
  48. PermAdminManageSystem = "manage_system"
  49. PermAdminManageDefender = "manage_defender"
  50. PermAdminViewDefender = "view_defender"
  51. PermAdminRetentionChecks = "retention_checks"
  52. PermAdminMetadataChecks = "metadata_checks"
  53. PermAdminViewEvents = "view_events"
  54. PermAdminManageEventRules = "manage_event_rules"
  55. PermAdminManageRoles = "manage_roles"
  56. PermAdminManageIPLists = "manage_ip_lists"
  57. )
  58. const (
  59. // GroupAddToUsersAsMembership defines that the admin's group will be added as membership group for new users
  60. GroupAddToUsersAsMembership = iota
  61. // GroupAddToUsersAsPrimary defines that the admin's group will be added as primary group for new users
  62. GroupAddToUsersAsPrimary
  63. // GroupAddToUsersAsSecondary defines that the admin's group will be added as secondary group for new users
  64. GroupAddToUsersAsSecondary
  65. )
  66. var (
  67. validAdminPerms = []string{PermAdminAny, PermAdminAddUsers, PermAdminChangeUsers, PermAdminDeleteUsers,
  68. PermAdminViewUsers, PermAdminManageFolders, PermAdminManageGroups, PermAdminViewConnections,
  69. PermAdminCloseConnections, PermAdminViewServerStatus, PermAdminManageAdmins, PermAdminManageRoles,
  70. PermAdminManageEventRules, PermAdminManageAPIKeys, PermAdminQuotaScans, PermAdminManageSystem,
  71. PermAdminManageDefender, PermAdminViewDefender, PermAdminManageIPLists, PermAdminRetentionChecks,
  72. PermAdminMetadataChecks, PermAdminViewEvents}
  73. forbiddenPermsForRoleAdmins = []string{PermAdminAny, PermAdminManageAdmins, PermAdminManageSystem,
  74. PermAdminManageEventRules, PermAdminManageIPLists, PermAdminManageRoles}
  75. )
  76. // AdminTOTPConfig defines the time-based one time password configuration
  77. type AdminTOTPConfig struct {
  78. Enabled bool `json:"enabled,omitempty"`
  79. ConfigName string `json:"config_name,omitempty"`
  80. Secret *kms.Secret `json:"secret,omitempty"`
  81. }
  82. func (c *AdminTOTPConfig) validate(username string) error {
  83. if !c.Enabled {
  84. c.ConfigName = ""
  85. c.Secret = kms.NewEmptySecret()
  86. return nil
  87. }
  88. if c.ConfigName == "" {
  89. return util.NewValidationError("totp: config name is mandatory")
  90. }
  91. if !util.Contains(mfa.GetAvailableTOTPConfigNames(), c.ConfigName) {
  92. return util.NewValidationError(fmt.Sprintf("totp: config name %q not found", c.ConfigName))
  93. }
  94. if c.Secret.IsEmpty() {
  95. return util.NewValidationError("totp: secret is mandatory")
  96. }
  97. if c.Secret.IsPlain() {
  98. c.Secret.SetAdditionalData(username)
  99. if err := c.Secret.Encrypt(); err != nil {
  100. return util.NewValidationError(fmt.Sprintf("totp: unable to encrypt secret: %v", err))
  101. }
  102. }
  103. return nil
  104. }
  105. // AdminPreferences defines the admin preferences
  106. type AdminPreferences struct {
  107. // Allow to hide some sections from the user page.
  108. // These are not security settings and are not enforced server side
  109. // in any way. They are only intended to simplify the user page in
  110. // the WebAdmin UI.
  111. //
  112. // 1 means hide groups section
  113. // 2 means hide filesystem section, "users_base_dir" must be set in the config file otherwise this setting is ignored
  114. // 4 means hide virtual folders section
  115. // 8 means hide profile section
  116. // 16 means hide ACLs section
  117. // 32 means hide disk and bandwidth quota limits section
  118. // 64 means hide advanced settings section
  119. //
  120. // The settings can be combined
  121. HideUserPageSections int `json:"hide_user_page_sections,omitempty"`
  122. // Defines the default expiration for newly created users as number of days.
  123. // 0 means no expiration
  124. DefaultUsersExpiration int `json:"default_users_expiration,omitempty"`
  125. }
  126. // HideGroups returns true if the groups section should be hidden
  127. func (p *AdminPreferences) HideGroups() bool {
  128. return p.HideUserPageSections&1 != 0
  129. }
  130. // HideFilesystem returns true if the filesystem section should be hidden
  131. func (p *AdminPreferences) HideFilesystem() bool {
  132. return config.UsersBaseDir != "" && p.HideUserPageSections&2 != 0
  133. }
  134. // HideVirtualFolders returns true if the virtual folder section should be hidden
  135. func (p *AdminPreferences) HideVirtualFolders() bool {
  136. return p.HideUserPageSections&4 != 0
  137. }
  138. // HideProfile returns true if the profile section should be hidden
  139. func (p *AdminPreferences) HideProfile() bool {
  140. return p.HideUserPageSections&8 != 0
  141. }
  142. // HideACLs returns true if the ACLs section should be hidden
  143. func (p *AdminPreferences) HideACLs() bool {
  144. return p.HideUserPageSections&16 != 0
  145. }
  146. // HideDiskQuotaAndBandwidthLimits returns true if the disk quota and bandwidth limits
  147. // section should be hidden
  148. func (p *AdminPreferences) HideDiskQuotaAndBandwidthLimits() bool {
  149. return p.HideUserPageSections&32 != 0
  150. }
  151. // HideAdvancedSettings returns true if the advanced settings section should be hidden
  152. func (p *AdminPreferences) HideAdvancedSettings() bool {
  153. return p.HideUserPageSections&64 != 0
  154. }
  155. // VisibleUserPageSections returns the number of visible sections
  156. // in the user page
  157. func (p *AdminPreferences) VisibleUserPageSections() int {
  158. var result int
  159. if !p.HideProfile() {
  160. result++
  161. }
  162. if !p.HideACLs() {
  163. result++
  164. }
  165. if !p.HideDiskQuotaAndBandwidthLimits() {
  166. result++
  167. }
  168. if !p.HideAdvancedSettings() {
  169. result++
  170. }
  171. return result
  172. }
  173. // AdminFilters defines additional restrictions for SFTPGo admins
  174. // TODO: rename to AdminOptions in v3
  175. type AdminFilters struct {
  176. // only clients connecting from these IP/Mask are allowed.
  177. // IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291
  178. // for example "192.0.2.0/24" or "2001:db8::/32"
  179. AllowList []string `json:"allow_list,omitempty"`
  180. // API key auth allows to impersonate this administrator with an API key
  181. AllowAPIKeyAuth bool `json:"allow_api_key_auth,omitempty"`
  182. // Time-based one time passwords configuration
  183. TOTPConfig AdminTOTPConfig `json:"totp_config,omitempty"`
  184. // Recovery codes to use if the user loses access to their second factor auth device.
  185. // Each code can only be used once, you should use these codes to login and disable or
  186. // reset 2FA for your account
  187. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  188. Preferences AdminPreferences `json:"preferences"`
  189. }
  190. // AdminGroupMappingOptions defines the options for admin/group mapping
  191. type AdminGroupMappingOptions struct {
  192. AddToUsersAs int `json:"add_to_users_as,omitempty"`
  193. }
  194. func (o *AdminGroupMappingOptions) validate() error {
  195. if o.AddToUsersAs < GroupAddToUsersAsMembership || o.AddToUsersAs > GroupAddToUsersAsSecondary {
  196. return util.NewValidationError(fmt.Sprintf("Invalid mode to add groups to new users: %d", o.AddToUsersAs))
  197. }
  198. return nil
  199. }
  200. // GetUserGroupType returns the type for the matching user group
  201. func (o *AdminGroupMappingOptions) GetUserGroupType() int {
  202. switch o.AddToUsersAs {
  203. case GroupAddToUsersAsPrimary:
  204. return sdk.GroupTypePrimary
  205. case GroupAddToUsersAsSecondary:
  206. return sdk.GroupTypeSecondary
  207. default:
  208. return sdk.GroupTypeMembership
  209. }
  210. }
  211. // AdminGroupMapping defines the mapping between an SFTPGo admin and a group
  212. type AdminGroupMapping struct {
  213. Name string `json:"name"`
  214. Options AdminGroupMappingOptions `json:"options"`
  215. }
  216. // Admin defines a SFTPGo admin
  217. type Admin struct {
  218. // Database unique identifier
  219. ID int64 `json:"id"`
  220. // 1 enabled, 0 disabled (login is not allowed)
  221. Status int `json:"status"`
  222. // Username
  223. Username string `json:"username"`
  224. Password string `json:"password,omitempty"`
  225. Email string `json:"email,omitempty"`
  226. Permissions []string `json:"permissions"`
  227. Filters AdminFilters `json:"filters,omitempty"`
  228. Description string `json:"description,omitempty"`
  229. AdditionalInfo string `json:"additional_info,omitempty"`
  230. // Groups membership
  231. Groups []AdminGroupMapping `json:"groups,omitempty"`
  232. // Creation time as unix timestamp in milliseconds. It will be 0 for admins created before v2.2.0
  233. CreatedAt int64 `json:"created_at"`
  234. // last update time as unix timestamp in milliseconds
  235. UpdatedAt int64 `json:"updated_at"`
  236. // Last login as unix timestamp in milliseconds
  237. LastLogin int64 `json:"last_login"`
  238. // Role name. If set the admin can only administer users with the same role.
  239. // Role admins cannot have the following permissions:
  240. // - manage_admins
  241. // - manage_apikeys
  242. // - manage_system
  243. // - manage_event_rules
  244. // - manage_roles
  245. Role string `json:"role,omitempty"`
  246. }
  247. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  248. func (a *Admin) CountUnusedRecoveryCodes() int {
  249. unused := 0
  250. for _, code := range a.Filters.RecoveryCodes {
  251. if !code.Used {
  252. unused++
  253. }
  254. }
  255. return unused
  256. }
  257. func (a *Admin) hashPassword() error {
  258. if a.Password != "" && !util.IsStringPrefixInSlice(a.Password, internalHashPwdPrefixes) {
  259. if config.PasswordValidation.Admins.MinEntropy > 0 {
  260. if err := passwordvalidator.Validate(a.Password, config.PasswordValidation.Admins.MinEntropy); err != nil {
  261. return util.NewValidationError(err.Error())
  262. }
  263. }
  264. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  265. pwd, err := bcrypt.GenerateFromPassword([]byte(a.Password), config.PasswordHashing.BcryptOptions.Cost)
  266. if err != nil {
  267. return err
  268. }
  269. a.Password = string(pwd)
  270. } else {
  271. pwd, err := argon2id.CreateHash(a.Password, argon2Params)
  272. if err != nil {
  273. return err
  274. }
  275. a.Password = pwd
  276. }
  277. }
  278. return nil
  279. }
  280. func (a *Admin) hasRedactedSecret() bool {
  281. return a.Filters.TOTPConfig.Secret.IsRedacted()
  282. }
  283. func (a *Admin) validateRecoveryCodes() error {
  284. for i := 0; i < len(a.Filters.RecoveryCodes); i++ {
  285. code := &a.Filters.RecoveryCodes[i]
  286. if code.Secret.IsEmpty() {
  287. return util.NewValidationError("mfa: recovery code cannot be empty")
  288. }
  289. if code.Secret.IsPlain() {
  290. code.Secret.SetAdditionalData(a.Username)
  291. if err := code.Secret.Encrypt(); err != nil {
  292. return util.NewValidationError(fmt.Sprintf("mfa: unable to encrypt recovery code: %v", err))
  293. }
  294. }
  295. }
  296. return nil
  297. }
  298. func (a *Admin) validatePermissions() error {
  299. a.Permissions = util.RemoveDuplicates(a.Permissions, false)
  300. if len(a.Permissions) == 0 {
  301. return util.NewValidationError("please grant some permissions to this admin")
  302. }
  303. if util.Contains(a.Permissions, PermAdminAny) {
  304. a.Permissions = []string{PermAdminAny}
  305. }
  306. for _, perm := range a.Permissions {
  307. if !util.Contains(validAdminPerms, perm) {
  308. return util.NewValidationError(fmt.Sprintf("invalid permission: %q", perm))
  309. }
  310. if a.Role != "" {
  311. if util.Contains(forbiddenPermsForRoleAdmins, perm) {
  312. return util.NewValidationError(fmt.Sprintf("a role admin cannot have the following permissions: %q",
  313. strings.Join(forbiddenPermsForRoleAdmins, ",")))
  314. }
  315. }
  316. }
  317. return nil
  318. }
  319. func (a *Admin) validateGroups() error {
  320. hasPrimary := false
  321. for _, g := range a.Groups {
  322. if g.Name == "" {
  323. return util.NewValidationError("group name is mandatory")
  324. }
  325. if err := g.Options.validate(); err != nil {
  326. return err
  327. }
  328. if g.Options.AddToUsersAs == GroupAddToUsersAsPrimary {
  329. if hasPrimary {
  330. return util.NewValidationError("only one primary group is allowed")
  331. }
  332. hasPrimary = true
  333. }
  334. }
  335. return nil
  336. }
  337. func (a *Admin) validate() error {
  338. a.SetEmptySecretsIfNil()
  339. if a.Username == "" {
  340. return util.NewValidationError("username is mandatory")
  341. }
  342. if err := checkReservedUsernames(a.Username); err != nil {
  343. return err
  344. }
  345. if a.Password == "" {
  346. return util.NewValidationError("please set a password")
  347. }
  348. if a.hasRedactedSecret() {
  349. return util.NewValidationError("cannot save an admin with a redacted secret")
  350. }
  351. if err := a.Filters.TOTPConfig.validate(a.Username); err != nil {
  352. return err
  353. }
  354. if err := a.validateRecoveryCodes(); err != nil {
  355. return err
  356. }
  357. if config.NamingRules&1 == 0 && !usernameRegex.MatchString(a.Username) {
  358. return util.NewValidationError(fmt.Sprintf("username %q is not valid, the following characters are allowed: a-zA-Z0-9-_.~", a.Username))
  359. }
  360. if err := a.hashPassword(); err != nil {
  361. return err
  362. }
  363. if err := a.validatePermissions(); err != nil {
  364. return err
  365. }
  366. if a.Email != "" && !util.IsEmailValid(a.Email) {
  367. return util.NewValidationError(fmt.Sprintf("email %q is not valid", a.Email))
  368. }
  369. a.Filters.AllowList = util.RemoveDuplicates(a.Filters.AllowList, false)
  370. for _, IPMask := range a.Filters.AllowList {
  371. _, _, err := net.ParseCIDR(IPMask)
  372. if err != nil {
  373. return util.NewValidationError(fmt.Sprintf("could not parse allow list entry %q : %v", IPMask, err))
  374. }
  375. }
  376. return a.validateGroups()
  377. }
  378. // GetGroupsAsString returns the user's groups as a string
  379. func (a *Admin) GetGroupsAsString() string {
  380. if len(a.Groups) == 0 {
  381. return ""
  382. }
  383. var groups []string
  384. for _, g := range a.Groups {
  385. groups = append(groups, g.Name)
  386. }
  387. sort.Strings(groups)
  388. return strings.Join(groups, ",")
  389. }
  390. // CheckPassword verifies the admin password
  391. func (a *Admin) CheckPassword(password string) (bool, error) {
  392. if config.PasswordCaching {
  393. found, match := cachedAdminPasswords.Check(a.Username, password, a.Password)
  394. if found {
  395. if !match {
  396. return false, ErrInvalidCredentials
  397. }
  398. return match, nil
  399. }
  400. }
  401. if strings.HasPrefix(a.Password, bcryptPwdPrefix) {
  402. if err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password)); err != nil {
  403. return false, ErrInvalidCredentials
  404. }
  405. cachedAdminPasswords.Add(a.Username, password, a.Password)
  406. return true, nil
  407. }
  408. match, err := argon2id.ComparePasswordAndHash(password, a.Password)
  409. if !match || err != nil {
  410. return false, ErrInvalidCredentials
  411. }
  412. if match && err == nil {
  413. cachedAdminPasswords.Add(a.Username, password, a.Password)
  414. }
  415. return match, err
  416. }
  417. // CanLoginFromIP returns true if login from the given IP is allowed
  418. func (a *Admin) CanLoginFromIP(ip string) bool {
  419. if len(a.Filters.AllowList) == 0 {
  420. return true
  421. }
  422. parsedIP := net.ParseIP(ip)
  423. if parsedIP == nil {
  424. return len(a.Filters.AllowList) == 0
  425. }
  426. for _, ipMask := range a.Filters.AllowList {
  427. _, network, err := net.ParseCIDR(ipMask)
  428. if err != nil {
  429. continue
  430. }
  431. if network.Contains(parsedIP) {
  432. return true
  433. }
  434. }
  435. return false
  436. }
  437. // CanLogin returns an error if the login is not allowed
  438. func (a *Admin) CanLogin(ip string) error {
  439. if a.Status != 1 {
  440. return fmt.Errorf("admin %q is disabled", a.Username)
  441. }
  442. if !a.CanLoginFromIP(ip) {
  443. return fmt.Errorf("login from IP %v not allowed", ip)
  444. }
  445. return nil
  446. }
  447. func (a *Admin) checkUserAndPass(password, ip string) error {
  448. if err := a.CanLogin(ip); err != nil {
  449. return err
  450. }
  451. if a.Password == "" || password == "" {
  452. return errors.New("credentials cannot be null or empty")
  453. }
  454. match, err := a.CheckPassword(password)
  455. if err != nil {
  456. return err
  457. }
  458. if !match {
  459. return ErrInvalidCredentials
  460. }
  461. return nil
  462. }
  463. // RenderAsJSON implements the renderer interface used within plugins
  464. func (a *Admin) RenderAsJSON(reload bool) ([]byte, error) {
  465. if reload {
  466. admin, err := provider.adminExists(a.Username)
  467. if err != nil {
  468. providerLog(logger.LevelError, "unable to reload admin before rendering as json: %v", err)
  469. return nil, err
  470. }
  471. admin.HideConfidentialData()
  472. return json.Marshal(admin)
  473. }
  474. a.HideConfidentialData()
  475. return json.Marshal(a)
  476. }
  477. // HideConfidentialData hides admin confidential data
  478. func (a *Admin) HideConfidentialData() {
  479. a.Password = ""
  480. if a.Filters.TOTPConfig.Secret != nil {
  481. a.Filters.TOTPConfig.Secret.Hide()
  482. }
  483. for _, code := range a.Filters.RecoveryCodes {
  484. if code.Secret != nil {
  485. code.Secret.Hide()
  486. }
  487. }
  488. a.SetNilSecretsIfEmpty()
  489. }
  490. // SetEmptySecretsIfNil sets the secrets to empty if nil
  491. func (a *Admin) SetEmptySecretsIfNil() {
  492. if a.Filters.TOTPConfig.Secret == nil {
  493. a.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  494. }
  495. }
  496. // SetNilSecretsIfEmpty set the secrets to nil if empty.
  497. // This is useful before rendering as JSON so the empty fields
  498. // will not be serialized.
  499. func (a *Admin) SetNilSecretsIfEmpty() {
  500. if a.Filters.TOTPConfig.Secret != nil && a.Filters.TOTPConfig.Secret.IsEmpty() {
  501. a.Filters.TOTPConfig.Secret = nil
  502. }
  503. }
  504. // HasPermission returns true if the admin has the specified permission
  505. func (a *Admin) HasPermission(perm string) bool {
  506. if util.Contains(a.Permissions, PermAdminAny) {
  507. return true
  508. }
  509. return util.Contains(a.Permissions, perm)
  510. }
  511. // GetPermissionsAsString returns permission as string
  512. func (a *Admin) GetPermissionsAsString() string {
  513. return strings.Join(a.Permissions, ", ")
  514. }
  515. // GetLastLoginAsString returns the last login as string
  516. func (a *Admin) GetLastLoginAsString() string {
  517. if a.LastLogin > 0 {
  518. return util.GetTimeFromMsecSinceEpoch(a.LastLogin).UTC().Format(iso8601UTCFormat)
  519. }
  520. return ""
  521. }
  522. // GetAllowedIPAsString returns the allowed IP as comma separated string
  523. func (a *Admin) GetAllowedIPAsString() string {
  524. return strings.Join(a.Filters.AllowList, ",")
  525. }
  526. // GetValidPerms returns the allowed admin permissions
  527. func (a *Admin) GetValidPerms() []string {
  528. return validAdminPerms
  529. }
  530. // CanManageMFA returns true if the admin can add a multi-factor authentication configuration
  531. func (a *Admin) CanManageMFA() bool {
  532. return len(mfa.GetAvailableTOTPConfigs()) > 0
  533. }
  534. // GetSignature returns a signature for this admin.
  535. // It will change after an update
  536. func (a *Admin) GetSignature() string {
  537. return strconv.FormatInt(a.UpdatedAt, 10)
  538. }
  539. func (a *Admin) getACopy() Admin {
  540. a.SetEmptySecretsIfNil()
  541. permissions := make([]string, len(a.Permissions))
  542. copy(permissions, a.Permissions)
  543. filters := AdminFilters{}
  544. filters.AllowList = make([]string, len(a.Filters.AllowList))
  545. filters.AllowAPIKeyAuth = a.Filters.AllowAPIKeyAuth
  546. filters.TOTPConfig.Enabled = a.Filters.TOTPConfig.Enabled
  547. filters.TOTPConfig.ConfigName = a.Filters.TOTPConfig.ConfigName
  548. filters.TOTPConfig.Secret = a.Filters.TOTPConfig.Secret.Clone()
  549. copy(filters.AllowList, a.Filters.AllowList)
  550. filters.RecoveryCodes = make([]RecoveryCode, 0)
  551. for _, code := range a.Filters.RecoveryCodes {
  552. if code.Secret == nil {
  553. code.Secret = kms.NewEmptySecret()
  554. }
  555. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  556. Secret: code.Secret.Clone(),
  557. Used: code.Used,
  558. })
  559. }
  560. filters.Preferences = AdminPreferences{
  561. HideUserPageSections: a.Filters.Preferences.HideUserPageSections,
  562. DefaultUsersExpiration: a.Filters.Preferences.DefaultUsersExpiration,
  563. }
  564. groups := make([]AdminGroupMapping, 0, len(a.Groups))
  565. for _, g := range a.Groups {
  566. groups = append(groups, AdminGroupMapping{
  567. Name: g.Name,
  568. Options: AdminGroupMappingOptions{
  569. AddToUsersAs: g.Options.AddToUsersAs,
  570. },
  571. })
  572. }
  573. return Admin{
  574. ID: a.ID,
  575. Status: a.Status,
  576. Username: a.Username,
  577. Password: a.Password,
  578. Email: a.Email,
  579. Permissions: permissions,
  580. Groups: groups,
  581. Filters: filters,
  582. AdditionalInfo: a.AdditionalInfo,
  583. Description: a.Description,
  584. LastLogin: a.LastLogin,
  585. CreatedAt: a.CreatedAt,
  586. UpdatedAt: a.UpdatedAt,
  587. Role: a.Role,
  588. }
  589. }
  590. func (a *Admin) setFromEnv() error {
  591. envUsername := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_USERNAME"))
  592. envPassword := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_PASSWORD"))
  593. if envUsername == "" || envPassword == "" {
  594. return errors.New(`to create the default admin you need to set the env vars "SFTPGO_DEFAULT_ADMIN_USERNAME" and "SFTPGO_DEFAULT_ADMIN_PASSWORD"`)
  595. }
  596. a.Username = envUsername
  597. a.Password = envPassword
  598. a.Status = 1
  599. a.Permissions = []string{PermAdminAny}
  600. return nil
  601. }