auth_utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 httpd
  15. import (
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "time"
  20. "github.com/go-chi/jwtauth/v5"
  21. "github.com/lestrrat-go/jwx/v2/jwt"
  22. "github.com/rs/xid"
  23. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  24. "github.com/drakkan/sftpgo/v2/internal/logger"
  25. "github.com/drakkan/sftpgo/v2/internal/util"
  26. )
  27. type tokenAudience = string
  28. const (
  29. tokenAudienceWebAdmin tokenAudience = "WebAdmin"
  30. tokenAudienceWebClient tokenAudience = "WebClient"
  31. tokenAudienceWebShare tokenAudience = "WebShare"
  32. tokenAudienceWebAdminPartial tokenAudience = "WebAdminPartial"
  33. tokenAudienceWebClientPartial tokenAudience = "WebClientPartial"
  34. tokenAudienceAPI tokenAudience = "API"
  35. tokenAudienceAPIUser tokenAudience = "APIUser"
  36. tokenAudienceCSRF tokenAudience = "CSRF"
  37. )
  38. type tokenValidation = int
  39. const (
  40. tokenValidationFull = iota
  41. tokenValidationNoIPMatch tokenValidation = iota
  42. )
  43. const (
  44. claimUsernameKey = "username"
  45. claimPermissionsKey = "permissions"
  46. claimRole = "role"
  47. claimAPIKey = "api_key"
  48. claimNodeID = "node_id"
  49. claimMustChangePasswordKey = "chpwd"
  50. claimMustSetSecondFactorKey = "2fa_required"
  51. claimRequiredTwoFactorProtocols = "2fa_protos"
  52. claimHideUserPageSection = "hus"
  53. basicRealm = "Basic realm=\"SFTPGo\""
  54. jwtCookieKey = "jwt"
  55. )
  56. var (
  57. tokenDuration = 20 * time.Minute
  58. shareTokenDuration = 12 * time.Hour
  59. // csrf token duration is greater than normal token duration to reduce issues
  60. // with the login form
  61. csrfTokenDuration = 6 * time.Hour
  62. tokenRefreshThreshold = 10 * time.Minute
  63. tokenValidationMode = tokenValidationFull
  64. )
  65. type jwtTokenClaims struct {
  66. Username string
  67. Permissions []string
  68. Role string
  69. Signature string
  70. Audience []string
  71. APIKeyID string
  72. NodeID string
  73. MustSetTwoFactorAuth bool
  74. MustChangePassword bool
  75. RequiredTwoFactorProtocols []string
  76. HideUserPageSections int
  77. }
  78. func (c *jwtTokenClaims) hasUserAudience() bool {
  79. for _, audience := range c.Audience {
  80. if audience == tokenAudienceWebClient || audience == tokenAudienceAPIUser {
  81. return true
  82. }
  83. }
  84. return false
  85. }
  86. func (c *jwtTokenClaims) asMap() map[string]any {
  87. claims := make(map[string]any)
  88. claims[claimUsernameKey] = c.Username
  89. claims[claimPermissionsKey] = c.Permissions
  90. if c.Role != "" {
  91. claims[claimRole] = c.Role
  92. }
  93. if c.APIKeyID != "" {
  94. claims[claimAPIKey] = c.APIKeyID
  95. }
  96. if c.NodeID != "" {
  97. claims[claimNodeID] = c.NodeID
  98. }
  99. claims[jwt.SubjectKey] = c.Signature
  100. if c.MustChangePassword {
  101. claims[claimMustChangePasswordKey] = c.MustChangePassword
  102. }
  103. if c.MustSetTwoFactorAuth {
  104. claims[claimMustSetSecondFactorKey] = c.MustSetTwoFactorAuth
  105. }
  106. if len(c.RequiredTwoFactorProtocols) > 0 {
  107. claims[claimRequiredTwoFactorProtocols] = c.RequiredTwoFactorProtocols
  108. }
  109. if c.HideUserPageSections > 0 {
  110. claims[claimHideUserPageSection] = c.HideUserPageSections
  111. }
  112. return claims
  113. }
  114. func (c *jwtTokenClaims) decodeSliceString(val any) []string {
  115. switch v := val.(type) {
  116. case []any:
  117. result := make([]string, 0, len(v))
  118. for _, elem := range v {
  119. switch elemValue := elem.(type) {
  120. case string:
  121. result = append(result, elemValue)
  122. }
  123. }
  124. return result
  125. case []string:
  126. return v
  127. default:
  128. return nil
  129. }
  130. }
  131. func (c *jwtTokenClaims) decodeBoolean(val any) bool {
  132. switch v := val.(type) {
  133. case bool:
  134. return v
  135. default:
  136. return false
  137. }
  138. }
  139. func (c *jwtTokenClaims) decodeString(val any) string {
  140. switch v := val.(type) {
  141. case string:
  142. return v
  143. default:
  144. return ""
  145. }
  146. }
  147. func (c *jwtTokenClaims) Decode(token map[string]any) {
  148. c.Permissions = nil
  149. c.Username = c.decodeString(token[claimUsernameKey])
  150. c.Signature = c.decodeString(token[jwt.SubjectKey])
  151. audience := token[jwt.AudienceKey]
  152. switch v := audience.(type) {
  153. case []string:
  154. c.Audience = v
  155. }
  156. if val, ok := token[claimAPIKey]; ok {
  157. c.APIKeyID = c.decodeString(val)
  158. }
  159. if val, ok := token[claimNodeID]; ok {
  160. c.NodeID = c.decodeString(val)
  161. }
  162. if val, ok := token[claimRole]; ok {
  163. c.Role = c.decodeString(val)
  164. }
  165. permissions := token[claimPermissionsKey]
  166. c.Permissions = c.decodeSliceString(permissions)
  167. if val, ok := token[claimMustChangePasswordKey]; ok {
  168. c.MustChangePassword = c.decodeBoolean(val)
  169. }
  170. if val, ok := token[claimMustSetSecondFactorKey]; ok {
  171. c.MustSetTwoFactorAuth = c.decodeBoolean(val)
  172. }
  173. if val, ok := token[claimRequiredTwoFactorProtocols]; ok {
  174. c.RequiredTwoFactorProtocols = c.decodeSliceString(val)
  175. }
  176. if val, ok := token[claimHideUserPageSection]; ok {
  177. switch v := val.(type) {
  178. case float64:
  179. c.HideUserPageSections = int(v)
  180. }
  181. }
  182. }
  183. func (c *jwtTokenClaims) isCriticalPermRemoved(permissions []string) bool {
  184. if util.Contains(permissions, dataprovider.PermAdminAny) {
  185. return false
  186. }
  187. if (util.Contains(c.Permissions, dataprovider.PermAdminManageAdmins) ||
  188. util.Contains(c.Permissions, dataprovider.PermAdminAny)) &&
  189. !util.Contains(permissions, dataprovider.PermAdminManageAdmins) &&
  190. !util.Contains(permissions, dataprovider.PermAdminAny) {
  191. return true
  192. }
  193. return false
  194. }
  195. func (c *jwtTokenClaims) hasPerm(perm string) bool {
  196. if util.Contains(c.Permissions, dataprovider.PermAdminAny) {
  197. return true
  198. }
  199. return util.Contains(c.Permissions, perm)
  200. }
  201. func (c *jwtTokenClaims) createToken(tokenAuth *jwtauth.JWTAuth, audience tokenAudience, ip string) (jwt.Token, string, error) {
  202. claims := c.asMap()
  203. now := time.Now().UTC()
  204. claims[jwt.JwtIDKey] = xid.New().String()
  205. claims[jwt.NotBeforeKey] = now.Add(-30 * time.Second)
  206. claims[jwt.ExpirationKey] = now.Add(tokenDuration)
  207. claims[jwt.AudienceKey] = []string{audience, ip}
  208. return tokenAuth.Encode(claims)
  209. }
  210. func (c *jwtTokenClaims) createTokenResponse(tokenAuth *jwtauth.JWTAuth, audience tokenAudience, ip string) (map[string]any, error) {
  211. token, tokenString, err := c.createToken(tokenAuth, audience, ip)
  212. if err != nil {
  213. return nil, err
  214. }
  215. response := make(map[string]any)
  216. response["access_token"] = tokenString
  217. response["expires_at"] = token.Expiration().Format(time.RFC3339)
  218. return response, nil
  219. }
  220. func (c *jwtTokenClaims) createAndSetCookie(w http.ResponseWriter, r *http.Request, tokenAuth *jwtauth.JWTAuth,
  221. audience tokenAudience, ip string,
  222. ) error {
  223. resp, err := c.createTokenResponse(tokenAuth, audience, ip)
  224. if err != nil {
  225. return err
  226. }
  227. var basePath string
  228. if audience == tokenAudienceWebAdmin || audience == tokenAudienceWebAdminPartial {
  229. basePath = webBaseAdminPath
  230. } else {
  231. basePath = webBaseClientPath
  232. }
  233. duration := tokenDuration
  234. if audience == tokenAudienceWebShare {
  235. duration = shareTokenDuration
  236. }
  237. http.SetCookie(w, &http.Cookie{
  238. Name: jwtCookieKey,
  239. Value: resp["access_token"].(string),
  240. Path: basePath,
  241. Expires: time.Now().Add(duration),
  242. MaxAge: int(duration / time.Second),
  243. HttpOnly: true,
  244. Secure: isTLS(r),
  245. SameSite: http.SameSiteStrictMode,
  246. })
  247. return nil
  248. }
  249. func (c *jwtTokenClaims) removeCookie(w http.ResponseWriter, r *http.Request, cookiePath string) {
  250. http.SetCookie(w, &http.Cookie{
  251. Name: jwtCookieKey,
  252. Value: "",
  253. Path: cookiePath,
  254. Expires: time.Unix(0, 0),
  255. MaxAge: -1,
  256. HttpOnly: true,
  257. Secure: isTLS(r),
  258. SameSite: http.SameSiteStrictMode,
  259. })
  260. invalidateToken(r)
  261. }
  262. func tokenFromContext(r *http.Request) string {
  263. if token, ok := r.Context().Value(oidcGeneratedToken).(string); ok {
  264. return token
  265. }
  266. return ""
  267. }
  268. func isTLS(r *http.Request) bool {
  269. if r.TLS != nil {
  270. return true
  271. }
  272. if proto, ok := r.Context().Value(forwardedProtoKey).(string); ok {
  273. return proto == "https"
  274. }
  275. return false
  276. }
  277. func isTokenInvalidated(r *http.Request) bool {
  278. var findTokenFns []func(r *http.Request) string
  279. findTokenFns = append(findTokenFns, jwtauth.TokenFromHeader)
  280. findTokenFns = append(findTokenFns, jwtauth.TokenFromCookie)
  281. findTokenFns = append(findTokenFns, tokenFromContext)
  282. isTokenFound := false
  283. for _, fn := range findTokenFns {
  284. token := fn(r)
  285. if token != "" {
  286. isTokenFound = true
  287. if _, ok := invalidatedJWTTokens.Load(token); ok {
  288. return true
  289. }
  290. }
  291. }
  292. return !isTokenFound
  293. }
  294. func invalidateToken(r *http.Request) {
  295. tokenString := jwtauth.TokenFromHeader(r)
  296. if tokenString != "" {
  297. invalidatedJWTTokens.Store(tokenString, time.Now().Add(tokenDuration).UTC())
  298. }
  299. tokenString = jwtauth.TokenFromCookie(r)
  300. if tokenString != "" {
  301. invalidatedJWTTokens.Store(tokenString, time.Now().Add(tokenDuration).UTC())
  302. }
  303. }
  304. func getUserFromToken(r *http.Request) *dataprovider.User {
  305. user := &dataprovider.User{}
  306. _, claims, err := jwtauth.FromContext(r.Context())
  307. if err != nil {
  308. return user
  309. }
  310. tokenClaims := jwtTokenClaims{}
  311. tokenClaims.Decode(claims)
  312. user.Username = tokenClaims.Username
  313. user.Filters.WebClient = tokenClaims.Permissions
  314. user.Role = tokenClaims.Role
  315. return user
  316. }
  317. func getAdminFromToken(r *http.Request) *dataprovider.Admin {
  318. admin := &dataprovider.Admin{}
  319. _, claims, err := jwtauth.FromContext(r.Context())
  320. if err != nil {
  321. return admin
  322. }
  323. tokenClaims := jwtTokenClaims{}
  324. tokenClaims.Decode(claims)
  325. admin.Username = tokenClaims.Username
  326. admin.Permissions = tokenClaims.Permissions
  327. admin.Filters.Preferences.HideUserPageSections = tokenClaims.HideUserPageSections
  328. admin.Role = tokenClaims.Role
  329. return admin
  330. }
  331. func createCSRFToken(ip string) string {
  332. claims := make(map[string]any)
  333. now := time.Now().UTC()
  334. claims[jwt.JwtIDKey] = xid.New().String()
  335. claims[jwt.NotBeforeKey] = now.Add(-30 * time.Second)
  336. claims[jwt.ExpirationKey] = now.Add(csrfTokenDuration)
  337. claims[jwt.AudienceKey] = []string{tokenAudienceCSRF, ip}
  338. _, tokenString, err := csrfTokenAuth.Encode(claims)
  339. if err != nil {
  340. logger.Debug(logSender, "", "unable to create CSRF token: %v", err)
  341. return ""
  342. }
  343. return tokenString
  344. }
  345. func verifyCSRFToken(tokenString, ip string) error {
  346. token, err := jwtauth.VerifyToken(csrfTokenAuth, tokenString)
  347. if err != nil || token == nil {
  348. logger.Debug(logSender, "", "error validating CSRF token %q: %v", tokenString, err)
  349. return fmt.Errorf("unable to verify form token: %v", err)
  350. }
  351. if !util.Contains(token.Audience(), tokenAudienceCSRF) {
  352. logger.Debug(logSender, "", "error validating CSRF token audience")
  353. return errors.New("the form token is not valid")
  354. }
  355. if tokenValidationMode != tokenValidationNoIPMatch {
  356. if !util.Contains(token.Audience(), ip) {
  357. logger.Debug(logSender, "", "error validating CSRF token IP audience")
  358. return errors.New("the form token is not valid")
  359. }
  360. }
  361. return nil
  362. }