예제 #1
0
        /// <remarks>This method has a asynchronous alternative.</remarks>
        public static string Calculate(HttpContent?content)
        {
            // Use a hash (digest) function like SHA256 to create a hashed value from the payload
            // in the body of the HTTP or HTTPS request.
            //
            // If the payload is empty, use an empty string as the input to the hash function.
            if (content == null)
            {
                // Per performance reasons, use the pre-computed hash of an empty string from the
                // AWS SDK
                return(AWS4Signer.EmptyBodySha256);
            }

            var contentStream = content.ReadAsStream();
            var hash          = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(contentStream);

            return(AWSSDKUtils.ToHex(hash, true));
        }
예제 #2
0
        public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            if (string.IsNullOrEmpty(awsAccessKeyId))
            {
                throw new ArgumentOutOfRangeException("awsAccessKeyId", "The AWS Access Key ID cannot be NULL or a Zero length string");
            }
            request.Parameters["AWSAccessKeyId"]   = awsAccessKeyId;
            request.Parameters["SignatureVersion"] = clientConfig.SignatureVersion;
            request.Parameters["SignatureMethod"]  = clientConfig.SignatureMethod.ToString();
            request.Parameters["Timestamp"]        = AWSSDKUtils.FormattedCurrentTimestampISO8601;
            request.Parameters.Remove("Signature");
            string text = AWSSDKUtils.CalculateStringToSignV2(request.Parameters, request.Endpoint.AbsoluteUri);

            metrics.AddProperty(Metric.StringToSign, text);
            string value = AbstractAWSSigner.ComputeHash(text, awsSecretAccessKey, clientConfig.SignatureMethod);

            request.Parameters["Signature"] = value;
        }
예제 #3
0
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            var sac = obj as SessionAWSCredentials;

            if (sac == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { _lastCredentials },
                       new object[] { sac._lastCredentials }));
        }
예제 #4
0
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            SSOImmutableCredentials ssoImmutableCredentials = obj as SSOImmutableCredentials;

            if (ssoImmutableCredentials == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { AccessKey, SecretKey, Token, Expiration },
                       new object[] { ssoImmutableCredentials.AccessKey, ssoImmutableCredentials.SecretKey, ssoImmutableCredentials.Token, Expiration }));
        }
        public async Task <CredentialsRefreshState> DetermineProcessCredentialAsync()
        {
            try
            {
                var processInfo = await AWSSDKUtils.RunProcessAsync(_processStartInfo).ConfigureAwait(false);

                return(SetCredentialsRefreshState(processInfo));
            }
            catch (ProcessAWSCredentialException)
            {
                throw;
            }
            catch (Exception e)
            {
                _logger.DebugFormat("Process recorded exception - {0}", e);
                throw new ProcessAWSCredentialException(string.Format(CultureInfo.CurrentCulture, "AWS credential process terminated with {0}", e.GetType()), e);
            }
        }
        /// <summary>
        /// Gets the persisted grant.
        /// </summary>
        /// <returns>The persisted grant.</returns>
        /// <param name="pgd">Pgd.</param>
        public static PersistedGrant GetPersistedGrant(this PersistedGrantDynamoDB pgd)
        {
            if (pgd == null)
            {
                return(null);
            }

            return(new PersistedGrant
            {
                Key = pgd.Key,
                ClientId = pgd.ClientId,
                SubjectId = pgd.SubjectId,
                Type = pgd.Type,
                CreationTime = AWSSDKUtils.ConvertFromUnixEpochSeconds(pgd.CreationTime),
                Expiration = AWSSDKUtils.ConvertFromUnixEpochSeconds(pgd.Expiration),
                Data = pgd.Data
            });
        }
        /// <summary>
        /// Gets the persisted grant dynamo db.
        /// </summary>
        /// <returns>The persisted grant dynamo db.</returns>
        /// <param name="pg">Pg.</param>
        public static PersistedGrantDynamoDB GetPersistedGrantDynamoDB(this PersistedGrant pg)
        {
            if (pg == null)
            {
                return(null);
            }

            return(new PersistedGrantDynamoDB
            {
                Key = pg.Key,
                ClientId = pg.ClientId,
                SubjectId = pg.SubjectId,
                Type = pg.Type,
                CreationTime = AWSSDKUtils.ConvertToUnixEpochSeconds(pg.CreationTime),
                Expiration = AWSSDKUtils.ConvertToUnixEpochSeconds(pg.Expiration.Value),
                Data = pg.Data
            });
        }
