Ejemplo n.º 1
0
        public static byte[] GetSigningKey(IAwsCredential credential, CredentialScope scope)
        {
            #region Preconditions

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

            #endregion

            var kSecret = Encoding.ASCII.GetBytes("AWS4" + credential.SecretAccessKey);

            var kDate      = HMACSHA256(kSecret, scope.Date.ToString("yyyyMMdd"));
            var kRegion    = HMACSHA256(kDate, scope.Region.Name);
            var kService   = HMACSHA256(kRegion, scope.Service.Name);
            var signingKey = HMACSHA256(kService, "aws4_request");

            return(signingKey);
        }
Ejemplo n.º 2
0
        public SqsQueue(AwsRegion region, string accountId, string queueName, IAwsCredential credential)
        {
            #region Preconditions

            if (accountId == null)
            {
                throw new ArgumentNullException(nameof(accountId));
            }

            if (queueName == null)
            {
                throw new ArgumentNullException(nameof(queueName));
            }

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            #endregion

            this.url = new Uri($"https://sqs.{region}.amazonaws.com/{accountId}/{queueName}");

            this.client = new SqsClient(region, credential);
        }
Ejemplo n.º 3
0
        public static string GetSignedUrl(GetUrlRequest request, IAwsCredential credential)
        {
            // You can specify any future expiration time in epoch or UNIX time (number of seconds since January 1, 1970).

            var unixTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            long expires = unixTime + (long)request.ExpiresIn.TotalSeconds;

            var stringToSign = ConstructStringToSign(
                httpVerb: HttpMethod.Get,
                contentType: string.Empty,
                bucketName: request.BucketName,
                key: request.Key,
                headers: emptyStringDictionary,
                query: string.Empty,
                expiresOrDate: expires.ToString()
                );

            var signature = ComputeSignature(credential.SecretAccessKey, stringToSign);

            return(new StringBuilder()
                   .Append("https://")
                   .Append(request.BucketName)
                   .Append(".s3.amazonaws.com/")
                   .Append(request.Key)
                   .Append("?AWSAccessKeyId=")
                   .Append(credential.AccessKeyId.UrlEncode())
                   .Append("&Expires=")
                   .Append(expires)
                   .Append("&Signature=")
                   .Append(signature.UrlEncode())
                   .ToString());
        }
Ejemplo n.º 4
0
        public AwsClient(AwsService service, AwsRegion region, IAwsCredential credential)
        {
            this.service    = service    ?? throw new ArgumentNullException(nameof(service));
            Region          = region     ?? throw new ArgumentNullException(nameof(region));
            this.credential = credential ?? throw new ArgumentNullException(nameof(credential));

            Endpoint = $"https://{service.Name}.{region.Name}.amazonaws.com/";
        }
Ejemplo n.º 5
0
        public SnsTopic(AwsRegion region, string accountId, string topicName, IAwsCredential credential)
        {
            if (accountId is null)
            {
                throw new ArgumentNullException(nameof(accountId));
            }

            if (topicName is null)
            {
                throw new ArgumentNullException(nameof(topicName));
            }

            this.client = new SnsClient(region, credential);
            this.arn    = $"arn:aws:sns:{region}:{accountId}:{topicName}";
        }
Ejemplo n.º 6
0
        public static string GetPresignedUrl(GetPresignedUrlRequest request, IAwsCredential credential, DateTime now)
        {
            HttpMethod method = request.Method.Equals("GET") ? HttpMethod.Get : new HttpMethod(request.Method);

            // TODO: support version querystring

            return(SignerV4.GetPresignedUrl(
                       credential: credential,
                       scope: new CredentialScope(now, request.Region, AwsService.S3),
                       date: now,
                       expires: request.ExpiresIn,
                       method: method,
                       requestUri: new Uri(request.GetUrl()),
                       payloadHash: UnsignedPayload
                       ));
        }
Ejemplo n.º 7
0
        public AwsClient(AwsService service, AwsRegion region, IAwsCredential credential)
        {
            this.service    = service ?? throw new ArgumentNullException(nameof(service));
            Region          = region ?? throw new ArgumentNullException(nameof(region));
            this.credential = credential ?? throw new ArgumentNullException(nameof(credential));

            Endpoint = $"https://{service.Name}.{region.Name}.amazonaws.com/";

            this.httpClient = new HttpClient(new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip
            })
            {
                DefaultRequestHeaders =
                {
                    { "User-Agent", "Carbon/2.5" }
                }
            };
        }
