コード例 #1
1
ファイル: S3Signer.cs プロジェクト: aws/aws-sdk-net
        public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            var signer = SelectSigner(this, _useSigV4, request, clientConfig);
            var aws4Signer = signer as AWS4Signer;
            var useV4 = aws4Signer != null;

            if (useV4)
            {
                AmazonS3Uri s3Uri;
                if (AmazonS3Uri.TryParseAmazonS3Uri(request.Endpoint, out s3Uri))
                {
                    if (s3Uri.Bucket != null)
                    {
                        RegionEndpoint cachedRegion;
                        if (BucketRegionDetector.BucketRegionCache.TryGetValue(s3Uri.Bucket, out cachedRegion))
                        {
                            request.AlternateEndpoint = cachedRegion;
                        }
                    }
                }

                var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
                request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
                if (request.UseChunkEncoding)
                    request.AWS4SignerResult = signingResult;
            }
            else
                SignRequest(request, metrics, awsAccessKeyId, awsSecretAccessKey);
        }
コード例 #2
0
 public abstract void Sign(
     IRequest request,
     ClientConfig clientConfig,
     RequestMetrics metrics,
     string awsAccessKeyId,
     string awsSecretAccessKey,
     SecureString secureKey);
コード例 #3
0
        private static void SignHttps(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            string nonce = Guid.NewGuid().ToString();
            string date  = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            string stringToSign;

            stringToSign = date + nonce;
            metrics.AddProperty(Metric.StringToSign, stringToSign);

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

            StringBuilder builder = new StringBuilder();

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

            builder.Append(GetSignedHeadersComponent(request) + ",");

            request.Headers[HeaderKeys.XAmzAuthorizationHeader] = builder.ToString();
            request.Headers[HeaderKeys.XAmzNonceHeader]         = nonce;
            request.Headers[HeaderKeys.XAmzDateHeader]          = date;
        }
コード例 #4
0
ファイル: S3Signer.cs プロジェクト: soumyamp/aws-sdk-net
        public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            var signer     = SelectSigner(this, _useSigV4, request, clientConfig);
            var aws4Signer = signer as AWS4Signer;
            var useV4      = aws4Signer != null;

            if (useV4)
            {
                AmazonS3Uri s3Uri;
                if (AmazonS3Uri.TryParseAmazonS3Uri(request.Endpoint, out s3Uri))
                {
                    if (s3Uri.Bucket != null)
                    {
                        RegionEndpoint cachedRegion;
                        if (BucketRegionDetector.BucketRegionCache.TryGetValue(s3Uri.Bucket, out cachedRegion))
                        {
                            request.AlternateEndpoint = cachedRegion;
                        }
                    }
                }

                var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
                request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
                if (request.UseChunkEncoding)
                {
                    request.AWS4SignerResult = signingResult;
                }
            }
            else
            {
                SignRequest(request, metrics, awsAccessKeyId, awsSecretAccessKey);
            }
        }
コード例 #5
0
            public QueueItem(
                bool mutatesSolutionState,
                bool requiresLSPSolution,
                ClientCapabilities clientCapabilities,
                string methodName,
                TextDocumentIdentifier?textDocument,
                TRequestType request,
                IRequestHandler <TRequestType, TResponseType> handler,
                Guid activityId,
                ILspLogger logger,
                RequestTelemetryLogger telemetryLogger,
                CancellationToken cancellationToken)
            {
                _completionSource = new TaskCompletionSource <TResponseType?>();
                // Set the tcs state to cancelled if the token gets cancelled outside of our callback (for example the server shutting down).
                cancellationToken.Register(() => _completionSource.TrySetCanceled(cancellationToken));

                Metrics = new RequestMetrics(methodName, telemetryLogger);

                _handler = handler;
                _logger  = logger;
                _request = request;

                ActivityId           = activityId;
                MutatesSolutionState = mutatesSolutionState;
                RequiresLSPSolution  = requiresLSPSolution;
                ClientCapabilities   = clientCapabilities;
                MethodName           = methodName;
                TextDocument         = textDocument;
            }
コード例 #6
0
 /// <summary>
 /// Calculates and signs the specified request using the asymmetric Sigv4 (Sigv4a) signing protocol.
 /// The resulting signature is added to the request headers as 'Authorization'. Parameters supplied in the request, either in
 /// the resource path as a query string or in the Parameters collection must not have been
 /// uri encoded. If they have, use the SignRequest method to obtain a signature.
 /// </summary>
 /// <param name="request">
 /// The request to compute the signature for. Additional headers mandated by the AWS4a protocol
 /// ('host' and 'x-amz-date') 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>AWS4a Signing Result</returns>
 public AWS4aSigningResult SignRequest(IRequest request,
                                       IClientConfig clientConfig,
                                       RequestMetrics metrics,
                                       ImmutableCredentials credentials)
 {
     return(_awsSigV4AProvider.SignRequest(request, clientConfig, metrics, credentials));
 }
コード例 #7
0
 public override void Sign(IRequest request,
                           IClientConfig clientConfig,
                           RequestMetrics metrics,
                           ImmutableCredentials credentials)
 {
     this.SignCount++;
 }