예제 #8
0
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            ImmutableCredentials ic = obj as ImmutableCredentials;

            if (ic == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { AccessKey, SecretKey, Token },
                       new object[] { ic.AccessKey, ic.SecretKey, ic.Token }));
        }
예제 #9
0
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            var bac = obj as BasicAWSCredentials;

            if (bac == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { _credentials },
                       new object[] { bac._credentials }));
        }
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            AssumeRoleImmutableCredentials aric = obj as AssumeRoleImmutableCredentials;

            if (aric == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { AccessKey, SecretKey, Token, Expiration },
                       new object[] { aric.AccessKey, aric.SecretKey, aric.Token, Expiration }));
        }
예제 #11
0
        /// <summary>
        /// Inspects the supplied evidence to return the signer appropriate for the operation
        /// </summary>
        /// <param name="useSigV4Setting">Global setting for the service</param>
        /// <param name="request">The request.</param>
        /// <param name="config">Configuration for the client</param>
        /// <returns>True if signature v4 request signing should be used</returns>
        protected static bool UseV4Signing(bool useSigV4Setting, IRequest request, IClientConfig config)
        {
            if (request.UseSigV4 ||
                config.SignatureVersion == "4" ||
                (useSigV4Setting && config.SignatureVersion != "2"))
            {
                return(true);
            }
            else
            {
                // do a cascading series of checks to try and arrive at whether we have
                // a recognisable region; this is required to use the AWS4 signer
                RegionEndpoint r = null;
                if (!string.IsNullOrEmpty(request.AuthenticationRegion))
                {
                    r = RegionEndpoint.GetBySystemName(request.AuthenticationRegion);
                }

                if (r == null && !string.IsNullOrEmpty(config.ServiceURL))
                {
                    var parsedRegion = AWSSDKUtils.DetermineRegion(config.ServiceURL);
                    if (!string.IsNullOrEmpty(parsedRegion))
                    {
                        r = RegionEndpoint.GetBySystemName(parsedRegion);
                    }
                }

                if (r == null && config.RegionEndpoint != null)
                {
                    r = config.RegionEndpoint;
                }

                if (r != null)
                {
                    var endpoint = r.GetEndpointForService(config.RegionEndpointServiceName, config.UseDualstackEndpoint);
                    if (endpoint != null && (endpoint.SignatureVersionOverride == "4" || string.IsNullOrEmpty(endpoint.SignatureVersionOverride)))
                    {
                        return(true);
                    }
                }

                return(false);
            }
        }
예제 #12
0
        /// <summary>
        /// Signs the specified request with the AWS2 signing protocol by using the
        /// AWS account credentials given in the method parameters.
        /// </summary>
        /// <param name="awsAccessKeyId">The AWS public key</param>
        /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
        /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
        /// <param name="request">The request to have the signature compute for</param>
        /// <param name="secureKey">The AWS secret key stored in a secure string</param>
        /// <param name="metrics">Request metrics</param>
        /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            if (String.IsNullOrEmpty(awsAccessKeyId))
            {
                throw new Exception("The AWS Access Key ID cannot be NULL or a Zero length string");
            }

            request.Parameters["AWSAccessKeyId"]   = awsAccessKeyId;
            request.Parameters["SignatureVersion"] = clientConfig.SignatureVersion;
            request.Parameters["SignatureMethod"]  = clientConfig.SignatureMethod.ToString();
            request.Parameters["Timestamp"]        = AWSSDKUtils.FormattedCurrentTimestampISO8601;

            string toSign = AWSSDKUtils.CalculateStringToSignV2(request.Parameters, clientConfig.DetermineServiceURL());

            metrics.AddProperty(RequestMetrics.Metric.StringToSign, toSign);
            string auth = ComputeHash(toSign, awsSecretAccessKey, secureKey, clientConfig.SignatureMethod);

            request.Parameters["Signature"] = auth;
        }
