This class is the base class of all the configurations settings to connect to a service.
示例#1
0
        private static void ApplyProxy(ClientConfig config)
        {
            var proxyAddress = KeePass.Program.Config.Integration.ProxyAddress;
            var proxyPort = KeePass.Program.Config.Integration.ProxyPort;
            var proxyType = KeePass.Program.Config.Integration.ProxyType;

            if (proxyType == ProxyServerType.Manual)
            {
                if (!string.IsNullOrEmpty(proxyAddress)) config.ProxyHost = proxyAddress;
                if (!string.IsNullOrEmpty(proxyPort)) config.ProxyPort = int.Parse(proxyPort);
                config.ProxyCredentials = ProxyTools.GetKeePassProxyCredentials();
            }
            else if (proxyType == ProxyServerType.System)
            {
                if (config.RegionEndpoint == null) return;

                var systemProxy = System.Net.WebRequest.DefaultWebProxy;
                var endpoint = config.RegionEndpoint.GetEndpointForService("s3");
                var uri = new Uri("https://" + endpoint.Hostname);

                if (systemProxy.IsBypassed(uri)) return;
                var proxyHost = systemProxy.GetProxy(uri);

                config.ProxyHost = proxyHost.Host;
                config.ProxyPort = proxyHost.Port;
                config.ProxyCredentials = systemProxy.Credentials;
            }
        }
示例#2
0
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            request.Headers["x-amz-date"] = AWSSDKUtils.FormattedCurrentTimestampRFC822;

            string toSign = buildSigningString(request.HttpMethod, request.CanonicalResource, request.Parameters, request.Headers);
            metrics.AddProperty(Metric.StringToSign, toSign);
            string auth = CryptoUtilFactory.CryptoInstance.HMACSign(toSign, awsSecretAccessKey, SigningAlgorithm.HmacSHA1);
            string authorization = string.Concat("AWS ", awsAccessKeyId, ":", auth);
            request.Headers[S3QueryParameter.Authorization.ToString()] = authorization;
        }
示例#3
0
        /// <summary>
        /// Calculates and signs the specified request using the AWS4 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="metrics">Request metrics</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>
        /// <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)
        {
            // clean up request from previous execution
            request.Headers.Remove("Authorization");

            SigningAlgorithm signingAlgorithm = SigningAlgorithm.HmacSHA256;

            DateTime dt = DateTime.UtcNow;
            string dateTime = dt.ToString(AWSSDKUtils.ISO8601BasicDateTimeFormat, CultureInfo.InvariantCulture);
            string dateStamp = dt.ToString("yyyyMMdd", CultureInfo.InvariantCulture);

            string region = DetermineRegion(clientConfig);
            string service = DetermineService(clientConfig);

            if (!request.Headers.ContainsKey("Host"))
            {
                string hostHeader = request.Endpoint.Host;
                if (!request.Endpoint.IsDefaultPort)
                    hostHeader += ":" + request.Endpoint.Port;
                request.Headers.Add("Host", hostHeader);
            }
            request.Headers["X-Amz-Date"] = dateTime;

            string scope = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}", dateStamp, region, service, TERMINATOR);
            List<string> headersToSign = GetHeadersForSigning(request.Headers);

            var queryString = request.UseQueryString ? AWSSDKUtils.GetParametersAsString(request.Parameters) : "";

            string canonicalRequest = GetCanonicalRequest(headersToSign,
                                                          new Uri(request.Endpoint, request.ResourcePath),
                                                          queryString,
                                                          request.Headers,
                                                          request.UseQueryString ? "" : GetRequestPayload(request),
                                                          request.ContentStreamHash,
                                                          request.HttpMethod);

            StringBuilder stringToSignBuilder = new StringBuilder();
            stringToSignBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}-{1}\n{2}\n{3}\n", SCHEME, ALGORITHM, dateTime, scope);

            byte[] canonicalRequestHashBytes = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(Encoding.UTF8.GetBytes(canonicalRequest));
            stringToSignBuilder.Append(AWSSDKUtils.ToHex(canonicalRequestHashBytes, true));

            byte[] hashKey = ComposeSigningKey(signingAlgorithm, awsSecretAccessKey, region, dateStamp, service);
            string stringToSign = stringToSignBuilder.ToString();
            metrics.AddProperty(Metric.StringToSign, stringToSign);
            byte[] signature = CryptoUtilFactory.CryptoInstance.HMACSignBinary(Encoding.UTF8.GetBytes(stringToSign), hashKey, SigningAlgorithm.HmacSHA256);

            StringBuilder authorizationHeader = new StringBuilder();
            authorizationHeader.AppendFormat("{0}-{1} ", SCHEME, ALGORITHM);
            authorizationHeader.AppendFormat("Credential={0}/{1}, ", awsAccessKeyId, scope);
            authorizationHeader.AppendFormat("SignedHeaders={0}, ", GetSignedHeaders(headersToSign));
            authorizationHeader.AppendFormat("Signature={0}", AWSSDKUtils.ToHex(signature, true));

            request.Headers["Authorization"] = authorizationHeader.ToString();
        }
