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.

utils.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-2020 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. package s3utils
  18. import (
  19. "bytes"
  20. "encoding/hex"
  21. "errors"
  22. "net"
  23. "net/url"
  24. "regexp"
  25. "sort"
  26. "strings"
  27. "unicode/utf8"
  28. )
  29. // Sentinel URL is the default url value which is invalid.
  30. var sentinelURL = url.URL{}
  31. // IsValidDomain validates if input string is a valid domain name.
  32. func IsValidDomain(host string) bool {
  33. // See RFC 1035, RFC 3696.
  34. host = strings.TrimSpace(host)
  35. if len(host) == 0 || len(host) > 255 {
  36. return false
  37. }
  38. // host cannot start or end with "-"
  39. if host[len(host)-1:] == "-" || host[:1] == "-" {
  40. return false
  41. }
  42. // host cannot start or end with "_"
  43. if host[len(host)-1:] == "_" || host[:1] == "_" {
  44. return false
  45. }
  46. // host cannot start with a "."
  47. if host[:1] == "." {
  48. return false
  49. }
  50. // All non alphanumeric characters are invalid.
  51. if strings.ContainsAny(host, "`~!@#$%^&*()+={}[]|\\\"';:><?/") {
  52. return false
  53. }
  54. // No need to regexp match, since the list is non-exhaustive.
  55. // We let it valid and fail later.
  56. return true
  57. }
  58. // IsValidIP parses input string for ip address validity.
  59. func IsValidIP(ip string) bool {
  60. return net.ParseIP(ip) != nil
  61. }
  62. // IsVirtualHostSupported - verifies if bucketName can be part of
  63. // virtual host. Currently only Amazon S3 and Google Cloud Storage
  64. // would support this.
  65. func IsVirtualHostSupported(endpointURL url.URL, bucketName string) bool {
  66. if endpointURL == sentinelURL {
  67. return false
  68. }
  69. // bucketName can be valid but '.' in the hostname will fail SSL
  70. // certificate validation. So do not use host-style for such buckets.
  71. if endpointURL.Scheme == "https" && strings.Contains(bucketName, ".") {
  72. return false
  73. }
  74. // Return true for all other cases
  75. return IsAmazonEndpoint(endpointURL) || IsGoogleEndpoint(endpointURL) || IsAliyunOSSEndpoint(endpointURL)
  76. }
  77. // Refer for region styles - https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
  78. // amazonS3HostHyphen - regular expression used to determine if an arg is s3 host in hyphenated style.
  79. var amazonS3HostHyphen = regexp.MustCompile(`^s3-(.*?).amazonaws.com$`)
  80. // amazonS3HostDualStack - regular expression used to determine if an arg is s3 host dualstack.
  81. var amazonS3HostDualStack = regexp.MustCompile(`^s3.dualstack.(.*?).amazonaws.com$`)
  82. // amazonS3HostDot - regular expression used to determine if an arg is s3 host in . style.
  83. var amazonS3HostDot = regexp.MustCompile(`^s3.(.*?).amazonaws.com$`)
  84. // amazonS3ChinaHost - regular expression used to determine if the arg is s3 china host.
  85. var amazonS3ChinaHost = regexp.MustCompile(`^s3.(cn.*?).amazonaws.com.cn$`)
  86. // Regular expression used to determine if the arg is elb host.
  87. var elbAmazonRegex = regexp.MustCompile(`elb(.*?).amazonaws.com$`)
  88. // Regular expression used to determine if the arg is elb host in china.
  89. var elbAmazonCnRegex = regexp.MustCompile(`elb(.*?).amazonaws.com.cn$`)
  90. // GetRegionFromURL - returns a region from url host.
  91. func GetRegionFromURL(endpointURL url.URL) string {
  92. if endpointURL == sentinelURL {
  93. return ""
  94. }
  95. if endpointURL.Host == "s3-external-1.amazonaws.com" {
  96. return ""
  97. }
  98. if IsAmazonGovCloudEndpoint(endpointURL) {
  99. return "us-gov-west-1"
  100. }
  101. // if elb's are used we cannot calculate which region it may be, just return empty.
  102. if elbAmazonRegex.MatchString(endpointURL.Host) || elbAmazonCnRegex.MatchString(endpointURL.Host) {
  103. return ""
  104. }
  105. parts := amazonS3HostDualStack.FindStringSubmatch(endpointURL.Host)
  106. if len(parts) > 1 {
  107. return parts[1]
  108. }
  109. parts = amazonS3HostHyphen.FindStringSubmatch(endpointURL.Host)
  110. if len(parts) > 1 {
  111. return parts[1]
  112. }
  113. parts = amazonS3ChinaHost.FindStringSubmatch(endpointURL.Host)
  114. if len(parts) > 1 {
  115. return parts[1]
  116. }
  117. parts = amazonS3HostDot.FindStringSubmatch(endpointURL.Host)
  118. if len(parts) > 1 {
  119. return parts[1]
  120. }
  121. return ""
  122. }
  123. // IsAliyunOSSEndpoint - Match if it is exactly Aliyun OSS endpoint.
  124. func IsAliyunOSSEndpoint(endpointURL url.URL) bool {
  125. return strings.HasSuffix(endpointURL.Host, "aliyuncs.com")
  126. }
  127. // IsAmazonEndpoint - Match if it is exactly Amazon S3 endpoint.
  128. func IsAmazonEndpoint(endpointURL url.URL) bool {
  129. if endpointURL.Host == "s3-external-1.amazonaws.com" || endpointURL.Host == "s3.amazonaws.com" {
  130. return true
  131. }
  132. return GetRegionFromURL(endpointURL) != ""
  133. }
  134. // IsAmazonGovCloudEndpoint - Match if it is exactly Amazon S3 GovCloud endpoint.
  135. func IsAmazonGovCloudEndpoint(endpointURL url.URL) bool {
  136. if endpointURL == sentinelURL {
  137. return false
  138. }
  139. return (endpointURL.Host == "s3-us-gov-west-1.amazonaws.com" ||
  140. IsAmazonFIPSGovCloudEndpoint(endpointURL))
  141. }
  142. // IsAmazonFIPSGovCloudEndpoint - Match if it is exactly Amazon S3 FIPS GovCloud endpoint.
  143. // See https://aws.amazon.com/compliance/fips.
  144. func IsAmazonFIPSGovCloudEndpoint(endpointURL url.URL) bool {
  145. if endpointURL == sentinelURL {
  146. return false
  147. }
  148. return endpointURL.Host == "s3-fips-us-gov-west-1.amazonaws.com" ||
  149. endpointURL.Host == "s3-fips.dualstack.us-gov-west-1.amazonaws.com"
  150. }
  151. // IsAmazonFIPSUSEastWestEndpoint - Match if it is exactly Amazon S3 FIPS US East/West endpoint.
  152. // See https://aws.amazon.com/compliance/fips.
  153. func IsAmazonFIPSUSEastWestEndpoint(endpointURL url.URL) bool {
  154. if endpointURL == sentinelURL {
  155. return false
  156. }
  157. switch endpointURL.Host {
  158. case "s3-fips.us-east-2.amazonaws.com":
  159. case "s3-fips.dualstack.us-west-1.amazonaws.com":
  160. case "s3-fips.dualstack.us-west-2.amazonaws.com":
  161. case "s3-fips.dualstack.us-east-2.amazonaws.com":
  162. case "s3-fips.dualstack.us-east-1.amazonaws.com":
  163. case "s3-fips.us-west-1.amazonaws.com":
  164. case "s3-fips.us-west-2.amazonaws.com":
  165. case "s3-fips.us-east-1.amazonaws.com":
  166. default:
  167. return false
  168. }
  169. return true
  170. }
  171. // IsAmazonFIPSEndpoint - Match if it is exactly Amazon S3 FIPS endpoint.
  172. // See https://aws.amazon.com/compliance/fips.
  173. func IsAmazonFIPSEndpoint(endpointURL url.URL) bool {
  174. return IsAmazonFIPSUSEastWestEndpoint(endpointURL) || IsAmazonFIPSGovCloudEndpoint(endpointURL)
  175. }
  176. // IsGoogleEndpoint - Match if it is exactly Google cloud storage endpoint.
  177. func IsGoogleEndpoint(endpointURL url.URL) bool {
  178. if endpointURL == sentinelURL {
  179. return false
  180. }
  181. return endpointURL.Host == "storage.googleapis.com"
  182. }
  183. // Expects ascii encoded strings - from output of urlEncodePath
  184. func percentEncodeSlash(s string) string {
  185. return strings.Replace(s, "/", "%2F", -1)
  186. }
  187. // QueryEncode - encodes query values in their URL encoded form. In
  188. // addition to the percent encoding performed by urlEncodePath() used
  189. // here, it also percent encodes '/' (forward slash)
  190. func QueryEncode(v url.Values) string {
  191. if v == nil {
  192. return ""
  193. }
  194. var buf bytes.Buffer
  195. keys := make([]string, 0, len(v))
  196. for k := range v {
  197. keys = append(keys, k)
  198. }
  199. sort.Strings(keys)
  200. for _, k := range keys {
  201. vs := v[k]
  202. prefix := percentEncodeSlash(EncodePath(k)) + "="
  203. for _, v := range vs {
  204. if buf.Len() > 0 {
  205. buf.WriteByte('&')
  206. }
  207. buf.WriteString(prefix)
  208. buf.WriteString(percentEncodeSlash(EncodePath(v)))
  209. }
  210. }
  211. return buf.String()
  212. }
  213. // TagDecode - decodes canonical tag into map of key and value.
  214. func TagDecode(ctag string) map[string]string {
  215. if ctag == "" {
  216. return map[string]string{}
  217. }
  218. tags := strings.Split(ctag, "&")
  219. tagMap := make(map[string]string, len(tags))
  220. var err error
  221. for _, tag := range tags {
  222. kvs := strings.SplitN(tag, "=", 2)
  223. if len(kvs) == 0 {
  224. return map[string]string{}
  225. }
  226. if len(kvs) == 1 {
  227. return map[string]string{}
  228. }
  229. tagMap[kvs[0]], err = url.PathUnescape(kvs[1])
  230. if err != nil {
  231. continue
  232. }
  233. }
  234. return tagMap
  235. }
  236. // TagEncode - encodes tag values in their URL encoded form. In
  237. // addition to the percent encoding performed by urlEncodePath() used
  238. // here, it also percent encodes '/' (forward slash)
  239. func TagEncode(tags map[string]string) string {
  240. if tags == nil {
  241. return ""
  242. }
  243. values := url.Values{}
  244. for k, v := range tags {
  245. values[k] = []string{v}
  246. }
  247. return QueryEncode(values)
  248. }
  249. // if object matches reserved string, no need to encode them
  250. var reservedObjectNames = regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$")
  251. // EncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences
  252. //
  253. // This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
  254. // non english characters cannot be parsed due to the nature in which url.Encode() is written
  255. //
  256. // This function on the other hand is a direct replacement for url.Encode() technique to support
  257. // pretty much every UTF-8 character.
  258. func EncodePath(pathName string) string {
  259. if reservedObjectNames.MatchString(pathName) {
  260. return pathName
  261. }
  262. var encodedPathname strings.Builder
  263. for _, s := range pathName {
  264. if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
  265. encodedPathname.WriteRune(s)
  266. continue
  267. }
  268. switch s {
  269. case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
  270. encodedPathname.WriteRune(s)
  271. continue
  272. default:
  273. len := utf8.RuneLen(s)
  274. if len < 0 {
  275. // if utf8 cannot convert return the same string as is
  276. return pathName
  277. }
  278. u := make([]byte, len)
  279. utf8.EncodeRune(u, s)
  280. for _, r := range u {
  281. hex := hex.EncodeToString([]byte{r})
  282. encodedPathname.WriteString("%" + strings.ToUpper(hex))
  283. }
  284. }
  285. }
  286. return encodedPathname.String()
  287. }
  288. // We support '.' with bucket names but we fallback to using path
  289. // style requests instead for such buckets.
  290. var (
  291. validBucketName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9\.\-\_\:]{1,61}[A-Za-z0-9]$`)
  292. validBucketNameStrict = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`)
  293. ipAddress = regexp.MustCompile(`^(\d+\.){3}\d+$`)
  294. )
  295. // Common checker for both stricter and basic validation.
  296. func checkBucketNameCommon(bucketName string, strict bool) (err error) {
  297. if strings.TrimSpace(bucketName) == "" {
  298. return errors.New("Bucket name cannot be empty")
  299. }
  300. if len(bucketName) < 3 {
  301. return errors.New("Bucket name cannot be shorter than 3 characters")
  302. }
  303. if len(bucketName) > 63 {
  304. return errors.New("Bucket name cannot be longer than 63 characters")
  305. }
  306. if ipAddress.MatchString(bucketName) {
  307. return errors.New("Bucket name cannot be an ip address")
  308. }
  309. if strings.Contains(bucketName, "..") || strings.Contains(bucketName, ".-") || strings.Contains(bucketName, "-.") {
  310. return errors.New("Bucket name contains invalid characters")
  311. }
  312. if strict {
  313. if !validBucketNameStrict.MatchString(bucketName) {
  314. err = errors.New("Bucket name contains invalid characters")
  315. }
  316. return err
  317. }
  318. if !validBucketName.MatchString(bucketName) {
  319. err = errors.New("Bucket name contains invalid characters")
  320. }
  321. return err
  322. }
  323. // CheckValidBucketName - checks if we have a valid input bucket name.
  324. func CheckValidBucketName(bucketName string) (err error) {
  325. return checkBucketNameCommon(bucketName, false)
  326. }
  327. // CheckValidBucketNameStrict - checks if we have a valid input bucket name.
  328. // This is a stricter version.
  329. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
  330. func CheckValidBucketNameStrict(bucketName string) (err error) {
  331. return checkBucketNameCommon(bucketName, true)
  332. }
  333. // CheckValidObjectNamePrefix - checks if we have a valid input object name prefix.
  334. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
  335. func CheckValidObjectNamePrefix(objectName string) error {
  336. if len(objectName) > 1024 {
  337. return errors.New("Object name cannot be longer than 1024 characters")
  338. }
  339. if !utf8.ValidString(objectName) {
  340. return errors.New("Object name with non UTF-8 strings are not supported")
  341. }
  342. return nil
  343. }
  344. // CheckValidObjectName - checks if we have a valid input object name.
  345. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
  346. func CheckValidObjectName(objectName string) error {
  347. if strings.TrimSpace(objectName) == "" {
  348. return errors.New("Object name cannot be empty")
  349. }
  350. return CheckValidObjectNamePrefix(objectName)
  351. }