예제 #13
0
        public static Uri ComposeUrl(IRequest iRequest)
        {
            Uri    endpoint = iRequest.Endpoint;
            string text     = iRequest.ResourcePath;

            if (text == null)
            {
                text = string.Empty;
            }
            else if (text.StartsWith("/", StringComparison.Ordinal))
            {
                text = text.Substring(1);
            }
            string        arg           = "?";
            StringBuilder stringBuilder = new StringBuilder();

            if (iRequest.SubResources.Count > 0)
            {
                foreach (KeyValuePair <string, string> subResource in iRequest.SubResources)
                {
                    stringBuilder.AppendFormat("{0}{1}", arg, subResource.Key);
                    if (subResource.Value != null)
                    {
                        stringBuilder.AppendFormat("={0}", subResource.Value);
                    }
                    arg = "&";
                }
            }
            if (iRequest.UseQueryString && iRequest.Parameters.Count > 0)
            {
                string parametersAsString = AWSSDKUtils.GetParametersAsString(iRequest.Parameters);
                stringBuilder.AppendFormat("{0}{1}", arg, parametersAsString);
            }
            if (AWSSDKUtils.HasBidiControlCharacters(text))
            {
                throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "Target resource path [{0}] has bidirectional characters, which are not supportedby System.Uri and thus cannot be handled by the .NET SDK.", text));
            }
            string str = AWSSDKUtils.UrlEncode(text, path: true) + stringBuilder;
            Uri    uri = new Uri(endpoint.AbsoluteUri + str);

            DontUnescapePathDotsAndSlashes(uri);
            return(uri);
        }
예제 #14
0
        /// <summary>
        /// Creates the HttpWebRequest and configures the end point, content, user agent and proxy settings.
        /// </summary>
        /// <param name="requestContext">The async request.</param>
        /// <returns>The web request that actually makes the call.</returns>
        protected virtual IHttpRequest <TRequestContent> CreateWebRequest(IRequestContext requestContext)
        {
            IRequest request     = requestContext.Request;
            Uri      url         = AmazonServiceClient.ComposeUrl(request);
            var      httpRequest = _requestFactory.CreateHttpRequest(url);

            httpRequest.ConfigureRequest(requestContext);

            httpRequest.Method = request.HttpMethod;
            if (request.MayContainRequestBody())
            {
                if (request.Content == null && request.ContentStream == null)
                {
                    string queryString = AWSSDKUtils.GetParametersAsString(request.Parameters);
                    request.Content = Encoding.UTF8.GetBytes(queryString);
                }

                if (request.Content != null)
                {
                    request.Headers[HeaderKeys.ContentLengthHeader] =
                        request.Content.Length.ToString(CultureInfo.InvariantCulture);
                }
                else if (request.ContentStream != null && !request.Headers.ContainsKey(HeaderKeys.ContentLengthHeader))
                {
                    request.Headers[HeaderKeys.ContentLengthHeader] =
                        request.ContentStream.Length.ToString(CultureInfo.InvariantCulture);
                }
            }
            else if (request.UseQueryString &&
                     (request.HttpMethod == "POST" ||
                      request.HttpMethod == "PUT"))
            {
                request.Content = new Byte[0];
            }

            if (requestContext.Unmarshaller is JsonResponseUnmarshaller)
            {
                // Currently the signature seems to be valid without including this header in the calculation.
                request.Headers["Accept"] = "application/json";
            }

            return(httpRequest);
        }
예제 #15
0
        public Dictionary <string, AttributeValue> GetAttributes()
        {
            Guid guid = Guid.NewGuid();

            Dictionary <string, AttributeValue> attributes = new Dictionary <string, AttributeValue>();

            attributes["_id"] = new AttributeValue {
                S = guid.ToString()
            };
            // Title is range-key
            attributes["publisher"] = new AttributeValue {
                S = doctor
            };
            // Other attributes

            attributes["subscriber"] = new AttributeValue {
                S = patient
            };
            attributes["createdBy"] = new AttributeValue {
                S = createdBy
            };

            attributes["body"] = new AttributeValue {
                S = message
            };
            //{
            //    SS = new List<string> { "Please come to the appointment for " +  doctor + " at " + scheduled.ToLongDateString(), "ATT:503-809-1602" }
            //};
            attributes["type"] = new AttributeValue {
                S = _type
            };
            attributes["seq"] = new AttributeValue {
                N = "1"
            };

            int epochSeconds = AWSSDKUtils.ConvertToUnixEpochSeconds(DateTime.Now.AddMinutes(0.5).ToUniversalTime());

            attributes["scheduled"] = new AttributeValue {
                N = epochSeconds.ToString()
            };

            return(attributes);
        }
        public static async Task <string> CalculateAsync(HttpContent content)
        {
            // Use a hash (digest) function like SHA256 to create a hashed value from the payload
            // in the body of the HTTP or HTTPS request.
            //
            // If the payload is empty, use an empty string as the input to the hash function.
            if (content == null)
            {
                // Per performance reasons, use the pre-computed hash of an empty string from the
                // AWS SDK
                return(AWS4Signer.EmptyBodySha256);
            }

            var data = await content.ReadAsByteArrayAsync();

            var hash = AWS4Signer.ComputeHash(data);

            return(AWSSDKUtils.ToHex(hash, true));
        }
