public SampleElasticsearchClient(string endPoint, Amazon.RegionEndpoint regionEndPoint)
        {
            AWSCredentials    awsCredentials = FallbackCredentialsFactory.GetCredentials();
            AwsHttpConnection conn           = new AwsHttpConnection(regionEndPoint.SystemName,
                                                                     new StaticCredentialsProvider(new AwsCredentials()
            {
                AccessKey = awsCredentials.GetCredentials().AccessKey,
                SecretKey = awsCredentials.GetCredentials().SecretKey,
                Token     = awsCredentials.GetCredentials().Token
            }));

            var pool = new SingleNodeConnectionPool(new Uri(endPoint));
            ConnectionSettings settings = new ConnectionSettings(pool, conn)
                                          .DisableDirectStreaming()
                                          .InferMappingFor <LogEntry>(m => m.IndexName("logs"));

            //.DefaultMappingFor<LogEntry>(m => m.IndexName("logs"));

            _esClient = new ElasticClient(settings);

            IndexName logIndex = IndexName.From <LogEntry>();

            var req = new IndexExistsRequest(logIndex);
            var res = _esClient.IndexExists(req);

            if (!res.Exists)
            {
                _esClient.CreateIndex("logs", c => c
                                      .Mappings(md => md.Map <LogEntry>(m => m.AutoMap())));
            }
        }
        private void SignRequest(IRequest request, RequestData requestData)
        {
            byte[] data = null;
            if (requestData.PostData != null)
            {
                data = requestData.PostData.WrittenBytes;
                if (data == null)
                {
                    using (var ms = new MemoryStream())
                    {
                        requestData.PostData.Write(ms, requestData.ConnectionSettings);
                        data = ms.ToArray();
                    }
                }
            }
            ImmutableCredentials credentials;

            try
            {
                credentials = _credentials.GetCredentials();
            }
            catch (Exception e)
            {
                throw new Exception("Unable to retrieve credentials required to sign the request.", e);
            }

            if (credentials == null)
            {
                throw new Exception("Unable to retrieve credentials required to sign the request.");
            }
            SignV4Util.SignRequest(request, data, credentials, _region.SystemName, "es");
        }
Exemple #3
0
        /// <summary>
        /// Send an Signature Version 4 signed HTTP request.
        /// </summary>
        /// <param name="self">
        /// The extension target.
        /// </param>
        /// <param name="request">
        /// The HTTP request message to send.
        /// </param>
        /// <param name="completionOption">
        /// One of the enumeration values that specifies when the operation should complete (as
        /// soon as a response is available or after reading the response content).
        /// </param>
        /// <param name="cancellationToken">
        /// The cancellation token to cancel operation.
        /// </param>
        /// <param name="regionName">
        /// The system name of the AWS region associated with the endpoint, e.g. "us-east-1".
        /// </param>
        /// <param name="serviceName">
        /// The signing name of the service, e.g. "execute-api".
        /// </param>
        /// <param name="credentials">
        /// AWS credentials containing the following parameters:
        /// - The AWS public key for the account making the service call.
        /// - The AWS secret key for the account making the call, in clear text.
        /// - The session token obtained from STS if request is authenticated using temporary
        ///   security credentials, e.g. a role.
        /// </param>
        /// <returns>
        /// The HTTP response message.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="request"/> is null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The request message was already sent by the <see cref="HttpClient"/> instance.
        /// </exception>
        /// <exception cref="HttpRequestException">
        /// The request failed due to an underlying issue such as network connectivity, DNS
        /// failure, or server certificate validation.
        /// </exception>
        /// <exception cref="TaskCanceledException">
        /// The request was canceled.
        /// <para/>
        /// -or-
        /// <para/>
        /// If the <see cref="TaskCanceledException"/> exception nests the
        /// <see cref="TimeoutException"/>: The request failed due to timeout.
        /// </exception>
        public static HttpResponseMessage Send(
            this HttpClient self,
            HttpRequestMessage request,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken,
            string regionName,
            string serviceName,
            AWSCredentials credentials)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            var immutableCredentials = credentials.GetCredentials();

            var response = self.Send(
                request,
                completionOption,
                cancellationToken,
                regionName,
                serviceName,
                immutableCredentials);

            return(response);
        }
Exemple #4
0
        public static CredentialProfileOptions ExtractProfileOptions(AWSCredentials credentials)
        {
            var type = credentials.GetType();

            if (type == typeof(BasicAWSCredentials) || type == typeof(SessionAWSCredentials))
            {
                var immutableCredentials = credentials.GetCredentials();
                return(new CredentialProfileOptions
                {
                    AccessKey = immutableCredentials.AccessKey,
                    SecretKey = immutableCredentials.SecretKey,
                    Token = immutableCredentials.Token
                });
            }

            if (PassThroughExtractTypes.Contains(type))
            {
                return(null);
            }

            if (ThrowExtractTypes.Contains(type))
            {
                throw new InvalidOperationException("Cannot save credentials of type " + type.Name);
            }

            throw new InvalidOperationException("Unrecognized credentials type: " + type.Name);
        }
