/**
         * Add authentication related and version parameters
         */
        private void AddRequiredParameters(IDictionary <string, string> parameters)
        {
            using (ImmutableCredentials immutableCredentials = this.credentials.GetCredentials())
            {
                if (String.IsNullOrEmpty(immutableCredentials.AccessKey))
                {
                    throw new AmazonSimpleNotificationServiceException("The AWS Access Key ID cannot be NULL or a Zero length string");
                }

                if (immutableCredentials.UseToken)
                {
                    parameters["SecurityToken"] = immutableCredentials.Token;
                }
                parameters["AWSAccessKeyId"]   = immutableCredentials.AccessKey;
                parameters["SignatureVersion"] = config.SignatureVersion;
                parameters["SignatureMethod"]  = config.SignatureMethod;
                parameters["Timestamp"]        = AWSSDKUtils.FormattedCurrentTimestampISO8601;
                parameters["Version"]          = config.ServiceVersion;
                if (!config.SignatureVersion.Equals("2"))
                {
                    throw new AmazonSimpleNotificationServiceException("Invalid Signature Version specified");
                }

                string url;
                if (config.RegionEndpoint != null)
                {
                    url = "https://" + config.RegionEndpoint.GetEndpointForService(config.RegionEndpointServiceName).Hostname;
                }
                else
                {
                    url = config.ServiceURL;
                }

                string toSign = AWSSDKUtils.CalculateStringToSignV2(parameters, url);

                KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(config.SignatureMethod.ToUpper());
                string             auth;

                if (immutableCredentials.UseSecureStringForSecretKey)
                {
                    auth = AWSSDKUtils.HMACSign(toSign, immutableCredentials.SecureSecretKey, algorithm);
                }
                else
                {
                    auth = AWSSDKUtils.HMACSign(toSign, immutableCredentials.ClearSecretKey, algorithm);
                }
                parameters["Signature"] = auth;
            }
        }
        private void SetPowershellSamlProfile(ImmutableCredentials awsSessionCredentials)
        {
            // create a pipeline and feed it the script text
            string script = String.Format("Set-AWSCredentials -AccessKey '{0}' -SecretKey '{1}' -SessionToken '{2}'", awsSessionCredentials.AccessKey, awsSessionCredentials.SecretKey, awsSessionCredentials.Token);

            Runspace theRunSpace = System.Management.Automation.Runspaces.Runspace.DefaultRunspace;

            if (theRunSpace.RunspaceStateInfo.State == RunspaceState.Opened)
            {
                using (Pipeline thePipeline = theRunSpace.CreateNestedPipeline(script, true))
                {
                    Collection <PSObject> theRetVal = thePipeline.Invoke();
                }
            }
        }
예제 #3
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"
            });
        }
예제 #4
0
        private static string GetHeadBucketPreSignedUrl(string bucketName, ImmutableCredentials credentials)
        {
            GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
            {
                BucketName = bucketName,
                Expires    = DateTime.Now.AddDays(1.0),
                Verb       = HttpVerb.HEAD,
                Protocol   = Protocol.HTTP
            };

            using (AmazonS3Client amazonS3Client = GetUsEast1ClientFromCredentials(credentials))
            {
                return(amazonS3Client.GetPreSignedURLInternal(request, useSigV2Fallback: false));
            }
        }
예제 #5
0
        private static void AddHeaders(
            HttpRequestMessage request,
            DateTime now,
            string serviceName,
            ImmutableCredentials credentials,
            string contentHash)
        {
            // Add required headers
            request.AddHeader(HeaderKeys.XAmzDateHeader, now.ToIso8601BasicDateTime());

            // Add conditional headers
            request.AddHeaderIf(credentials.UseToken, HeaderKeys.XAmzSecurityTokenHeader, credentials.Token);
            request.AddHeaderIf(!request.Headers.Contains(HeaderKeys.HostHeader), HeaderKeys.HostHeader, request.RequestUri !.Host);
            request.AddHeaderIf(serviceName == ServiceName.S3, HeaderKeys.XAmzContentSha256Header, contentHash);
        }