예제 #17
0
        /// <summary>
        /// Computes and returns the canonicalized query string, if query parameters have been supplied.
        /// Parameters with no value will be canonicalized as 'param='. The expectation is that parameters
        /// have not already been url encoded prior to canonicalization.
        /// </summary>
        /// <param name="parameters">The set of parameters to be encoded in the query string</param>
        /// <param name="uriEncodeParameters">
        /// Parameters must be uri encoded into the canonical request and by default the signer expects
        /// that the supplied collection contains non-encoded data. Set this to false if the encoding was
        /// done prior to signer entry.
        /// </param>
        /// <returns>The uri encoded query string parameters in canonical ordering</returns>
        protected static string CanonicalizeQueryParameters(IDictionary <string, string> parameters,
                                                            bool uriEncodeParameters = true)
        {
            if (parameters == null || parameters.Count == 0)
            {
                return(string.Empty);
            }

            var canonicalQueryString = new StringBuilder();
            var queryParams          = new SortedDictionary <string, string>(parameters, StringComparer.Ordinal);

            foreach (var p in queryParams)
            {
                if (canonicalQueryString.Length > 0)
                {
                    canonicalQueryString.Append("&");
                }
                if (uriEncodeParameters)
                {
                    if (string.IsNullOrEmpty(p.Value))
                    {
                        canonicalQueryString.AppendFormat("{0}=", AWSSDKUtils.UrlEncode(p.Key, false));
                    }
                    else
                    {
                        canonicalQueryString.AppendFormat("{0}={1}", AWSSDKUtils.UrlEncode(p.Key, false), AWSSDKUtils.UrlEncode(p.Value, false));
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(p.Value))
                    {
                        canonicalQueryString.AppendFormat("{0}=", p.Key);
                    }
                    else
                    {
                        canonicalQueryString.AppendFormat("{0}={1}", p.Key, p.Value);
                    }
                }
            }

            return(canonicalQueryString.ToString());
        }
예제 #18
0
        private X509Certificate2 GetX509Certificate()
        {
            lock (certificateCache)
            {
                if (certificateCache.ContainsKey(this.SigningCertURL))
                {
                    return(certificateCache[this.SigningCertURL]);
                }
                else
                {
                    for (int retries = 1; retries <= MAX_RETRIES; retries++)
                    {
                        try
                        {
                            HttpWebRequest request = HttpWebRequest.Create(this.SigningCertURL) as HttpWebRequest;
                            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                                using (var reader = new StreamReader(response.GetResponseStream()))
                                {
                                    var content   = reader.ReadToEnd().Trim();
                                    var pemObject = new PemReader(new StringReader(content)).ReadPemObject();

                                    X509Certificate2 certificate = new X509Certificate2(pemObject.Content);
                                    certificateCache[this.SigningCertURL] = certificate;
                                    return(certificate);
                                }
                        }
                        catch (Exception e)
                        {
                            if (retries == MAX_RETRIES)
                            {
                                throw new Exception(string.Format("Unable to download signing cert after {0} retries", MAX_RETRIES), e);
                            }
                            else
                            {
                                AWSSDKUtils.Sleep((int)(Math.Pow(4, retries) * 100));
                            }
                        }
                    }
                }

                throw new Exception(string.Format("Unable to download signing cert after {0} retries", MAX_RETRIES));
            }
        }
        private byte[] GetRequestData(IRequest request)
        {
            byte[] requestData;
            if (request.Content == null)
            {
                string queryString = AWSSDKUtils.GetParametersAsString(request.Parameters);
                requestData = Encoding.UTF8.GetBytes(queryString);
            }
            else
            {
                requestData = request.Content;
            }

            if (logger.IsDebugEnabled)
            {
                this.logger.DebugFormat("Request body's content size {0}", requestData.Length);
            }
            return(requestData);
        }
