postpolicyform.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package policy
  2. /*
  3. * MinIO Cloud Storage, (C) 2015, 2016, 2017 MinIO, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. import (
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. "reflect"
  23. "strconv"
  24. "strings"
  25. "time"
  26. )
  27. // startWithConds - map which indicates if a given condition supports starts-with policy operator
  28. var startsWithConds = map[string]bool{
  29. "$acl": true,
  30. "$bucket": false,
  31. "$cache-control": true,
  32. "$content-type": true,
  33. "$content-disposition": true,
  34. "$content-encoding": true,
  35. "$expires": true,
  36. "$key": true,
  37. "$success_action_redirect": true,
  38. "$redirect": true,
  39. "$success_action_status": false,
  40. "$x-amz-algorithm": false,
  41. "$x-amz-credential": false,
  42. "$x-amz-date": false,
  43. }
  44. // Add policy conditionals.
  45. const (
  46. policyCondEqual = "eq"
  47. policyCondStartsWith = "starts-with"
  48. policyCondContentLength = "content-length-range"
  49. )
  50. // toString - Safely convert interface to string without causing panic.
  51. func toString(val interface{}) string {
  52. switch v := val.(type) {
  53. case string:
  54. return v
  55. default:
  56. return ""
  57. }
  58. }
  59. // toLowerString - safely convert interface to lower string
  60. func toLowerString(val interface{}) string {
  61. return strings.ToLower(toString(val))
  62. }
  63. // toInteger _ Safely convert interface to integer without causing panic.
  64. func toInteger(val interface{}) (int64, error) {
  65. switch v := val.(type) {
  66. case float64:
  67. return int64(v), nil
  68. case int64:
  69. return v, nil
  70. case int:
  71. return int64(v), nil
  72. case string:
  73. i, err := strconv.Atoi(v)
  74. return int64(i), err
  75. default:
  76. return 0, errors.New("Invalid number format")
  77. }
  78. }
  79. // isString - Safely check if val is of type string without causing panic.
  80. func isString(val interface{}) bool {
  81. _, ok := val.(string)
  82. return ok
  83. }
  84. // ContentLengthRange - policy content-length-range field.
  85. type contentLengthRange struct {
  86. Min int64
  87. Max int64
  88. Valid bool // If content-length-range was part of policy
  89. }
  90. // PostPolicyForm provides strict static type conversion and validation for Amazon S3's POST policy JSON string.
  91. type PostPolicyForm struct {
  92. Expiration time.Time // Expiration date and time of the POST policy.
  93. Conditions struct { // Conditional policy structure.
  94. Policies []struct {
  95. Operator string
  96. Key string
  97. Value string
  98. }
  99. ContentLengthRange contentLengthRange
  100. }
  101. }
  102. // ParsePostPolicyForm - Parse JSON policy string into typed PostPolicyForm structure.
  103. func ParsePostPolicyForm(policy string) (ppf PostPolicyForm, e error) {
  104. // Convert po into interfaces and
  105. // perform strict type conversion using reflection.
  106. var rawPolicy struct {
  107. Expiration string `json:"expiration"`
  108. Conditions []interface{} `json:"conditions"`
  109. }
  110. err := json.Unmarshal([]byte(policy), &rawPolicy)
  111. if err != nil {
  112. return ppf, err
  113. }
  114. parsedPolicy := PostPolicyForm{}
  115. // Parse expiry time.
  116. parsedPolicy.Expiration, err = time.Parse(time.RFC3339Nano, rawPolicy.Expiration)
  117. if err != nil {
  118. return ppf, err
  119. }
  120. // Parse conditions.
  121. for _, val := range rawPolicy.Conditions {
  122. switch condt := val.(type) {
  123. case map[string]interface{}: // Handle key:value map types.
  124. for k, v := range condt {
  125. if !isString(v) { // Pre-check value type.
  126. // All values must be of type string.
  127. return parsedPolicy, fmt.Errorf("Unknown type %s of conditional field value %s found in POST policy form", reflect.TypeOf(condt).String(), condt)
  128. }
  129. // {"acl": "public-read" } is an alternate way to indicate - [ "eq", "$acl", "public-read" ]
  130. // In this case we will just collapse this into "eq" for all use cases.
  131. parsedPolicy.Conditions.Policies = append(parsedPolicy.Conditions.Policies, struct {
  132. Operator string
  133. Key string
  134. Value string
  135. }{
  136. policyCondEqual, "$" + strings.ToLower(k), toString(v),
  137. })
  138. }
  139. case []interface{}: // Handle array types.
  140. if len(condt) != 3 { // Return error if we have insufficient elements.
  141. return parsedPolicy, fmt.Errorf("Malformed conditional fields %s of type %s found in POST policy form", condt, reflect.TypeOf(condt).String())
  142. }
  143. switch toLowerString(condt[0]) {
  144. case policyCondEqual, policyCondStartsWith:
  145. for _, v := range condt { // Pre-check all values for type.
  146. if !isString(v) {
  147. // All values must be of type string.
  148. return parsedPolicy, fmt.Errorf("Unknown type %s of conditional field value %s found in POST policy form", reflect.TypeOf(condt).String(), condt)
  149. }
  150. }
  151. operator, matchType, value := toLowerString(condt[0]), toLowerString(condt[1]), toString(condt[2])
  152. if !strings.HasPrefix(matchType, "$") {
  153. return parsedPolicy, fmt.Errorf("Invalid according to Policy: Policy Condition failed: [%s, %s, %s]", operator, matchType, value)
  154. }
  155. parsedPolicy.Conditions.Policies = append(parsedPolicy.Conditions.Policies, struct {
  156. Operator string
  157. Key string
  158. Value string
  159. }{
  160. operator, matchType, value,
  161. })
  162. case policyCondContentLength:
  163. min, err := toInteger(condt[1])
  164. if err != nil {
  165. return parsedPolicy, err
  166. }
  167. max, err := toInteger(condt[2])
  168. if err != nil {
  169. return parsedPolicy, err
  170. }
  171. parsedPolicy.Conditions.ContentLengthRange = contentLengthRange{
  172. Min: min,
  173. Max: max,
  174. Valid: true,
  175. }
  176. default:
  177. // Condition should be valid.
  178. return parsedPolicy, fmt.Errorf("Unknown type %s of conditional field value %s found in POST policy form",
  179. reflect.TypeOf(condt).String(), condt)
  180. }
  181. default:
  182. return parsedPolicy, fmt.Errorf("Unknown field %s of type %s found in POST policy form",
  183. condt, reflect.TypeOf(condt).String())
  184. }
  185. }
  186. return parsedPolicy, nil
  187. }
  188. // checkPolicyCond returns a boolean to indicate if a condition is satisified according
  189. // to the passed operator
  190. func checkPolicyCond(op string, input1, input2 string) bool {
  191. switch op {
  192. case policyCondEqual:
  193. return input1 == input2
  194. case policyCondStartsWith:
  195. return strings.HasPrefix(input1, input2)
  196. }
  197. return false
  198. }
  199. // CheckPostPolicy - apply policy conditions and validate input values.
  200. // (http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html)
  201. func CheckPostPolicy(formValues http.Header, postPolicyForm PostPolicyForm) error {
  202. // Check if policy document expiry date is still not reached
  203. if !postPolicyForm.Expiration.After(time.Now().UTC()) {
  204. return fmt.Errorf("Invalid according to Policy: Policy expired")
  205. }
  206. // map to store the metadata
  207. metaMap := make(map[string]string)
  208. for _, policy := range postPolicyForm.Conditions.Policies {
  209. if strings.HasPrefix(policy.Key, "$x-amz-meta-") {
  210. formCanonicalName := http.CanonicalHeaderKey(strings.TrimPrefix(policy.Key, "$"))
  211. metaMap[formCanonicalName] = policy.Value
  212. }
  213. }
  214. // Check if any extra metadata field is passed as input
  215. for key := range formValues {
  216. if strings.HasPrefix(key, "X-Amz-Meta-") {
  217. if _, ok := metaMap[key]; !ok {
  218. return fmt.Errorf("Invalid according to Policy: Extra input fields: %s", key)
  219. }
  220. }
  221. }
  222. // Flag to indicate if all policies conditions are satisfied
  223. var condPassed bool
  224. // Iterate over policy conditions and check them against received form fields
  225. for _, policy := range postPolicyForm.Conditions.Policies {
  226. // Form fields names are in canonical format, convert conditions names
  227. // to canonical for simplification purpose, so `$key` will become `Key`
  228. formCanonicalName := http.CanonicalHeaderKey(strings.TrimPrefix(policy.Key, "$"))
  229. // Operator for the current policy condition
  230. op := policy.Operator
  231. // If the current policy condition is known
  232. if startsWithSupported, condFound := startsWithConds[policy.Key]; condFound {
  233. // Check if the current condition supports starts-with operator
  234. if op == policyCondStartsWith && !startsWithSupported {
  235. return fmt.Errorf("Invalid according to Policy: Policy Condition failed")
  236. }
  237. // Check if current policy condition is satisfied
  238. condPassed = checkPolicyCond(op, formValues.Get(formCanonicalName), policy.Value)
  239. if !condPassed {
  240. return fmt.Errorf("Invalid according to Policy: Policy Condition failed")
  241. }
  242. } else {
  243. // This covers all conditions X-Amz-Meta-* and X-Amz-*
  244. if strings.HasPrefix(policy.Key, "$x-amz-meta-") || strings.HasPrefix(policy.Key, "$x-amz-") {
  245. // Check if policy condition is satisfied
  246. condPassed = checkPolicyCond(op, formValues.Get(formCanonicalName), policy.Value)
  247. if !condPassed {
  248. return fmt.Errorf("Invalid according to Policy: Policy Condition failed: [%s, %s, %s]", op, policy.Key, policy.Value)
  249. }
  250. }
  251. }
  252. }
  253. return nil
  254. }