コード例 #8
0
        private void SignRequest(IRequest request, AbstractAWSSigner signer, RequestMetrics metrics)
        {
            // Check if request should be signed
            if (credentials is AnonymousAWSCredentials)
            {
                return;
            }

            metrics.StartEvent(RequestMetrics.Metric.CredentialsRequestTime);
            using (ImmutableCredentials immutableCredentials = credentials.GetCredentials())
            {
                metrics.StopEvent(RequestMetrics.Metric.CredentialsRequestTime);
                if (immutableCredentials.UseToken)
                {
                    ClientProtocol protocol = DetermineProtocol(signer);
                    switch (protocol)
                    {
                    case ClientProtocol.QueryStringProtocol:
                        request.Parameters["SecurityToken"] = immutableCredentials.Token;
                        break;

                    case ClientProtocol.RestProtocol:
                        request.Headers["x-amz-security-token"] = immutableCredentials.Token;
                        break;

                    default:
                        throw new InvalidDataException("Cannot determine protocol");
                    }
                }
                signer.Sign(request, this.config, immutableCredentials.AccessKey, immutableCredentials.ClearSecretKey, immutableCredentials.SecureSecretKey);
            }
        }
コード例 #9
0
        public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
        {
            var signer      = SelectSigner(this, _useSigV4, request, clientConfig);
            var aws4Signer  = signer as AWS4Signer;
            var aws4aSigner = signer as AWS4aSignerCRTWrapper;
            var useV4       = aws4Signer != null;
            var useV4a      = aws4aSigner != null;

            if (useV4a)
            {
                var signingResult = aws4aSigner.SignRequest(request, clientConfig, metrics, credentials);
                if (request.UseChunkEncoding)
                {
                    request.AWS4aSignerResult = signingResult;
                }
            }
            else if (useV4)
            {
                _regionDetector?.Invoke(request);
                var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
                request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
                if (request.UseChunkEncoding)
                {
                    request.AWS4SignerResult = signingResult;
                }
            }
            else
            {
                SignRequest(request, metrics, credentials.AccessKey, credentials.SecretKey);
            }
        }
コード例 #10
0
 public void Store(RequestMetrics db)
 {
     var response = _repository
                    .ESClient()
                    .Index(db, s => s
                           .Index(RequestMetrics.Name));
 }
コード例 #11
0
 public abstract void Sign(
     IRequest request,
     ClientConfig clientConfig,
     RequestMetrics metrics,
     string awsAccessKeyId,
     string awsSecretAccessKey,
     SecureString secureKey);
コード例 #12
0
        /// <summary>
        /// Sign method
        /// </summary>
        /// <param name="request"></param>
        /// <param name="clientConfig"></param>
        /// <param name="metrics"></param>
        /// <param name="awsAccessKeyId"></param>
        /// <param name="awsSecretAccessKey"></param>
        public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            base.Sign(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
            //内容Md5
            SetContentMd5(request);
            //移除Md5
            //RemoveContentMd5(request);

            //设置Copy头
            SetCopySource(request);

            //设置User-Agent
            SetUserAgent(request);

            //resourcePath
            var resourcePath = GetResourcePath(request);
            //待签名字符串
            var canonicalString = RestUtil.MakeKS3CanonicalString(request.HttpMethod, resourcePath, request, null);

            var hmacBytes = HmacUtil.GetHmacSha1(canonicalString, awsSecretAccessKey);
            //签名
            var signature = Convert.ToBase64String(hmacBytes);

            //默认头部添加
            if (!request.Headers.ContainsKey(Headers.CONTENT_TYPE))
            {
                request.Headers.Add(Headers.CONTENT_TYPE, Headers.DEFAULT_MIMETYPE);
            }
            //如果已经添加了认证,就移除
            if (request.Headers.ContainsKey(Headers.AUTHORIZATION))
            {
                request.Headers.Remove(Headers.AUTHORIZATION);
            }
            request.Headers.Add("Authorization", "KSS " + awsAccessKeyId + ":" + signature);
        }
コード例 #13
0
ファイル: EpoxyConnection.cs プロジェクト: xrcdev/bond
        private async Task SendReplyAsync(
            ulong conversationId, IMessage response, ILayerStack layerStack, RequestMetrics requestMetrics)
        {
            var sendContext = new EpoxySendContext(this, ConnectionMetrics, requestMetrics);

            IBonded layerData;
            Error   layerError = LayerStackUtils.ProcessOnSend(
                layerStack, MessageType.RESPONSE, sendContext, out layerData, logger);

            // If there was a layer error, replace the response with the layer error
            if (layerError != null)
            {
                logger.Site().Error("{0} Sending reply for conversation ID {1} failed due to layer error (Code: {2}, Message: {3}).",
                                    this, conversationId, layerError.error_code, layerError.message);

                // Set layer error as result of this Bond method call, replacing original response.
                // Since this error will be returned to client, cleanse out internal server error details, if any.
                response = Message.FromError(Errors.CleanseInternalServerError(layerError));
            }

            var frame = MessageToFrame(conversationId, null, null, EpoxyMessageType.RESPONSE, response, layerData, logger);

            logger.Site().Debug("{0} Sending reply for conversation ID {1}.", this, conversationId);

            bool wasSent = await SendFrameAsync(frame);

            logger.Site().Debug("{0} Sending reply for conversation ID {1} {2}.",
                                this, conversationId, wasSent ? "succeedeed" : "failed");
        }