Exemple #5
0
        protected Message MakeSetCredentialsMessage(AWSCredentials awsCredentials, bool forMetrics)
        {
            var immutableCredentials = awsCredentials.GetCredentials();

            var creds = new Credentials
            {
                Akid      = immutableCredentials.AccessKey,
                SecretKey = immutableCredentials.SecretKey
            };

            if (immutableCredentials.UseToken)
            {
                creds.Token = immutableCredentials.Token;
            }

            var setCredentials = new SetCredentials
            {
                Credentials = creds,
                ForMetrics  = forMetrics
            };

            return(new Message
            {
                SetCredentials = setCredentials,
                Id = ulong.MaxValue
            });
        }
Exemple #6
0
        protected override void PreInvoke(IExecutionContext executionContext)
        {
            var request = executionContext.RequestContext.OriginalRequest;
            var config  = executionContext.RequestContext.ClientConfig;

            var copySnapshotRequest = request as CopySnapshotRequest;

            if (copySnapshotRequest != null)
            {
                if (string.IsNullOrEmpty(copySnapshotRequest.DestinationRegion))
                {
                    copySnapshotRequest.DestinationRegion = AWS4Signer.DetermineSigningRegion(config, "ec2", alternateEndpoint: null);
                }
                if (string.IsNullOrEmpty(copySnapshotRequest.SourceRegion))
                {
                    throw new AmazonEC2Exception("SourceRegion is required to perform the copy snapshot.");
                }

                var endpoint = RegionEndpoint.GetBySystemName(copySnapshotRequest.SourceRegion);
                if (endpoint == null)
                {
                    throw new AmazonEC2Exception(string.Format(CultureInfo.InvariantCulture, "No endpoint for region {0}.", copySnapshotRequest.SourceRegion));
                }

                // Make sure the presigned URL is currently null so we don't attempt to generate
                // a presigned URL with a presigned URL.
                copySnapshotRequest.PresignedUrl = null;

                // Marshall this request but switch to the source region and make it a GET request.
                var marshaller = new CopySnapshotRequestMarshaller();
                var irequest   = marshaller.Marshall(copySnapshotRequest);
                irequest.UseQueryString = true;
                irequest.HttpMethod     = "GET";
                irequest.Parameters.Add("X-Amz-Expires", AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry.ToString(CultureInfo.InvariantCulture));
                irequest.Endpoint = new Uri("https://" + endpoint.GetEndpointForService(config.RegionEndpointServiceName).Hostname);

                // Create presigned URL.
                var metrics = new RequestMetrics();
                var immutableCredentials = _credentials.GetCredentials();

                if (immutableCredentials.UseToken)
                {
                    irequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
                }

                var signingResult = AWS4PreSignedUrlSigner.SignRequest(irequest,
                                                                       config,
                                                                       metrics,
                                                                       immutableCredentials.AccessKey,
                                                                       immutableCredentials.SecretKey,
                                                                       "ec2",
                                                                       copySnapshotRequest.SourceRegion);

                var authorization = "&" + signingResult.ForQueryParameters;
                var url           = AmazonServiceClient.ComposeUrl(irequest);

                copySnapshotRequest.PresignedUrl = url.AbsoluteUri + authorization;
            }
        }
        private static void AddStoredCredential(AWSCredentials creds, string profileName)
        {
            string niceProfile = profileName.Replace(' ', '-');

            Console.WriteLine("Pushing credential " + niceProfile);
            RunConfigure(string.Format("set aws_access_key_id {0} --profile {1}", creds.GetCredentials().AccessKey, niceProfile), true, false);
            RunConfigure(string.Format("set aws_secret_access_key {0} --profile {1}", creds.GetCredentials().SecretKey, niceProfile), true, false);
        }