예제 #6
0
 /// <summary>
 /// Computes and returns an AWS4 signature for the specified canonicalized request
 /// </summary>
 /// <param name="credentials"></param>
 /// <param name="region"></param>
 /// <param name="signedAt"></param>
 /// <param name="service"></param>
 /// <param name="signedHeaders"></param>
 /// <param name="canonicalRequest"></param>
 /// <returns></returns>
 public static AWS4SigningResult ComputeSignature(ImmutableCredentials credentials,
                                                  string region,
                                                  DateTime signedAt,
                                                  string service,
                                                  string signedHeaders,
                                                  string canonicalRequest)
 {
     return(ComputeSignature(credentials.AccessKey,
                             credentials.SecretKey,
                             region,
                             signedAt,
                             service,
                             signedHeaders,
                             canonicalRequest));
 }
 /// <summary>
 /// Send a Signature Version 4 signed PUT request with a cancellation token as an
 /// asynchronous operation.
 /// </summary>
 /// <param name="self">
 /// The extension target.
 /// </param>
 /// <param name="requestUri">
 /// The Uri the request is sent to.
 /// </param>
 /// <param name="content">
 /// The HTTP request content sent to the server.
 /// </param>
 /// <param name="cancellationToken">
 /// A cancellation token that can be used by other objects or threads to receive notice of
 /// cancellation.
 /// </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 task object representing the asynchronous operation.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// The <paramref name="requestUri"/> is null.
 /// </exception>
 /// <exception cref="HttpRequestException">
 /// The request failed due to an underlying issue such as network connectivity, DNS
 /// failure, server certificate validation or timeout.
 /// </exception>
 /// <remarks>
 /// This operation will not block. The returned <see cref="Task{TResult}"/> object will
 /// complete once the entire response including content is read.
 /// </remarks>
 public static Task <HttpResponseMessage> PutAsync(
     this HttpClient self,
     string requestUri,
     HttpContent content,
     CancellationToken cancellationToken,
     string regionName,
     string serviceName,
     ImmutableCredentials credentials) =>
 self.PutAsync(
     requestUri.ToUri(),
     content,
     cancellationToken,
     regionName,
     serviceName,
     credentials);
 /// <summary>
 /// Send a Signature Version 4 signed GET request to the specified Uri with an HTTP
 /// completion option and a cancellation token as an asynchronous operation.
 /// </summary>
 /// <param name="self">
 /// The extension target.
 /// </param>
 /// <param name="requestUri">
 /// The Uri the request is sent to.
 /// </param>
 /// <param name="completionOption">
 /// An HTTP completion option value that indicates when the operation should be considered
 /// completed.
 /// </param>
 /// <param name="cancellationToken">
 /// A cancellation token that can be used by other objects or threads to receive notice of
 /// cancellation.
 /// </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 task object representing the asynchronous operation.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// The <paramref name="requestUri"/> is null.
 /// </exception>
 /// <exception cref="HttpRequestException">
 /// The request failed due to an underlying issue such as network connectivity, DNS
 /// failure, server certificate validation or timeout.
 /// </exception>
 /// <remarks>
 /// This operation will not block. Depending on the value of the
 /// <paramref name="completionOption"/> parameter, the returned <see cref="Task{TResult}"/>
 /// object will complete as soon as a response is available or the entire response
 /// including content is read.
 /// </remarks>
 public static Task <HttpResponseMessage> GetAsync(
     this HttpClient self,
     Uri requestUri,
     HttpCompletionOption completionOption,
     CancellationToken cancellationToken,
     string regionName,
     string serviceName,
     ImmutableCredentials credentials) =>
 self.SendAsync(
     new HttpRequestMessage(HttpMethod.Get, requestUri),
     completionOption,
     cancellationToken,
     regionName,
     serviceName,
     credentials);
 private static AmazonS3Client GetUsEast1ClientFromCredentials(ImmutableCredentials credentials)
 {
     if (credentials == null)
     {
         return(new AmazonS3Client(new AnonymousAWSCredentials(), RegionEndpoint.USEast1));
     }
     else if (credentials.UseToken)
     {
         return(new AmazonS3Client(credentials.AccessKey, credentials.SecretKey, credentials.Token, RegionEndpoint.USEast1));
     }
     else
     {
         return(new AmazonS3Client(credentials.AccessKey, credentials.SecretKey, RegionEndpoint.USEast1));
     }
 }