예제 #20
0
 public string ComputeContentStreamHash()
 {
     if (contentStream == null)
     {
         return(null);
     }
     if (contentStreamHash == null)
     {
         Stream stream = WrapperStream.SearchWrappedStream(contentStream, (Stream s) => s.CanSeek);
         if (stream != null)
         {
             long   position = stream.Position;
             byte[] data     = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(stream);
             contentStreamHash = AWSSDKUtils.ToHex(data, lowercase: true);
             stream.Seek(position, SeekOrigin.Begin);
         }
     }
     return(contentStreamHash);
 }
예제 #21
0
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            var p = obj as CredentialProfile;

            if (p == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { Name, Options, Region, ProfileType, CanCreateAWSCredentials, UniqueKey },
                       new object[] { p.Name, p.Options, p.Region, p.ProfileType, p.CanCreateAWSCredentials, p.UniqueKey }) &&
                   AWSSDKUtils.DictionariesAreEqual(Properties, p.Properties));
        }
        /// <summary>
        /// Generate a policy document that describes custom access permissions to
        /// apply via a private distribution's signed URL.
        /// </summary>
        /// <param name="resourcePath">
        /// An optional HTTP/S or RTMP resource path that restricts which
        /// distribution and S3 objects will be accessible in a signed
        /// URL. For standard distributions the resource URL will be
        /// <tt>"http://" + distributionName + "/" + path</tt> (may
        /// also include URL parameters. For distributions with the HTTPS
        /// required protocol, the resource URL must start with
        /// <tt>"https://"</tt>. RTMP resources do not take the form of a
        /// URL, and instead the resource path is nothing but the stream's
        /// name. The '*' and '?' characters can be used as a wildcards to
        /// allow multi-character or single-character matches
        /// respectively:
        /// <ul>
        /// <li><tt>*</tt> : All distributions/objects will be accessible</li>
        /// <li><tt>a1b2c3d4e5f6g7.cloudfront.net/*</tt> : All objects
        /// within the distribution a1b2c3d4e5f6g7 will be accessible</li>
        /// <li><tt>a1b2c3d4e5f6g7.cloudfront.net/path/to/object.txt</tt>
        /// : Only the S3 object named <tt>path/to/object.txt</tt> in the
        /// distribution a1b2c3d4e5f6g7 will be accessible.</li>
        /// </ul>
        /// If this parameter is null the policy will permit access to all
        /// distributions and S3 objects associated with the certificate
        /// keypair used to generate the signed URL.
        /// </param>
        /// <param name="expiresOn">The time and date when the signed URL will expire.</param>
        /// <param name="limitToIpAddressCIDR">An optional range of client IP addresses that will be allowed
        /// to access the distribution, specified as a CIDR range. If
        /// null, the CIDR will be <tt>0.0.0.0/0</tt> and any client will
        /// be permitted.</param>
        /// <param name="activeFrom">An optional UTC time and date when the signed URL will become
        /// active. A value of DateTime.MinValue (the default value of DateTime) is ignored.
        /// </param>
        /// <returns>A policy document describing the access permission to apply when
        /// generating a signed URL.</returns>
        public static string BuildPolicyForSignedUrl(string resourcePath,
                                                     DateTime expiresOn,
                                                     string limitToIpAddressCIDR,
                                                     DateTime activeFrom)
        {
            // Reference:
            // http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html#private-content-custom-policy-statement

            // Validate if activeFrom (time at which the URL will be active)
            // is less than expiresOn (time at which the URL will expire)
            if (activeFrom > expiresOn)
            {
                throw new AmazonClientException("The parameter activeFrom (time at which the URL will be active)" +
                                                "must be less than expiresOn (time at which the URL will expire).");
            }

            if (resourcePath == null)
            {
                resourcePath = "*";
            }
            string ipAddress = (string.IsNullOrEmpty(limitToIpAddressCIDR) ? "0.0.0.0/0" // No IP restriction
                    : limitToIpAddressCIDR);

            string policy = "{\"Statement\": [{"
                            + "\"Resource\":\""
                            + resourcePath
                            + "\""
                            + ",\"Condition\":{"
                            + "\"DateLessThan\":{\"AWS:EpochTime\":"
                            + AWSSDKUtils.ConvertToUnixEpochSeconds(expiresOn.ToUniversalTime())
                            + "}"
                            + ",\"IpAddress\":{\"AWS:SourceIp\":\""
                            + ipAddress
                            + "\"}"
                            // Ignore epochDateGreaterThan if its value is DateTime.MinValue, the default value of DateTime.
                            + (activeFrom > DateTime.MinValue ? ",\"DateGreaterThan\":{\"AWS:EpochTime\":"
                               + AWSSDKUtils.ConvertToUnixEpochSeconds(activeFrom.ToUniversalTime()) + "}"
                            : string.Empty)
                            + "}}]}";

            return(policy);
        }