Ejemplo n.º 8
0
        public HostManager(IAwsCredential awsCredential, PlatformDb db, IEventLogger eventLog)
        {
            Validate.NotNull(awsCredential, nameof(awsCredential));

            this.db       = db ?? throw new ArgumentNullException(nameof(db));
            this.eventLog = eventLog ?? throw new ArgumentNullException(nameof(eventLog));

            var region = AwsRegion.USEast1; // TODO: Configurable

            ec2 = new Ec2Client(region, awsCredential);
            ssm = new SsmClient(region, awsCredential);

            var elb = new ElbClient(region, awsCredential);

            this.clusterService      = new ClusterService(db);
            this.clusterManager      = new ClusterManager(clusterService, elb, eventLog);
            this.hostService         = new HostService(db);
            this.imageService        = new ImageService(db);
            this.hostTemplateService = new HostTemplateService(db);
        }
Ejemplo n.º 9
0
        public SqsQueue(AwsRegion region, string accountId, string queueName, IAwsCredential credential)
        {
            if (region is null)
            {
                throw new ArgumentNullException(nameof(region));
            }

            if (accountId is null)
            {
                throw new ArgumentNullException(nameof(accountId));
            }

            if (queueName is null)
            {
                throw new ArgumentNullException(nameof(queueName));
            }

            this.url = new Uri($"https://sqs.{region}.amazonaws.com/{accountId}/{queueName}");

            this.client = new SqsClient(region, credential);
        }
Ejemplo n.º 10
0
        public void Sign(IAwsCredential credential, CredentialScope scope, HttpRequestMessage request)
        {
            #region Preconditions

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

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

            #endregion

            // If we're using S3, ensure the request content has been signed
            if (scope.Service == AwsService.S3 && !request.Headers.Contains("x-amz-content-sha256"))
            {
                request.Headers.Add("x-amz-content-sha256", ComputeSHA256(request.Content));
            }

            var signingKey = GetSigningKey(credential, scope);

            var stringToSign = GetStringToSign(scope, request);

            var signature = Signature.ComputeHmacSha256(signingKey, Encoding.UTF8.GetBytes(stringToSign)).ToHexString();

            var signedHeaders = GetSignedHeaders(request);

            // AWS4-HMAC-SHA256 Credential={0},SignedHeaders={0},Signature={0}
            var auth = $"AWS4-HMAC-SHA256 Credential={credential.AccessKeyId}/{scope},SignedHeaders={signedHeaders},Signature={signature}";

            request.Headers.TryAddWithoutValidation("Authorization", auth);
        }
Ejemplo n.º 11
0
        public static string GetPresignedUrl(GetPresignedUrlRequest request, IAwsCredential credential, DateTime now)
        {
            var scope = new CredentialScope(now, request.Region, AwsService.S3);

            var urlBuilder = StringBuilderCache.Aquire()
                             .Append("https://")
                             .Append(request.Host)
                             .Append('/')
                             .Append(request.BucketName)
                             .Append('/')
                             .Append(request.Key);

            // TODO: support version querystring

            var message = new HttpRequestMessage(new HttpMethod(request.Method), StringBuilderCache.ExtractAndRelease(urlBuilder));

            SignerV4.Default.Presign(credential, scope, now, request.ExpiresIn, message, "UNSIGNED-PAYLOAD");

            string signedUrl = message.RequestUri.ToString();

            return(signedUrl);
        }
Ejemplo n.º 12
0
 public S3Bucket(AwsRegion region, string bucketName, IAwsCredential credential)
     : this(bucketName, new S3Client(region, credential))
 {
 }
Ejemplo n.º 13
0
 public RdsService(AwsRegion region, IAwsCredential credential)
 {
     this.region     = region ?? throw new ArgumentNullException(nameof(region));
     this.credential = credential ?? throw new ArgumentNullException(nameof(credential));
 }
Ejemplo n.º 14
0
 public static byte[] GetSigningKey(IAwsCredential credential, in CredentialScope scope)
Ejemplo n.º 15
0
 public LambdaClient(AwsRegion region, IAwsCredential credential)
     : base(AwsService.Lambda, region, credential)
 {
 }
Ejemplo n.º 16
0
 public CloudWatchClient(AwsRegion region, IAwsCredential credentials)
     : base(AwsService.Monitoring, region, credentials)
 {
 }
Ejemplo n.º 17
0
 public KinesisClient(IAwsCredential credential)
     : base(AwsService.Kinesis, AwsRegion.USEast1, credential)
 {
 }
Ejemplo n.º 18
0
 public ElbClient(AwsRegion region, IAwsCredential credential)
     : base(AwsService.Elb, region, credential)
 {
 }
Ejemplo n.º 19
0
 public SnsClient(AwsRegion region, IAwsCredential credential)
     : base(AwsService.Sns, region, credential)
 {
 }
