share.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. "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. // GetScopeAsString returns the share's scope as string.
  71. // Used in web pages
  72. func (s *Share) GetScopeAsString() string {
  73. switch s.Scope {
  74. case ShareScopeWrite:
  75. return "Write"
  76. case ShareScopeReadWrite:
  77. return "Read/Write"
  78. default:
  79. return "Read"
  80. }
  81. }
  82. // IsExpired returns true if the share is expired
  83. func (s *Share) IsExpired() bool {
  84. if s.ExpiresAt > 0 {
  85. return s.ExpiresAt < util.GetTimeAsMsSinceEpoch(time.Now())
  86. }
  87. return false
  88. }
  89. // GetInfoString returns share's info as string.
  90. func (s *Share) GetInfoString() string {
  91. var result strings.Builder
  92. if s.ExpiresAt > 0 {
  93. t := util.GetTimeFromMsecSinceEpoch(s.ExpiresAt)
  94. result.WriteString(fmt.Sprintf("Expiration: %v. ", t.Format("2006-01-02 15:04"))) // YYYY-MM-DD HH:MM
  95. }
  96. if s.LastUseAt > 0 {
  97. t := util.GetTimeFromMsecSinceEpoch(s.LastUseAt)
  98. result.WriteString(fmt.Sprintf("Last use: %v. ", t.Format("2006-01-02 15:04")))
  99. }
  100. if s.MaxTokens > 0 {
  101. result.WriteString(fmt.Sprintf("Usage: %v/%v. ", s.UsedTokens, s.MaxTokens))
  102. } else {
  103. result.WriteString(fmt.Sprintf("Used tokens: %v. ", s.UsedTokens))
  104. }
  105. if len(s.AllowFrom) > 0 {
  106. result.WriteString(fmt.Sprintf("Allowed IP/Mask: %v. ", len(s.AllowFrom)))
  107. }
  108. if s.Password != "" {
  109. result.WriteString("Password protected.")
  110. }
  111. return result.String()
  112. }
  113. // GetAllowedFromAsString returns the allowed IP as comma separated string
  114. func (s *Share) GetAllowedFromAsString() string {
  115. return strings.Join(s.AllowFrom, ",")
  116. }
  117. func (s *Share) getACopy() Share {
  118. allowFrom := make([]string, len(s.AllowFrom))
  119. copy(allowFrom, s.AllowFrom)
  120. return Share{
  121. ID: s.ID,
  122. ShareID: s.ShareID,
  123. Name: s.Name,
  124. Description: s.Description,
  125. Scope: s.Scope,
  126. Paths: s.Paths,
  127. Username: s.Username,
  128. CreatedAt: s.CreatedAt,
  129. UpdatedAt: s.UpdatedAt,
  130. LastUseAt: s.LastUseAt,
  131. ExpiresAt: s.ExpiresAt,
  132. Password: s.Password,
  133. MaxTokens: s.MaxTokens,
  134. UsedTokens: s.UsedTokens,
  135. AllowFrom: allowFrom,
  136. }
  137. }
  138. // RenderAsJSON implements the renderer interface used within plugins
  139. func (s *Share) RenderAsJSON(reload bool) ([]byte, error) {
  140. if reload {
  141. share, err := provider.shareExists(s.ShareID, s.Username)
  142. if err != nil {
  143. providerLog(logger.LevelError, "unable to reload share before rendering as json: %v", err)
  144. return nil, err
  145. }
  146. share.HideConfidentialData()
  147. return json.Marshal(share)
  148. }
  149. s.HideConfidentialData()
  150. return json.Marshal(s)
  151. }
  152. // HideConfidentialData hides share confidential data
  153. func (s *Share) HideConfidentialData() {
  154. if s.Password != "" {
  155. s.Password = redactedPassword
  156. }
  157. }
  158. // HasRedactedPassword returns true if this share has a redacted password
  159. func (s *Share) HasRedactedPassword() bool {
  160. return s.Password == redactedPassword
  161. }
  162. func (s *Share) hashPassword() error {
  163. if s.Password != "" && !util.IsStringPrefixInSlice(s.Password, internalHashPwdPrefixes) {
  164. user, err := UserExists(s.Username, "")
  165. if err != nil {
  166. return util.NewGenericError(fmt.Sprintf("unable to validate user: %v", err))
  167. }
  168. if minEntropy := user.getMinPasswordEntropy(); minEntropy > 0 {
  169. if err := passwordvalidator.Validate(s.Password, minEntropy); err != nil {
  170. return util.NewValidationError(err.Error())
  171. }
  172. }
  173. if config.PasswordHashing.Algo == HashingAlgoBcrypt {
  174. hashed, err := bcrypt.GenerateFromPassword([]byte(s.Password), config.PasswordHashing.BcryptOptions.Cost)
  175. if err != nil {
  176. return err
  177. }
  178. s.Password = string(hashed)
  179. } else {
  180. hashed, err := argon2id.CreateHash(s.Password, argon2Params)
  181. if err != nil {
  182. return err
  183. }
  184. s.Password = hashed
  185. }
  186. }
  187. return nil
  188. }
  189. func (s *Share) validatePaths() error {
  190. var paths []string
  191. for _, p := range s.Paths {
  192. if strings.TrimSpace(p) != "" {
  193. paths = append(paths, p)
  194. }
  195. }
  196. s.Paths = paths
  197. if len(s.Paths) == 0 {
  198. return util.NewValidationError("at least a shared path is required")
  199. }
  200. for idx := range s.Paths {
  201. s.Paths[idx] = util.CleanPath(s.Paths[idx])
  202. }
  203. s.Paths = util.RemoveDuplicates(s.Paths, false)
  204. if s.Scope >= ShareScopeWrite && len(s.Paths) != 1 {
  205. return util.NewValidationError("the write share scope requires exactly one path")
  206. }
  207. // check nested paths
  208. if len(s.Paths) > 1 {
  209. for idx := range s.Paths {
  210. for innerIdx := range s.Paths {
  211. if idx == innerIdx {
  212. continue
  213. }
  214. if util.IsDirOverlapped(s.Paths[idx], s.Paths[innerIdx], true, "/") {
  215. return util.NewGenericError("shared paths cannot be nested")
  216. }
  217. }
  218. }
  219. }
  220. return nil
  221. }
  222. func (s *Share) validate() error {
  223. if s.ShareID == "" {
  224. return util.NewValidationError("share_id is mandatory")
  225. }
  226. if s.Name == "" {
  227. return util.NewValidationError("name is mandatory")
  228. }
  229. if s.Scope < ShareScopeRead || s.Scope > ShareScopeReadWrite {
  230. return util.NewValidationError(fmt.Sprintf("invalid scope: %v", s.Scope))
  231. }
  232. if err := s.validatePaths(); err != nil {
  233. return err
  234. }
  235. if s.ExpiresAt > 0 {
  236. if !s.IsRestore && s.ExpiresAt < util.GetTimeAsMsSinceEpoch(time.Now()) {
  237. return util.NewValidationError("expiration must be in the future")
  238. }
  239. } else {
  240. s.ExpiresAt = 0
  241. }
  242. if s.MaxTokens < 0 {
  243. return util.NewValidationError("invalid max tokens")
  244. }
  245. if s.Username == "" {
  246. return util.NewValidationError("username is mandatory")
  247. }
  248. if s.HasRedactedPassword() {
  249. return util.NewValidationError("cannot save a share with a redacted password")
  250. }
  251. if err := s.hashPassword(); err != nil {
  252. return err
  253. }
  254. s.AllowFrom = util.RemoveDuplicates(s.AllowFrom, false)
  255. for _, IPMask := range s.AllowFrom {
  256. _, _, err := net.ParseCIDR(IPMask)
  257. if err != nil {
  258. return util.NewValidationError(fmt.Sprintf("could not parse allow from entry %q : %v", IPMask, err))
  259. }
  260. }
  261. return nil
  262. }
  263. // CheckCredentials verifies the share credentials if a password if set
  264. func (s *Share) CheckCredentials(password string) (bool, error) {
  265. if s.Password == "" {
  266. return true, nil
  267. }
  268. if password == "" {
  269. return false, ErrInvalidCredentials
  270. }
  271. if strings.HasPrefix(s.Password, bcryptPwdPrefix) {
  272. if err := bcrypt.CompareHashAndPassword([]byte(s.Password), []byte(password)); err != nil {
  273. return false, ErrInvalidCredentials
  274. }
  275. return true, nil
  276. }
  277. match, err := argon2id.ComparePasswordAndHash(password, s.Password)
  278. if !match || err != nil {
  279. return false, ErrInvalidCredentials
  280. }
  281. return match, err
  282. }
  283. // GetRelativePath returns the specified absolute path as relative to the share base path
  284. func (s *Share) GetRelativePath(name string) string {
  285. if len(s.Paths) == 0 {
  286. return ""
  287. }
  288. return util.CleanPath(strings.TrimPrefix(name, s.Paths[0]))
  289. }
  290. // IsUsable checks if the share is usable from the specified IP
  291. func (s *Share) IsUsable(ip string) (bool, error) {
  292. if s.MaxTokens > 0 && s.UsedTokens >= s.MaxTokens {
  293. return false, util.NewRecordNotFoundError("max share usage exceeded")
  294. }
  295. if s.ExpiresAt > 0 {
  296. if s.ExpiresAt < util.GetTimeAsMsSinceEpoch(time.Now()) {
  297. return false, util.NewRecordNotFoundError("share expired")
  298. }
  299. }
  300. if len(s.AllowFrom) == 0 {
  301. return true, nil
  302. }
  303. parsedIP := net.ParseIP(ip)
  304. if parsedIP == nil {
  305. return false, ErrLoginNotAllowedFromIP
  306. }
  307. for _, ipMask := range s.AllowFrom {
  308. _, network, err := net.ParseCIDR(ipMask)
  309. if err != nil {
  310. continue
  311. }
  312. if network.Contains(parsedIP) {
  313. return true, nil
  314. }
  315. }
  316. return false, ErrLoginNotAllowedFromIP
  317. }