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.

511 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
4 years ago
5 years ago
4 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
3 years ago
5 years 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. glog.V(3).Infof("loading static config file %s", option.Config)
  106. if err := iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {
  107. glog.Fatalf("fail to load config file %s: %v", option.Config, err)
  108. }
  109. } else {
  110. glog.V(3).Infof("no static config file specified... loading config from filer %s", option.Filer)
  111. if err := iam.loadS3ApiConfigurationFromFiler(option); err != nil {
  112. glog.Warningf("fail to load config: %v", err)
  113. }
  114. }
  115. return iam
  116. }
  117. func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFiler(option *S3ApiServerOption) (err error) {
  118. var content []byte
  119. err = pb.WithFilerClient(false, 0, option.Filer, option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  120. glog.V(3).Infof("loading config %s from filer %s", filer.IamConfigDirectory+"/"+filer.IamIdentityFile, option.Filer)
  121. content, err = filer.ReadInsideFiler(client, filer.IamConfigDirectory, filer.IamIdentityFile)
  122. return err
  123. })
  124. if err != nil {
  125. return fmt.Errorf("read S3 config: %v", err)
  126. }
  127. return iam.LoadS3ApiConfigurationFromBytes(content)
  128. }
  129. func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName string) error {
  130. content, readErr := os.ReadFile(fileName)
  131. if readErr != nil {
  132. glog.Warningf("fail to read %s : %v", fileName, readErr)
  133. return fmt.Errorf("fail to read %s : %v", fileName, readErr)
  134. }
  135. return iam.LoadS3ApiConfigurationFromBytes(content)
  136. }
  137. func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromBytes(content []byte) error {
  138. s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
  139. if err := filer.ParseS3ConfigurationFromBytes(content, s3ApiConfiguration); err != nil {
  140. glog.Warningf("unmarshal error: %v", err)
  141. return fmt.Errorf("unmarshal error: %v", err)
  142. }
  143. if err := filer.CheckDuplicateAccessKey(s3ApiConfiguration); err != nil {
  144. return err
  145. }
  146. if err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {
  147. return err
  148. }
  149. return nil
  150. }
  151. func (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {
  152. var identities []*Identity
  153. var identityAnonymous *Identity
  154. accessKeyIdent := make(map[string]*Identity)
  155. accounts := make(map[string]*Account)
  156. emailAccount := make(map[string]*Account)
  157. foundAccountAdmin := false
  158. foundAccountAnonymous := false
  159. for _, account := range config.Accounts {
  160. glog.V(3).Infof("loading account name=%s, id=%s", account.DisplayName, account.Id)
  161. switch account.Id {
  162. case AccountAdmin.Id:
  163. AccountAdmin = Account{
  164. Id: account.Id,
  165. DisplayName: account.DisplayName,
  166. EmailAddress: account.EmailAddress,
  167. }
  168. accounts[account.Id] = &AccountAdmin
  169. foundAccountAdmin = true
  170. case AccountAnonymous.Id:
  171. AccountAnonymous = Account{
  172. Id: account.Id,
  173. DisplayName: account.DisplayName,
  174. EmailAddress: account.EmailAddress,
  175. }
  176. accounts[account.Id] = &AccountAnonymous
  177. foundAccountAnonymous = true
  178. default:
  179. t := Account{
  180. Id: account.Id,
  181. DisplayName: account.DisplayName,
  182. EmailAddress: account.EmailAddress,
  183. }
  184. accounts[account.Id] = &t
  185. }
  186. if account.EmailAddress != "" {
  187. emailAccount[account.EmailAddress] = accounts[account.Id]
  188. }
  189. }
  190. if !foundAccountAdmin {
  191. accounts[AccountAdmin.Id] = &AccountAdmin
  192. emailAccount[AccountAdmin.EmailAddress] = &AccountAdmin
  193. }
  194. if !foundAccountAnonymous {
  195. accounts[AccountAnonymous.Id] = &AccountAnonymous
  196. emailAccount[AccountAnonymous.EmailAddress] = &AccountAnonymous
  197. }
  198. for _, ident := range config.Identities {
  199. glog.V(3).Infof("loading identity %s", ident.Name)
  200. t := &Identity{
  201. Name: ident.Name,
  202. Credentials: nil,
  203. Actions: nil,
  204. }
  205. switch {
  206. case ident.Name == AccountAnonymous.Id:
  207. t.Account = &AccountAnonymous
  208. identityAnonymous = t
  209. case ident.Account == nil:
  210. t.Account = &AccountAdmin
  211. default:
  212. if account, ok := accounts[ident.Account.Id]; ok {
  213. t.Account = account
  214. } else {
  215. t.Account = &AccountAdmin
  216. glog.Warningf("identity %s is associated with a non exist account ID, the association is invalid", ident.Name)
  217. }
  218. }
  219. for _, action := range ident.Actions {
  220. t.Actions = append(t.Actions, Action(action))
  221. }
  222. for _, cred := range ident.Credentials {
  223. t.Credentials = append(t.Credentials, &Credential{
  224. AccessKey: cred.AccessKey,
  225. SecretKey: cred.SecretKey,
  226. })
  227. accessKeyIdent[cred.AccessKey] = t
  228. }
  229. identities = append(identities, t)
  230. }
  231. iam.m.Lock()
  232. // atomically switch
  233. iam.identities = identities
  234. iam.identityAnonymous = identityAnonymous
  235. iam.accounts = accounts
  236. iam.emailAccount = emailAccount
  237. iam.accessKeyIdent = accessKeyIdent
  238. if !iam.isAuthEnabled { // one-directional, no toggling
  239. iam.isAuthEnabled = len(identities) > 0
  240. }
  241. iam.m.Unlock()
  242. return nil
  243. }
  244. func (iam *IdentityAccessManagement) isEnabled() bool {
  245. return iam.isAuthEnabled
  246. }
  247. func (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {
  248. iam.m.RLock()
  249. defer iam.m.RUnlock()
  250. if ident, ok := iam.accessKeyIdent[accessKey]; ok {
  251. for _, credential := range ident.Credentials {
  252. if credential.AccessKey == accessKey {
  253. return ident, credential, true
  254. }
  255. }
  256. }
  257. glog.V(1).Infof("could not find accessKey %s", accessKey)
  258. return nil, nil, false
  259. }
  260. func (iam *IdentityAccessManagement) lookupAnonymous() (identity *Identity, found bool) {
  261. iam.m.RLock()
  262. defer iam.m.RUnlock()
  263. if iam.identityAnonymous != nil {
  264. return iam.identityAnonymous, true
  265. }
  266. return nil, false
  267. }
  268. func (iam *IdentityAccessManagement) GetAccountNameById(canonicalId string) string {
  269. iam.m.RLock()
  270. defer iam.m.RUnlock()
  271. if account, ok := iam.accounts[canonicalId]; ok {
  272. return account.DisplayName
  273. }
  274. return ""
  275. }
  276. func (iam *IdentityAccessManagement) GetAccountIdByEmail(email string) string {
  277. iam.m.RLock()
  278. defer iam.m.RUnlock()
  279. if account, ok := iam.emailAccount[email]; ok {
  280. return account.Id
  281. }
  282. return ""
  283. }
  284. func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {
  285. return func(w http.ResponseWriter, r *http.Request) {
  286. if !iam.isEnabled() {
  287. f(w, r)
  288. return
  289. }
  290. identity, errCode := iam.authRequest(r, action)
  291. glog.V(3).Infof("auth error: %v", errCode)
  292. if errCode == s3err.ErrNone {
  293. if identity != nil && identity.Name != "" {
  294. r.Header.Set(s3_constants.AmzIdentityId, identity.Name)
  295. if identity.isAdmin() {
  296. r.Header.Set(s3_constants.AmzIsAdmin, "true")
  297. } else if _, ok := r.Header[s3_constants.AmzIsAdmin]; ok {
  298. r.Header.Del(s3_constants.AmzIsAdmin)
  299. }
  300. }
  301. f(w, r)
  302. return
  303. }
  304. s3err.WriteErrorResponse(w, r, errCode)
  305. }
  306. }
  307. // check whether the request has valid access keys
  308. func (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action) (*Identity, s3err.ErrorCode) {
  309. var identity *Identity
  310. var s3Err s3err.ErrorCode
  311. var found bool
  312. var authType string
  313. switch getRequestAuthType(r) {
  314. case authTypeUnknown:
  315. glog.V(3).Infof("unknown auth type")
  316. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  317. return identity, s3err.ErrAccessDenied
  318. case authTypePresignedV2, authTypeSignedV2:
  319. glog.V(3).Infof("v2 auth type")
  320. identity, s3Err = iam.isReqAuthenticatedV2(r)
  321. authType = "SigV2"
  322. case authTypeStreamingSigned, authTypeSigned, authTypePresigned:
  323. glog.V(3).Infof("v4 auth type")
  324. identity, s3Err = iam.reqSignatureV4Verify(r)
  325. authType = "SigV4"
  326. case authTypePostPolicy:
  327. glog.V(3).Infof("post policy auth type")
  328. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  329. return identity, s3err.ErrNone
  330. case authTypeJWT:
  331. glog.V(3).Infof("jwt auth type")
  332. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  333. return identity, s3err.ErrNotImplemented
  334. case authTypeAnonymous:
  335. authType = "Anonymous"
  336. if identity, found = iam.lookupAnonymous(); !found {
  337. r.Header.Set(s3_constants.AmzAuthType, authType)
  338. return identity, s3err.ErrAccessDenied
  339. }
  340. default:
  341. return identity, s3err.ErrNotImplemented
  342. }
  343. if len(authType) > 0 {
  344. r.Header.Set(s3_constants.AmzAuthType, authType)
  345. }
  346. if s3Err != s3err.ErrNone {
  347. return identity, s3Err
  348. }
  349. glog.V(3).Infof("user name: %v actions: %v, action: %v", identity.Name, identity.Actions, action)
  350. bucket, object := s3_constants.GetBucketAndObject(r)
  351. prefix := s3_constants.GetPrefix(r)
  352. if object == "/" && prefix != "" {
  353. // Using the aws cli with s3, and s3api, and with boto3, the object is always set to "/"
  354. // but the prefix is set to the actual object key
  355. object = prefix
  356. }
  357. if !identity.canDo(action, bucket, object) {
  358. return identity, s3err.ErrAccessDenied
  359. }
  360. r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id)
  361. return identity, s3err.ErrNone
  362. }
  363. func (iam *IdentityAccessManagement) authUser(r *http.Request) (*Identity, s3err.ErrorCode) {
  364. var identity *Identity
  365. var s3Err s3err.ErrorCode
  366. var found bool
  367. var authType string
  368. switch getRequestAuthType(r) {
  369. case authTypeStreamingSigned:
  370. return identity, s3err.ErrNone
  371. case authTypeUnknown:
  372. glog.V(3).Infof("unknown auth type")
  373. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  374. return identity, s3err.ErrAccessDenied
  375. case authTypePresignedV2, authTypeSignedV2:
  376. glog.V(3).Infof("v2 auth type")
  377. identity, s3Err = iam.isReqAuthenticatedV2(r)
  378. authType = "SigV2"
  379. case authTypeSigned, authTypePresigned:
  380. glog.V(3).Infof("v4 auth type")
  381. identity, s3Err = iam.reqSignatureV4Verify(r)
  382. authType = "SigV4"
  383. case authTypePostPolicy:
  384. glog.V(3).Infof("post policy auth type")
  385. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  386. return identity, s3err.ErrNone
  387. case authTypeJWT:
  388. glog.V(3).Infof("jwt auth type")
  389. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  390. return identity, s3err.ErrNotImplemented
  391. case authTypeAnonymous:
  392. authType = "Anonymous"
  393. identity, found = iam.lookupAnonymous()
  394. if !found {
  395. r.Header.Set(s3_constants.AmzAuthType, authType)
  396. return identity, s3err.ErrAccessDenied
  397. }
  398. default:
  399. return identity, s3err.ErrNotImplemented
  400. }
  401. if len(authType) > 0 {
  402. r.Header.Set(s3_constants.AmzAuthType, authType)
  403. }
  404. glog.V(3).Infof("auth error: %v", s3Err)
  405. if s3Err != s3err.ErrNone {
  406. return identity, s3Err
  407. }
  408. return identity, s3err.ErrNone
  409. }
  410. func (identity *Identity) canDo(action Action, bucket string, objectKey string) bool {
  411. if identity.isAdmin() {
  412. return true
  413. }
  414. for _, a := range identity.Actions {
  415. // Case where the Resource provided is
  416. // "Resource": [
  417. // "arn:aws:s3:::*"
  418. // ]
  419. if a == action {
  420. return true
  421. }
  422. }
  423. if bucket == "" {
  424. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s -- bucket is empty", identity.Name, action, bucket+objectKey)
  425. return false
  426. }
  427. glog.V(3).Infof("checking if %s can perform %s on bucket '%s'", identity.Name, action, bucket+objectKey)
  428. target := string(action) + ":" + bucket + objectKey
  429. adminTarget := s3_constants.ACTION_ADMIN + ":" + bucket + objectKey
  430. limitedByBucket := string(action) + ":" + bucket
  431. adminLimitedByBucket := s3_constants.ACTION_ADMIN + ":" + bucket
  432. for _, a := range identity.Actions {
  433. act := string(a)
  434. if strings.HasSuffix(act, "*") {
  435. if strings.HasPrefix(target, act[:len(act)-1]) {
  436. return true
  437. }
  438. if strings.HasPrefix(adminTarget, act[:len(act)-1]) {
  439. return true
  440. }
  441. } else {
  442. if act == limitedByBucket {
  443. return true
  444. }
  445. if act == adminLimitedByBucket {
  446. return true
  447. }
  448. }
  449. }
  450. //log error
  451. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s", identity.Name, action, bucket+objectKey)
  452. return false
  453. }
  454. func (identity *Identity) isAdmin() bool {
  455. for _, a := range identity.Actions {
  456. if a == "Admin" {
  457. return true
  458. }
  459. }
  460. return false
  461. }