Exemple #8
0
        public async Task <GraphQLResponse> PostSignedRequestAsync(
            GraphQLRequest request,
            IDictionary <string, string> headers,
            CancellationToken cancellationToken)
        {
            GraphQLResponse   graphQlResponse;
            AWS4RequestSigner signer;
            var credentials = awsCredentials?.GetCredentials();

            signer = credentials == null
                ? new AWS4RequestSigner(accessKey, secretKey)
                : new AWS4RequestSigner(credentials.AccessKey, credentials.SecretKey);

            using (StringContent httpContent =
                       new StringContent(JsonConvert.SerializeObject(request, this.options.JsonSerializerSettings)))
            {
                httpContent.Headers.ContentType = this.options.MediaType;

                using (var httpRequest = new HttpRequestMessage
                {
                    Content = httpContent, Method = HttpMethod.Post, RequestUri = options.EndPoint
                })
                {
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            httpRequest.Headers.Add(header.Key, header.Value);
                        }
                    }

                    if (credentials != null)
                    {
                        if (!string.IsNullOrEmpty(credentials.Token))
                        {
                            httpRequest.Headers.Add(SessionTokenHeader, credentials.Token);
                        }
                    }
                    else if (!string.IsNullOrEmpty(sessionToken))
                    {
                        httpRequest.Headers.Add(SessionTokenHeader, sessionToken);
                    }

                    await signer.Sign(httpRequest, serviceName, region);

                    using (HttpResponseMessage httpResponseMessage =
                               await this.httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false))
                    {
                        graphQlResponse = await this.ReadHttpResponseMessageAsync(httpResponseMessage)
                                          .ConfigureAwait(false);
                    }
                }
            }

            return(graphQlResponse);
        }
Exemple #9
0
        /// <summary>
        /// Generate a token for IAM authentication to an RDS database.
        /// </summary>
        /// <param name="credentials">The credentials for the token.</param>
        /// <param name="region">The region of the RDS database.</param>
        /// <param name="hostname">Hostname of the RDS database.</param>
        /// <param name="port">Port of the RDS database.</param>
        /// <param name="dbUser">Database user for the token.</param>
        /// <returns></returns>
        public static string GenerateAuthToken(AWSCredentials credentials, RegionEndpoint region, string hostname, int port, string dbUser)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }

            if (region == null)
            {
                throw new ArgumentNullException("region");
            }

            if (port < 0 || port > 65535)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "{0} is an invalid port. Port must be 0 to 65535.", port));
            }

            hostname = hostname?.Trim();
            if (string.IsNullOrEmpty(hostname))
            {
                throw new ArgumentException("Hostname must not be null or empty.");
            }

            dbUser = dbUser?.Trim();
            if (string.IsNullOrEmpty(dbUser))
            {
                throw new ArgumentException("DBUser must not be null or empty.");
            }

            GenerateRDSAuthTokenRequest authTokenRequest = new GenerateRDSAuthTokenRequest();
            IRequest request = new DefaultRequest(authTokenRequest, RDSServiceName);

            request.UseQueryString = true;
            request.HttpMethod     = HTTPGet;
            request.Parameters.Add(XAmzExpires, FifteenMinutes.TotalSeconds.ToString(CultureInfo.InvariantCulture));
            request.Parameters.Add(DBUserKey, dbUser);
            request.Parameters.Add(ActionKey, ActionValue);
            request.Endpoint = new UriBuilder(HTTPS, hostname, port).Uri;

            var immutableCredentials = credentials.GetCredentials();

            if (immutableCredentials.UseToken)
            {
                request.Parameters[XAmzSecurityToken] = immutableCredentials.Token;
            }

            var signingResult = AWS4PreSignedUrlSigner.SignRequest(request, null, new RequestMetrics(), immutableCredentials.AccessKey,
                                                                   immutableCredentials.SecretKey, RDSServiceName, region.SystemName);

            var authorization = "&" + signingResult.ForQueryParameters;
            var url           = AmazonServiceClient.ComposeUrl(request);

            // remove the https:// and append the authorization
            return(url.AbsoluteUri.Substring(HTTPS.Length + URISchemeDelimiter.Length) + authorization);
        }
