auth_credentials.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. package s3api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "strings"
  7. "sync"
  8. "github.com/seaweedfs/seaweedfs/weed/filer"
  9. "github.com/seaweedfs/seaweedfs/weed/glog"
  10. "github.com/seaweedfs/seaweedfs/weed/pb"
  11. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
  13. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  14. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  15. )
  16. type Action string
  17. type Iam interface {
  18. Check(f http.HandlerFunc, actions ...Action) http.HandlerFunc
  19. }
  20. type IdentityAccessManagement struct {
  21. m sync.RWMutex
  22. identities []*Identity
  23. accessKeyIdent map[string]*Identity
  24. accounts map[string]*Account
  25. emailAccount map[string]*Account
  26. hashes map[string]*sync.Pool
  27. hashCounters map[string]*int32
  28. identityAnonymous *Identity
  29. hashMu sync.RWMutex
  30. domain string
  31. isAuthEnabled bool
  32. }
  33. type Identity struct {
  34. Name string
  35. Account *Account
  36. Credentials []*Credential
  37. Actions []Action
  38. }
  39. // Account represents a system user, a system user can
  40. // configure multiple IAM-Users, IAM-Users can configure
  41. // permissions respectively, and each IAM-User can
  42. // configure multiple security credentials
  43. type Account struct {
  44. //Name is also used to display the "DisplayName" as the owner of the bucket or object
  45. DisplayName string
  46. EmailAddress string
  47. //Id is used to identify an Account when granting cross-account access(ACLs) to buckets and objects
  48. Id string
  49. }
  50. // Predefined Accounts
  51. var (
  52. // AccountAdmin is used as the default account for IAM-Credentials access without Account configured
  53. AccountAdmin = Account{
  54. DisplayName: "admin",
  55. EmailAddress: "admin@example.com",
  56. Id: s3_constants.AccountAdminId,
  57. }
  58. // AccountAnonymous is used to represent the account for anonymous access
  59. AccountAnonymous = Account{
  60. DisplayName: "anonymous",
  61. EmailAddress: "anonymous@example.com",
  62. Id: s3_constants.AccountAnonymousId,
  63. }
  64. )
  65. type Credential struct {
  66. AccessKey string
  67. SecretKey string
  68. }
  69. func (i *Identity) isAnonymous() bool {
  70. return i.Account.Id == s3_constants.AccountAnonymousId
  71. }
  72. func (action Action) isAdmin() bool {
  73. return strings.HasPrefix(string(action), s3_constants.ACTION_ADMIN)
  74. }
  75. func (action Action) isOwner(bucket string) bool {
  76. return string(action) == s3_constants.ACTION_ADMIN+":"+bucket
  77. }
  78. func (action Action) overBucket(bucket string) bool {
  79. return strings.HasSuffix(string(action), ":"+bucket) || strings.HasSuffix(string(action), ":*")
  80. }
  81. // "Permission": "FULL_CONTROL"|"WRITE"|"WRITE_ACP"|"READ"|"READ_ACP"
  82. func (action Action) getPermission() Permission {
  83. switch act := strings.Split(string(action), ":")[0]; act {
  84. case s3_constants.ACTION_ADMIN:
  85. return Permission("FULL_CONTROL")
  86. case s3_constants.ACTION_WRITE:
  87. return Permission("WRITE")
  88. case s3_constants.ACTION_WRITE_ACP:
  89. return Permission("WRITE_ACP")
  90. case s3_constants.ACTION_READ:
  91. return Permission("READ")
  92. case s3_constants.ACTION_READ_ACP:
  93. return Permission("READ_ACP")
  94. default:
  95. return Permission("")
  96. }
  97. }
  98. func NewIdentityAccessManagement(option *S3ApiServerOption) *IdentityAccessManagement {
  99. iam := &IdentityAccessManagement{
  100. domain: option.DomainName,
  101. hashes: make(map[string]*sync.Pool),
  102. hashCounters: make(map[string]*int32),
  103. }
  104. if option.Config != "" {
  105. if err := iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {
  106. glog.Fatalf("fail to load config file %s: %v", option.Config, err)
  107. }
  108. } else {
  109. if err := iam.loadS3ApiConfigurationFromFiler(option); err != nil {
  110. glog.Warningf("fail to load config: %v", err)
  111. }
  112. }
  113. return iam
  114. }
  115. func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFiler(option *S3ApiServerOption) (err error) {
  116. var content []byte
  117. err = pb.WithFilerClient(false, 0, option.Filer, option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  118. content, err = filer.ReadInsideFiler(client, filer.IamConfigDirectory, filer.IamIdentityFile)
  119. return err
  120. })
  121. if err != nil {
  122. return fmt.Errorf("read S3 config: %v", err)
  123. }
  124. return iam.LoadS3ApiConfigurationFromBytes(content)
  125. }
  126. func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName string) error {
  127. content, readErr := os.ReadFile(fileName)
  128. if readErr != nil {
  129. glog.Warningf("fail to read %s : %v", fileName, readErr)
  130. return fmt.Errorf("fail to read %s : %v", fileName, readErr)
  131. }
  132. return iam.LoadS3ApiConfigurationFromBytes(content)
  133. }
  134. func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromBytes(content []byte) error {
  135. s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
  136. if err := filer.ParseS3ConfigurationFromBytes(content, s3ApiConfiguration); err != nil {
  137. glog.Warningf("unmarshal error: %v", err)
  138. return fmt.Errorf("unmarshal error: %v", err)
  139. }
  140. if err := filer.CheckDuplicateAccessKey(s3ApiConfiguration); err != nil {
  141. return err
  142. }
  143. if err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {
  144. return err
  145. }
  146. return nil
  147. }
  148. func (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {
  149. var identities []*Identity
  150. var identityAnonymous *Identity
  151. accessKeyIdent := make(map[string]*Identity)
  152. accounts := make(map[string]*Account)
  153. emailAccount := make(map[string]*Account)
  154. foundAccountAdmin := false
  155. foundAccountAnonymous := false
  156. for _, account := range config.Accounts {
  157. switch account.Id {
  158. case AccountAdmin.Id:
  159. AccountAdmin = Account{
  160. Id: account.Id,
  161. DisplayName: account.DisplayName,
  162. EmailAddress: account.EmailAddress,
  163. }
  164. accounts[account.Id] = &AccountAdmin
  165. foundAccountAdmin = true
  166. case AccountAnonymous.Id:
  167. AccountAnonymous = Account{
  168. Id: account.Id,
  169. DisplayName: account.DisplayName,
  170. EmailAddress: account.EmailAddress,
  171. }
  172. accounts[account.Id] = &AccountAnonymous
  173. foundAccountAnonymous = true
  174. default:
  175. t := Account{
  176. Id: account.Id,
  177. DisplayName: account.DisplayName,
  178. EmailAddress: account.EmailAddress,
  179. }
  180. accounts[account.Id] = &t
  181. }
  182. if account.EmailAddress != "" {
  183. emailAccount[account.EmailAddress] = accounts[account.Id]
  184. }
  185. }
  186. if !foundAccountAdmin {
  187. accounts[AccountAdmin.Id] = &AccountAdmin
  188. emailAccount[AccountAdmin.EmailAddress] = &AccountAdmin
  189. }
  190. if !foundAccountAnonymous {
  191. accounts[AccountAnonymous.Id] = &AccountAnonymous
  192. emailAccount[AccountAnonymous.EmailAddress] = &AccountAnonymous
  193. }
  194. for _, ident := range config.Identities {
  195. t := &Identity{
  196. Name: ident.Name,
  197. Credentials: nil,
  198. Actions: nil,
  199. }
  200. switch {
  201. case ident.Name == AccountAnonymous.Id:
  202. t.Account = &AccountAnonymous
  203. identityAnonymous = t
  204. case ident.Account == nil:
  205. t.Account = &AccountAdmin
  206. default:
  207. if account, ok := accounts[ident.Account.Id]; ok {
  208. t.Account = account
  209. } else {
  210. t.Account = &AccountAdmin
  211. glog.Warningf("identity %s is associated with a non exist account ID, the association is invalid", ident.Name)
  212. }
  213. }
  214. for _, action := range ident.Actions {
  215. t.Actions = append(t.Actions, Action(action))
  216. }
  217. for _, cred := range ident.Credentials {
  218. t.Credentials = append(t.Credentials, &Credential{
  219. AccessKey: cred.AccessKey,
  220. SecretKey: cred.SecretKey,
  221. })
  222. accessKeyIdent[cred.AccessKey] = t
  223. }
  224. identities = append(identities, t)
  225. }
  226. iam.m.Lock()
  227. // atomically switch
  228. iam.identities = identities
  229. iam.identityAnonymous = identityAnonymous
  230. iam.accounts = accounts
  231. iam.emailAccount = emailAccount
  232. iam.accessKeyIdent = accessKeyIdent
  233. if !iam.isAuthEnabled { // one-directional, no toggling
  234. iam.isAuthEnabled = len(identities) > 0
  235. }
  236. iam.m.Unlock()
  237. return nil
  238. }
  239. func (iam *IdentityAccessManagement) isEnabled() bool {
  240. return iam.isAuthEnabled
  241. }
  242. func (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {
  243. iam.m.RLock()
  244. defer iam.m.RUnlock()
  245. if ident, ok := iam.accessKeyIdent[accessKey]; ok {
  246. for _, credential := range ident.Credentials {
  247. if credential.AccessKey == accessKey {
  248. return ident, credential, true
  249. }
  250. }
  251. }
  252. glog.V(1).Infof("could not find accessKey %s", accessKey)
  253. return nil, nil, false
  254. }
  255. func (iam *IdentityAccessManagement) lookupAnonymous() (identity *Identity, found bool) {
  256. iam.m.RLock()
  257. defer iam.m.RUnlock()
  258. if iam.identityAnonymous != nil {
  259. return iam.identityAnonymous, true
  260. }
  261. return nil, false
  262. }
  263. func (iam *IdentityAccessManagement) GetAccountNameById(canonicalId string) string {
  264. iam.m.RLock()
  265. defer iam.m.RUnlock()
  266. if account, ok := iam.accounts[canonicalId]; ok {
  267. return account.DisplayName
  268. }
  269. return ""
  270. }
  271. func (iam *IdentityAccessManagement) GetAccountIdByEmail(email string) string {
  272. iam.m.RLock()
  273. defer iam.m.RUnlock()
  274. if account, ok := iam.emailAccount[email]; ok {
  275. return account.Id
  276. }
  277. return ""
  278. }
  279. func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {
  280. return func(w http.ResponseWriter, r *http.Request) {
  281. if !iam.isEnabled() {
  282. f(w, r)
  283. return
  284. }
  285. identity, errCode := iam.authRequest(r, action)
  286. glog.V(3).Infof("auth error: %v", errCode)
  287. if errCode == s3err.ErrNone {
  288. if identity != nil && identity.Name != "" {
  289. r.Header.Set(s3_constants.AmzIdentityId, identity.Name)
  290. if identity.isAdmin() {
  291. r.Header.Set(s3_constants.AmzIsAdmin, "true")
  292. } else if _, ok := r.Header[s3_constants.AmzIsAdmin]; ok {
  293. r.Header.Del(s3_constants.AmzIsAdmin)
  294. }
  295. }
  296. f(w, r)
  297. return
  298. }
  299. s3err.WriteErrorResponse(w, r, errCode)
  300. }
  301. }
  302. // check whether the request has valid access keys
  303. func (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action) (*Identity, s3err.ErrorCode) {
  304. var identity *Identity
  305. var s3Err s3err.ErrorCode
  306. var found bool
  307. var authType string
  308. switch getRequestAuthType(r) {
  309. case authTypeStreamingSigned:
  310. return identity, s3err.ErrNone
  311. case authTypeUnknown:
  312. glog.V(3).Infof("unknown auth type")
  313. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  314. return identity, s3err.ErrAccessDenied
  315. case authTypePresignedV2, authTypeSignedV2:
  316. glog.V(3).Infof("v2 auth type")
  317. identity, s3Err = iam.isReqAuthenticatedV2(r)
  318. authType = "SigV2"
  319. case authTypeSigned, authTypePresigned:
  320. glog.V(3).Infof("v4 auth type")
  321. identity, s3Err = iam.reqSignatureV4Verify(r)
  322. authType = "SigV4"
  323. case authTypePostPolicy:
  324. glog.V(3).Infof("post policy auth type")
  325. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  326. return identity, s3err.ErrNone
  327. case authTypeJWT:
  328. glog.V(3).Infof("jwt auth type")
  329. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  330. return identity, s3err.ErrNotImplemented
  331. case authTypeAnonymous:
  332. authType = "Anonymous"
  333. if identity, found = iam.lookupAnonymous(); !found {
  334. r.Header.Set(s3_constants.AmzAuthType, authType)
  335. return identity, s3err.ErrAccessDenied
  336. }
  337. default:
  338. return identity, s3err.ErrNotImplemented
  339. }
  340. if len(authType) > 0 {
  341. r.Header.Set(s3_constants.AmzAuthType, authType)
  342. }
  343. if s3Err != s3err.ErrNone {
  344. return identity, s3Err
  345. }
  346. glog.V(3).Infof("user name: %v actions: %v, action: %v", identity.Name, identity.Actions, action)
  347. bucket, object := s3_constants.GetBucketAndObject(r)
  348. if !identity.canDo(action, bucket, object) {
  349. return identity, s3err.ErrAccessDenied
  350. }
  351. r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id)
  352. return identity, s3err.ErrNone
  353. }
  354. func (iam *IdentityAccessManagement) authUser(r *http.Request) (*Identity, s3err.ErrorCode) {
  355. var identity *Identity
  356. var s3Err s3err.ErrorCode
  357. var found bool
  358. var authType string
  359. switch getRequestAuthType(r) {
  360. case authTypeStreamingSigned:
  361. return identity, s3err.ErrNone
  362. case authTypeUnknown:
  363. glog.V(3).Infof("unknown auth type")
  364. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  365. return identity, s3err.ErrAccessDenied
  366. case authTypePresignedV2, authTypeSignedV2:
  367. glog.V(3).Infof("v2 auth type")
  368. identity, s3Err = iam.isReqAuthenticatedV2(r)
  369. authType = "SigV2"
  370. case authTypeSigned, authTypePresigned:
  371. glog.V(3).Infof("v4 auth type")
  372. identity, s3Err = iam.reqSignatureV4Verify(r)
  373. authType = "SigV4"
  374. case authTypePostPolicy:
  375. glog.V(3).Infof("post policy auth type")
  376. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  377. return identity, s3err.ErrNone
  378. case authTypeJWT:
  379. glog.V(3).Infof("jwt auth type")
  380. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  381. return identity, s3err.ErrNotImplemented
  382. case authTypeAnonymous:
  383. authType = "Anonymous"
  384. identity, found = iam.lookupAnonymous()
  385. if !found {
  386. r.Header.Set(s3_constants.AmzAuthType, authType)
  387. return identity, s3err.ErrAccessDenied
  388. }
  389. default:
  390. return identity, s3err.ErrNotImplemented
  391. }
  392. if len(authType) > 0 {
  393. r.Header.Set(s3_constants.AmzAuthType, authType)
  394. }
  395. glog.V(3).Infof("auth error: %v", s3Err)
  396. if s3Err != s3err.ErrNone {
  397. return identity, s3Err
  398. }
  399. return identity, s3err.ErrNone
  400. }
  401. func (identity *Identity) canDo(action Action, bucket string, objectKey string) bool {
  402. if identity.isAdmin() {
  403. return true
  404. }
  405. for _, a := range identity.Actions {
  406. if a == action {
  407. return true
  408. }
  409. }
  410. if bucket == "" {
  411. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s -- bucket is empty", identity.Name, action, bucket+objectKey)
  412. return false
  413. }
  414. target := string(action) + ":" + bucket + objectKey
  415. adminTarget := s3_constants.ACTION_ADMIN + ":" + bucket + objectKey
  416. limitedByBucket := string(action) + ":" + bucket
  417. adminLimitedByBucket := s3_constants.ACTION_ADMIN + ":" + bucket
  418. for _, a := range identity.Actions {
  419. act := string(a)
  420. if strings.HasSuffix(act, "*") {
  421. if strings.HasPrefix(target, act[:len(act)-1]) {
  422. return true
  423. }
  424. if strings.HasPrefix(adminTarget, act[:len(act)-1]) {
  425. return true
  426. }
  427. } else {
  428. if act == limitedByBucket {
  429. return true
  430. }
  431. if act == adminLimitedByBucket {
  432. return true
  433. }
  434. }
  435. }
  436. //log error
  437. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s", identity.Name, action, bucket+objectKey)
  438. return false
  439. }
  440. func (identity *Identity) isAdmin() bool {
  441. for _, a := range identity.Actions {
  442. if a == "Admin" {
  443. return true
  444. }
  445. }
  446. return false
  447. }