示例#4
0
 /// <summary>
 /// Signs the specified request with the AWS3 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="metrics">Request metrics</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>
 /// <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) 
 {
     if (UseAws3Https)
     {
         SignHttps(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
     }
     else
     {
         SignHttp(request, metrics, awsAccessKeyId, awsSecretAccessKey);
     }
 }
示例#5
0
 /// <summary>
 /// Signs the specified request with the AWS3 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>
 /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
 public override void Sign(IRequest request, ClientConfig clientConfig, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey) 
 {
     if (UseAws3Https)
     {
         SignHttps(request, clientConfig, awsAccessKeyId, awsSecretAccessKey, secureKey);
     }
     else
     {
         SignHttp(request, clientConfig, awsAccessKeyId, awsSecretAccessKey, secureKey);
     }
 }
示例#6
0
        /// <summary>
        /// Calculates and signs the specified request using the AWS4 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>
        /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
        public override void Sign(IRequest request, ClientConfig clientConfig, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            string signingAlgorithm = SigningAlgorithm.HmacSHA256.ToString().ToUpper();

            DateTime dt = DateTime.UtcNow;
            string dateTime = dt.ToString(AWSSDKUtils.ISO8601BasicDateTimeFormat, CultureInfo.InvariantCulture);
            string dateStamp = dt.ToString("yyyyMMdd", CultureInfo.InvariantCulture);

            string region = DetermineRegion(clientConfig);
            string service = DetermineService(clientConfig);

            if (!request.Headers.ContainsKey("Host"))
            {
                string hostHeader = request.Endpoint.Host;
                if (!request.Endpoint.IsDefaultPort)
                    hostHeader += ":" + request.Endpoint.Port;
                request.Headers.Add("Host", hostHeader);
            }
            request.Headers.Add("X-Amz-Date", dateTime);

            string scope = string.Format("{0}/{1}/{2}/{3}", dateStamp, region, service, TERMINATOR);
            List<string> headersToSign = GetHeadersForSigning(request.Headers);

            var queryString = request.UseQueryString ? AWSSDKUtils.GetParametersAsString(request.Parameters) : "";

            string canonicalRequest = GetCanonicalRequest(headersToSign,
                                                          new Uri(request.Endpoint, request.ResourcePath),
                                                          queryString,
                                                          request.Headers,
                                                          request.UseQueryString ? "" : GetRequestPayload(request),
                                                          request.ContentStreamHash,
                                                          request.HttpMethod);

            StringBuilder stringToSign = new StringBuilder();
            stringToSign.AppendFormat("{0}-{1}\n{2}\n{3}\n", SCHEME, ALGORITHM, dateTime, scope);

            byte[] canonicalRequestHashBytes = CanonicalizationHash.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest));
            stringToSign.Append(AWSSDKUtils.ToHex(canonicalRequestHashBytes, true));

            KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(signingAlgorithm);
            kha.Key = ComposeSigningKey(signingAlgorithm, awsSecretAccessKey, secureKey, region, dateStamp, service);
            byte[] signature = kha.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString()));

            StringBuilder authorizationHeader = new StringBuilder();
            authorizationHeader.AppendFormat("{0}-{1} ", SCHEME, ALGORITHM);
            authorizationHeader.AppendFormat("Credential={0}/{1}, ", awsAccessKeyId, scope);
            authorizationHeader.AppendFormat("SignedHeaders={0}, ", GetSignedHeaders(headersToSign));
            authorizationHeader.AppendFormat("Signature={0}", AWSSDKUtils.ToHex(signature, true));

            request.Headers.Add("Authorization", authorizationHeader.ToString());
        }