예제 #23
0
        public static string DetermineSigningRegion(IClientConfig clientConfig, string serviceName, RegionEndpoint alternateEndpoint, IRequest request)
        {
            if (alternateEndpoint != null)
            {
                RegionEndpoint.Endpoint endpointForService = alternateEndpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint);
                if (endpointForService.AuthRegion != null)
                {
                    return(endpointForService.AuthRegion);
                }
                return(alternateEndpoint.SystemName);
            }
            string authenticationRegion = clientConfig.AuthenticationRegion;

            if (request != null && request.AuthenticationRegion != null)
            {
                authenticationRegion = request.AuthenticationRegion;
            }
            if (!string.IsNullOrEmpty(authenticationRegion))
            {
                return(authenticationRegion.ToLowerInvariant());
            }
            if (!string.IsNullOrEmpty(clientConfig.ServiceURL))
            {
                string text = AWSSDKUtils.DetermineRegion(clientConfig.ServiceURL);
                if (!string.IsNullOrEmpty(text))
                {
                    return(text.ToLowerInvariant());
                }
            }
            RegionEndpoint regionEndpoint = clientConfig.RegionEndpoint;

            if (regionEndpoint != null)
            {
                RegionEndpoint.Endpoint endpointForService2 = regionEndpoint.GetEndpointForService(serviceName, clientConfig.UseDualstackEndpoint);
                if (!string.IsNullOrEmpty(endpointForService2.AuthRegion))
                {
                    return(endpointForService2.AuthRegion);
                }
                return(regionEndpoint.SystemName);
            }
            return(string.Empty);
        }
예제 #24
0
        /// <summary>
        /// Creates the HttpWebRequest and configures the end point, content, user agent and proxy settings.
        /// </summary>
        /// <param name="requestContext">The async request.</param>
        /// <returns>The web request that actually makes the call.</returns>
        protected virtual IHttpRequest <TRequestContent> CreateWebRequest(IRequestContext requestContext)
        {
            IRequest request     = requestContext.Request;
            Uri      url         = AmazonServiceClient.ComposeUrl(request);
            var      httpRequest = _requestFactory.CreateHttpRequest(url);

            httpRequest.ConfigureRequest(requestContext);

            httpRequest.Method = request.HttpMethod;
            if (request.MayContainRequestBody())
            {
                var content = request.Content;
                if (request.SetContentFromParameters || (content == null && request.ContentStream == null))
                {
                    // Mapping parameters to query string or body are mutually exclusive.
                    if (!request.UseQueryString)
                    {
                        string queryString = AWSSDKUtils.GetParametersAsString(request);
                        content         = Encoding.UTF8.GetBytes(queryString);
                        request.Content = content;
                        request.SetContentFromParameters = true;
                    }
                    else
                    {
                        request.Content = new Byte[0];
                    }
                }

                if (content != null)
                {
                    request.Headers[HeaderKeys.ContentLengthHeader] =
                        content.Length.ToString(CultureInfo.InvariantCulture);
                }
                else if (request.ContentStream != null && request.ContentStream.CanSeek && !request.Headers.ContainsKey(HeaderKeys.ContentLengthHeader))
                {
                    request.Headers[HeaderKeys.ContentLengthHeader] =
                        request.ContentStream.Length.ToString(CultureInfo.InvariantCulture);
                }
            }

            return(httpRequest);
        }
