admin.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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 %#v 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 %#v 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 %#v : %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 strings.HasPrefix(a.Password, bcryptPwdPrefix) {
  392. if err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password)); err != nil {
  393. return false, ErrInvalidCredentials
  394. }
  395. return true, nil
  396. }
  397. match, err := argon2id.ComparePasswordAndHash(password, a.Password)
  398. if !match || err != nil {
  399. return false, ErrInvalidCredentials
  400. }
  401. return match, err
  402. }
  403. // CanLoginFromIP returns true if login from the given IP is allowed
  404. func (a *Admin) CanLoginFromIP(ip string) bool {
  405. if len(a.Filters.AllowList) == 0 {
  406. return true
  407. }
  408. parsedIP := net.ParseIP(ip)
  409. if parsedIP == nil {
  410. return len(a.Filters.AllowList) == 0
  411. }
  412. for _, ipMask := range a.Filters.AllowList {
  413. _, network, err := net.ParseCIDR(ipMask)
  414. if err != nil {
  415. continue
  416. }
  417. if network.Contains(parsedIP) {
  418. return true
  419. }
  420. }
  421. return false
  422. }
  423. // CanLogin returns an error if the login is not allowed
  424. func (a *Admin) CanLogin(ip string) error {
  425. if a.Status != 1 {
  426. return fmt.Errorf("admin %#v is disabled", a.Username)
  427. }
  428. if !a.CanLoginFromIP(ip) {
  429. return fmt.Errorf("login from IP %v not allowed", ip)
  430. }
  431. return nil
  432. }
  433. func (a *Admin) checkUserAndPass(password, ip string) error {
  434. if err := a.CanLogin(ip); err != nil {
  435. return err
  436. }
  437. if a.Password == "" || password == "" {
  438. return errors.New("credentials cannot be null or empty")
  439. }
  440. match, err := a.CheckPassword(password)
  441. if err != nil {
  442. return err
  443. }
  444. if !match {
  445. return ErrInvalidCredentials
  446. }
  447. return nil
  448. }
  449. // RenderAsJSON implements the renderer interface used within plugins
  450. func (a *Admin) RenderAsJSON(reload bool) ([]byte, error) {
  451. if reload {
  452. admin, err := provider.adminExists(a.Username)
  453. if err != nil {
  454. providerLog(logger.LevelError, "unable to reload admin before rendering as json: %v", err)
  455. return nil, err
  456. }
  457. admin.HideConfidentialData()
  458. return json.Marshal(admin)
  459. }
  460. a.HideConfidentialData()
  461. return json.Marshal(a)
  462. }
  463. // HideConfidentialData hides admin confidential data
  464. func (a *Admin) HideConfidentialData() {
  465. a.Password = ""
  466. if a.Filters.TOTPConfig.Secret != nil {
  467. a.Filters.TOTPConfig.Secret.Hide()
  468. }
  469. for _, code := range a.Filters.RecoveryCodes {
  470. if code.Secret != nil {
  471. code.Secret.Hide()
  472. }
  473. }
  474. a.SetNilSecretsIfEmpty()
  475. }
  476. // SetEmptySecretsIfNil sets the secrets to empty if nil
  477. func (a *Admin) SetEmptySecretsIfNil() {
  478. if a.Filters.TOTPConfig.Secret == nil {
  479. a.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  480. }
  481. }
  482. // SetNilSecretsIfEmpty set the secrets to nil if empty.
  483. // This is useful before rendering as JSON so the empty fields
  484. // will not be serialized.
  485. func (a *Admin) SetNilSecretsIfEmpty() {
  486. if a.Filters.TOTPConfig.Secret != nil && a.Filters.TOTPConfig.Secret.IsEmpty() {
  487. a.Filters.TOTPConfig.Secret = nil
  488. }
  489. }
  490. // HasPermission returns true if the admin has the specified permission
  491. func (a *Admin) HasPermission(perm string) bool {
  492. if util.Contains(a.Permissions, PermAdminAny) {
  493. return true
  494. }
  495. return util.Contains(a.Permissions, perm)
  496. }
  497. // GetPermissionsAsString returns permission as string
  498. func (a *Admin) GetPermissionsAsString() string {
  499. return strings.Join(a.Permissions, ", ")
  500. }
  501. // GetLastLoginAsString returns the last login as string
  502. func (a *Admin) GetLastLoginAsString() string {
  503. if a.LastLogin > 0 {
  504. return util.GetTimeFromMsecSinceEpoch(a.LastLogin).UTC().Format(iso8601UTCFormat)
  505. }
  506. return ""
  507. }
  508. // GetAllowedIPAsString returns the allowed IP as comma separated string
  509. func (a *Admin) GetAllowedIPAsString() string {
  510. return strings.Join(a.Filters.AllowList, ",")
  511. }
  512. // GetValidPerms returns the allowed admin permissions
  513. func (a *Admin) GetValidPerms() []string {
  514. return validAdminPerms
  515. }
  516. // CanManageMFA returns true if the admin can add a multi-factor authentication configuration
  517. func (a *Admin) CanManageMFA() bool {
  518. return len(mfa.GetAvailableTOTPConfigs()) > 0
  519. }
  520. // GetSignature returns a signature for this admin.
  521. // It will change after an update
  522. func (a *Admin) GetSignature() string {
  523. return strconv.FormatInt(a.UpdatedAt, 10)
  524. }
  525. func (a *Admin) getACopy() Admin {
  526. a.SetEmptySecretsIfNil()
  527. permissions := make([]string, len(a.Permissions))
  528. copy(permissions, a.Permissions)
  529. filters := AdminFilters{}
  530. filters.AllowList = make([]string, len(a.Filters.AllowList))
  531. filters.AllowAPIKeyAuth = a.Filters.AllowAPIKeyAuth
  532. filters.TOTPConfig.Enabled = a.Filters.TOTPConfig.Enabled
  533. filters.TOTPConfig.ConfigName = a.Filters.TOTPConfig.ConfigName
  534. filters.TOTPConfig.Secret = a.Filters.TOTPConfig.Secret.Clone()
  535. copy(filters.AllowList, a.Filters.AllowList)
  536. filters.RecoveryCodes = make([]RecoveryCode, 0)
  537. for _, code := range a.Filters.RecoveryCodes {
  538. if code.Secret == nil {
  539. code.Secret = kms.NewEmptySecret()
  540. }
  541. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  542. Secret: code.Secret.Clone(),
  543. Used: code.Used,
  544. })
  545. }
  546. filters.Preferences = AdminPreferences{
  547. HideUserPageSections: a.Filters.Preferences.HideUserPageSections,
  548. DefaultUsersExpiration: a.Filters.Preferences.DefaultUsersExpiration,
  549. }
  550. groups := make([]AdminGroupMapping, 0, len(a.Groups))
  551. for _, g := range a.Groups {
  552. groups = append(groups, AdminGroupMapping{
  553. Name: g.Name,
  554. Options: AdminGroupMappingOptions{
  555. AddToUsersAs: g.Options.AddToUsersAs,
  556. },
  557. })
  558. }
  559. return Admin{
  560. ID: a.ID,
  561. Status: a.Status,
  562. Username: a.Username,
  563. Password: a.Password,
  564. Email: a.Email,
  565. Permissions: permissions,
  566. Groups: groups,
  567. Filters: filters,
  568. AdditionalInfo: a.AdditionalInfo,
  569. Description: a.Description,
  570. LastLogin: a.LastLogin,
  571. CreatedAt: a.CreatedAt,
  572. UpdatedAt: a.UpdatedAt,
  573. Role: a.Role,
  574. }
  575. }
  576. func (a *Admin) setFromEnv() error {
  577. envUsername := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_USERNAME"))
  578. envPassword := strings.TrimSpace(os.Getenv("SFTPGO_DEFAULT_ADMIN_PASSWORD"))
  579. if envUsername == "" || envPassword == "" {
  580. return errors.New(`to create the default admin you need to set the env vars "SFTPGO_DEFAULT_ADMIN_USERNAME" and "SFTPGO_DEFAULT_ADMIN_PASSWORD"`)
  581. }
  582. a.Username = envUsername
  583. a.Password = envPassword
  584. a.Status = 1
  585. a.Permissions = []string{PermAdminAny}
  586. return nil
  587. }