Exemple #10
0
        public static void AssertClientHasCredentials(AmazonServiceClient client, AWSCredentials credentials)
        {
            var prop = client.GetType().GetProperty("Credentials", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            var actualCredentials = ((AWSCredentials)prop.GetValue(client)).GetCredentials();
            var givenCredentials  = credentials.GetCredentials();

            if (actualCredentials?.AccessKey != givenCredentials.AccessKey ||
                actualCredentials?.SecretKey != givenCredentials.SecretKey ||
                actualCredentials?.Token != givenCredentials.Token)
            {
                throw new Exception("Credentials do not match");
            }
        }
        /// <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>
        /// <returns></returns>
        public static S3PostUploadSignedPolicy GetSignedPolicy(string policy, AWSCredentials credentials)
        {
            var policyBytes  = Encoding.UTF8.GetBytes(policy.Trim().Replace("\r", "").Replace("\n", ""));
            var base64Policy = Convert.ToBase64String(policyBytes);

            string signature = null;

            if (credentials.GetCredentials().UseSecureStringForSecretKey)
            {
                signature = AWSSDKUtils.HMACSign(Encoding.UTF8.GetBytes(base64Policy), credentials.GetCredentials().SecureSecretKey, new HMACSHA1());
            }
            else
            {
                signature = AWSSDKUtils.HMACSign(Encoding.UTF8.GetBytes(base64Policy), credentials.GetCredentials().ClearSecretKey, new HMACSHA1());
            }

            return(new S3PostUploadSignedPolicy
            {
                Policy = base64Policy,
                Signature = signature,
                AccessKeyId = credentials.GetCredentials().AccessKey
            });
        }
Exemple #12
0
        public static S3PostUploadSignedPolicy GetSignedPolicy(string policy, AWSCredentials credentials)
        {
            ImmutableCredentials credentials2 = credentials.GetCredentials();
            string text      = Convert.ToBase64String(credentials2.get_UseToken() ? addTokenToPolicy(policy, credentials2.get_Token()) : Encoding.UTF8.GetBytes(policy.Trim()));
            string signature = CryptoUtilFactory.get_CryptoInstance().HMACSign(Encoding.UTF8.GetBytes(text), credentials2.get_SecretKey(), 0);

            return(new S3PostUploadSignedPolicy
            {
                Policy = text,
                Signature = signature,
                AccessKeyId = credentials2.get_AccessKey(),
                SecurityToken = credentials2.get_Token(),
                SignatureVersion = "2"
            });
        }
        /// <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>
        /// <returns></returns>
        public static S3PostUploadSignedPolicy GetSignedPolicy(string policy, AWSCredentials credentials)
        {
            var policyBytes  = Encoding.UTF8.GetBytes(policy.Trim());
            var base64Policy = Convert.ToBase64String(policyBytes);

            string signature = null;

            signature = CryptoUtilFactory.CryptoInstance.HMACSign(Encoding.UTF8.GetBytes(base64Policy), credentials.GetCredentials().SecretKey, SigningAlgorithm.HmacSHA1);

            return(new S3PostUploadSignedPolicy
            {
                Policy = base64Policy,
                Signature = signature,
                AccessKeyId = credentials.GetCredentials().AccessKey
            });
        }
        public static async Task SignRequestAsync(this HttpRequestMessage httpRequestMessage, string region, string service, AWSCredentials credentials)
        {
            var creds = credentials.GetCredentials();
            var canonicalizedQueryParameters = string.Empty;

            if (!string.IsNullOrEmpty(httpRequestMessage.RequestUri.Query))
            {
                canonicalizedQueryParameters = signer.CanonicalizeQueryParameters(httpRequestMessage.RequestUri.Query.TrimStart('?'));
            }

            DateTime requestDateTimeInUTC = AWSSDKUtils.CorrectedUtcNow;
            var      dictionary           = new Dictionary <string, string>
            {
                { "host", httpRequestMessage.RequestUri.Host },
                { "x-amz-date", requestDateTimeInUTC.ToString("yyyyMMddTHHmmssZ") }
            };

            var requestBody = await httpRequestMessage.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(requestBody))
            {
                httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            }

            var    uri = httpRequestMessage.RequestUri;
            string canonicalServiceUri = uri.LocalPath;
            string requestMethod       = httpRequestMessage.Method.Method.ToUpper();

            var aWSSigV4AuthorizationValue = signer.GetAWSSigV4AuthorizationValue(dictionary,
                                                                                  canonicalizedQueryParameters,
                                                                                  canonicalServiceUri,
                                                                                  region,
                                                                                  service,
                                                                                  creds,
                                                                                  requestMethod,
                                                                                  requestBody,
                                                                                  requestDateTimeInUTC);

            httpRequestMessage.Headers.TryAddWithoutValidation("Authorization", aWSSigV4AuthorizationValue);
            httpRequestMessage.Headers.TryAddWithoutValidation("x-amz-date", requestDateTimeInUTC.ToString("yyyyMMddTHHmmssZ"));

            if (creds.UseToken)
            {
                httpRequestMessage.Headers.TryAddWithoutValidation("x-amz-security-token", creds.Token);
            }
        }
        /// <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>
        /// <returns>A signed policy object for use with an S3PostUploadRequest.</returns>
        public static S3PostUploadSignedPolicy GetSignedPolicy(string policy, AWSCredentials credentials)
        {
            ImmutableCredentials iCreds = credentials.GetCredentials();
            var policyBytes             = iCreds.UseToken
                ? addTokenToPolicy(policy, iCreds.Token)
                : Encoding.UTF8.GetBytes(policy.Trim());
            var    base64Policy = Convert.ToBase64String(policyBytes);
            string signature    = CryptoUtilFactory.CryptoInstance.HMACSign(Encoding.UTF8.GetBytes(base64Policy), iCreds.SecretKey, SigningAlgorithm.HmacSHA1);

            return(new S3PostUploadSignedPolicy
            {
                Policy = base64Policy,
                Signature = signature,
                AccessKeyId = iCreds.AccessKey,
                SecurityToken = iCreds.Token
            });
        }