예제 #25
0
        internal static string DetermineRegion(ClientConfig clientConfig)
        {
            if (!string.IsNullOrEmpty(clientConfig.AuthenticationRegion))
            {
                return(clientConfig.AuthenticationRegion.ToLower(CultureInfo.InvariantCulture));
            }

            if (!string.IsNullOrEmpty(clientConfig.ServiceURL))
            {
                var parsedRegion = AWSSDKUtils.DetermineRegion(clientConfig.ServiceURL);
                if (!string.IsNullOrEmpty(parsedRegion))
                {
                    return(parsedRegion.ToLower(CultureInfo.InvariantCulture));
                }
            }

            return(clientConfig.RegionEndpoint != null
                ? clientConfig.RegionEndpoint.SystemName
                : string.Empty);
        }
예제 #26
0
        private static string BuildPolicyString(string bucketName, string prefix, int expireInMinutes)
        {
            StringBuilder builder = new StringBuilder("{", 0x200);

            builder.Append("\"expiration\": \"");
            builder.Append(AWSSDKUtils.GetFormattedTimestampISO8601(expireInMinutes));
            builder.Append("\",");
            builder.Append("\"conditions\": [");
            builder.Append("{\"bucket\": \"");
            builder.Append(bucketName);
            builder.Append("\"},");
            builder.Append("{\"acl\": \"");
            builder.Append("ec2-bundle-read");
            builder.Append("\"},");
            builder.Append("[\"starts-with\", \"$key\", \"");
            builder.Append(prefix);
            builder.Append("\"]");
            builder.Append("]}");
            return(builder.ToString());
        }
예제 #27
0
            public override bool Equals(object obj)
            {
                if (object.ReferenceEquals(this, obj))
                {
                    return(true);
                }

                CacheKey ck = obj as CacheKey;

                if (ck == null)
                {
                    return(false);
                }

                var allEqual = AWSSDKUtils.AreEqual(
                    new object[] { this.ImmutableCredentials, this.RegionEndpoint, this.ServiceUrl, this.CacheType },
                    new object[] { ck.ImmutableCredentials, ck.RegionEndpoint, ck.ServiceUrl, ck.CacheType });

                return(allEqual);
            }
        /// <summary>
        ///  Given a policy and AWS credentials, produce a S3PostUploadSignedPolicy.
        /// </summary>
        /// <param name="policy">JSON string representing the policy to sign</param>
        /// <param name="credentials">Credentials to sign the policy with</param>
        /// <param name="region">Service region endpoint.</param>
        /// <returns>A signed policy object for use with an S3PostUploadRequest.</returns>
        public static S3PostUploadSignedPolicy GetSignedPolicyV4(string policy, AWSCredentials credentials, RegionEndpoint region)
        {
            var signedAt = AWSSDKUtils.CorrectedUtcNow;

            ImmutableCredentials iCreds = credentials.GetCredentials();
            var algorithm        = "AWS4-HMAC-SHA256";
            var dateStamp        = Runtime.Internal.Auth.AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat);
            var dateTimeStamp    = Runtime.Internal.Auth.AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateTimeFormat);
            var credentialString = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}/{4}/", iCreds.AccessKey, dateStamp, region.SystemName, "s3", Runtime.Internal.Auth.AWS4Signer.Terminator);

            Dictionary <string, string> extraConditions = new Dictionary <string, string> {
                { S3Constants.PostFormDataXAmzCredential, credentialString },
                { S3Constants.PostFormDataXAmzAlgorithm, algorithm },
                { S3Constants.PostFormDataXAmzDate, dateTimeStamp }
            };

            if (iCreds.UseToken)
            {
                extraConditions[S3Constants.PostFormDataSecurityToken] = iCreds.Token;
            }

            var policyBytes = addConditionsToPolicy(policy, extraConditions);

            var base64Policy = Convert.ToBase64String(policyBytes);

            var signingKey = Runtime.Internal.Auth.AWS4Signer.ComposeSigningKey(iCreds.SecretKey, region.SystemName, dateStamp, "s3");

            var signature = AWSSDKUtils.ToHex(Runtime.Internal.Auth.AWS4Signer.ComputeKeyedHash(SigningAlgorithm.HmacSHA256, signingKey, base64Policy), true);

            return(new S3PostUploadSignedPolicy
            {
                Policy = base64Policy,
                Signature = signature,
                AccessKeyId = iCreds.AccessKey,
                SecurityToken = iCreds.Token,
                SignatureVersion = "4",
                Algorithm = algorithm,
                Date = dateTimeStamp,
                Credential = credentialString
            });
        }