コード例 #14
0
            public QueueItem(
                bool mutatesSolutionState,
                bool requiresLSPSolution,
                ClientCapabilities clientCapabilities,
                string?clientName,
                string methodName,
                TextDocumentIdentifier?textDocument,
                Guid activityId,
                ILspLogger logger,
                RequestTelemetryLogger telemetryLogger,
                Action <Exception> handleQueueFailure,
                Func <RequestContext?, CancellationToken, Task> callbackAsync,
                CancellationToken cancellationToken)
            {
                Metrics = new RequestMetrics(methodName, telemetryLogger);

                _callbackAsync = callbackAsync;
                _logger        = logger;

                ActivityId           = activityId;
                MutatesSolutionState = mutatesSolutionState;
                RequiresLSPSolution  = requiresLSPSolution;
                ClientCapabilities   = clientCapabilities;
                ClientName           = clientName;
                MethodName           = methodName;
                TextDocument         = textDocument;
                HandleQueueFailure   = handleQueueFailure;
                CancellationToken    = cancellationToken;
            }
コード例 #15
0
 /// <summary>
 /// Calculates and signs the specified request using the Asymmetric SigV4 signing protocol
 /// by using theAWS account credentials given in the method parameters. The resulting signature
 /// is added to the request headers as 'Authorization'.
 /// </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>
 public void Sign(IRequest request,
                  IClientConfig clientConfig,
                  RequestMetrics metrics,
                  ImmutableCredentials credentials)
 {
     SignRequest(request, clientConfig, metrics, credentials);
 }
コード例 #16
0
        public override void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials)
        {
            var useSigV4    = request.SignatureVersion == SignatureVersion.SigV4;
            var signer      = SelectSigner(this, useSigV4, request, clientConfig);
            var aws4aSigner = signer as AWS4aSignerCRTWrapper;
            var aws4Signer  = signer as AWS4Signer;
            var useV4a      = aws4aSigner != null;
            var useV4       = aws4Signer != null;

            AWSSigningResultBase signingResult;

            if (useV4a)
            {
                signingResult = aws4aSigner.SignRequest(request, clientConfig, metrics, credentials);
            }
            else if (useV4)
            {
                signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, credentials.AccessKey, credentials.SecretKey);
            }
            else
            {
                throw new AmazonClientException("EventBridge supports only SigV4 and SigV4a signature versions");
            }

            request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
        }
コード例 #17
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;
            }
        }
コード例 #18
0
 public override void Sign(IRequest request,
                           IClientConfig clientConfig,
                           RequestMetrics metrics,
                           string awsAccessKeyId,
                           string awsSecretAccessKey)
 {
     this.SignCount++;
 }
コード例 #19
0
 protected void LogFinishedResponse(RequestMetrics metrics, UnmarshallerContext context, long contentLength)
 {
     metrics.AddProperty(Metric.BytesProcessed, contentLength);
     if (SupportResponseLogging && (Config.LogResponse || AWSConfigs.LoggingConfig.LogResponses == ResponseLoggingOption.Always))
     {
         this.logger.DebugFormat("Received response: [{0}]", context.ResponseBody);
     }
 }
コード例 #20
0
        public override void Sign(IRequest request, string awsAccessKeyId, string awsSecretAccessKey)
        {
            //请求指标
            var metrics = new RequestMetrics();
            SignerRequestParamsEx signerParams = new SignerRequestParamsEx(request, this.regionName, this.serviceName, "SDK-HMAC-SHA256");

            SignHttp(request, metrics, awsAccessKeyId, awsSecretAccessKey, signerParams);
        }
コード例 #21
0
 /// <summary>
 /// Calculates and signs the specified request using the AWS4 signing protocol by using the
 /// AWS account credentials given in the method parameters. The resulting signature is added
 /// to the request headers as 'Authorization'.
 /// </summary>
 /// <param name="request">
 /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
 /// ('host' and 'x-amz-date') will be added to the request before signing.
 /// </param>
 /// <param name="clientConfig">
 /// Adding supporting data for the service call required by the signer (notably authentication
 /// region, endpoint and service name).
 /// </param>
 /// <param name="metrics">
 /// Metrics for the request
 /// </param>
 /// <param name="awsAccessKeyId">
 /// The AWS public key for the account making the service call.
 /// </param>
 /// <param name="awsSecretAccessKey">
 /// The AWS secret key for the account making the call, in clear text
 /// </param>
 /// <exception cref="Amazon.Runtime.SignatureException">
 /// If any problems are encountered while signing the request.
 /// </exception>
 public override void Sign(IRequest request,
                           ClientConfig clientConfig,
                           RequestMetrics metrics,
                           string awsAccessKeyId,
                           string awsSecretAccessKey)
 {
     throw new InvalidOperationException("PreSignedUrl signature computation is not supported by this method; use SignRequest instead.");
 }
コード例 #22
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;
            }
        }
コード例 #23
0
        private static void SignHttpEx(IRequest request, RequestMetrics metrics, string awsAccessKeyId,
                                       string awsSecretAccessKey, SignerRequestParamsEx param = null)
        {
            string date       = "20171006T170510Z"; //AWSSDKUtils.FormattedCurrentTimestampISO8601;
            string hostHeader = request.Endpoint.Host;

            request.Headers[HttpHeaderKeys.HostHeader] = hostHeader;
            request.Headers[HttpHeaderKeys.SdkData]    = date;
        }
コード例 #24
0
 /// <summary>
 /// Calculates the asymmetric Sigv4 (Sigv4a) signature for a presigned url.
 /// </summary>
 /// <param name="request">
 /// The request to compute the signature for.
 /// </param>
 /// <param name="clientConfig">
 /// Adding supporting data for the service call required by the signer (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">
 /// The service to sign for
 /// </param>
 /// <param name="overrideSigningRegion">
 /// The region to sign to, if null then the region the client is configured for will be used.
 /// </param>
 /// <returns>AWS4a Signing Result</returns>
 public AWS4aSigningResult Presign4a(IRequest request,
                                     IClientConfig clientConfig,
                                     RequestMetrics metrics,
                                     ImmutableCredentials credentials,
                                     string service,
                                     string overrideSigningRegion)
 {
     return(_awsSigV4AProvider.Presign4a(request, clientConfig, metrics, credentials, service, overrideSigningRegion));
 }