Exemple #16
0
        public static S3PostUploadSignedPolicy GetSignedPolicyV4(string policy, AWSCredentials credentials, RegionEndpoint region)
        {
            DateTime             correctedUtcNow = AWSSDKUtils.get_CorrectedUtcNow();
            ImmutableCredentials credentials2    = credentials.GetCredentials();
            string text  = "AWS4-HMAC-SHA256";
            string text2 = AWS4Signer.FormatDateTime(correctedUtcNow, "yyyyMMdd");
            string text3 = AWS4Signer.FormatDateTime(correctedUtcNow, "yyyyMMddTHHmmssZ");
            string text4 = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}/{4}/", credentials2.get_AccessKey(), text2, region.get_SystemName(), "s3", "aws4_request");
            Dictionary <string, string> dictionary = new Dictionary <string, string>
            {
                {
                    S3Constants.PostFormDataXAmzCredential,
                    text4
                },
                {
                    S3Constants.PostFormDataXAmzAlgorithm,
                    text
                },
                {
                    S3Constants.PostFormDataXAmzDate,
                    text3
                }
            };

            if (credentials2.get_UseToken())
            {
                dictionary[S3Constants.PostFormDataSecurityToken] = credentials2.get_Token();
            }
            string text5 = Convert.ToBase64String(addConditionsToPolicy(policy, dictionary));

            byte[] array     = AWS4Signer.ComposeSigningKey(credentials2.get_SecretKey(), region.get_SystemName(), text2, "s3");
            string signature = AWSSDKUtils.ToHex(AWS4Signer.ComputeKeyedHash(1, array, text5), true);

            return(new S3PostUploadSignedPolicy
            {
                Policy = text5,
                Signature = signature,
                AccessKeyId = credentials2.get_AccessKey(),
                SecurityToken = credentials2.get_Token(),
                SignatureVersion = "4",
                Algorithm = text,
                Date = text3,
                Credential = text4
            });
        }
Exemple #17
0
        /// <summary>
        /// Retrieves the credentials to be used for the current call before
        /// invoking the next handler.
        /// </summary>
        /// <param name="executionContext"></param>
        protected override void PreInvoke(IExecutionContext executionContext)
        {
            ImmutableCredentials ic = null;

            if (_credentials == null || _credentials is AnonymousAWSCredentials)
            {
                ic = null;
            }
            else
            {
                using (executionContext.RequestContext.Metrics.StartEvent(Metric.CredentialsRequestTime))
                {
                    ic = _credentials.GetCredentials();
                }
            }

            executionContext.RequestContext.ImmutableCredentials = ic;
        }
        /// <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
            });
        }
