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.

540 lines
17 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
  1. package iamapi
  2. import (
  3. "crypto/sha1"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "math/rand"
  8. "net/http"
  9. "net/url"
  10. "reflect"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/seaweedfs/seaweedfs/weed/glog"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
  17. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  18. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  19. "github.com/aws/aws-sdk-go/service/iam"
  20. )
  21. const (
  22. charsetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  23. charset = charsetUpper + "abcdefghijklmnopqrstuvwxyz/"
  24. policyDocumentVersion = "2012-10-17"
  25. StatementActionAdmin = "*"
  26. StatementActionWrite = "Put*"
  27. StatementActionWriteAcp = "PutBucketAcl"
  28. StatementActionRead = "Get*"
  29. StatementActionReadAcp = "GetBucketAcl"
  30. StatementActionList = "List*"
  31. StatementActionTagging = "Tagging*"
  32. StatementActionDelete = "DeleteBucket*"
  33. )
  34. var (
  35. seededRand *rand.Rand = rand.New(
  36. rand.NewSource(time.Now().UnixNano()))
  37. policyDocuments = map[string]*PolicyDocument{}
  38. policyLock = sync.RWMutex{}
  39. )
  40. func MapToStatementAction(action string) string {
  41. switch action {
  42. case StatementActionAdmin:
  43. return s3_constants.ACTION_ADMIN
  44. case StatementActionWrite:
  45. return s3_constants.ACTION_WRITE
  46. case StatementActionWriteAcp:
  47. return s3_constants.ACTION_WRITE_ACP
  48. case StatementActionRead:
  49. return s3_constants.ACTION_READ
  50. case StatementActionReadAcp:
  51. return s3_constants.ACTION_READ_ACP
  52. case StatementActionList:
  53. return s3_constants.ACTION_LIST
  54. case StatementActionTagging:
  55. return s3_constants.ACTION_TAGGING
  56. case StatementActionDelete:
  57. return s3_constants.ACTION_DELETE_BUCKET
  58. default:
  59. return ""
  60. }
  61. }
  62. func MapToIdentitiesAction(action string) string {
  63. switch action {
  64. case s3_constants.ACTION_ADMIN:
  65. return StatementActionAdmin
  66. case s3_constants.ACTION_WRITE:
  67. return StatementActionWrite
  68. case s3_constants.ACTION_WRITE_ACP:
  69. return StatementActionWriteAcp
  70. case s3_constants.ACTION_READ:
  71. return StatementActionRead
  72. case s3_constants.ACTION_READ_ACP:
  73. return StatementActionReadAcp
  74. case s3_constants.ACTION_LIST:
  75. return StatementActionList
  76. case s3_constants.ACTION_TAGGING:
  77. return StatementActionTagging
  78. case s3_constants.ACTION_DELETE_BUCKET:
  79. return StatementActionDelete
  80. default:
  81. return ""
  82. }
  83. }
  84. const (
  85. USER_DOES_NOT_EXIST = "the user with name %s cannot be found."
  86. )
  87. type Statement struct {
  88. Effect string `json:"Effect"`
  89. Action []string `json:"Action"`
  90. Resource []string `json:"Resource"`
  91. }
  92. type Policies struct {
  93. Policies map[string]PolicyDocument `json:"policies"`
  94. }
  95. type PolicyDocument struct {
  96. Version string `json:"Version"`
  97. Statement []*Statement `json:"Statement"`
  98. }
  99. func (p PolicyDocument) String() string {
  100. b, _ := json.Marshal(p)
  101. return string(b)
  102. }
  103. func Hash(s *string) string {
  104. h := sha1.New()
  105. h.Write([]byte(*s))
  106. return fmt.Sprintf("%x", h.Sum(nil))
  107. }
  108. func StringWithCharset(length int, charset string) string {
  109. b := make([]byte, length)
  110. for i := range b {
  111. b[i] = charset[seededRand.Intn(len(charset))]
  112. }
  113. return string(b)
  114. }
  115. func (iama *IamApiServer) ListUsers(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp ListUsersResponse) {
  116. for _, ident := range s3cfg.Identities {
  117. resp.ListUsersResult.Users = append(resp.ListUsersResult.Users, &iam.User{UserName: &ident.Name})
  118. }
  119. return resp
  120. }
  121. func (iama *IamApiServer) ListAccessKeys(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp ListAccessKeysResponse) {
  122. status := iam.StatusTypeActive
  123. userName := values.Get("UserName")
  124. for _, ident := range s3cfg.Identities {
  125. if userName != "" && userName != ident.Name {
  126. continue
  127. }
  128. for _, cred := range ident.Credentials {
  129. resp.ListAccessKeysResult.AccessKeyMetadata = append(resp.ListAccessKeysResult.AccessKeyMetadata,
  130. &iam.AccessKeyMetadata{UserName: &ident.Name, AccessKeyId: &cred.AccessKey, Status: &status},
  131. )
  132. }
  133. }
  134. return resp
  135. }
  136. func (iama *IamApiServer) CreateUser(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp CreateUserResponse) {
  137. userName := values.Get("UserName")
  138. resp.CreateUserResult.User.UserName = &userName
  139. s3cfg.Identities = append(s3cfg.Identities, &iam_pb.Identity{Name: userName})
  140. return resp
  141. }
  142. func (iama *IamApiServer) DeleteUser(s3cfg *iam_pb.S3ApiConfiguration, userName string) (resp DeleteUserResponse, err *IamError) {
  143. for i, ident := range s3cfg.Identities {
  144. if userName == ident.Name {
  145. s3cfg.Identities = append(s3cfg.Identities[:i], s3cfg.Identities[i+1:]...)
  146. return resp, nil
  147. }
  148. }
  149. return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(USER_DOES_NOT_EXIST, userName)}
  150. }
  151. func (iama *IamApiServer) GetUser(s3cfg *iam_pb.S3ApiConfiguration, userName string) (resp GetUserResponse, err *IamError) {
  152. for _, ident := range s3cfg.Identities {
  153. if userName == ident.Name {
  154. resp.GetUserResult.User = iam.User{UserName: &ident.Name}
  155. return resp, nil
  156. }
  157. }
  158. return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(USER_DOES_NOT_EXIST, userName)}
  159. }
  160. func (iama *IamApiServer) UpdateUser(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp UpdateUserResponse, err *IamError) {
  161. userName := values.Get("UserName")
  162. newUserName := values.Get("NewUserName")
  163. if newUserName != "" {
  164. for _, ident := range s3cfg.Identities {
  165. if userName == ident.Name {
  166. ident.Name = newUserName
  167. return resp, nil
  168. }
  169. }
  170. } else {
  171. return resp, nil
  172. }
  173. return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(USER_DOES_NOT_EXIST, userName)}
  174. }
  175. func GetPolicyDocument(policy *string) (policyDocument PolicyDocument, err error) {
  176. if err = json.Unmarshal([]byte(*policy), &policyDocument); err != nil {
  177. return PolicyDocument{}, err
  178. }
  179. return policyDocument, err
  180. }
  181. func (iama *IamApiServer) CreatePolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp CreatePolicyResponse, iamError *IamError) {
  182. policyName := values.Get("PolicyName")
  183. policyDocumentString := values.Get("PolicyDocument")
  184. policyDocument, err := GetPolicyDocument(&policyDocumentString)
  185. if err != nil {
  186. return CreatePolicyResponse{}, &IamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
  187. }
  188. policyId := Hash(&policyDocumentString)
  189. arn := fmt.Sprintf("arn:aws:iam:::policy/%s", policyName)
  190. resp.CreatePolicyResult.Policy.PolicyName = &policyName
  191. resp.CreatePolicyResult.Policy.Arn = &arn
  192. resp.CreatePolicyResult.Policy.PolicyId = &policyId
  193. policies := Policies{}
  194. policyLock.Lock()
  195. defer policyLock.Unlock()
  196. if err = iama.s3ApiConfig.GetPolicies(&policies); err != nil {
  197. return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
  198. }
  199. policies.Policies[policyName] = policyDocument
  200. if err = iama.s3ApiConfig.PutPolicies(&policies); err != nil {
  201. return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
  202. }
  203. return resp, nil
  204. }
  205. type IamError struct {
  206. Code string
  207. Error error
  208. }
  209. // https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutUserPolicy.html
  210. func (iama *IamApiServer) PutUserPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp PutUserPolicyResponse, iamError *IamError) {
  211. userName := values.Get("UserName")
  212. policyName := values.Get("PolicyName")
  213. policyDocumentString := values.Get("PolicyDocument")
  214. policyDocument, err := GetPolicyDocument(&policyDocumentString)
  215. if err != nil {
  216. return PutUserPolicyResponse{}, &IamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
  217. }
  218. policyDocuments[policyName] = &policyDocument
  219. actions, err := GetActions(&policyDocument)
  220. if err != nil {
  221. return PutUserPolicyResponse{}, &IamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
  222. }
  223. // Log the actions
  224. glog.V(3).Infof("PutUserPolicy: actions=%v", actions)
  225. for _, ident := range s3cfg.Identities {
  226. if userName != ident.Name {
  227. continue
  228. }
  229. ident.Actions = actions
  230. return resp, nil
  231. }
  232. return PutUserPolicyResponse{}, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("the user with name %s cannot be found", userName)}
  233. }
  234. func (iama *IamApiServer) GetUserPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp GetUserPolicyResponse, err *IamError) {
  235. userName := values.Get("UserName")
  236. policyName := values.Get("PolicyName")
  237. for _, ident := range s3cfg.Identities {
  238. if userName != ident.Name {
  239. continue
  240. }
  241. resp.GetUserPolicyResult.UserName = userName
  242. resp.GetUserPolicyResult.PolicyName = policyName
  243. if len(ident.Actions) == 0 {
  244. return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: errors.New("no actions found")}
  245. }
  246. policyDocument := PolicyDocument{Version: policyDocumentVersion}
  247. statements := make(map[string][]string)
  248. for _, action := range ident.Actions {
  249. // parse "Read:EXAMPLE-BUCKET"
  250. act := strings.Split(action, ":")
  251. resource := "*"
  252. if len(act) == 2 {
  253. resource = fmt.Sprintf("arn:aws:s3:::%s/*", act[1])
  254. }
  255. statements[resource] = append(statements[resource],
  256. fmt.Sprintf("s3:%s", MapToIdentitiesAction(act[0])),
  257. )
  258. }
  259. for resource, actions := range statements {
  260. isEqAction := false
  261. for i, statement := range policyDocument.Statement {
  262. if reflect.DeepEqual(statement.Action, actions) {
  263. policyDocument.Statement[i].Resource = append(
  264. policyDocument.Statement[i].Resource, resource)
  265. isEqAction = true
  266. break
  267. }
  268. }
  269. if isEqAction {
  270. continue
  271. }
  272. policyDocumentStatement := Statement{
  273. Effect: "Allow",
  274. Action: actions,
  275. }
  276. policyDocumentStatement.Resource = append(policyDocumentStatement.Resource, resource)
  277. policyDocument.Statement = append(policyDocument.Statement, &policyDocumentStatement)
  278. }
  279. resp.GetUserPolicyResult.PolicyDocument = policyDocument.String()
  280. return resp, nil
  281. }
  282. return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(USER_DOES_NOT_EXIST, userName)}
  283. }
  284. func (iama *IamApiServer) DeleteUserPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp PutUserPolicyResponse, err *IamError) {
  285. userName := values.Get("UserName")
  286. for i, ident := range s3cfg.Identities {
  287. if ident.Name == userName {
  288. s3cfg.Identities = append(s3cfg.Identities[:i], s3cfg.Identities[i+1:]...)
  289. return resp, nil
  290. }
  291. }
  292. return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(USER_DOES_NOT_EXIST, userName)}
  293. }
  294. func GetActions(policy *PolicyDocument) ([]string, error) {
  295. var actions []string
  296. for _, statement := range policy.Statement {
  297. if statement.Effect != "Allow" {
  298. return nil, fmt.Errorf("not a valid effect: '%s'. Only 'Allow' is possible", statement.Effect)
  299. }
  300. for _, resource := range statement.Resource {
  301. // Parse "arn:aws:s3:::my-bucket/shared/*"
  302. res := strings.Split(resource, ":")
  303. if len(res) != 6 || res[0] != "arn" || res[1] != "aws" || res[2] != "s3" {
  304. return nil, fmt.Errorf("not a valid resource: '%s'. Expected prefix 'arn:aws:s3'", res)
  305. }
  306. for _, action := range statement.Action {
  307. // Parse "s3:Get*"
  308. act := strings.Split(action, ":")
  309. if len(act) != 2 || act[0] != "s3" {
  310. return nil, fmt.Errorf("not a valid action: '%s'. Expected prefix 's3:'", act)
  311. }
  312. statementAction := MapToStatementAction(act[1])
  313. if res[5] == "*" {
  314. actions = append(actions, statementAction)
  315. continue
  316. }
  317. // Parse my-bucket/shared/*
  318. path := strings.Split(res[5], "/")
  319. if len(path) != 2 || path[1] != "*" {
  320. glog.Infof("not match bucket: %s", path)
  321. continue
  322. }
  323. actions = append(actions, fmt.Sprintf("%s:%s", statementAction, path[0]))
  324. }
  325. }
  326. }
  327. return actions, nil
  328. }
  329. func (iama *IamApiServer) CreateAccessKey(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp CreateAccessKeyResponse) {
  330. userName := values.Get("UserName")
  331. status := iam.StatusTypeActive
  332. accessKeyId := StringWithCharset(21, charsetUpper)
  333. secretAccessKey := StringWithCharset(42, charset)
  334. resp.CreateAccessKeyResult.AccessKey.AccessKeyId = &accessKeyId
  335. resp.CreateAccessKeyResult.AccessKey.SecretAccessKey = &secretAccessKey
  336. resp.CreateAccessKeyResult.AccessKey.UserName = &userName
  337. resp.CreateAccessKeyResult.AccessKey.Status = &status
  338. changed := false
  339. for _, ident := range s3cfg.Identities {
  340. if userName == ident.Name {
  341. ident.Credentials = append(ident.Credentials,
  342. &iam_pb.Credential{AccessKey: accessKeyId, SecretKey: secretAccessKey})
  343. changed = true
  344. break
  345. }
  346. }
  347. if !changed {
  348. s3cfg.Identities = append(s3cfg.Identities,
  349. &iam_pb.Identity{
  350. Name: userName,
  351. Credentials: []*iam_pb.Credential{
  352. {
  353. AccessKey: accessKeyId,
  354. SecretKey: secretAccessKey,
  355. },
  356. },
  357. },
  358. )
  359. }
  360. return resp
  361. }
  362. func (iama *IamApiServer) DeleteAccessKey(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp DeleteAccessKeyResponse) {
  363. userName := values.Get("UserName")
  364. accessKeyId := values.Get("AccessKeyId")
  365. for _, ident := range s3cfg.Identities {
  366. if userName == ident.Name {
  367. for i, cred := range ident.Credentials {
  368. if cred.AccessKey == accessKeyId {
  369. ident.Credentials = append(ident.Credentials[:i], ident.Credentials[i+1:]...)
  370. break
  371. }
  372. }
  373. break
  374. }
  375. }
  376. return resp
  377. }
  378. // handleImplicitUsername adds username who signs the request to values if 'username' is not specified
  379. // According to https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-access-key.html/
  380. // "If you do not specify a user name, IAM determines the user name implicitly based on the Amazon Web
  381. // Services access key ID signing the request."
  382. func handleImplicitUsername(r *http.Request, values url.Values) {
  383. if len(r.Header["Authorization"]) == 0 || values.Get("UserName") != "" {
  384. return
  385. }
  386. // get username who signs the request. For a typical Authorization:
  387. // "AWS4-HMAC-SHA256 Credential=197FSAQ7HHTA48X64O3A/20220420/test1/iam/aws4_request, SignedHeaders=content-type;
  388. // host;x-amz-date, Signature=6757dc6b3d7534d67e17842760310e99ee695408497f6edc4fdb84770c252dc8",
  389. // the "test1" will be extracted as the username
  390. glog.V(4).Infof("Authorization field: %v", r.Header["Authorization"][0])
  391. s := strings.Split(r.Header["Authorization"][0], "Credential=")
  392. if len(s) < 2 {
  393. return
  394. }
  395. s = strings.Split(s[1], ",")
  396. if len(s) < 2 {
  397. return
  398. }
  399. s = strings.Split(s[0], "/")
  400. if len(s) < 5 {
  401. return
  402. }
  403. userName := s[2]
  404. values.Set("UserName", userName)
  405. }
  406. func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
  407. if err := r.ParseForm(); err != nil {
  408. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  409. return
  410. }
  411. values := r.PostForm
  412. s3cfg := &iam_pb.S3ApiConfiguration{}
  413. if err := iama.s3ApiConfig.GetS3ApiConfiguration(s3cfg); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
  414. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  415. return
  416. }
  417. glog.V(4).Infof("DoActions: %+v", values)
  418. var response interface{}
  419. var iamError *IamError
  420. changed := true
  421. switch r.Form.Get("Action") {
  422. case "ListUsers":
  423. response = iama.ListUsers(s3cfg, values)
  424. changed = false
  425. case "ListAccessKeys":
  426. handleImplicitUsername(r, values)
  427. response = iama.ListAccessKeys(s3cfg, values)
  428. changed = false
  429. case "CreateUser":
  430. response = iama.CreateUser(s3cfg, values)
  431. case "GetUser":
  432. userName := values.Get("UserName")
  433. response, iamError = iama.GetUser(s3cfg, userName)
  434. if iamError != nil {
  435. writeIamErrorResponse(w, r, iamError)
  436. return
  437. }
  438. changed = false
  439. case "UpdateUser":
  440. response, iamError = iama.UpdateUser(s3cfg, values)
  441. if iamError != nil {
  442. glog.Errorf("UpdateUser: %+v", iamError.Error)
  443. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  444. return
  445. }
  446. case "DeleteUser":
  447. userName := values.Get("UserName")
  448. response, iamError = iama.DeleteUser(s3cfg, userName)
  449. if iamError != nil {
  450. writeIamErrorResponse(w, r, iamError)
  451. return
  452. }
  453. case "CreateAccessKey":
  454. handleImplicitUsername(r, values)
  455. response = iama.CreateAccessKey(s3cfg, values)
  456. case "DeleteAccessKey":
  457. handleImplicitUsername(r, values)
  458. response = iama.DeleteAccessKey(s3cfg, values)
  459. case "CreatePolicy":
  460. response, iamError = iama.CreatePolicy(s3cfg, values)
  461. if iamError != nil {
  462. glog.Errorf("CreatePolicy: %+v", iamError.Error)
  463. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  464. return
  465. }
  466. case "PutUserPolicy":
  467. var iamError *IamError
  468. response, iamError = iama.PutUserPolicy(s3cfg, values)
  469. if iamError != nil {
  470. glog.Errorf("PutUserPolicy: %+v", iamError.Error)
  471. writeIamErrorResponse(w, r, iamError)
  472. return
  473. }
  474. case "GetUserPolicy":
  475. response, iamError = iama.GetUserPolicy(s3cfg, values)
  476. if iamError != nil {
  477. writeIamErrorResponse(w, r, iamError)
  478. return
  479. }
  480. changed = false
  481. case "DeleteUserPolicy":
  482. if response, iamError = iama.DeleteUserPolicy(s3cfg, values); iamError != nil {
  483. writeIamErrorResponse(w, r, iamError)
  484. return
  485. }
  486. default:
  487. errNotImplemented := s3err.GetAPIError(s3err.ErrNotImplemented)
  488. errorResponse := ErrorResponse{}
  489. errorResponse.Error.Code = &errNotImplemented.Code
  490. errorResponse.Error.Message = &errNotImplemented.Description
  491. s3err.WriteXMLResponse(w, r, errNotImplemented.HTTPStatusCode, errorResponse)
  492. return
  493. }
  494. if changed {
  495. err := iama.s3ApiConfig.PutS3ApiConfiguration(s3cfg)
  496. if err != nil {
  497. var iamError = IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
  498. writeIamErrorResponse(w, r, &iamError)
  499. return
  500. }
  501. }
  502. s3err.WriteXMLResponse(w, r, http.StatusOK, response)
  503. }