auth_utils.go 11 KB

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