コード例 #25
0
 public override UnmarshallerContext CreateContext(
     IWebResponseData response,
     bool readEntireResponse,
     Stream stream,
     RequestMetrics metrics,
     bool isException)
 {
     return(CreateContext(response, readEntireResponse, stream, metrics, isException, null));
 }
コード例 #26
0
        /// <summary>
        /// Calculates and signs the specified request using the AWS4 signing protocol by using the
        /// AWS account credentials given in the method parameters.
        /// </summary>
        /// <param name="request">
        /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
        /// ('host' and 'x-amz-date') 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="awsAccessKeyId">
        /// The AWS public key for the account making the service call.
        /// </param>
        /// <param name="awsSecretAccessKey">
        /// The AWS secret key for the account making the call, in clear text.
        /// </param>
        /// <exception cref="Amazon.Runtime.SignatureException">
        /// If any problems are encountered while signing the request.
        /// </exception>
        /// <remarks>
        /// Parameters passed as part of the resource path should be uri-encoded prior to
        /// entry to the signer. Parameters passed in the request.Parameters collection should
        /// be not be encoded; encoding will be done for these parameters as part of the
        /// construction of the canonical request.
        /// </remarks>
        public AWS4SigningResult SignRequest(IRequest request,
                                             ClientConfig clientConfig,
                                             RequestMetrics metrics,
                                             string awsAccessKeyId,
                                             string awsSecretAccessKey)
        {
            var signedAt = InitializeHeaders(request.Headers, request.Endpoint);
            var region   = DetermineRegion(clientConfig);
            var service  = DetermineService(clientConfig);

            var resourcePathParamStart = -1;
            var resourcePath           = string.Empty;

            // Extract the true resource path, less any query parameters or sub resource
            if (!string.IsNullOrEmpty(request.ResourcePath))
            {
                resourcePathParamStart = request.ResourcePath.IndexOf('?');
                resourcePath           = resourcePathParamStart == -1 ? request.ResourcePath : request.ResourcePath.Substring(0, resourcePathParamStart);
            }

            // if UseQueryString is indicated and Parameters are present, canonicalize those (including uri encoding them)
            // otherwise if we spotted parameters in the resource path, canonicalize those instead (which should be encoded
            // already)
            var canonicalQueryParams = string.Empty;

            if (request.UseQueryString && request.Parameters.Count > 0)
            {
                canonicalQueryParams = CanonicalizeQueryParameters(request.Parameters);
            }
            else if (resourcePathParamStart != -1)
            {
                canonicalQueryParams = CanonicalizeQueryParameters(request.ResourcePath.Substring(resourcePathParamStart + 1), false);
            }

            var bodyHash         = SetRequestBodyHash(request);
            var sortedHeaders    = SortHeaders(request.Headers);
            var canonicalRequest = CanonicalizeRequest(resourcePath,
                                                       request.HttpMethod,
                                                       sortedHeaders,
                                                       canonicalQueryParams,
                                                       bodyHash);

            if (metrics != null)
            {
                metrics.AddProperty(Metric.CanonicalRequest, canonicalRequest);
            }

            return(ComputeSignature(awsAccessKeyId,
                                    awsSecretAccessKey,
                                    region,
                                    signedAt,
                                    service,
                                    CanonicalizeHeaderNames(sortedHeaders),
                                    canonicalRequest,
                                    metrics));
        }
コード例 #27
0
        internal static void SignRequest(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            request.Headers[HeaderKeys.XAmzDateHeader] = AWSSDKUtils.FormattedCurrentTimestampRFC822;

            var stringToSign = BuildStringToSign(request);
            metrics.AddProperty(Metric.StringToSign, stringToSign);
            var auth = CryptoUtilFactory.CryptoInstance.HMACSign(stringToSign, awsSecretAccessKey, SigningAlgorithm.HmacSHA1);
            var authorization = string.Concat("AWS ", awsAccessKeyId, ":", auth);
            request.Headers[HeaderKeys.AuthorizationHeader] = authorization;
        }
コード例 #28
0
        /// <summary>
        /// Calculates and signs the specified request using the AWS4 signing protocol by using the
        /// AWS account credentials given in the method parameters. The resulting signature is added
        /// to the request headers as 'Authorization'. Parameters supplied in the request, either in
        /// the resource path as a query string or in the Parameters collection must not have been
        /// uri encoded. If they have, use the SignRequest method to obtain a signature.
        /// </summary>
        /// <param name="request">
        /// The request to compute the signature for. Additional headers mandated by the AWS4 protocol
        /// ('host' and 'x-amz-date') 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="awsAccessKeyId">
        /// The AWS public key for the account making the service call.
        /// </param>
        /// <param name="awsSecretAccessKey">
        /// The AWS secret key for the account making the call, in clear text.
        /// </param>
        /// <exception cref="Amazon.Runtime.SignatureException">
        /// If any problems are encountered while signing the request.
        /// </exception>
        public override void Sign(IRequest request,
                                  ClientConfig clientConfig,
                                  RequestMetrics metrics,
                                  string awsAccessKeyId,
                                  string awsSecretAccessKey)
        {
            var signingResult = SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);

            request.Headers[AuthorizationHeader] = signingResult.ForAuthorizationHeader;
        }