Ejemplo n.º 20
0
 public S3Client(AwsRegion region, IAwsCredential credential)
     : this(region, host : $"s3.dualstack.{region.Name}.amazonaws.com", credential : credential)
 {
 }
Ejemplo n.º 21
0
 public S3Client(AwsRegion region, string host, IAwsCredential credential)
     : base(AwsService.S3, region, credential)
 {
     Host = host ?? throw new ArgumentNullException(nameof(host));
 }
Ejemplo n.º 22
0
 public KinesisFirehoseClient(AwsRegion region, IAwsCredential credential)
     : base(AwsService.KinesisFirehose, region, credential)
 {
 }
Ejemplo n.º 23
0
        // http://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html

        public void Presign(
            IAwsCredential credential,
            CredentialScope scope,
            DateTime date,
            TimeSpan expires,
            HttpRequestMessage request)
        {
            #region Preconditions

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

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

            #endregion

            var signingKey = GetSigningKey(credential, scope);

            var queryParameters = new SortedDictionary <string, string>();

            foreach (var pair in ParseQueryString(request.RequestUri.Query))
            {
                queryParameters[pair.Key] = pair.Value;
            }

            var timestamp = date.ToString(format: isoDateTimeFormat);

            queryParameters["X-Amz-Algorithm"]  = "AWS4-HMAC-SHA256";
            queryParameters["X-Amz-Credential"] = $"{credential.AccessKeyId}/{scope}";

            if (credential.SecurityToken != null)
            {
                queryParameters["X-Amz-Security-Token"] = credential.SecurityToken;
            }

            queryParameters["X-Amz-Date"]          = timestamp;
            queryParameters["X-Amz-Expires"]       = expires.TotalSeconds.ToString(); // in seconds
            queryParameters["X-Amz-SignedHeaders"] = "host";

            var canonicalHeaders = "host:" + request.RequestUri.Host;

            if (!request.RequestUri.IsDefaultPort)
            {
                canonicalHeaders += ":" + request.RequestUri.Port;
            }

            var canonicalRequest = GetCanonicalRequest(
                method: request.Method,
                canonicalURI: request.RequestUri.AbsolutePath,
                canonicalQueryString: CanonicizeQueryString(queryParameters),
                canonicalHeaders: canonicalHeaders,
                signedHeaders: "host",
                payloadHash: emptySha256
                );

            var stringToSign = GetStringToSign(
                scope,
                timestamp,
                canonicalRequest
                );

            var signature = Signature.ComputeHmacSha256(
                key: signingKey,
                data: Encoding.UTF8.GetBytes(stringToSign)
                ).ToHexString();

            /*
             * queryString = Action=action
             * queryString += &X-Amz-Algorithm=algorithm
             * queryString += &X-Amz-Credential= urlencode(access_key_ID + '/' + credential_scope)
             * queryString += &X-Amz-Date=date
             * queryString += &X-Amz-Expires=timeout interval
             * queryString += &X-Amz-SignedHeaders=signed_headers
             */

            var queryString = string.Join("&",
                                          queryParameters.Select(pair => WebUtility.UrlEncode(pair.Key) + "=" + WebUtility.UrlEncode(pair.Value))
                                          ) + "&X-Amz-Signature=" + signature;

            var url = request.RequestUri.ToString();

            request.RequestUri = new Uri(
                url.Substring(0, url.IndexOf("?")) + "?" + queryString
                );
        }
Ejemplo n.º 24
0
 public DynamoTable(IAwsCredential credential)
     : this(metadata.Name, new DynamoDbClient(AwsRegion.USEast1, credential))
 {
 }
Ejemplo n.º 25
0
 public DynamoDbClient(AwsRegion region, IAwsCredential credential)
     : base(AwsService.DynamoDb, region, credential)
 {
     httpClient.Timeout = TimeSpan.FromSeconds(10);
 }
Ejemplo n.º 26
0
 public static string GetPresignedUrl(GetPresignedUrlRequest request, IAwsCredential credential)
 {
     return(GetPresignedUrl(request, credential, DateTime.UtcNow));
 }
Ejemplo n.º 27
0
 public KmsProtector(AwsRegion region, string keyId, IAwsCredential credential)
     : this(new KmsClient(region, credential), keyId)
 {
 }
Ejemplo n.º 28
0
 public DynamoTable(string tableName, IAwsCredential credential)
     : this(tableName, new DynamoDbClient(AwsRegion.USEast1, credential))
 {
 }
Ejemplo n.º 29
0
 public CodeBuildClient(AwsRegion region, IAwsCredential credential)
     : base(AwsService.CodeBuild, region, credential)
 {
 }
Ejemplo n.º 30
0
 public Route53Client(IAwsCredential credential)
     : base(AwsService.Route53, AwsRegion.USEast1, credential)
 {
 }