예제 #10
0
        private static string WriteCreds(string profileName, ImmutableCredentials ic)
        {
            string configPath = Path.GetFullPath("credentials");

            using (var stream = File.Open(configPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (var writer = new StreamWriter(stream))
                {
                    AppendCredentialsSet(writer, profileName + "0", basicCreds);
                    AppendCredentialsSet(writer, profileName + "1", sessionCreds);
                    AppendCredentialsSet(writer, profileName, ic);
                    AppendCredentialsSet(writer, profileName + "2", basicCreds);
                    AppendCredentialsSet(writer, profileName + "3", sessionCreds);
                }

            return(configPath);
        }
예제 #11
0
        public void ProcessAuthorizationHeaderSuccess()
        {
            var request = new HttpRequestMessage();
            var creds   = new ImmutableCredentials("accessKeyId", "secretKey", "token");

            ServerModeHttpClientAuthorizationHandler.AddAuthorizationHeader(request, creds);

            if (!request.Headers.TryGetValues("Authorization", out var value))
            {
                throw new Exception("Missing Authorization header");
            }

            var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(value.FirstOrDefault(), new NoEncryptionProvider());

            Assert.True(authResults.Succeeded);
        }
        /// <summary>
        /// Calls pre invoke logic before calling the next handler
        /// in the pipeline.
        /// </summary>
        /// <typeparam name="T">The response type for the current request.</typeparam>
        /// <param name="executionContext">The execution context, it contains the
        /// request and response context.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public override async System.Threading.Tasks.Task <T> InvokeAsync <T>(IExecutionContext executionContext)
        {
            ImmutableCredentials ic = null;

            if (Credentials != null && !(Credentials is AnonymousAWSCredentials))
            {
                using (executionContext.RequestContext.Metrics.StartEvent(Metric.CredentialsRequestTime))
                {
                    ic = await Credentials.GetCredentialsAsync().ConfigureAwait(false);
                }
            }

            executionContext.RequestContext.ImmutableCredentials = ic;

            return(await base.InvokeAsync <T>(executionContext).ConfigureAwait(false));
        }
        // https://gist.github.com/jesusnoseq/da3b259dcef697fc310be878800d1c33
        void AuthenticatedGet(ImmutableCredentials cognitoCredentials)
        {
            // ************* REQUEST VALUES *************
            string accessKey     = cognitoCredentials.AccessKey;
            string secretKey     = cognitoCredentials.SecretKey;
            string securityToken = cognitoCredentials.Token;

            string algorithm         = "AWS4-HMAC-SHA256";
            string method            = "GET";
            string service           = "execute-api";
            string serviceForSigning = "apigateway";
            string contentType       = "application/json";
            string expires           = "900";
            string amzDate           = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ");
            string dateStamp         = DateTime.UtcNow.ToString("yyyyMMdd");
        }
예제 #14
0
 private static void ValidateArguments(
     HttpRequestMessage request,
     string regionName,
     string serviceName,
     ImmutableCredentials credentials)
 {
     if (request == null)
     {
         throw new ArgumentNullException(nameof(request));
     }
     if (request.Headers.Contains(HeaderKeys.XAmzDateHeader))
     {
         throw new ArgumentException(ErrorMessages.XAmzDateHeaderExists, nameof(request));
     }
     if (request.Headers.Authorization != null)
     {
         throw new ArgumentException(ErrorMessages.AuthorizationHeaderExists, nameof(request));
     }
     if (request.Headers.Contains(HeaderKeys.AuthorizationHeader))
     {
         throw new ArgumentException(ErrorMessages.AuthorizationHeaderExists, nameof(request));
     }
     if (regionName == null)
     {
         throw new ArgumentNullException(nameof(regionName));
     }
     if (regionName == string.Empty)
     {
         throw new ArgumentException(ErrorMessages.InvalidRegionName, nameof(regionName));
     }
     if (serviceName == null)
     {
         throw new ArgumentNullException(nameof(serviceName));
     }
     if (serviceName == string.Empty)
     {
         throw new ArgumentException(ErrorMessages.InvalidServiceName, nameof(serviceName));
     }
     if (serviceName == ServiceName.S3 && request.Method == HttpMethod.Post)
     {
         throw new NotSupportedException(ErrorMessages.S3DoesNotSupportPost);
     }
     if (credentials == null)
     {
         throw new ArgumentNullException(nameof(credentials));
     }
 }
예제 #15
0
        /// /// <summary>
        /// Calculates the signature for the specified request using the Asymmetric SigV4
        /// signing protocol in preparation for generating a presigned URL.
        /// </summary>
        /// <param name="request">
        /// The request to compute the signature for. Additional headers mandated by the
        /// SigV4a protocol will be added to the request before signing.
        /// </param>
        /// <param name="clientConfig">
        /// Client configuration data encompassing the service call (notably authentication
        /// region, endpoint and service name).
        /// </param>
        /// <param name="metrics">Metrics for the request</param>
        /// <param name="credentials">The AWS credentials for the account making the service call</param>
        /// <param name="service">Service to sign the request for</param>
        /// <param name="overrideSigningRegion">Region to sign the request for</param>
        /// <returns>AWS4aSigningResult for the given request</returns>
        public AWS4aSigningResult Presign4a(IRequest request,
                                            IClientConfig clientConfig,
                                            RequestMetrics metrics,
                                            ImmutableCredentials credentials,
                                            string service,
                                            string overrideSigningRegion)
        {
            var signedAt  = AWS4Signer.InitializeHeaders(request.Headers, request.Endpoint);
            var regionSet = overrideSigningRegion ?? AWS4Signer.DetermineSigningRegion(clientConfig, service, request.AlternateEndpoint, request);

            var signingConfig = PrepareCRTSigningConfig(AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS, regionSet, service, signedAt, credentials);

            if (AWS4PreSignedUrlSigner.ServicesUsingUnsignedPayload.Contains(service))
            {
                signingConfig.SignedBodyValue = AWS4Signer.UnsignedPayload;
            }
            else
            {
                signingConfig.SignedBodyValue = AWS4Signer.EmptyBodySha256;
            }

            // The expiration may have already be set in a header when marshalling the GetPreSignedUrlRequest -> IRequest
            if (request.Parameters != null && request.Parameters.ContainsKey(HeaderKeys.XAmzExpires))
            {
                signingConfig.ExpirationInSeconds = Convert.ToUInt64(request.Parameters[HeaderKeys.XAmzExpires]);
            }

            var crtRequest    = CrtHttpRequestConverter.ConvertToCrtRequest(request);
            var signingResult = AwsSigner.SignHttpRequest(crtRequest, signingConfig);

            string authorizationValue = Encoding.Default.GetString(signingResult.Get().Signature);
            var    dateStamp          = AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat);
            var    scope = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", dateStamp, service, AWS4Signer.Terminator);

            AWS4aSigningResult result = new AWS4aSigningResult(
                credentials.AccessKey,
                signedAt,
                CrtHttpRequestConverter.ExtractSignedHeaders(signingResult.Get().SignedRequest),
                scope,
                regionSet,
                authorizationValue,
                service,
                signingResult.Get().SignedRequest.Uri,
                credentials);

            return(result);
        }
        /// <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
            });
        }