示例#7
0
        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");
            }

            string dateTime = AWSSDKUtils.GetFormattedTimestampRFC822(0);
            request.Headers.Add("X-Amz-Date", dateTime);

            string signature = ComputeHash(dateTime, awsSecretAccessKey, secureKey, SigningAlgorithm.HmacSHA1);

            request.Headers.Add("Authorization", "AWS " + awsAccessKeyId + ":" + signature);
        }
示例#8
0
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            var signer = SelectSigner(this, _useSigV4, request, clientConfig);
            var aws4Signer = signer as AWS4Signer;
            var useV4 = aws4Signer != null;

            //var aws4Signer = SelectSigner(clientConfig) as AWS4Signer;
            if (useV4)
            {
                var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
                request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
                if (request.UseChunkEncoding)
                    request.AWS4SignerResult = signingResult;
            }
            else
                SignRequest(request, metrics, awsAccessKeyId, awsSecretAccessKey);
        }
示例#9
0
        /// <summary>
        /// Creates the service client using the credentials and client config.
        /// </summary>
        /// <param name="credentials"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        private static AmazonServiceClient CreateClient(Type serviceInterfaceType, AWSCredentials credentials, ClientConfig config)
        {
            var clientTypeName = serviceInterfaceType.Namespace + "." + serviceInterfaceType.Name.Substring(1) + "Client";
            var clientType = serviceInterfaceType.GetTypeInfo().Assembly.GetType(clientTypeName);
            if (clientType == null)
            {
                throw new AmazonClientException($"Failed to find service client {clientTypeName} which implements {serviceInterfaceType.FullName}.");
            }

            var constructor = clientType.GetConstructor(new Type[] { typeof(AWSCredentials), config.GetType() });
            if (constructor == null)
            {
                throw new AmazonClientException($"Service client {clientTypeName} misisng a constructor with parameters AWSCredentials and {config.GetType().FullName}.");
            }

            var client = constructor.Invoke(new object[] { credentials, config }) as AmazonServiceClient;
            return client;
        }
示例#10
0
        private void SignHttps(IRequest request, ClientConfig clientConfig, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            string nonce = Guid.NewGuid().ToString();
            string date = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            string stringToSign;

            stringToSign = date + nonce;

            string signature = ComputeHash(stringToSign, awsSecretAccessKey, secureKey, clientConfig.SignatureMethod);

            StringBuilder builder = new StringBuilder();
            builder.Append(HTTPS_SCHEME).Append(" ");
            builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ",");
            builder.Append("Algorithm=" + clientConfig.SignatureMethod.ToString() + ",");
            builder.Append("SignedHeaders=x-amz-date;x-amz-nonce,");
            builder.Append("Signature=" + signature);

            request.Headers[AUTHORIZATION_HEADER] = builder.ToString();
            request.Headers[NONCE_HEADER] = nonce;
            request.Headers["x-amz-date"] = date;
        }
        static string DetermineBucketRegionCode(ClientConfig config)
        {
            if (config.RegionEndpoint != null && string.IsNullOrEmpty(config.ServiceURL))
                return config.RegionEndpoint.SystemName;

            return AWSSDKUtils.DetermineRegion(config.DetermineServiceURL());
        }
示例#12
0
 private static string DetermineService(ClientConfig clientConfig)
 {
     if (!string.IsNullOrEmpty(clientConfig.AuthenticationServiceName))
         return clientConfig.AuthenticationServiceName.ToLower();
     else
         return AWSSDKUtils.DetermineService(clientConfig.DetermineServiceURL()).ToLower();
 }