コード例 #29
0
        protected override void ProcessPreRequestHandlers(AmazonWebServiceRequest request)
        {
            base.ProcessPreRequestHandlers(request);

            var requestCopySnapshot = request as CopySnapshotRequest;

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


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

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

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

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

                var signingResult = AWS4PreSignedUrlSigner.SignRequest(irequest,
                                                                       this.Config,
                                                                       metrics,
                                                                       immutableCredentials.AccessKey,
                                                                       immutableCredentials.SecretKey,
                                                                       "ec2",
                                                                       requestCopySnapshot.SourceRegion);

                var authorization = "&" + signingResult.ForQueryParameters;
                Uri url           = ComposeUrl(irequest, irequest.Endpoint);

                requestCopySnapshot.PresignedUrl = url.AbsoluteUri + authorization;
            }
        }
コード例 #30
0
        private static void SignHttp(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
            string           text      = Guid.NewGuid().ToString();
            string           formattedCurrentTimestampRFC = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            bool             flag = IsHttpsRequest(request);

            flag = false;
            request.Headers["Date"]       = formattedCurrentTimestampRFC;
            request.Headers["X-Amz-Date"] = formattedCurrentTimestampRFC;
            request.Headers.Remove("X-Amzn-Authorization");
            string text2 = request.Endpoint.Host;

            if (!request.Endpoint.IsDefaultPort)
            {
                text2 = text2 + ":" + request.Endpoint.Port;
            }
            request.Headers["host"] = text2;
            byte[] array = null;
            string text3;

            if (flag)
            {
                request.Headers["x-amz-nonce"] = text;
                text3 = formattedCurrentTimestampRFC + text;
                array = Encoding.UTF8.GetBytes(text3);
            }
            else
            {
                Uri endpoint = request.Endpoint;
                if (!string.IsNullOrEmpty(request.ResourcePath))
                {
                    endpoint = new Uri(request.Endpoint, request.ResourcePath);
                }
                text3 = request.HttpMethod + "\n" + GetCanonicalizedResourcePath(endpoint) + "\n" + GetCanonicalizedQueryString(request.Parameters) + "\n" + GetCanonicalizedHeadersForStringToSign(request) + "\n" + GetRequestPayload(request);
                array = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(Encoding.UTF8.GetBytes(text3));
            }
            metrics.AddProperty(Metric.StringToSign, text3);
            string        str           = AbstractAWSSigner.ComputeHash(array, awsSecretAccessKey, algorithm);
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(flag ? "AWS3-HTTPS" : "AWS3");
            stringBuilder.Append(" ");
            stringBuilder.Append("AWSAccessKeyId=" + awsAccessKeyId + ",");
            stringBuilder.Append("Algorithm=" + algorithm.ToString() + ",");
            if (!flag)
            {
                stringBuilder.Append(GetSignedHeadersComponent(request) + ",");
            }
            stringBuilder.Append("Signature=" + str);
            string value = stringBuilder.ToString();

            request.Headers["X-Amzn-Authorization"] = value;
        }
コード例 #31
0
ファイル: S3Signer.cs プロジェクト: Bectinced-aeN/vrcsdk
        internal static void SignRequest(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            request.get_Headers()["X-Amz-Date"] = AWSSDKUtils.get_FormattedCurrentTimestampRFC822();
            string text = BuildStringToSign(request);

            metrics.AddProperty(17, (object)text);
            string str   = CryptoUtilFactory.get_CryptoInstance().HMACSign(text, awsSecretAccessKey, 0);
            string value = "AWS " + awsAccessKeyId + ":" + str;

            request.get_Headers()["Authorization"] = value;
        }
コード例 #32
0
 /// <summary>
 /// Signs the specified request with the AWS3 signing protocol by using the
 /// AWS account credentials given in the method parameters.
 /// </summary>
 /// <param name="awsAccessKeyId">The AWS public key</param>
 /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
 /// <param name="metrics">Request metrics</param>
 /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
 /// <param name="request">The request to have the signature compute for</param>
 /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
 public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
 {
     if (UseAws3Https)
     {
         SignHttps(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
     }
     else
     {
         SignHttp(request, metrics, awsAccessKeyId, awsSecretAccessKey);
     }
 }
コード例 #33
0
ファイル: S3Signer.cs プロジェクト: imclab/aws-sdk-unity
        internal static void SignRequest(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            request.Headers[HeaderKeys.XAmzDateHeader] = AWSSDKUtils.FormattedCurrentTimestampRFC822;

            var stringToSign = BuildStringToSign(request);

            metrics.AddProperty(Metric.StringToSign, stringToSign);
            var auth          = CryptoUtilFactory.CryptoInstance.HMACSign(stringToSign, awsSecretAccessKey, SigningAlgorithm.HmacSHA1);
            var authorization = string.Concat("AWS ", awsAccessKeyId, ":", auth);

            request.Headers[HeaderKeys.AuthorizationHeader] = authorization;
        }
コード例 #34
0
        internal void SignRequest(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            request.Headers["x-amz-date"] = AWSSDKUtils.FormattedCurrentTimestampRFC822;

            string toSign = buildSigningString(request.HttpMethod, request.CanonicalResource, request.Parameters, request.Headers);

            metrics.AddProperty(Metric.StringToSign, toSign);
            string auth          = CryptoUtilFactory.CryptoInstance.HMACSign(toSign, awsSecretAccessKey, SigningAlgorithm.HmacSHA1);
            string authorization = string.Concat("AWS ", awsAccessKeyId, ":", auth);

            request.Headers[S3QueryParameter.Authorization.ToString()] = authorization;
        }
コード例 #35
0
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            if (String.IsNullOrEmpty(awsAccessKeyId))
            {
                throw new Exception("The AWS Access Key ID cannot be NULL or a Zero length string");
            }

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

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

            request.Headers.Add("Authorization", "AWS " + awsAccessKeyId + ":" + signature);
        }