예제 #17
0
        protected override void PreInvoke(IExecutionContext executionContext)
        {
            ImmutableCredentials ic = null;

            if (Credentials != null && (Credentials is BasicServiceCredentials))
            {
                try
                {
                    ic = Credentials.GetCredentials();
                }
                finally
                {
                }
            }

            executionContext.RequestContext.ImmutableCredentials = ic;
        }
예제 #18
0
 public TestSuiteContext()
 {
     RegionName  = "us-east-1";
     ServiceName = "service";
     UtcNow      = new DateTime(
         2015,
         8,
         30,
         12,
         36,
         00,
         DateTimeKind.Utc);
     Credentials = new ImmutableCredentials(
         "AKIDEXAMPLE",
         "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
         null);
 }
예제 #19
0
 /// <summary>
 /// Constructs a new signing result instance for a computed signature
 /// </summary>
 /// <param name="awsAccessKeyId">The access key that was included in the signature</param>
 /// <param name="signedAt">Date/time (UTC) that the signature was computed</param>
 /// <param name="signedHeaders">The collection of headers names that were included in the signature</param>
 /// <param name="scope">Formatted 'scope' value for signing (YYYYMMDD/region/service/aws4_request)</param>
 /// <param name="regionSet">The set of AWS regions this signature is valid for</param>
 /// <param name="signature">Computed signature</param>
 /// <param name="service">Service the request was signed for</param>
 /// <param name="presignedUri">Presigned Uri</param>
 /// <param name="credentials">Credentials of the AWS account making the signed request</param>
 public AWS4aSigningResult(string awsAccessKeyId,
                           DateTime signedAt,
                           string signedHeaders,
                           string scope,
                           string regionSet,
                           string signature,
                           string service,
                           string presignedUri,
                           ImmutableCredentials credentials) :
     base(awsAccessKeyId, signedAt, signedHeaders, scope)
 {
     _regionSet    = regionSet;
     _signature    = signature;
     _service      = service;
     _presignedUri = presignedUri;
     _credentials  = credentials;
 }