示例#13
0
 protected AmazonUnityServiceClient(string awsAccessKeyId, string awsSecretAccessKey, ClientConfig config)
     : base(awsAccessKeyId, awsSecretAccessKey, config)
 {
 }
 internal AmazonWebServiceClient(AWSCredentials credentials, ClientConfig config, AuthenticationTypes authenticationType)
     : base(credentials, config, authenticationType)
 {
 }
 internal AmazonWebServiceClient(string awsAccessKeyId, string awsSecretAccessKey, ClientConfig config, AuthenticationTypes authenticationType)
     : base((AWSCredentials) new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey),
            config, authenticationType)
 {
 }
示例#16
0
 private static string DetermineRegion(ClientConfig clientConfig)
 {
     if (!string.IsNullOrEmpty(clientConfig.AuthenticationRegion))
         return clientConfig.AuthenticationRegion.ToLower(CultureInfo.InvariantCulture);
     else
         return AWSSDKUtils.DetermineRegion(clientConfig.DetermineServiceURL()).ToLower(CultureInfo.InvariantCulture);
 }
示例#17
0
        private void SignHttp(IRequest request, ClientConfig clientConfig, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
            string nonce = Guid.NewGuid().ToString();
            string date = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            bool isHttps = IsHttpsRequest(request);

            // Temporarily disabling the AWS3 HTTPS signing scheme and only using AWS3 HTTP
            isHttps = false;

            request.Headers["Date"] = date;
            request.Headers["X-Amz-Date"] = date;

            // AWS3 HTTP requires that we sign the Host header
            // so we have to have it in the request by the time we sign.
            string hostHeader = request.Endpoint.Host;
            if (!request.Endpoint.IsDefaultPort)
                hostHeader += ":" + request.Endpoint.Port;
            request.Headers["Host"] = hostHeader;

            byte[] bytesToSign;
            string stringToSign;
            if (isHttps)
            {
                request.Headers[NONCE_HEADER] = nonce;
                stringToSign = date + nonce;
                bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
            }
            else
            {
                Uri url = request.Endpoint;
                if (!string.IsNullOrEmpty(request.ResourcePath))
                    url = new Uri(request.Endpoint, request.ResourcePath);

                stringToSign = request.HttpMethod + "\n"
                    + GetCanonicalizedResourcePath(url) + "\n"
                    + GetCanonicalizedQueryString(request.Parameters) + "\n"
                    + GetCanonicalizedHeadersForStringToSign(request) + "\n"
                    + GetRequestPayload(request);

                bytesToSign = CanonicalizationHash.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            }

            string signature = ComputeHash(bytesToSign, awsSecretAccessKey, secureKey, algorithm);

            StringBuilder builder = new StringBuilder();
            builder.Append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME);
            builder.Append(" ");
            builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ",");
            builder.Append("Algorithm=" + algorithm.ToString() + ",");

            if (!isHttps)
            {
                builder.Append(GetSignedHeadersComponent(request) + ",");
            }

            builder.Append("Signature=" + signature);
            string authorizationHeader = builder.ToString();
            request.Headers[AUTHORIZATION_HEADER] = authorizationHeader;
        }
示例#18
0
 protected AmazonUnityServiceClient(AWSCredentials credentials, ClientConfig config) :
     base(credentials, config)
 {
 }
示例#19
0
 private static string DetermineRegion(ClientConfig clientConfig)
 {
     if (!string.IsNullOrEmpty(clientConfig.AuthenticationRegion))
         return clientConfig.AuthenticationRegion.ToLower();
     else
         return AWSSDKUtils.DetermineRegion(clientConfig.ServiceURL).ToLower();
 }
示例#20
0
        internal AmazonWebServiceClient(string awsAccessKeyId, string awsSecretAccessKey, ClientConfig config)
        {
            this.logger = new Logger(this.GetType());
            this.config = config;

            if (!String.IsNullOrEmpty(awsSecretAccessKey))
            {
                if (config.UseSecureStringForAwsSecretKey)
                {
                    this.awsSecretAccessKey = new SecureString();
                    foreach (char ch in awsSecretAccessKey.ToCharArray())
                    {
                        this.awsSecretAccessKey.AppendChar(ch);
                    }
                    this.awsSecretAccessKey.MakeReadOnly();
                }
                else
                {
                    clearAwsSecretAccessKey = awsSecretAccessKey;
                }
            }
            this.awsAccessKeyId = awsAccessKeyId;
        }