admin.go 20 KB

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