コード例 #36
0
ファイル: ConsoleMetricsSink.cs プロジェクト: xornand/bond
 public void Emit(RequestMetrics metrics)
 {
     var sb = new StringBuilder(nameof(RequestMetrics) + " {\n");
     sb.Append($"\trequest ID: {metrics.request_id}\n");
     sb.Append($"\tconnection ID: {metrics.connection_id}\n");
     sb.Append($"\tendpoints: {metrics.local_endpoint} <-> {metrics.remote_endpoint}\n");
     sb.Append($"\tmethod: {metrics.method_name}\n");
     sb.Append($"\ttotal millis: {metrics.total_time_millis}\n");
     sb.Append($"\tservice millis: {metrics.service_method_time_millis}\n");
     var errstr = metrics.error?.ToString() ?? "none";
     sb.Append($"\terror: {errstr}\n");
     sb.Append("}\n");
     Console.Write(sb);
 }
コード例 #37
0
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            var signer = SelectSigner(this, _useSigV4, request, clientConfig);
            var aws4Signer = signer as AWS4Signer;
            var useV4 = aws4Signer != null;

            //var aws4Signer = SelectSigner(clientConfig) as AWS4Signer;
            if (useV4)
            {
                var signingResult = aws4Signer.SignRequest(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey);
                request.Headers[HeaderKeys.AuthorizationHeader] = signingResult.ForAuthorizationHeader;
                if (request.UseChunkEncoding)
                    request.AWS4SignerResult = signingResult;
            }
            else
                SignRequest(request, metrics, awsAccessKeyId, awsSecretAccessKey);
        }
コード例 #38
0
        /// <summary>
        /// Signs the specified request with the AWS2 signing protocol by using the
        /// AWS account credentials given in the method parameters.
        /// </summary>
        /// <param name="awsAccessKeyId">The AWS public key</param>
        /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
        /// <param name="metrics">Request metrics</param>
        /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
        /// <param name="request">The request to have the signature compute for</param>
        /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            if (String.IsNullOrEmpty(awsAccessKeyId))
            {
                throw new ArgumentOutOfRangeException("awsAccessKeyId", "The AWS Access Key ID cannot be NULL or a Zero length string");
            }
          
            request.Parameters["AWSAccessKeyId"] = awsAccessKeyId;
            request.Parameters["SignatureVersion"] = clientConfig.SignatureVersion;
            request.Parameters["SignatureMethod"] = clientConfig.SignatureMethod.ToString();
            request.Parameters["Timestamp"] = AWSSDKUtils.FormattedCurrentTimestampISO8601;

            string toSign = AWSSDKUtils.CalculateStringToSignV2(request.Parameters, clientConfig.DetermineServiceURL());
            metrics.AddProperty(Metric.StringToSign, toSign);
            string auth = ComputeHash(toSign, awsSecretAccessKey, clientConfig.SignatureMethod);
            request.Parameters["Signature"] = auth;
        }
コード例 #39
0
ファイル: Contexts.cs プロジェクト: csdahlberg/bond
 protected SendContext(ConnectionMetrics connectionMetrics, RequestMetrics requestMetrics)
     : base(connectionMetrics, requestMetrics) {}
コード例 #40
0
ファイル: Contexts.cs プロジェクト: csdahlberg/bond
 protected ReceiveContext(ConnectionMetrics connectionMetrics, RequestMetrics requestMetrics)
     : base(connectionMetrics, requestMetrics) {}
コード例 #41
0
ファイル: MetricsTests.cs プロジェクト: csdahlberg/bond
 public void Emit(RequestMetrics metrics)
 {
     LastRequestMetrics = metrics;
     RequestMetricsReceived++;
 }