예제 #20
0
    private IEnumerator CognitoCredentialsForIdentity(string identityId, Dictionary <string, string> logins = null)
    {
        var amzDate = DateTime.Now.ToString("yyyyMMddTHHmmssZ");
        var request = new Dictionary <string, object> {
            { "IdentityId", identityId }
        };

        if (logins != null)
        {
            request.Add("Logins", logins);
        }
        var dataString = JsonConvert.SerializeObject(request);
        var data       = System.Text.Encoding.UTF8.GetBytes(dataString);
        var post       = UnityWebRequest.Put("https://cognito-identity.us-east-1.amazonaws.com/", data);

        post.SetRequestHeader("Content-Type", "application/x-amz-json-1.1");
        post.SetRequestHeader("X-AMZ-TARGET", "com.amazonaws.cognito.identity.model.AWSCognitoIdentityService.GetCredentialsForIdentity");
        post.SetRequestHeader("X-Amz-Date", amzDate);
        post.method = UnityWebRequest.kHttpVerbPOST;
        yield return(post.SendWebRequest());

        if (!post.isNetworkError && !post.isHttpError)
        {
            var response = JObject.Parse(post.downloadHandler.text);
            if (identityId != response["IdentityId"].ToString())
            {
                _dbg("Cognito user has been changed! Old: " + identityId + " New: " + response["IdentityId"].ToString());
            }
            credentials = new ImmutableCredentials(
                //response["IdentityId"].ToString(),
                response["Credentials"]["AccessKeyId"].ToString(),
                response["Credentials"]["SecretKey"].ToString(),
                response["Credentials"]["SessionToken"].ToString()
                //Convert.ToUInt64(response["Credentials"]["Expiration"].ToString()),
                //logins != null
                );
            //_dbg("credentials:");
            //_dbg($"\t* AccessKey:{credentials.AccessKey}");
            //_dbg($"\t* SecretKey:{credentials.SecretKey}");
            //_dbg($"\t* SessionToken:{credentials.Token}");
        }
        else
        {
            _dbg("Ups! Credentials not found");
        }
    }
