utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-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. 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)
  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. // GetRegionFromURL - returns a region from url host.
  87. func GetRegionFromURL(endpointURL url.URL) string {
  88. if endpointURL == sentinelURL {
  89. return ""
  90. }
  91. if endpointURL.Host == "s3-external-1.amazonaws.com" {
  92. return ""
  93. }
  94. if IsAmazonGovCloudEndpoint(endpointURL) {
  95. return "us-gov-west-1"
  96. }
  97. parts := amazonS3HostDualStack.FindStringSubmatch(endpointURL.Host)
  98. if len(parts) > 1 {
  99. return parts[1]
  100. }
  101. parts = amazonS3HostHyphen.FindStringSubmatch(endpointURL.Host)
  102. if len(parts) > 1 {
  103. return parts[1]
  104. }
  105. parts = amazonS3ChinaHost.FindStringSubmatch(endpointURL.Host)
  106. if len(parts) > 1 {
  107. return parts[1]
  108. }
  109. parts = amazonS3HostDot.FindStringSubmatch(endpointURL.Host)
  110. if len(parts) > 1 {
  111. return parts[1]
  112. }
  113. return ""
  114. }
  115. // IsAmazonEndpoint - Match if it is exactly Amazon S3 endpoint.
  116. func IsAmazonEndpoint(endpointURL url.URL) bool {
  117. if endpointURL.Host == "s3-external-1.amazonaws.com" || endpointURL.Host == "s3.amazonaws.com" {
  118. return true
  119. }
  120. return GetRegionFromURL(endpointURL) != ""
  121. }
  122. // IsAmazonGovCloudEndpoint - Match if it is exactly Amazon S3 GovCloud endpoint.
  123. func IsAmazonGovCloudEndpoint(endpointURL url.URL) bool {
  124. if endpointURL == sentinelURL {
  125. return false
  126. }
  127. return (endpointURL.Host == "s3-us-gov-west-1.amazonaws.com" ||
  128. IsAmazonFIPSGovCloudEndpoint(endpointURL))
  129. }
  130. // IsAmazonFIPSGovCloudEndpoint - Match if it is exactly Amazon S3 FIPS GovCloud endpoint.
  131. // See https://aws.amazon.com/compliance/fips.
  132. func IsAmazonFIPSGovCloudEndpoint(endpointURL url.URL) bool {
  133. if endpointURL == sentinelURL {
  134. return false
  135. }
  136. return endpointURL.Host == "s3-fips-us-gov-west-1.amazonaws.com" ||
  137. endpointURL.Host == "s3-fips.dualstack.us-gov-west-1.amazonaws.com"
  138. }
  139. // IsAmazonFIPSUSEastWestEndpoint - Match if it is exactly Amazon S3 FIPS US East/West endpoint.
  140. // See https://aws.amazon.com/compliance/fips.
  141. func IsAmazonFIPSUSEastWestEndpoint(endpointURL url.URL) bool {
  142. if endpointURL == sentinelURL {
  143. return false
  144. }
  145. switch endpointURL.Host {
  146. case "s3-fips.us-east-2.amazonaws.com":
  147. case "s3-fips.dualstack.us-west-1.amazonaws.com":
  148. case "s3-fips.dualstack.us-west-2.amazonaws.com":
  149. case "s3-fips.dualstack.us-east-2.amazonaws.com":
  150. case "s3-fips.dualstack.us-east-1.amazonaws.com":
  151. case "s3-fips.us-west-1.amazonaws.com":
  152. case "s3-fips.us-west-2.amazonaws.com":
  153. case "s3-fips.us-east-1.amazonaws.com":
  154. default:
  155. return false
  156. }
  157. return true
  158. }
  159. // IsAmazonFIPSEndpoint - Match if it is exactly Amazon S3 FIPS endpoint.
  160. // See https://aws.amazon.com/compliance/fips.
  161. func IsAmazonFIPSEndpoint(endpointURL url.URL) bool {
  162. return IsAmazonFIPSUSEastWestEndpoint(endpointURL) || IsAmazonFIPSGovCloudEndpoint(endpointURL)
  163. }
  164. // IsGoogleEndpoint - Match if it is exactly Google cloud storage endpoint.
  165. func IsGoogleEndpoint(endpointURL url.URL) bool {
  166. if endpointURL == sentinelURL {
  167. return false
  168. }
  169. return endpointURL.Host == "storage.googleapis.com"
  170. }
  171. // Expects ascii encoded strings - from output of urlEncodePath
  172. func percentEncodeSlash(s string) string {
  173. return strings.Replace(s, "/", "%2F", -1)
  174. }
  175. // QueryEncode - encodes query values in their URL encoded form. In
  176. // addition to the percent encoding performed by urlEncodePath() used
  177. // here, it also percent encodes '/' (forward slash)
  178. func QueryEncode(v url.Values) string {
  179. if v == nil {
  180. return ""
  181. }
  182. var buf bytes.Buffer
  183. keys := make([]string, 0, len(v))
  184. for k := range v {
  185. keys = append(keys, k)
  186. }
  187. sort.Strings(keys)
  188. for _, k := range keys {
  189. vs := v[k]
  190. prefix := percentEncodeSlash(EncodePath(k)) + "="
  191. for _, v := range vs {
  192. if buf.Len() > 0 {
  193. buf.WriteByte('&')
  194. }
  195. buf.WriteString(prefix)
  196. buf.WriteString(percentEncodeSlash(EncodePath(v)))
  197. }
  198. }
  199. return buf.String()
  200. }
  201. // if object matches reserved string, no need to encode them
  202. var reservedObjectNames = regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$")
  203. // EncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences
  204. //
  205. // This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
  206. // non english characters cannot be parsed due to the nature in which url.Encode() is written
  207. //
  208. // This function on the other hand is a direct replacement for url.Encode() technique to support
  209. // pretty much every UTF-8 character.
  210. func EncodePath(pathName string) string {
  211. if reservedObjectNames.MatchString(pathName) {
  212. return pathName
  213. }
  214. var encodedPathname string
  215. for _, s := range pathName {
  216. if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
  217. encodedPathname = encodedPathname + string(s)
  218. continue
  219. }
  220. switch s {
  221. case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
  222. encodedPathname = encodedPathname + string(s)
  223. continue
  224. default:
  225. len := utf8.RuneLen(s)
  226. if len < 0 {
  227. // if utf8 cannot convert return the same string as is
  228. return pathName
  229. }
  230. u := make([]byte, len)
  231. utf8.EncodeRune(u, s)
  232. for _, r := range u {
  233. hex := hex.EncodeToString([]byte{r})
  234. encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
  235. }
  236. }
  237. }
  238. return encodedPathname
  239. }
  240. // We support '.' with bucket names but we fallback to using path
  241. // style requests instead for such buckets.
  242. var (
  243. validBucketName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9\.\-\_\:]{1,61}[A-Za-z0-9]$`)
  244. validBucketNameStrict = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`)
  245. ipAddress = regexp.MustCompile(`^(\d+\.){3}\d+$`)
  246. )
  247. // Common checker for both stricter and basic validation.
  248. func checkBucketNameCommon(bucketName string, strict bool) (err error) {
  249. if strings.TrimSpace(bucketName) == "" {
  250. return errors.New("Bucket name cannot be empty")
  251. }
  252. if len(bucketName) < 3 {
  253. return errors.New("Bucket name cannot be smaller than 3 characters")
  254. }
  255. if len(bucketName) > 63 {
  256. return errors.New("Bucket name cannot be greater than 63 characters")
  257. }
  258. if ipAddress.MatchString(bucketName) {
  259. return errors.New("Bucket name cannot be an ip address")
  260. }
  261. if strings.Contains(bucketName, "..") || strings.Contains(bucketName, ".-") || strings.Contains(bucketName, "-.") {
  262. return errors.New("Bucket name contains invalid characters")
  263. }
  264. if strict {
  265. if !validBucketNameStrict.MatchString(bucketName) {
  266. err = errors.New("Bucket name contains invalid characters")
  267. }
  268. return err
  269. }
  270. if !validBucketName.MatchString(bucketName) {
  271. err = errors.New("Bucket name contains invalid characters")
  272. }
  273. return err
  274. }
  275. // CheckValidBucketName - checks if we have a valid input bucket name.
  276. func CheckValidBucketName(bucketName string) (err error) {
  277. return checkBucketNameCommon(bucketName, false)
  278. }
  279. // CheckValidBucketNameStrict - checks if we have a valid input bucket name.
  280. // This is a stricter version.
  281. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
  282. func CheckValidBucketNameStrict(bucketName string) (err error) {
  283. return checkBucketNameCommon(bucketName, true)
  284. }
  285. // CheckValidObjectNamePrefix - checks if we have a valid input object name prefix.
  286. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
  287. func CheckValidObjectNamePrefix(objectName string) error {
  288. if len(objectName) > 1024 {
  289. return errors.New("Object name cannot be greater than 1024 characters")
  290. }
  291. if !utf8.ValidString(objectName) {
  292. return errors.New("Object name with non UTF-8 strings are not supported")
  293. }
  294. return nil
  295. }
  296. // CheckValidObjectName - checks if we have a valid input object name.
  297. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
  298. func CheckValidObjectName(objectName string) error {
  299. if strings.TrimSpace(objectName) == "" {
  300. return errors.New("Object name cannot be empty")
  301. }
  302. return CheckValidObjectNamePrefix(objectName)
  303. }