예제 #29
0
        public static string Build(
            DateTime now,
            string regionName,
            string serviceName,
            ImmutableCredentials credentials,
            string signedHeaders,
            string credentialScope,
            string stringToSign)
        {
            // The following pseudocode shows the construction of the Authorization header value.
            //
            //   <algorithm> Credential=<access key id>/<credential scope>, SignedHeaders=<signed headers>, Signature=<signature>
            //
            // Note the following:
            //
            // - There is no comma between the algorithm and Credential. However, the SignedHeaders
            //   and Signature are separated from the preceding values with a comma.
            // - The Credential value starts with the access key id, which is followed by a forward
            //   slash (/), which is followed by the credential scope. The secret access key is
            //   used to derive the signing key for the signature, but is not included in the
            //   signing information sent in the request.
            //
            // To derive your signing key, use your secret access key to create a series of hash-
            // based message authentication codes (HMACs).
            //
            // Note that the date used in the hashing process is in the format YYYYMMDD (for
            // example, 20150830), and does not include the time.
            var signingKey = AWS4Signer.ComposeSigningKey(
                credentials.SecretKey,
                regionName,
                now.ToIso8601BasicDate(),
                serviceName);

            // Calculate the signature. To do this, use the signing key that you derived and the
            // string to sign as inputs to the keyed hash function. After you calculate the
            // signature, convert the binary value to a hexadecimal representation.
            var hash      = AWS4Signer.ComputeKeyedHash(SigningAlgorithm.HmacSHA256, signingKey, stringToSign);
            var signature = AWSSDKUtils.ToHex(hash, true);

            return($"{AWS4Signer.AWS4AlgorithmTag} Credential={credentials.AccessKey}/{credentialScope}, SignedHeaders={signedHeaders}, Signature={signature}");
        }
예제 #30
0
        /// <summary>
        /// Constructs the signed trailing headers, optionally including
        /// the selected checksum for this stream's data. For example:
        /// trailing-header-A:value CRLF
        /// trailing-header-B:value CRLF
        /// x-amz-trailer-signature:signature_value CRLF
        /// CRLF
        /// </summary>
        /// <returns>Stream chunk containing the trailing headers and their signature</returns>
        private string ConstructSignedTrailersChunk()
        {
            // If the trailing headers included a trailing checksum, set the hash value
            if (_hashAlgorithm != null)
            {
                _hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);
                _trailingHeaders[ChecksumUtils.GetChecksumHeaderKey(_trailingChecksum)] = Convert.ToBase64String(_hashAlgorithm.Hash);
            }

            string chunkSignature;

            if (HeaderSigningResult is AWS4SigningResult)
            {
                var sortedTrailingHeaders        = AWS4Signer.SortAndPruneHeaders(_trailingHeaders);
                var canonicalizedTrailingHeaders = AWS4Signer.CanonicalizeHeaders(sortedTrailingHeaders);

                var chunkStringToSign =
                    TRAILING_HEADER_STRING_TO_SIGN_PREFIX + "\n" +
                    HeaderSigningResult.ISO8601DateTime + "\n" +
                    HeaderSigningResult.Scope + "\n" +
                    PreviousChunkSignature + "\n" +
                    AWSSDKUtils.ToHex(AWS4Signer.ComputeHash(canonicalizedTrailingHeaders), true);

                chunkSignature = AWSSDKUtils.ToHex(AWS4Signer.SignBlob(((AWS4SigningResult)HeaderSigningResult).GetSigningKey(), chunkStringToSign), true);
            }
            else // SigV4a
            {
                chunkSignature = Sigv4aSigner.SignTrailingHeaderChunk(_trailingHeaders, PreviousChunkSignature, (AWS4aSigningResult)HeaderSigningResult).PadRight(V4A_SIGNATURE_LENGTH, '*');
            }

            var chunk = new StringBuilder();

            // The order here must match the order of keys sent already in the X-Amz-Trailer header.
            foreach (var kvp in _trailingHeaders.OrderBy(kvp => kvp.Key))
            {
                chunk.Append($"{kvp.Key}:{kvp.Value}{STREAM_NEWLINE}");
            }
            chunk.Append($"{TRAILING_HEADER_SIGNATURE_KEY}:{chunkSignature}{STREAM_NEWLINE}");
            chunk.Append(STREAM_NEWLINE);
            return(chunk.ToString());
        }