Exemple #19
0
        /// <summary>
        /// Auto-generates pre-signed URLs for requests that implement <see cref="IPreSignedUrlRequest"/>.
        /// if the PreSignedUrl property isn't set and the SourceRegion property is set.
        /// </summary>
        /// <param name="executionContext"></param>
        protected virtual void PreInvoke(IExecutionContext executionContext)
        {
            var preSignedUrlRequest = executionContext.RequestContext.OriginalRequest as IPreSignedUrlRequest;

            if (preSignedUrlRequest != null && preSignedUrlRequest.SourceRegion != null && preSignedUrlRequest.PreSignedUrl == null)
            {
                var config = executionContext.RequestContext.ClientConfig;

                var endpoint = RegionEndpoint.GetBySystemName(preSignedUrlRequest.SourceRegion);
                if (endpoint == null)
                {
                    throw new AmazonRDSException(string.Format(CultureInfo.InvariantCulture, "No endpoint for region {0}.", preSignedUrlRequest.SourceRegion));
                }

                // Marshall this request and prepare it to be signed
                var marshaller = executionContext.RequestContext.Marshaller;
                var iRequest   = marshaller.Marshall(preSignedUrlRequest as AmazonWebServiceRequest);
                iRequest.UseQueryString = true;
                iRequest.HttpMethod     = HTTPGet;
                iRequest.Endpoint       = new UriBuilder(UriSchemeHTTPS, endpoint.GetEndpointForService(config.RegionEndpointServiceName).Hostname).Uri;
                iRequest.Parameters[DestinationRegionParameterKey] = executionContext.RequestContext.ClientConfig.RegionEndpoint.SystemName;
                // Most pre signed URLS also have an X-Amz-Expires header.  But RDS just ignores it and always imposes a +/- 14 minute time limit instead.

                var immutableCredentials = _credentials.GetCredentials();
                if (immutableCredentials.UseToken)
                {
                    // Don't use HeaderKeys.XAmzSecurityTokenHeader because RDS treats this as case-sensitive
                    iRequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
                }

                // Create presigned URL and assign it
                var signingResult = AWS4PreSignedUrlSigner.SignRequest(iRequest, config, new RequestMetrics(),
                                                                       immutableCredentials.AccessKey, immutableCredentials.SecretKey, RDSServiceNameForSigning, preSignedUrlRequest.SourceRegion);

                var authorization = "&" + signingResult.ForQueryParameters;

                preSignedUrlRequest.PreSignedUrl = AmazonServiceClient.ComposeUrl(iRequest).AbsoluteUri + authorization;
            }
        }
        /// <summary>
        /// <para>
        /// Auto-generates pre-signed URLs for requests that implement <see cref="IPreSignedUrlRequest"/>.
        /// if the PreSignedUrl property isn't set and the SourceRegion property is set.
        /// </para>
        /// </summary>
        /// <param name="executionContext"></param>
        protected virtual void PreInvoke(IExecutionContext executionContext)
        {
            var preSignedUrlRequest = executionContext.RequestContext.OriginalRequest as IPreSignedUrlRequest;

            if (preSignedUrlRequest != null && preSignedUrlRequest.SourceRegion != null && preSignedUrlRequest.PreSignedUrl == null)
            {
                var config = executionContext.RequestContext.ClientConfig;

                var endpoint = RegionEndpoint.GetBySystemName(preSignedUrlRequest.SourceRegion);
                if (endpoint == null)
                {
                    throw new AmazonNeptuneException(string.Format(CultureInfo.InvariantCulture, "No endpoint for region {0}.", preSignedUrlRequest.SourceRegion));
                }

                // Marshall this request and prepare it to be signed
                var marshaller = executionContext.RequestContext.Marshaller;
                var iRequest   = marshaller.Marshall(preSignedUrlRequest as AmazonWebServiceRequest);
                iRequest.UseQueryString = true;
                iRequest.HttpMethod     = HTTPGet;
                iRequest.Endpoint       = new UriBuilder(UriSchemeHTTPS, endpoint.GetEndpointForService(config).Hostname).Uri;
                iRequest.Parameters[DestinationRegionParameterKey] = executionContext.RequestContext.ClientConfig.RegionEndpoint.SystemName;
                iRequest.Parameters[XAmzExpires] = ((int)ExpirationTime.TotalSeconds).ToString(CultureInfo.InvariantCulture);

                var immutableCredentials = _credentials.GetCredentials();
                if (immutableCredentials.UseToken)
                {
                    iRequest.Parameters[XAmzSecurityToken] = immutableCredentials.Token;
                }

                // Create presigned URL and assign it
                var signingResult = AWS4PreSignedUrlSigner.SignRequest(iRequest, config, new RequestMetrics(),
                                                                       immutableCredentials.AccessKey, immutableCredentials.SecretKey, NeptuneServiceNameForSigning, preSignedUrlRequest.SourceRegion);

                var authorization = "&" + signingResult.ForQueryParameters;

                preSignedUrlRequest.PreSignedUrl = AmazonServiceClient.ComposeUrl(iRequest).AbsoluteUri + authorization;
            }
        }
