You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

526 lines
15 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 months ago
4 years ago
5 years ago
5 months ago
4 years ago
5 years ago
5 months ago
5 months ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 months ago
5 years ago
4 years ago
5 years ago
3 years ago
5 years ago
5 months ago
5 months ago
5 months ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  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.AccountId == AccountAdmin.Id:
  205. t.Account = &AccountAdmin
  206. case ident.AccountId == "":
  207. t.Account = &AccountAdmin
  208. default:
  209. if account, ok := accounts[ident.AccountId]; ok {
  210. t.Account = account
  211. } else {
  212. t.Account = &AccountAdmin
  213. glog.Warningf("identity %s is associated with a non exist account ID, the association is invalid", ident.Name)
  214. }
  215. }
  216. for _, action := range ident.Actions {
  217. t.Actions = append(t.Actions, Action(action))
  218. }
  219. for _, cred := range ident.Credentials {
  220. t.Credentials = append(t.Credentials, &Credential{
  221. AccessKey: cred.AccessKey,
  222. SecretKey: cred.SecretKey,
  223. })
  224. accessKeyIdent[cred.AccessKey] = t
  225. }
  226. identities = append(identities, t)
  227. }
  228. iam.m.Lock()
  229. // atomically switch
  230. iam.identities = identities
  231. iam.identityAnonymous = identityAnonymous
  232. iam.accounts = accounts
  233. iam.emailAccount = emailAccount
  234. iam.accessKeyIdent = accessKeyIdent
  235. if !iam.isAuthEnabled { // one-directional, no toggling
  236. iam.isAuthEnabled = len(identities) > 0
  237. }
  238. iam.m.Unlock()
  239. return nil
  240. }
  241. func (iam *IdentityAccessManagement) isEnabled() bool {
  242. return iam.isAuthEnabled
  243. }
  244. func (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {
  245. iam.m.RLock()
  246. defer iam.m.RUnlock()
  247. if ident, ok := iam.accessKeyIdent[accessKey]; ok {
  248. for _, credential := range ident.Credentials {
  249. if credential.AccessKey == accessKey {
  250. return ident, credential, true
  251. }
  252. }
  253. }
  254. glog.V(1).Infof("could not find accessKey %s", accessKey)
  255. return nil, nil, false
  256. }
  257. func (iam *IdentityAccessManagement) lookupAnonymous() (identity *Identity, found bool) {
  258. iam.m.RLock()
  259. defer iam.m.RUnlock()
  260. if iam.identityAnonymous != nil {
  261. return iam.identityAnonymous, true
  262. }
  263. return nil, false
  264. }
  265. func (iam *IdentityAccessManagement) GetAccountNameById(canonicalId string) string {
  266. iam.m.RLock()
  267. defer iam.m.RUnlock()
  268. if account, ok := iam.accounts[canonicalId]; ok {
  269. return account.DisplayName
  270. }
  271. return ""
  272. }
  273. func (iam *IdentityAccessManagement) GetAccountIdByEmail(email string) string {
  274. iam.m.RLock()
  275. defer iam.m.RUnlock()
  276. if account, ok := iam.emailAccount[email]; ok {
  277. return account.Id
  278. }
  279. return ""
  280. }
  281. func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {
  282. return Auth(iam, nil, f, action, false)
  283. }
  284. func (s3a *S3ApiServer) AuthWithAcl(f http.HandlerFunc, action Action) http.HandlerFunc {
  285. return Auth(s3a.iam, s3a.bucketRegistry, f, action, true)
  286. }
  287. func (s3a *S3ApiServer) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {
  288. return Auth(s3a.iam, s3a.bucketRegistry, f, action, false)
  289. }
  290. func Auth(iam *IdentityAccessManagement, br *BucketRegistry, f http.HandlerFunc, action Action, supportAcl bool) http.HandlerFunc {
  291. return func(w http.ResponseWriter, r *http.Request) {
  292. //unset predefined headers
  293. delete(r.Header, s3_constants.AmzAccountId)
  294. delete(r.Header, s3_constants.ExtAmzOwnerKey)
  295. delete(r.Header, s3_constants.ExtAmzAclKey)
  296. if !iam.isEnabled() {
  297. f(w, r)
  298. return
  299. }
  300. identity, errCode := authRequest(iam, br, r, action, supportAcl)
  301. if errCode == s3err.ErrNone {
  302. if identity != nil && identity.Name != "" {
  303. r.Header.Set(s3_constants.AmzIdentityId, identity.Name)
  304. if identity.isAdmin() {
  305. r.Header.Set(s3_constants.AmzIsAdmin, "true")
  306. } else if _, ok := r.Header[s3_constants.AmzIsAdmin]; ok {
  307. r.Header.Del(s3_constants.AmzIsAdmin)
  308. }
  309. }
  310. f(w, r)
  311. return
  312. }
  313. s3err.WriteErrorResponse(w, r, errCode)
  314. }
  315. }
  316. // check whether the request has valid access keys
  317. func (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action) (*Identity, s3err.ErrorCode) {
  318. return authRequest(iam, nil, r, action, false)
  319. }
  320. func authRequest(iam *IdentityAccessManagement, br *BucketRegistry, r *http.Request, action Action, supportAcl bool) (*Identity, s3err.ErrorCode) {
  321. var identity *Identity
  322. var s3Err s3err.ErrorCode
  323. var authType string
  324. switch getRequestAuthType(r) {
  325. case authTypeStreamingSigned:
  326. return identity, s3err.ErrNone
  327. case authTypeUnknown:
  328. glog.V(3).Infof("unknown auth type")
  329. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  330. return identity, s3err.ErrAccessDenied
  331. case authTypePresignedV2, authTypeSignedV2:
  332. glog.V(3).Infof("v2 auth type")
  333. identity, s3Err = iam.isReqAuthenticatedV2(r)
  334. authType = "SigV2"
  335. case authTypeSigned, authTypePresigned:
  336. glog.V(3).Infof("v4 auth type")
  337. identity, s3Err = iam.reqSignatureV4Verify(r)
  338. authType = "SigV4"
  339. case authTypePostPolicy:
  340. glog.V(3).Infof("post policy auth type")
  341. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  342. return identity, s3err.ErrNone
  343. case authTypeJWT:
  344. glog.V(3).Infof("jwt auth type")
  345. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  346. return identity, s3err.ErrNotImplemented
  347. case authTypeAnonymous:
  348. if supportAcl && br != nil {
  349. bucket, _ := s3_constants.GetBucketAndObject(r)
  350. bucketMetadata, errorCode := br.GetBucketMetadata(bucket)
  351. if errorCode != s3err.ErrNone {
  352. return nil, errorCode
  353. }
  354. if bucketMetadata.ObjectOwnership != s3_constants.OwnershipBucketOwnerEnforced {
  355. return iam.identityAnonymous, s3err.ErrNone
  356. }
  357. }
  358. authType = "Anonymous"
  359. identity = iam.identityAnonymous
  360. default:
  361. return identity, s3err.ErrNotImplemented
  362. }
  363. if identity == nil || len(identity.Actions) == 0 {
  364. r.Header.Set(s3_constants.AmzAuthType, authType)
  365. return identity, s3err.ErrAccessDenied
  366. }
  367. if len(authType) > 0 {
  368. r.Header.Set(s3_constants.AmzAuthType, authType)
  369. }
  370. if s3Err != s3err.ErrNone {
  371. return identity, s3Err
  372. }
  373. glog.V(3).Infof("user name: %v actions: %v, action: %v", identity.Name, identity.Actions, action)
  374. bucket, object := s3_constants.GetBucketAndObject(r)
  375. if !identity.canDo(action, bucket, object) {
  376. return identity, s3err.ErrAccessDenied
  377. }
  378. r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id)
  379. return identity, s3err.ErrNone
  380. }
  381. func (iam *IdentityAccessManagement) authUser(r *http.Request) (*Identity, s3err.ErrorCode) {
  382. var identity *Identity
  383. var s3Err s3err.ErrorCode
  384. var found bool
  385. var authType string
  386. switch getRequestAuthType(r) {
  387. case authTypeStreamingSigned:
  388. return identity, s3err.ErrNone
  389. case authTypeUnknown:
  390. glog.V(3).Infof("unknown auth type")
  391. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  392. return identity, s3err.ErrAccessDenied
  393. case authTypePresignedV2, authTypeSignedV2:
  394. glog.V(3).Infof("v2 auth type")
  395. identity, s3Err = iam.isReqAuthenticatedV2(r)
  396. authType = "SigV2"
  397. case authTypeSigned, authTypePresigned:
  398. glog.V(3).Infof("v4 auth type")
  399. identity, s3Err = iam.reqSignatureV4Verify(r)
  400. authType = "SigV4"
  401. case authTypePostPolicy:
  402. glog.V(3).Infof("post policy auth type")
  403. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  404. return identity, s3err.ErrNone
  405. case authTypeJWT:
  406. glog.V(3).Infof("jwt auth type")
  407. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  408. return identity, s3err.ErrNotImplemented
  409. case authTypeAnonymous:
  410. authType = "Anonymous"
  411. identity, found = iam.lookupAnonymous()
  412. if !found {
  413. r.Header.Set(s3_constants.AmzAuthType, authType)
  414. return identity, s3err.ErrAccessDenied
  415. }
  416. default:
  417. return identity, s3err.ErrNotImplemented
  418. }
  419. if len(authType) > 0 {
  420. r.Header.Set(s3_constants.AmzAuthType, authType)
  421. }
  422. glog.V(3).Infof("auth error: %v", s3Err)
  423. if s3Err != s3err.ErrNone {
  424. return identity, s3Err
  425. }
  426. return identity, s3err.ErrNone
  427. }
  428. func (identity *Identity) canDo(action Action, bucket string, objectKey string) bool {
  429. if identity.isAdmin() {
  430. return true
  431. }
  432. for _, a := range identity.Actions {
  433. if a == action {
  434. return true
  435. }
  436. }
  437. if bucket == "" {
  438. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s -- bucket is empty", identity.Name, action, bucket+objectKey)
  439. return false
  440. }
  441. target := string(action) + ":" + bucket + objectKey
  442. adminTarget := s3_constants.ACTION_ADMIN + ":" + bucket + objectKey
  443. limitedByBucket := string(action) + ":" + bucket
  444. adminLimitedByBucket := s3_constants.ACTION_ADMIN + ":" + bucket
  445. for _, a := range identity.Actions {
  446. act := string(a)
  447. if strings.HasSuffix(act, "*") {
  448. if strings.HasPrefix(target, act[:len(act)-1]) {
  449. return true
  450. }
  451. if strings.HasPrefix(adminTarget, act[:len(act)-1]) {
  452. return true
  453. }
  454. } else {
  455. if act == limitedByBucket {
  456. return true
  457. }
  458. if act == adminLimitedByBucket {
  459. return true
  460. }
  461. }
  462. }
  463. //log error
  464. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s", identity.Name, action, bucket+objectKey)
  465. return false
  466. }
  467. func (identity *Identity) isAdmin() bool {
  468. for _, a := range identity.Actions {
  469. if a == "Admin" {
  470. return true
  471. }
  472. }
  473. return false
  474. }