コード例 #42
0
        /// <summary>
        /// Create a signed URL allowing access to a resource that would 
        /// usually require authentication.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When using query string authentication you create a query,
        /// specify an expiration time for the query, sign it with your
        /// signature, place the data in an HTTP request, and distribute
        /// the request to a user or embed the request in a web page.
        /// </para>
        /// <para>
        /// A PreSigned URL can be generated for GET, PUT, DELETE and HEAD
        /// operations on your bucketName, keys, and versions.
        /// </para>
        /// </remarks>
        /// <param name="request">The GetPreSignedUrlRequest that defines the
        /// parameters of the operation.</param>
        /// <returns>A string that is the signed http request.</returns>
        /// <exception cref="T:System.ArgumentException" />
        /// <exception cref="T:System.ArgumentNullException" />
        public string GetPreSignedURL(GetPreSignedUrlRequest request)
        {
            if (Credentials == null)
                throw new AmazonS3Exception("Credentials must be specified, cannot call method anonymously");

            if (request == null)
                throw new ArgumentNullException("request", "The PreSignedUrlRequest specified is null!");

            if (!request.IsSetExpires())
                throw new InvalidOperationException("The Expires specified is null!");

            var aws4Signing = AWSConfigs.S3Config.UseSignatureVersion4;
            var region = AWS4Signer.DetermineSigningRegion(Config, "s3", alternateEndpoint: null, request: null);
            if (aws4Signing && string.IsNullOrEmpty(region))
                throw new InvalidOperationException("To use AWS4 signing, a region must be specified in the client configuration using the AuthenticationRegion or Region properties, or be determinable from the service URL.");

            RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(region);
            if (endpoint.GetEndpointForService("s3").SignatureVersionOverride == "4")
                aws4Signing = true;

            var immutableCredentials = Credentials.GetCredentials();
            var irequest = Marshall(request, immutableCredentials.AccessKey, immutableCredentials.Token, aws4Signing);

            irequest.Endpoint = EndpointResolver.DetermineEndpoint(this.Config, irequest);

            var context = new Amazon.Runtime.Internal.ExecutionContext(new Amazon.Runtime.Internal.RequestContext(true) { Request = irequest, ClientConfig = this.Config }, null);
            AmazonS3PostMarshallHandler handler = new AmazonS3PostMarshallHandler();
            handler.ProcessRequestHandlers(context);

            var metrics = new RequestMetrics();

            string authorization;
            if (aws4Signing)
            {
                var aws4Signer = new AWS4PreSignedUrlSigner();
                var signingResult = aws4Signer.SignRequest(irequest,
                                                           this.Config,
                                                           metrics,
                                                           immutableCredentials.AccessKey,
                                                           immutableCredentials.SecretKey);
                authorization = "&" + signingResult.ForQueryParameters;
            }
            else
            {
                this.Signer.Sign(irequest, this.Config, metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
                authorization = irequest.Headers[HeaderKeys.AuthorizationHeader];
                authorization = authorization.Substring(authorization.IndexOf(":", StringComparison.Ordinal) + 1);
                authorization = "&Signature=" + AmazonS3Util.UrlEncode(authorization, false);
            }

            Uri url = AmazonServiceClient.ComposeUrl(irequest);
            string result = url.AbsoluteUri + authorization;

            Protocol protocol = DetermineProtocol();
            if (request.Protocol != protocol)
            {
                switch (protocol)
                {
                    case Protocol.HTTP:
                        result = result.Replace("http://", "https://");
                        break;
                    case Protocol.HTTPS:
                        result = result.Replace("https://", "http://");
                        break;
                }
            }
            return result;
        }
コード例 #43
0
ファイル: Metrics.cs プロジェクト: csdahlberg/bond
 public static void FinishRequestMetrics(RequestMetrics requestMetrics, Stopwatch totalTime)
 {
     requestMetrics.total_time_millis = totalTime.Elapsed.TotalMilliseconds;
 }
コード例 #44
0
ファイル: AWS3Signer.cs プロジェクト: shaunbowe/aws-sdk-net
        private void SignHttps(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            string nonce = Guid.NewGuid().ToString();
            string date = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            string stringToSign;

            stringToSign = date + nonce;
            metrics.AddProperty(RequestMetrics.Metric.StringToSign, stringToSign);

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

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

            request.Headers[AUTHORIZATION_HEADER] = builder.ToString();
            request.Headers[NONCE_HEADER] = nonce;
            request.Headers["x-amz-date"] = date;
        }
コード例 #45
0
        /// <summary>
        /// Calculates and signs the specified request using the AWS4 signing protocol by using the
        /// AWS account credentials given in the method parameters.
        /// </summary>
        /// <param name="awsAccessKeyId">The AWS public key</param>
        /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
        /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
        /// <param name="request">The request to have the signature compute for</param>
        /// <param name="secureKey">The AWS secret key stored in a secure string</param>
        /// <param name="metrics">Request metrics</param>
        /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
        public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            // clean up request from previous execution
            request.Headers.Remove("Authorization");

            string signingAlgorithm = SigningAlgorithm.HmacSHA256.ToString().ToUpper();

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

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

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

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

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

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

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

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

            KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(signingAlgorithm);
            kha.Key = ComposeSigningKey(signingAlgorithm, awsSecretAccessKey, secureKey, region, dateStamp, service);
            string stringToSign = stringToSignBuilder.ToString();
            metrics.AddProperty(RequestMetrics.Metric.StringToSign, stringToSign);
            byte[] signature = kha.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));

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

            request.Headers["Authorization"] = authorizationHeader.ToString();
        }
コード例 #46
0
ファイル: Contexts.cs プロジェクト: csdahlberg/bond
 protected Context(ConnectionMetrics connectionMetrics, RequestMetrics requestMetrics)
 {
     ConnectionMetrics = connectionMetrics;
     RequestMetrics = requestMetrics;
 }
コード例 #47
0
 public SimpleInMemSendContext(SimpleInMemConnection connection, ConnectionMetrics connectionMetrics, RequestMetrics requestMetrics)
     : base(connectionMetrics, requestMetrics)
 {
     Connection = connection;
 }
コード例 #48
0
ファイル: AWS3Signer.cs プロジェクト: shaunbowe/aws-sdk-net
        private void SignHttp(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
            string nonce = Guid.NewGuid().ToString();
            string date = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            bool isHttps = IsHttpsRequest(request);

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

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

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

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

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

                bytesToSign = CanonicalizationHash.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            }
            metrics.AddProperty(RequestMetrics.Metric.StringToSign, stringToSign);

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

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

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

            builder.Append("Signature=" + signature);
            string authorizationHeader = builder.ToString();
            request.Headers[AUTHORIZATION_HEADER] = authorizationHeader;
        }