Exemple #21
0
        private bool tryGetLocalDBContext(out IDynamoDBContext context)
        {
            var            profileStore   = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials = null;

            if (profileStore.TryGetAWSCredentials(_profileName, out awsCredentials))
            {
                var credentials = awsCredentials.GetCredentials();
                context = getDBClientOnLocal(credentials.AccessKey, credentials.SecretKey);
                return(true);
            }
            else if (File.Exists(_localCredsUri + _localCredsFilename))
            {
                ICollection <string> keys = new List <string>();

                using (StreamReader stream = File.OpenText(_localCredsUri + _localCredsFilename))
                {
                    keys.Add(stream.ReadLine());
                    keys.Add(stream.ReadLine());

                    context = getDBClientOnLocal(keys.ElementAt <string>(0), keys.ElementAt <string>(1));
                    if (context != null)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            else
            {
                context = null;
                return(false);
            }
        }
Exemple #22
0
 public EC2(AWSCredentials awsCredentials, string accountId, RegionEndpoint regionEndpoint) : this(awsCredentials.GetCredentials().AccessKey, awsCredentials.GetCredentials().SecretKey, accountId, regionEndpoint.SystemName)
 {
 }
Exemple #23
0
        /// <summary>
        /// Custom pipeline handler
        /// </summary>
        /// <param name="executionContext"></param>
        protected void PreInvoke(IExecutionContext executionContext)
        {
            var request = executionContext.RequestContext.OriginalRequest;
            var config  = executionContext.RequestContext.ClientConfig;

            var runInstancesRequest = request as RunInstancesRequest;

            if (runInstancesRequest != null)
            {
                if (runInstancesRequest.IsSetBlockDeviceMappings())
                {
                    var mappings = runInstancesRequest.BlockDeviceMappings;
                    foreach (var mapping in mappings)
                    {
                        if (mapping.IsSetEbs())
                        {
                            var ebs = mapping.Ebs;
                            if (ebs.IsSetSnapshotId() &&
                                ebs.IsSetEncrypted() &&
                                ebs.Encrypted == false)
                            {
                                ebs.ClearEncryptedFlag();
                            }
                        }
                    }
                }
            }

            // replace null Tag.Value with empty string
            var createTagsRequest = request as CreateTagsRequest;

            if (createTagsRequest != null)
            {
                if (createTagsRequest.IsSetTags())
                {
                    var tags = createTagsRequest.Tags;
                    foreach (var tag in tags)
                    {
                        if (tag != null && tag.Value == null)
                        {
                            tag.Value = string.Empty;
                        }
                    }
                }
            }

            var copySnapshotRequest = request as CopySnapshotRequest;

            if (copySnapshotRequest != null)
            {
                if (string.IsNullOrEmpty(copySnapshotRequest.DestinationRegion))
                {
                    copySnapshotRequest.DestinationRegion = AWS4Signer.DetermineSigningRegion(config, "ec2", alternateEndpoint: null, request: null);
                }
                if (string.IsNullOrEmpty(copySnapshotRequest.SourceRegion))
                {
                    throw new AmazonEC2Exception("SourceRegion is required to perform the copy snapshot.");
                }

                var endpoint = RegionEndpoint.GetBySystemName(copySnapshotRequest.SourceRegion);
                if (endpoint == null)
                {
                    throw new AmazonEC2Exception(string.Format(CultureInfo.InvariantCulture, "No endpoint for region {0}.", copySnapshotRequest.SourceRegion));
                }

                // Make sure the presigned URL is currently null so we don't attempt to generate
                // a presigned URL with a presigned URL.
                copySnapshotRequest.PresignedUrl = null;

                // Marshall this request but switch to the source region and make it a GET request.
                var marshaller = new CopySnapshotRequestMarshaller();
                var irequest   = marshaller.Marshall(copySnapshotRequest);
                irequest.UseQueryString = true;
                irequest.HttpMethod     = "GET";
                irequest.Parameters.Add("X-Amz-Expires", AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry.ToString(CultureInfo.InvariantCulture));
                irequest.Endpoint = new Uri("https://" + endpoint.GetEndpointForService(config.RegionEndpointServiceName).Hostname);

                // Create presigned URL.
                var metrics = new RequestMetrics();
                var immutableCredentials = _credentials.GetCredentials();

                if (immutableCredentials.UseToken)
                {
                    irequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
                }

                var signingResult = AWS4PreSignedUrlSigner.SignRequest(irequest,
                                                                       config,
                                                                       metrics,
                                                                       immutableCredentials.AccessKey,
                                                                       immutableCredentials.SecretKey,
                                                                       "ec2",
                                                                       copySnapshotRequest.SourceRegion);

                var authorization = "&" + signingResult.ForQueryParameters;
                var url           = AmazonServiceClient.ComposeUrl(irequest);

                copySnapshotRequest.PresignedUrl = url.AbsoluteUri + authorization;
            }

            var authorizeSecurityGroupEgressRequest = request as AuthorizeSecurityGroupEgressRequest;

            if (authorizeSecurityGroupEgressRequest != null)
            {
                if (authorizeSecurityGroupEgressRequest.IsSetIpPermissions())
                {
                    SelectModifiedIpRange(authorizeSecurityGroupEgressRequest.IpPermissions);
                }
            }

            var authorizeSecurityGroupIngressRequest = request as AuthorizeSecurityGroupIngressRequest;

            if (authorizeSecurityGroupIngressRequest != null)
            {
                if (authorizeSecurityGroupIngressRequest.IsSetIpPermissions())
                {
                    SelectModifiedIpRange(authorizeSecurityGroupIngressRequest.IpPermissions);
                }
            }

            var revokeSecurityGroupEgressRequest = request as RevokeSecurityGroupEgressRequest;

            if (revokeSecurityGroupEgressRequest != null)
            {
                if (revokeSecurityGroupEgressRequest.IsSetIpPermissions())
                {
                    SelectModifiedIpRange(revokeSecurityGroupEgressRequest.IpPermissions);
                }
            }

            var revokeSecurityGroupIngressRequest = request as RevokeSecurityGroupIngressRequest;

            if (revokeSecurityGroupIngressRequest != null)
            {
                if (revokeSecurityGroupIngressRequest.IsSetIpPermissions())
                {
                    SelectModifiedIpRange(revokeSecurityGroupIngressRequest.IpPermissions);
                }
            }

            var updateSecurityGroupRuleDescriptionsEgressRequest = request as UpdateSecurityGroupRuleDescriptionsEgressRequest;

            if (updateSecurityGroupRuleDescriptionsEgressRequest != null)
            {
                if (updateSecurityGroupRuleDescriptionsEgressRequest.IsSetIpPermissions())
                {
                    SelectModifiedIpRange(updateSecurityGroupRuleDescriptionsEgressRequest.IpPermissions);
                }
            }

            var updateSecurityGroupRuleDescriptionsIngressRequest = request as UpdateSecurityGroupRuleDescriptionsIngressRequest;

            if (updateSecurityGroupRuleDescriptionsIngressRequest != null)
            {
                if (updateSecurityGroupRuleDescriptionsIngressRequest.IsSetIpPermissions())
                {
                    SelectModifiedIpRange(updateSecurityGroupRuleDescriptionsIngressRequest.IpPermissions);
                }
            }
        }
        /// <summary>
        /// Generate a presigned URL based on a <see cref="SynthesizeSpeechRequest"/>.
        /// </summary>
        /// <param name="credentials">The credentials to use in the presigned URL.</param>
        /// <param name="region">The region for the URL.</param>
        /// <param name="request">The request to base the presigned URL on.</param>
        /// <returns></returns>
        public static string GeneratePresignedUrl(AWSCredentials credentials, RegionEndpoint region, SynthesizeSpeechRequest request)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }

            if (region == null)
            {
                throw new ArgumentNullException("region");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // Marshall this request and prepare it to be signed
            var marshaller = new SynthesizeSpeechRequestMarshaller();
            var iRequest   = marshaller.Marshall(request);

            iRequest.UseQueryString          = true;
            iRequest.HttpMethod              = HTTPGet;
            iRequest.Endpoint                = new UriBuilder(HTTPS, region.GetEndpointForService(PollyServiceName).Hostname).Uri;
            iRequest.Parameters[XAmzExpires] = ((int)FifteenMinutes.TotalSeconds).ToString(CultureInfo.InvariantCulture);

            if (request.IsSetLexiconNames())
            {
                iRequest.ParameterCollection.Add("LexiconNames", request.LexiconNames);
            }

            if (request.IsSetOutputFormat())
            {
                iRequest.Parameters["OutputFormat"] = request.OutputFormat.ToString();
            }

            if (request.IsSetSampleRate())
            {
                iRequest.Parameters["SampleRate"] = request.SampleRate.ToString();
            }

            if (request.IsSetText())
            {
                iRequest.Parameters["Text"] = request.Text;
            }

            if (request.IsSetTextType())
            {
                iRequest.Parameters["TextType"] = request.TextType.ToString();
            }

            if (request.IsSetVoiceId())
            {
                iRequest.Parameters["VoiceId"] = request.VoiceId;
            }

            if (request.IsSetSpeechMarkTypes())
            {
                iRequest.ParameterCollection.Add("SpeechMarkTypes", request.SpeechMarkTypes);
            }

            if (request.IsSetLanguageCode())
            {
                iRequest.ParameterCollection.Add("LanguageCode", request.LanguageCode);
            }

            var immutableCredentials = credentials.GetCredentials();

            if (immutableCredentials.UseToken)
            {
                // Don't use HeaderKeys.XAmzSecurityTokenHeader because Polly treats this as case-sensitive
                iRequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
            }

            // Only the host header should be signed, and the signer adds that.
            // So clear out headers.
            iRequest.Headers.Clear();

            // Create presigned URL and assign it
            var signingResult = AWS4PreSignedUrlSigner.SignRequest(iRequest, null, new RequestMetrics(),
                                                                   immutableCredentials.AccessKey, immutableCredentials.SecretKey, PollyServiceName, region.SystemName);

            var authorization = "&" + signingResult.ForQueryParameters;

            return(AmazonServiceClient.ComposeUrl(iRequest).AbsoluteUri + authorization);
        }
Exemple #25
0
 private AmazonSQSClient(AWSCredentials credentials, AmazonSQSConfig config)
 {
     this.config                  = config;
     this.awsAccessKeyId          = credentials.GetCredentials().AccessKey;
     this.clearAwsSecretAccessKey = credentials.GetCredentials().SecretKey;
 }
Exemple #26
0
 public void Upload(Stream objectToUpload, int iteration)
 {
     try
     {
         PutS3ObjectSample.Run("v3/" + iteration + ".png", objectToUpload, _region, _bucketName, _credentials.GetCredentials().AccessKey, _credentials.GetCredentials().SecretKey);
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
     }
 }
 private static void SetDefaultCredential(AWSCredentials creds)
 {
     RunConfigure(string.Format("set aws_access_key_id {0}", creds.GetCredentials().AccessKey), true, false);
     RunConfigure(string.Format("set aws_secret_access_key {0}", creds.GetCredentials().SecretKey), true, false);
 }