예제 #21
0
        internal static void SignRequest(IRequestContext requestContext)
        {
            ImmutableCredentials immutableCredentials = requestContext.ImmutableCredentials;

            if (immutableCredentials == null)
            {
                return;
            }

            try
            {
                requestContext.Signer.Sign(requestContext.Request, immutableCredentials.AccessKey, immutableCredentials.SecretKey, immutableCredentials.SecurityToken);
            }
            finally
            {
            }
        }
예제 #22
0
        /// <summary>
        /// Calculates the signature for the specified request using the Asymmetric SigV4 signing protocol
        /// </summary>
        /// <param name="request">
        /// The request to compute the signature for. Additional headers mandated by the
        /// SigV4a protocol will be added to the request before signing.
        /// </param>
        /// <param name="clientConfig">
        /// Client configuration data encompassing the service call (notably authentication
        /// region, endpoint and service name).
        /// </param>
        /// <param name="metrics">Metrics for the request</param>
        /// <param name="credentials">The AWS credentials for the account making the service call</param>
        /// <returns>AWS4aSigningResult for the given request</returns>
        public AWS4aSigningResult SignRequest(IRequest request,
                                              IClientConfig clientConfig,
                                              RequestMetrics metrics,
                                              ImmutableCredentials credentials)
        {
            var signedAt           = AWS4Signer.InitializeHeaders(request.Headers, request.Endpoint);
            var serviceSigningName = !string.IsNullOrEmpty(request.OverrideSigningServiceName) ? request.OverrideSigningServiceName : AWS4Signer.DetermineService(clientConfig);
            var regionSet          = AWS4Signer.DetermineSigningRegion(clientConfig, clientConfig.RegionEndpointServiceName, request.AlternateEndpoint, request);

            request.DeterminedSigningRegion = regionSet;
            AWS4Signer.SetXAmzTrailerHeader(request.Headers, request.TrailingHeaders);

            var signingConfig = PrepareCRTSigningConfig(AwsSignatureType.HTTP_REQUEST_VIA_HEADERS, regionSet, serviceSigningName, signedAt, credentials);

            // If the request should use a fixed x-amz-content-sha256 header value, determine the appropriate one
            var fixedBodyHash = request.TrailingHeaders?.Count > 0
                ? AWS4Signer.V4aStreamingBodySha256WithTrailer
                : AWS4Signer.V4aStreamingBodySha256;

            signingConfig.SignedBodyValue = AWS4Signer.SetRequestBodyHash(request, SignPayload, fixedBodyHash, ChunkedUploadWrapperStream.V4A_SIGNATURE_LENGTH);

            var crtRequest    = CrtHttpRequestConverter.ConvertToCrtRequest(request);
            var signingResult = AwsSigner.SignHttpRequest(crtRequest, signingConfig);

            var authorizationValue = Encoding.Default.GetString(signingResult.Get().Signature);
            var signedCrtRequest   = signingResult.Get().SignedRequest;

            CrtHttpRequestConverter.CopyHeadersFromCrtRequest(request, signedCrtRequest);

            var dateStamp = AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat);
            var scope     = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", dateStamp, serviceSigningName, AWS4Signer.Terminator);

            AWS4aSigningResult result = new AWS4aSigningResult(
                credentials.AccessKey,
                signedAt,
                CrtHttpRequestConverter.ExtractSignedHeaders(signedCrtRequest),
                scope,
                regionSet,
                authorizationValue,
                serviceSigningName,
                "",
                credentials);

            return(result);
        }
