share.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. "fmt"
  18. "net"
  19. "strings"
  20. "time"
  21. "github.com/alexedwards/argon2id"
  22. passwordvalidator "github.com/wagslane/go-password-validator"
  23. "golang.org/x/crypto/bcrypt"
  24. "github.com/drakkan/sftpgo/v2/internal/logger"
  25. "github.com/drakkan/sftpgo/v2/internal/util"
  26. )
  27. // ShareScope defines the supported share scopes
  28. type ShareScope int
  29. // Supported share scopes
  30. const (
  31. ShareScopeRead ShareScope = iota + 1
  32. ShareScopeWrite
  33. ShareScopeReadWrite
  34. )
  35. const (
  36. redactedPassword = "[**redacted**]"
  37. )
  38. // Share defines files and or directories shared with external users
  39. type Share struct {
  40. // Database unique identifier
  41. ID int64 `json:"-"`
  42. // Unique ID used to access this object
  43. ShareID string `json:"id"`
  44. Name string `json:"name"`
  45. Description string `json:"description,omitempty"`
  46. Scope ShareScope `json:"scope"`
  47. // Paths to files or directories, for ShareScopeWrite it must be exactly one directory
  48. Paths []string `json:"paths"`
  49. // Username who shared this object
  50. Username string `json:"username"`
  51. CreatedAt int64 `json:"created_at"`
  52. UpdatedAt int64 `json:"updated_at"`
  53. // 0 means never used
  54. LastUseAt int64 `json:"last_use_at,omitempty"`
  55. // ExpiresAt expiration date/time as unix timestamp in milliseconds, 0 means no expiration
  56. ExpiresAt int64 `json:"expires_at,omitempty"`
  57. // Optional password to protect the share
  58. Password string `json:"password"`
  59. // Limit the available access tokens, 0 means no limit
  60. MaxTokens int `json:"max_tokens,omitempty"`
  61. // Used tokens
  62. UsedTokens int `json:"used_tokens,omitempty"`
  63. // Limit the share availability to these IPs/CIDR networks
  64. AllowFrom []string `json:"allow_from,omitempty"`
  65. // set for restores, we don't have to validate the expiration date
  66. // otherwise we fail to restore existing shares and we have to insert
  67. // all the previous values with no modifications
  68. IsRestore bool `json:"-"`
  69. }
  70. // IsExpired returns true if the share is expired
  71. func (s *Share) IsExpired() bool {
  72. if s.ExpiresAt > 0 {
  73. return s.ExpiresAt < util.GetTimeAsMsSinceEpoch(time.Now())
  74. }
  75. return false
  76. }
  77. // GetAllowedFromAsString returns the allowed IP as comma separated string
  78. func (s *Share) GetAllowedFromAsString() string {
  79. return strings.Join(s.AllowFrom, ",")
  80. }
  81. func (s *Share) getACopy() Share {
  82. allowFrom := make([]string, len(s.AllowFrom))
  83. copy(allowFrom, s.AllowFrom)
  84. return Share{
  85. ID: s.ID,
  86. ShareID: s.ShareID,
  87. Name: s.Name,
  88. Description: s.Description,
  89. Scope: s.Scope,
  90. Paths: s.Paths,
  91. Username: s.Username,
  92. CreatedAt: s.CreatedAt,
  93. UpdatedAt: s.UpdatedAt,
  94. LastUseAt: s.LastUseAt,
  95. ExpiresAt: s.ExpiresAt,
  96. Password: s.Password,
  97. MaxTokens: s.MaxTokens,
  98. UsedTokens: s.UsedTokens,
  99. AllowFrom: allowFrom,
  100. }
  101. }
  102. // RenderAsJSON implements the renderer interface used within plugins
  103. func (s *Share) RenderAsJSON(reload bool) ([]byte, error) {
  104. if reload {
  105. share, err := provider.shareExists(s.ShareID, s.Username)
  106. if err != nil {
  107. providerLog(logger.LevelError, "unable to reload share before rendering as json: %v", err)
  108. return nil, err
  109. }
  110. share.HideConfidentialData()
  111. return json.Marshal(share)
  112. }
  113. s.HideConfidentialData()
  114. return json.Marshal(s)
  115. }
  116. // HideConfidentialData hides share confidential data
  117. func (s *Share) HideConfidentialData() {
  118. if s.Password != "" {
  119. s.Password = redactedPassword
  120. }
  121. }
  122. // HasRedactedPassword returns true if this share has a redacted password
  123. func (s *Share) HasRedactedPassword() bool {
  124. return s.Password == redactedPassword
  125. }
  126. func (s *Share) hashPassword() error {
  127. if s.Password != "" && !util.IsStringPrefixInSlice(s.Password, internalHashPwdPrefixes) {
  128. user, err := UserExists(s.Username, "")
  129. if err != nil {
  130. return util.NewGenericError(fmt.Sprintf("unable to validate user: %v", err))
  131. }
  132. if minEntropy := user.getMinPasswordEntropy(); minEntropy > 0 {
  133. if err := passwordvalidator.Validate(s.Password, minEntropy); err != nil {
  134. return util.NewI18nError(util.NewValidationError(err.Error()), util.I18nErrorPasswordComplexity)
  135. }
  136. }
  137. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  138. hashed, err := bcrypt.GenerateFromPassword([]byte(s.Password), config.PasswordHashing.BcryptOptions.Cost)
  139. if err != nil {
  140. return err
  141. }
  142. s.Password = util.BytesToString(hashed)
  143. } else {
  144. hashed, err := argon2id.CreateHash(s.Password, argon2Params)
  145. if err != nil {
  146. return err
  147. }
  148. s.Password = hashed
  149. }
  150. }
  151. return nil
  152. }
  153. func (s *Share) validatePaths() error {
  154. var paths []string
  155. for _, p := range s.Paths {
  156. if strings.TrimSpace(p) != "" {
  157. paths = append(paths, p)
  158. }
  159. }
  160. s.Paths = paths
  161. if len(s.Paths) == 0 {
  162. return util.NewI18nError(util.NewValidationError("at least a shared path is required"), util.I18nErrorSharePathRequired)
  163. }
  164. for idx := range s.Paths {
  165. s.Paths[idx] = util.CleanPath(s.Paths[idx])
  166. }
  167. s.Paths = util.RemoveDuplicates(s.Paths, false)
  168. if s.Scope >= ShareScopeWrite && len(s.Paths) != 1 {
  169. return util.NewI18nError(util.NewValidationError("the write share scope requires exactly one path"), util.I18nErrorShareWriteScope)
  170. }
  171. // check nested paths
  172. if len(s.Paths) > 1 {
  173. for idx := range s.Paths {
  174. for innerIdx := range s.Paths {
  175. if idx == innerIdx {
  176. continue
  177. }
  178. if s.Paths[idx] == "/" || s.Paths[innerIdx] == "/" || util.IsDirOverlapped(s.Paths[idx], s.Paths[innerIdx], true, "/") {
  179. return util.NewI18nError(util.NewGenericError("shared paths cannot be nested"), util.I18nErrorShareNestedPaths)
  180. }
  181. }
  182. }
  183. }
  184. return nil
  185. }
  186. func (s *Share) validate() error {
  187. if s.ShareID == "" {
  188. return util.NewValidationError("share_id is mandatory")
  189. }
  190. if s.Name == "" {
  191. return util.NewI18nError(util.NewValidationError("name is mandatory"), util.I18nErrorNameRequired)
  192. }
  193. if s.Scope < ShareScopeRead || s.Scope > ShareScopeReadWrite {
  194. return util.NewI18nError(util.NewValidationError(fmt.Sprintf("invalid scope: %v", s.Scope)), util.I18nErrorShareScope)
  195. }
  196. if err := s.validatePaths(); err != nil {
  197. return err
  198. }
  199. if s.ExpiresAt > 0 {
  200. if !s.IsRestore && s.ExpiresAt < util.GetTimeAsMsSinceEpoch(time.Now()) {
  201. return util.NewI18nError(util.NewValidationError("expiration must be in the future"), util.I18nErrorShareExpirationPast)
  202. }
  203. } else {
  204. s.ExpiresAt = 0
  205. }
  206. if s.MaxTokens < 0 {
  207. return util.NewI18nError(util.NewValidationError("invalid max tokens"), util.I18nErrorShareMaxTokens)
  208. }
  209. if s.Username == "" {
  210. return util.NewI18nError(util.NewValidationError("username is mandatory"), util.I18nErrorUsernameRequired)
  211. }
  212. if s.HasRedactedPassword() {
  213. return util.NewValidationError("cannot save a share with a redacted password")
  214. }
  215. if err := s.hashPassword(); err != nil {
  216. return err
  217. }
  218. s.AllowFrom = util.RemoveDuplicates(s.AllowFrom, false)
  219. for _, IPMask := range s.AllowFrom {
  220. _, _, err := net.ParseCIDR(IPMask)
  221. if err != nil {
  222. return util.NewI18nError(
  223. util.NewValidationError(fmt.Sprintf("could not parse allow from entry %q : %v", IPMask, err)),
  224. util.I18nErrorInvalidIPMask,
  225. )
  226. }
  227. }
  228. return nil
  229. }
  230. // CheckCredentials verifies the share credentials if a password if set
  231. func (s *Share) CheckCredentials(password string) (bool, error) {
  232. if s.Password == "" {
  233. return true, nil
  234. }
  235. if password == "" {
  236. return false, ErrInvalidCredentials
  237. }
  238. if strings.HasPrefix(s.Password, bcryptPwdPrefix) {
  239. if err := bcrypt.CompareHashAndPassword([]byte(s.Password), []byte(password)); err != nil {
  240. return false, ErrInvalidCredentials
  241. }
  242. return true, nil
  243. }
  244. match, err := argon2id.ComparePasswordAndHash(password, s.Password)
  245. if !match || err != nil {
  246. return false, ErrInvalidCredentials
  247. }
  248. return match, err
  249. }
  250. // GetRelativePath returns the specified absolute path as relative to the share base path
  251. func (s *Share) GetRelativePath(name string) string {
  252. if len(s.Paths) == 0 {
  253. return ""
  254. }
  255. return util.CleanPath(strings.TrimPrefix(name, s.Paths[0]))
  256. }
  257. // IsUsable checks if the share is usable from the specified IP
  258. func (s *Share) IsUsable(ip string) (bool, error) {
  259. if s.MaxTokens > 0 && s.UsedTokens >= s.MaxTokens {
  260. return false, util.NewI18nError(util.NewRecordNotFoundError("max share usage exceeded"), util.I18nErrorShareUsage)
  261. }
  262. if s.ExpiresAt > 0 {
  263. if s.ExpiresAt < util.GetTimeAsMsSinceEpoch(time.Now()) {
  264. return false, util.NewI18nError(util.NewRecordNotFoundError("share expired"), util.I18nErrorShareExpired)
  265. }
  266. }
  267. if len(s.AllowFrom) == 0 {
  268. return true, nil
  269. }
  270. parsedIP := net.ParseIP(ip)
  271. if parsedIP == nil {
  272. return false, util.NewI18nError(ErrLoginNotAllowedFromIP, util.I18nErrorLoginFromIPDenied)
  273. }
  274. for _, ipMask := range s.AllowFrom {
  275. _, network, err := net.ParseCIDR(ipMask)
  276. if err != nil {
  277. continue
  278. }
  279. if network.Contains(parsedIP) {
  280. return true, nil
  281. }
  282. }
  283. return false, util.NewI18nError(ErrLoginNotAllowedFromIP, util.I18nErrorLoginFromIPDenied)
  284. }