コード例 #49
0
ファイル: AWS3Signer.cs プロジェクト: shaunbowe/aws-sdk-net
 /// <summary>
 /// Signs the specified request with the AWS3 signing protocol by using the
 /// AWS account credentials given in the method parameters.
 /// </summary>
 /// <param name="awsAccessKeyId">The AWS public key</param>
 /// <param name="awsSecretAccessKey">The AWS secret key used to sign the request in clear text</param>
 /// <param name="clientConfig">The configuration that specifies which hashing algorithm to use</param>
 /// <param name="request">The request to have the signature compute for</param>
 /// <param name="secureKey">The AWS secret key stored in a secure string</param>
 /// <param name="metrics">Request metrics</param>
 /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
 public override void Sign(IRequest request, ClientConfig clientConfig, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
 {
     if (UseAws3Https)
     {
         SignHttps(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey, secureKey);
     }
     else
     {
         SignHttp(request, clientConfig, metrics, awsAccessKeyId, awsSecretAccessKey, secureKey);
     }
 }
コード例 #50
0
 public void Emit(RequestMetrics metrics)
 {
     RequestMetricses.Add(metrics);
 }
コード例 #51
0
 public override UnmarshallerContext CreateContext(IWebResponseData response, bool readEntireResponse, Stream stream, RequestMetrics metrics)
 {
     if (response.IsHeaderPresent(AMZ_ID_2))
         metrics.AddProperty(Metric.AmzId2, response.GetHeaderValue(AMZ_ID_2));
     return base.CreateContext(response, readEntireResponse, stream, metrics);
 }
コード例 #52
0
            /// <summary>
            /// This method was copied from AWS4PreSignedUrlSigner.SignRequest and adapted for this utility.
            /// </summary>
            /// <param name="request"></param>
            /// <param name="metrics"></param>
            /// <param name="awsAccessKeyId"></param>
            /// <param name="awsSecretAccessKey"></param>
            /// <param name="service"></param>
            /// <param name="region"></param>
            /// <returns></returns>
            public static AWS4SigningResult SignSynthesizeSpeechRequest(IRequest request,
                                         RequestMetrics metrics,
                                         string awsAccessKeyId,
                                         string awsSecretAccessKey,
                                         string service,
                                         string region)
            {
                // clean up any prior signature in the headers if resigning
                request.Headers.Remove(HeaderKeys.AuthorizationHeader);
                if (!request.Headers.ContainsKey(HeaderKeys.HostHeader))
                {
                    var hostHeader = request.Endpoint.Host;
                    if (!request.Endpoint.IsDefaultPort)
                        hostHeader += ":" + request.Endpoint.Port;
                    request.Headers.Add(HeaderKeys.HostHeader, hostHeader);
                }

                var signedAt = AWSSDKUtils.CorrectedUtcNow;

                // AWS4 presigned urls got S3 are expected to contain a 'UNSIGNED-PAYLOAD' magic string
                // during signing (other services use the empty-body sha)
                if (request.Headers.ContainsKey(HeaderKeys.XAmzContentSha256Header))
                    request.Headers.Remove(HeaderKeys.XAmzContentSha256Header);

                var sortedHeaders = SortAndPruneHeaders(request.Headers);
                var canonicalizedHeaderNames = CanonicalizeHeaderNames(sortedHeaders);

                var parametersToCanonicalize = GetParametersToCanonicalize(request);
                parametersToCanonicalize.Add(XAmzAlgorithm, AWS4AlgorithmTag);
                parametersToCanonicalize.Add(XAmzCredential,
                                             string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}/{4}",
                                                           awsAccessKeyId,
                                                           FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat),
                                                           region,
                                                           service,
                                                           Terminator));

                parametersToCanonicalize.Add(HeaderKeys.XAmzDateHeader, FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateTimeFormat));
                parametersToCanonicalize.Add(HeaderKeys.XAmzSignedHeadersHeader, canonicalizedHeaderNames);

                var canonicalQueryParams = CanonicalizeQueryParametersForSynthesizeSpeech(parametersToCanonicalize, true);

                var canonicalRequest = CanonicalizeRequest(request.Endpoint,
                                                           request.ResourcePath,
                                                           request.HttpMethod,
                                                           sortedHeaders,
                                                           canonicalQueryParams,
                                                           service == "s3" ? UnsignedPayload : EmptyBodySha256);
                if (metrics != null)
                    metrics.AddProperty(Metric.CanonicalRequest, canonicalRequest);

                return ComputeSignature(awsAccessKeyId,
                                        awsSecretAccessKey,
                                        region,
                                        signedAt,
                                        service,
                                        canonicalizedHeaderNames,
                                        canonicalRequest,
                                        metrics);
            }
コード例 #53
0
ファイル: Metrics.cs プロジェクト: csdahlberg/bond
 public void Emit(RequestMetrics metrics)
 {
     Sink?.Emit(metrics);
 }
コード例 #54
0
 internal TimingEvent(RequestMetrics metrics, Metric metric)
 {
     this.metrics = metrics;
     this.metric = metric;
 }
コード例 #55
-1
ファイル: EpoxyContexts.cs プロジェクト: csdahlberg/bond
 public EpoxySendContext(EpoxyConnection connection, ConnectionMetrics connectionMetrics, RequestMetrics requestMetrics)
     : base(connectionMetrics, requestMetrics)
 {
     Connection = connection;
 }