예제 #23
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
            });
        }
예제 #24
0
        /// Resolves the AWS credentials that will be used to authenticate to AWS
        /// by way of signing a request to the AWS STS <c>GetCallerIdentity</c>
        /// API endpoint.  If explicity credentials have been provided in the
        /// configuration options passed into this instance constructure, then they
        /// will be used, otherwise, the credentials will be resolved as described
        /// in the AWS SDK process for
        /// <see cref="https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html#creds-locate"
        /// >Accessing Credentials and Profiles in an Application</see>.
        public async Task AuthenticateToAwsIamAsync()
        {
            if (_awsCreds == null)
            {
                _logger.LogInformation("explicity AWS credentials are not provided,"
                                       + " attempting to resolve from the running context");

                var creds = FallbackCredentialsFactory.GetCredentials(false);
                _awsCreds = await creds.GetCredentialsAsync();

                _logger.LogInformation("resolved to Access Key: " + _awsCreds.AccessKey);
            }

            if (_awsCreds == null)
            {
                throw new Exception("AWS credentials could not be resolved");
            }
        }
예제 #25
0
        private async void initFields(AWSCredentialsProfile profile)
        {
            toggleFields(false);

            // Get this profile's credentials asynchronously
            _origProfile = profile;
            using (new WaitCursor()) {
                _origCreds = await profile.Credentials.GetCredentialsAsync();
            }

            // Initialize controls with these credentials
            this.Text               = string.Format(EditProfileTitle, _origProfile.Name);
            TxtProfileName.Text     = _origProfile.Name;
            TxtAccessKeyID.Text     = _origCreds.AccessKey;
            TxtSecretAccessKey.Text = _origCreds.SecretKey;

            toggleFields(true);
        }
예제 #26
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>
        /// Send an Signature Version 4 signed HTTP request as an asynchronous operation.
        /// </summary>
        /// <param name="self">
        /// The extension target.
        /// </param>
        /// <param name="request">
        /// The HTTP request message to send.
        /// </param>
        /// <param name="completionOption">
        /// When the operation should complete (as soon as a response is available or after reading
        /// the whole 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 task object representing the asynchronous operation.
        /// </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, server certificate validation or timeout.
        /// </exception>
        /// <remarks>
        /// This operation will not block. Depending on the value of the
        /// <paramref name="completionOption"/> parameter, the returned <see cref="Task{TResult}"/>
        /// object will complete as soon as a response is available or the entire response
        /// including content is read.
        /// </remarks>
        public static async Task <HttpResponseMessage> SendAsync(
            this HttpClient self,
            HttpRequestMessage request,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken,
            string regionName,
            string serviceName,
            ImmutableCredentials credentials)
        {
            if (self == null)
            {
                throw new ArgumentNullException(nameof(self));
            }

            await Signer.SignAsync(self, request, DateTime.UtcNow, regionName, serviceName, credentials);

            return(await self.SendAsync(request, completionOption, cancellationToken));
        }
예제 #28
0
        private string Sign(ImmutableCredentials credentialsImmutable, string hashedRequestPayload, string requestMethod, string canonicalUri, string canonicalQueryString)
        {
            var currentDateTime = DateTime.UtcNow;
            var dateStamp       = currentDateTime.ToString("yyyMMdd");
            var requestDate     = currentDateTime.ToString("yyyyMMddTHHmmssZ");

            var credentialsScope = string.Format("{0}/{1}/{2}/aws4_request", dateStamp, ServiceRegion.ToString(), ServiceName);

            var headers = new SortedDictionary <string, string>
            {
                { "content-type", ContentType },
                { "host", Host },
                { "x-amz-date", requestDate },
                { "x-amz-security-token", credentialsImmutable.Token }
            };

            string canonicalHeaders = string.Join("\n", headers.Select(x => x.Key.ToLowerInvariant() + ":" + x.Value.Trim())) + "\n";

            // Task 1: Create a Canonical Request For Signature Version 4
            string canonicalRequest       = requestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + SignedHeaders + "\n" + hashedRequestPayload;
            string hashedCanonicalRequest = HexEncode(Hash(ToBytes(canonicalRequest)));

            // Task 2: Create a String to Sign for Signature Version 4
            string stringToSign = Algorithm + "\n" + requestDate + "\n" + credentialsScope + "\n" + hashedCanonicalRequest;

            // Task 3: Calculate the AWS Signature Version 4
            byte[] signingKey = GetSignatureKey(credentialsImmutable.SecretKey, dateStamp, ServiceRegion.ToString(), ServiceName);
            string signature  = HexEncode(HmacSha256(stringToSign, signingKey));

            // Task 4: Prepare a signed request
            // Authorization: algorithm Credential=access key ID/credential scope, SignedHeadaers=SignedHeaders, Signature=signature

            string authorization = string.Format("{0} Credential={1}/{2}/{3}/{4}/aws4_request, SignedHeaders={5}, Signature={6}",
                                                 Algorithm,
                                                 credentialsImmutable.AccessKey,
                                                 dateStamp,
                                                 ServiceRegion,
                                                 ServiceName,
                                                 SignedHeaders,
                                                 signature
                                                 );

            return(authorization);
        }
        public ReportHandlerTests()
        {
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            chain.TryGetAWSCredentials("DD MWS", out awsCredentials);
            creds = awsCredentials.GetCredentials();

            serviceContext.MwsAuthToken    = mWSAuthToken;
            serviceContext.AppVersion      = appVersion;
            serviceContext.AccessKey       = creds.AccessKey;
            serviceContext.SecretKey       = creds.SecretKey;
            serviceContext.SellerId        = sellerId;
            serviceContext.ApplicationName = "test";
            serviceContext.MwsServiceUrl   = serviceURL;

            mockLogger    = new Mock <ILogger>();
            reportHandler = new ReportHandler(serviceContext, mockLogger.Object);
        }
예제 #30
0
        public async Task <Creds> GetCredsAsync()
        {
            ImmutableCredentials iCreds = null;

            try
            {
                iCreds = await Credentials.GetCredentialsAsync();

                return(new Creds()
                {
                    AccessKey = iCreds.AccessKey,
                    SecretKey = iCreds.SecretKey,
                    Token = iCreds.Token
                });
            } catch (Exception e)
            {
                return(new Creds());
            }
        }
 /// <summary>
 /// Computes and returns an AWS4 signature for the specified canonicalized request
 /// </summary>
 /// <param name="credentials"></param>
 /// <param name="region"></param>
 /// <param name="signedAt"></param>
 /// <param name="service"></param>
 /// <param name="signedHeaders"></param>
 /// <param name="canonicalRequest"></param>
 /// <returns></returns>
 public static AWS4SigningResult ComputeSignature(ImmutableCredentials credentials,
                                                  string region,
                                                  DateTime signedAt,
                                                  string service,
                                                  string signedHeaders,
                                                  string canonicalRequest)
 {
     return ComputeSignature(credentials.AccessKey,
                             credentials.SecretKey,
                             region,
                             signedAt,
                             service,
                             signedHeaders,
                             canonicalRequest);
 }
예제 #32
0
 /// <summary>
 /// Return the credentials for the profile if valid credentials can be found.
 /// </summary>
 /// <param name="profileName">name of profile to find credentials for</param>
 /// <param name="credentials">the credentials for the profile</param>
 /// <returns>true if the profile was found and it contained valid credentials, false otherwise</returns>
 public bool TryGetCredentials(string profileName, out ImmutableCredentials credentials)
 {
     credentials = GetCredentials(profileName, false);
     return credentials != null;
 }