Immutable representation of AWS credentials.
예제 #1
1
        /// <summary>
        /// Calculates the AWS4 signature using the supplied request parameters and AWS account credentials.
        /// </summary>
        /// <param name="parameters">Request header parameters to be included in the signature</param>
        /// <param name="serviceURL">Service endpoint URL</param>
        /// <param name="authenticationServiceName">
        /// The short-form name of the target service for inclusion in the signature; only needed if this 
        /// cannot be determined by parsing the endpoint.
        /// </param>
        /// <param name="authenticationRegion">
        /// Region name for inclusion in the signature; only needed if this  cannot be determined by parsing 
        /// the endpoint.
        /// </param>
        /// <param name="httpMethod">The HTTP method used to make the request.</param>
        /// <param name="credentials">User credentials</param>
        /// <returns>The signature string to be added as header 'Authorization' on the eventual request</returns>
        /// <exception cref="Amazon.Runtime.SignatureException">If any problems are encountered while signing the request</exception>
        public static string CalculateSignature(IDictionary<string, string> parameters,
                                                string serviceURL,
                                                string httpMethod,
                                                string authenticationServiceName,
                                                string authenticationRegion,
                                                ImmutableCredentials credentials)
        {
            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;
            if (!string.IsNullOrEmpty(authenticationRegion))
                region = authenticationRegion;
            else
                region = AWSSDKUtils.DetermineRegion(serviceURL).ToLower();
            string service = authenticationServiceName.Trim().ToLower();

            if (!parameters.ContainsKey("Host"))
                parameters.Add("Host", serviceURL);
            parameters.Add("X-Amz-Date", dateTime);

            string scope = string.Format("{0}/{1}/{2}/{3}", dateStamp, region, service, TERMINATOR);

            List<string> headersToSign = GetHeadersForSigning(parameters);
            string canonicalRequest = GetCanonicalRequest(headersToSign,
                                                          new Uri(serviceURL),
                                                          "",
                                                          parameters,
                                                          AWSSDKUtils.GetParametersAsString(parameters),
                                                          null, // No support for binary request body yet here.
                                                          httpMethod);

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

            HashAlgorithm ha = HashAlgorithm.Create("SHA-256");
            byte[] canonicalRequestHashBytes = ha.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest));
            stringToSign.Append(AWSSDKUtils.ToHex(canonicalRequestHashBytes, true));

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

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

            return authorizationHeader.ToString();
        }
예제 #2
0
    // Called by Unity when the Gameobject is created
    void Start()
    {
        FindObjectOfType <UIManager>().SetTextBox("Setting up Client..");

        // Set up Mobile SDK
        UnityInitializer.AttachToGameObject(this.gameObject);
        AWSConfigs.AWSRegion  = MatchmakingClient.regionString;
        AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;

        // Get Cognito Identity and start Connecting to server once we have the identity
        CognitoAWSCredentials credentials = new CognitoAWSCredentials(
            MatchmakingClient.identityPoolID,
            MatchmakingClient.region
            );

        credentials.GetCredentialsAsync(
            (response) => {
            Debug.Log("Received CognitoCredentials: " + response.Response);
            cognitoCredentials = response.Response;

            // Start a coroutine for the connection process to keep UI updated while it's happening
            StartCoroutine(ConnectToServer());
        }
            );
    }
예제 #3
0
        private static void LoadSettings(string settingsResourcePartialName = "settings.json")
        {
            SetDefaults();

            var storedSettings = GetStoredSettings(settingsResourcePartialName);
            if (storedSettings == null)
                return;

            try
            {
                var ic = new ImmutableCredentials(storedSettings.AccessKeyId, storedSettings.SecretAccessKey, storedSettings.SessionToken);
                Credentials = new StoredCredentials(ic);
            }
            catch(Exception e)
            {
                Console.WriteError("Unable to parse get credentials from settings file, defaulting to anonymous credentials. Exception: {0}", e.ToString());
                Credentials = new AnonymousAWSCredentials();
            }

            try
            {
                RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(storedSettings.RegionEndpoint);
            }
            catch(Exception e)
            {
                Console.WriteError("Unable to parse RegionEndpoint from settings file, defaulting to {0}. Exception: {1}", DefaultRegion, e.ToString());
                RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(DefaultRegion);
            }
            ResultsBucket = storedSettings.ResultsBucket;
            ResultsTopic = storedSettings.ResultsTopic;
        }
예제 #4
0
 public void TestCredentialsFile()
 {
     var ic = new ImmutableCredentials("access-key", "secret-key", null);
     TestCredentialsFile(ic);
     ic = new ImmutableCredentials("access-key", "secret-key", "token");
     TestCredentialsFile(ic);
 }
예제 #5
0
 /// <summary>
 /// Use a HEAD bucket request to get the region for the given bucket.
 ///
 /// This method creates an AmazonS3Client from the credentials passed in.
 /// It's critical that the AmazonS3Client is not used to make any requests that will
 /// be routed through the pipeline.
 /// </summary>
 /// <param name="bucketName"></param>
 /// <param name="credentials"></param>
 /// <returns>the value of the x-amz-bucket-region header from the response</returns>
 private static async Task<string> GetBucketRegionNoPipelineAsync(string bucketName, ImmutableCredentials credentials)
 {
     var headBucketPreSignedUrl = GetHeadBucketPreSignedUrl(bucketName, credentials);
     using (var s3Client = GetUsEast1ClientFromCredentials(credentials))
     {
         return (await AmazonS3HttpUtil.GetHeadAsync(s3Client, s3Client.Config, headBucketPreSignedUrl,
             HeaderKeys.XAmzBucketRegion).ConfigureAwait(false)).HeaderValue;
     }
 }
예제 #6
0
 /// <summary>
 /// Use a HEAD bucket request to get the region for the given bucket.
 ///
 /// This method creates an AmazonS3Client from the credentials passed in.
 /// It's critical that the AmazonS3Client is not used to make any requests that will
 /// be routed through the pipeline.
 /// </summary>
 /// <param name="bucketName"></param>
 /// <param name="credentials"></param>
 /// <returns>the value of the x-amz-bucket-region header from the response</returns>
 private static string GetBucketRegionNoPipeline(string bucketName, ImmutableCredentials credentials)
 {
     var headBucketPreSignedUrl = GetHeadBucketPreSignedUrl(bucketName, credentials);
     using (var s3Client = GetUsEast1ClientFromCredentials(credentials))
     {
         var response = AmazonS3HttpUtil.GetHead(s3Client, s3Client.Config, headBucketPreSignedUrl, HeaderKeys.XAmzBucketRegion);
         return response.HeaderValue;
     }
 }
        public SystemEnvironmentAWSCredentials()
        {
            string accessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID");
            string secretKey = Environment.GetEnvironmentVariable("AWS_SECRET_KEY");

            if (String.IsNullOrEmpty(accessKey) || String.IsNullOrEmpty(secretKey))
            {
                throw new Exception("No credentials found in the system environment.");
            }
            _credentials = new ImmutableCredentials(accessKey, secretKey, "");
        }
예제 #8
0
    // Called by Unity when the Gameobject is created
    void Start()
    {
        FindObjectOfType <UIManager>().SetTextBox("Setting up Client..");

        // Get an identity and connect to server
        CognitoAWSCredentials credentials = new CognitoAWSCredentials(
            MatchmakingClient.identityPoolID,
            MatchmakingClient.region);

        Client.cognitoCredentials = credentials.GetCredentials();
        Debug.Log("Got credentials: " + Client.cognitoCredentials.AccessKey + "," + Client.cognitoCredentials.SecretKey);

        StartCoroutine(ConnectToServer());
    }
        /// <summary>
        /// Returns a copy of the most recent instance profile credentials.
        /// </summary>
        public override ImmutableCredentials GetCredentials()
        {
            CheckIsIMDSEnabled();
            ImmutableCredentials credentials = null;

            // Try to acquire read lock. The thread would be blocked if another thread has write lock.
            if (credentialsLock.TryEnterReadLock(credentialsLockTimeout))
            {
                try
                {
                    credentials = lastRetrievedCredentials?.Copy();

                    if (credentials != null)
                    {
                        return(credentials);
                    }
                }
                finally
                {
                    credentialsLock.ExitReadLock();
                }
            }

            // If there's no credentials cached, hit IMDS directly. Try to acquire write lock.
            if (credentialsLock.TryEnterWriteLock(credentialsLockTimeout))
            {
                try
                {
                    // Check for last retrieved credentials again in case other thread might have already fetched it.
                    credentials = lastRetrievedCredentials?.Copy();
                    if (credentials == null)
                    {
                        credentials = FetchCredentials();
                        lastRetrievedCredentials = credentials;
                    }
                }
                finally
                {
                    credentialsLock.ExitWriteLock();
                }
            }

            if (credentials == null)
            {
                throw new AmazonServiceException(FailedToGetCredentialsMessage);
            }

            return(credentials);
        }
예제 #10
0
        /// <summary>
        /// Constructs an instance of StoredProfileAWSCredentials. Credentials will be searched for using the profileName parameter.
        /// </summary>
        /// <param name="profileName">The profile name to search for credentials for</param>
        /// <param name="profilesLocation">Overrides the location to search for credentials</param>
        /// <remarks>
        /// If credential materials cannot be read or are invalid due to missing data
        /// an InvalidDataException is thrown. If no credentials can be located, an ArgumentException
        /// is thrown.
        /// </remarks>
        public StoredProfileAWSCredentials(string profileName, string profilesLocation)
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            var lookupName = string.IsNullOrEmpty(profileName) ? DEFAULT_PROFILE_NAME : profileName;

            ProfileName      = lookupName;
            ProfilesLocation = null;

            // If not overriding the credentials lookup location check the SDK Store for credentials. If an override is being used then
            // assume the intent is to use the credentials file.
            if (string.IsNullOrEmpty(profilesLocation) && ProfileManager.IsProfileKnown(lookupName))
            {
                AWSCredentialsProfile.Validate(lookupName);
                AWSCredentials credentials;
                if (ProfileManager.TryGetAWSCredentials(lookupName, out credentials))
                {
                    this._wrappedCredentials = credentials.GetCredentials();
                    var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials));
                    logger.InfoFormat("Credentials found using account name {0} and looking in SDK account store.", lookupName);
                }
            }

            // If credentials weren't found in the SDK store then search the shared credentials file.
            if (this._wrappedCredentials == null)
            {
                var credentialsFilePath = DetermineCredentialsFilePath(profilesLocation);
                if (!string.IsNullOrEmpty(credentialsFilePath) && File.Exists(credentialsFilePath))
                {
                    var parser  = new CredentialsFileParser(credentialsFilePath);
                    var section = parser.FindSection(lookupName);
                    if (section != null)
                    {
                        section.Validate();
                        this._wrappedCredentials = section.Credentials;
                        var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials));
                        logger.InfoFormat("Credentials found using account name {0} and looking in {1}.", lookupName, credentialsFilePath);
                    }

                    ProfilesLocation = credentialsFilePath;
                }
            }

            // No credentials found so error out.
            if (this._wrappedCredentials == null)
            {
                throw new ArgumentException("App.config does not contain credentials information. Either add the AWSAccessKey and AWSSecretKey properties or the AWSProfileName property.");
            }
        }
예제 #11
0
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_wrappedCredentials != null)
                    {
                        _wrappedCredentials.Dispose();
                        _wrappedCredentials = null;
                    }
                }

                _disposed = true;
            }
        }
예제 #12
0
        /// <summary>
        /// Constructs an instance of EnvironmentVariablesAWSCredentials. If no credentials are found in the environment variables
        /// then an InvalidOperationException.
        /// </summary>
        public EnvironmentVariablesAWSCredentials()
        {
            string accessKeyId = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_ACCESSKEY);
            string secretKey   = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_SECRETKEY);

            if (string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(secretKey))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                  "The environment variables {0} and {1} were not set with AWS credentials.", ENVIRONMENT_VARIABLE_ACCESSKEY, ENVIRONMENT_VARIABLE_SECRETKEY));
            }

            string sessionToken = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_SESSION_TOKEN);

            this._wrappedCredentials = new ImmutableCredentials(accessKeyId, secretKey, sessionToken);
            LOGGER.InfoFormat("Credentials found using environment variables.");
        }
예제 #13
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_lastCredentials != null)
                    {
                        _lastCredentials.Dispose();
                        _lastCredentials = null;
                    }
                }

                _disposed = true;
            }
        }
예제 #14
0
 public SessionAWSCredentials(string awsAccessKeyId, string awsSecretAccessKey, string token)
 {
     if (string.IsNullOrEmpty(awsAccessKeyId))
     {
         throw new ArgumentNullException("awsAccessKeyId");
     }
     if (string.IsNullOrEmpty(awsSecretAccessKey))
     {
         throw new ArgumentNullException("awsSecretAccessKey");
     }
     if (string.IsNullOrEmpty(token))
     {
         throw new ArgumentNullException("token");
     }
     _lastCredentials = new ImmutableCredentials(awsAccessKeyId, awsSecretAccessKey, token);
 }
예제 #15
0
    // Called when Start game button is clicked
    void StartGame()
    {
        if (!this.gameStartRequested)
        {
            this.startGameButton.gameObject.SetActive(false);
            this.gameStartRequested = true;

            FindObjectOfType <UIManager>().SetTextBox("Setting up Client..");

            // Get the Region enum from the string value
            this.region = Amazon.RegionEndpoint.GetBySystemName(regionString);
            Debug.Log("My Region endpoint: " + this.region);

            // Check if we have stored an identity and request credentials for that existing identity
            Client.cognitoID = PlayerPrefs.GetString("CognitoID", null);
            if (Client.cognitoID != null && Client.cognitoID != "")
            {
                Debug.Log("Requesting credentials for existing identity: " + Client.cognitoID);
                var response = Task.Run(() => GetCredentialsForExistingIdentity(Client.cognitoID));
                response.Wait(5000);
                Client.cognitoID          = response.Result.IdentityId;
                Client.cognitoCredentials = new Amazon.Runtime.ImmutableCredentials(response.Result.Credentials.AccessKeyId, response.Result.Credentials.SecretKey, response.Result.Credentials.SessionToken);
            }
            // Else get a new identity
            else
            {
                Debug.Log("Requesting a new playeridentity as none stored yet.");
                CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                    this.identityPoolID,
                    this.region);
                Client.cognitoCredentials = credentials.GetCredentials();
                Client.cognitoID          = credentials.GetIdentityId();
                Debug.Log("Got Cognito ID: " + credentials.GetIdentityId());

                // Store to player prefs and save for future games
                PlayerPrefs.SetString("CognitoID", Client.cognitoID);
                PlayerPrefs.Save();
            }

            // Get latencies to regions
            this.MeasureLatencies();

            // Connect to the server now that we have our identity, credendtials and latencies
            StartCoroutine(ConnectToServer());
        }
    }
예제 #16
0
 private void ValidateAuthentication(ImmutableCredentials immutableCredentials)
 {
     if (immutableCredentials.UseToken)  // token supplied
     {
         if ((authenticationType & AuthenticationTypes.Session) != AuthenticationTypes.Session)
         {
             throw new AmazonServiceException("Client does not support session authentication");
         }
     }
     else  // no token supplied
     {
         if ((authenticationType & AuthenticationTypes.User) != AuthenticationTypes.User)
         {
             throw new AmazonServiceException("Client does not support user authentication");
         }
     }
 }
예제 #17
0
        /// <summary>
        /// Constructs an instance of StoredProfileAWSCredentials. Credentials will be searched for using the profileName parameter.
        /// </summary>
        /// <param name="profileName">The profile name to search for credentials for</param>
        /// <param name="profilesLocation">Overrides the location to search for credentials</param>
        public StoredProfileAWSCredentials(string profileName, string profilesLocation)
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            var lookupName = string.IsNullOrEmpty(profileName) ? DEFAULT_PROFILE_NAME : profileName;

            ProfileName      = lookupName;
            ProfilesLocation = null;

            // If not overriding the credentials lookup location check the SDK Store for credentials. If an override is being used then
            // assume the intent is to use the credentials file.
            if (string.IsNullOrEmpty(profilesLocation))
            {
                AWSCredentials credentials;
                if (Amazon.Util.ProfileManager.TryGetAWSCredentials(lookupName, out credentials))
                {
                    this._wrappedCredentials = credentials.GetCredentials();
                    LOGGER.InfoFormat("Credentials found using account name {0} and looking in SDK account store.", lookupName);
                }
            }

            // If credentials weren't found in the SDK store then search the shared credentials file.
            if (this._wrappedCredentials == null)
            {
                var credentialsFilePath = DetermineCredentialsFilePath(profilesLocation);
                if (File.Exists(credentialsFilePath))
                {
                    string accessKeyId, secretKey;
                    SearchCredentialsFile(credentialsFilePath, lookupName, out accessKeyId, out secretKey);

                    if (accessKeyId != null && secretKey != null)
                    {
                        this._wrappedCredentials = new ImmutableCredentials(accessKeyId, secretKey, null);
                        LOGGER.InfoFormat("Credentials found using account name {0} and looking in {1}.", lookupName, credentialsFilePath);
                    }

                    ProfilesLocation = credentialsFilePath;
                }
            }

            // No credentials found so error out.
            if (this._wrappedCredentials == null)
            {
                throw new ArgumentException("App.config does not contain credentials information. Either add the AWSAccessKey and AWSSecretKey or AWSProfileName.");
            }
        }
예제 #18
0
        /// <summary>
        /// Constructs an instance of EnvironmentAWSCredentials and attempts to load AccessKey and SecretKey from ConfigurationManager.AppSettings
        /// </summary>
        public EnvironmentAWSCredentials()
        {
            string accessKey = ConfigurationManager.GetAccessKey();
            string secretKey = ConfigurationManager.GetSecretKey();

            if (string.IsNullOrEmpty(accessKey))
            {
                throw new ArgumentException(string.Format("Access Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your access key.", "AWSAccessKey"));
            }

            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentException(string.Format("Secret Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your secret key.", "AWSSecretKey"));
            }

            this.wrappedCredentials = new ImmutableCredentials(accessKey, secretKey);
        }
예제 #19
0
        /// <summary>
        /// Constructs an instance of EnvironmentAWSCredentials and attempts to load AccessKey and SecretKey from ConfigurationManager.AppSettings
        /// </summary>
        public EnvironmentAWSCredentials()
        {
            string accessKey = ConfigurationManager.GetAccessKey();
            string secretKey = ConfigurationManager.GetSecretKey();

            if (string.IsNullOrEmpty(accessKey))
            {
                throw new ArgumentException(string.Format("Access Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your access key.", "AWSAccessKey"));
            }

            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentException(string.Format("Secret Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your secret key.", "AWSSecretKey"));
            }

            this.wrappedCredentials = new ImmutableCredentials(accessKey, secretKey);
        }
예제 #20
0
        /// <summary>
        /// Constructs an instance of EnvironmentAWSCredentials and attempts
        /// to load AccessKey and SecretKey from ConfigurationManager.AppSettings
        /// </summary>
        public EnvironmentAWSCredentials()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            var accessKey = appConfig[ACCESSKEY];
            var secretKey = appConfig[SECRETKEY];

            if (string.IsNullOrEmpty(accessKey))
            {
                throw new ArgumentException(string.Format("Access Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your access key.", ACCESSKEY));
            }
            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentException(string.Format("Secret Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your secret key.", SECRETKEY));
            }

            this._wrappedCredentials = new ImmutableCredentials(accessKey, secretKey, null, false);
        }
예제 #21
0
        /// <summary>
        /// Constructs an instance of EnvironmentAWSCredentials and attempts
        /// to load AccessKey and SecretKey from ConfigurationManager.AppSettings
        /// </summary>
        public EnvironmentAWSCredentials()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            // Use hardcoded credentials
            if (!string.IsNullOrEmpty(appConfig[ACCESSKEY]) && !string.IsNullOrEmpty(appConfig[SECRETKEY]))
            {
                var accessKey = appConfig[ACCESSKEY];
                var secretKey = appConfig[SECRETKEY];
                this._wrappedCredentials = new ImmutableCredentials(accessKey, secretKey, null);
                LOGGER.InfoFormat("Credentials found with {0} and {1} app settings", ACCESSKEY, SECRETKEY);
            }
            // Fallback to the StoredProfileAWSCredentials provider
            else
            {
                this._wrappedCredentials = new StoredProfileAWSCredentials().GetCredentials();
            }
        }
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(this, obj))
            {
                return(true);
            }

            ImmutableCredentials ic = obj as ImmutableCredentials;

            if (ic == null)
            {
                return(false);
            }

            return(AWSSDKUtils.AreEqual(
                       new object[] { AccessKey, SecretKey, Token },
                       new object[] { ic.AccessKey, ic.SecretKey, ic.Token }));
        }
        /// <summary>
        /// Returns a copy of the most recent instance profile credentials.
        /// </summary>
        public override ImmutableCredentials GetCredentials()
        {
            CheckIsIMDSEnabled();

            var credentials = lastRetrievedCredentials?.Copy();

            // If there's no credentials cached, hit IMDS directly.
            if (credentials == null)
            {
                credentials = FetchCredentials();
                lastRetrievedCredentials = credentials;
            }

            if (credentials == null)
            {
                throw new AmazonServiceException(FailedToGetCredentialsMessage);
            }

            return(credentials);
        }
예제 #24
0
        private static AmazonSecurityTokenService ConstructSTSClient(AWSCredentials credentials, AmazonSecurityTokenServiceConfig config)
        {
            using (ImmutableCredentials immmutableCredentials = credentials.GetCredentials())
            {
                if (immmutableCredentials.UseToken)
                {
                    throw new ArgumentException("Session credentials cannot be used to create refreshing session credentials");
                }

                AmazonSecurityTokenServiceClient stsClient;
                if (immmutableCredentials.UseSecureStringForSecretKey)
                {
                    stsClient = new AmazonSecurityTokenServiceClient(immmutableCredentials.AccessKey, GetClearSecretKey(immmutableCredentials.SecureSecretKey), config);
                }
                else
                {
                    stsClient = new AmazonSecurityTokenServiceClient(immmutableCredentials.AccessKey, immmutableCredentials.ClearSecretKey, config);
                }
                return(stsClient);
            }
        }
예제 #25
0
        private static void TestCredentialsFile(ImmutableCredentials ic)
        {
            var profileName = "testProfile";
            var profilesLocation = WriteCreds(profileName, ic);
            var creds = new StoredProfileAWSCredentials(profileName, profilesLocation);
            var rc = creds.GetCredentials();
            Assert.AreEqual(ic.SecretKey, rc.SecretKey);
            Assert.AreEqual(ic.AccessKey, rc.AccessKey);
            Assert.AreEqual(ic.UseToken, rc.UseToken);
            Assert.AreEqual(ic.Token, rc.Token);

            for (int i = 0; i < 4; i++)
            {
                creds = new StoredProfileAWSCredentials(profileName + i, profilesLocation);
                Assert.IsNotNull(creds);
                rc = creds.GetCredentials();
                Assert.IsNotNull(rc.AccessKey);
                Assert.IsNotNull(rc.SecretKey);
                var shouldHaveToken = (i % 2 == 1);
                Assert.AreEqual(shouldHaveToken, rc.UseToken);
            }
        }
        protected void SignRequest(IRequestData requestData)
        {
            // credentials would be null in the case of anonymous users getting public resources from S3
            if (Credentials == null || Credentials is AnonymousAWSCredentials)
            {
                return;
            }

            using (requestData.Metrics.StartEvent(Metric.RequestSigningTime))
            {
                requestData.Metrics.StartEvent(Metric.CredentialsRequestTime);
                ImmutableCredentials immutableCredentials = Credentials.GetCredentials();
                // credentials would be null in the case of anonymous users getting public resources from S3
                if (immutableCredentials == null)
                {
                    return;
                }
                requestData.Metrics.StopEvent(Metric.CredentialsRequestTime);
                if (immutableCredentials.UseToken)
                {
                    ClientProtocol protocol = requestData.Signer.Protocol;
                    switch (protocol)
                    {
                    case ClientProtocol.QueryStringProtocol:
                        requestData.Request.Parameters["SecurityToken"] = immutableCredentials.Token;
                        break;

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

                    default:
                        throw new InvalidDataException("Cannot determine protocol");
                    }
                }
                requestData.Signer.Sign(requestData.Request, this.Config, requestData.Metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
            }
        }
예제 #27
0
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }
            ImmutableCredentials immutableCredentials = obj as ImmutableCredentials;

            if (immutableCredentials == null)
            {
                return(false);
            }
            return(AWSSDKUtils.AreEqual(new object[3]
            {
                AccessKey,
                SecretKey,
                Token
            }, new object[3]
            {
                immutableCredentials.AccessKey,
                immutableCredentials.SecretKey,
                immutableCredentials.Token
            }));
        }
        private void SignRequest(IRequest request, AbstractAWSSigner signer)
        {
            using (ImmutableCredentials immutableCredentials = credentials.GetCredentials())
            {
                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);
            }
        }
예제 #29
0
 /// <summary>
 /// Returns a copy of the current credentials.
 /// </summary>
 /// <returns></returns>
 public ImmutableCredentials Copy()
 {
     ImmutableCredentials credentials = new ImmutableCredentials
     {
         AccessKey = this.AccessKey,
         ClearSecretKey = this.ClearSecretKey,
         SecureSecretKey = (this.SecureSecretKey == null ? null : this.SecureSecretKey.Copy()),
         Token = this.Token,
     };
     return credentials;
 }
예제 #30
0
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_wrappedCredentials != null)
                    {
                        _wrappedCredentials.Dispose();
                        _wrappedCredentials = null;
                    }
                }

                _disposed = true;
            }
        }
예제 #31
0
        /// <summary>
        /// Constructs an instance of EnvironmentAWSCredentials and attempts
        /// to load AccessKey and SecretKey from ConfigurationManager.AppSettings
        /// </summary>
        public EnvironmentAWSCredentials()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            var accessKey = appConfig[ACCESSKEY];
            var secretKey = appConfig[SECRETKEY];

            if (string.IsNullOrEmpty(accessKey))
                throw new ArgumentException(string.Format("Access Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your access key.", ACCESSKEY));
            if (string.IsNullOrEmpty(secretKey))
                throw new ArgumentException(string.Format("Secret Key could not be found.  Add an appsetting to your App.config with the name {0} with a value of your secret key.", SECRETKEY));

            this._wrappedCredentials = new ImmutableCredentials(accessKey, secretKey, null, false);
        }
예제 #32
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;
        }
예제 #33
0
 /// <summary>
 /// Returns a copy of the current credentials.
 /// </summary>
 /// <returns></returns>
 public ImmutableCredentials Copy()
 {
     ImmutableCredentials credentials2 = new ImmutableCredentials();
     credentials2.AccessKey = this.AccessKey;
     credentials2.SecretKey = this.SecretKey;
     return credentials2;
 }
예제 #34
0
 /// <summary>
 /// Constructs a BasicAWSCredentials object for the specified accessKey and secretKey,
 /// with the useSecureString flag to signal if the secretKey should be stored as SecureString
 /// </summary>
 /// <param name="accessKey"></param>
 /// <param name="secretKey"></param>
 /// <param name="useSecureString">
 /// True if secretKey should be stored in SecureString. False if secretKey should be stored as clear string.
 /// </param>
 public BasicAWSCredentials(string accessKey, string secretKey, bool useSecureString)
 {
     _credentials = new ImmutableCredentials(accessKey, secretKey, null, useSecureString);
 }
        /// <summary>
        /// Constructs an instance of StoredProfileAWSCredentials. Credentials will be searched for using the profileName parameter.
        /// </summary>
        /// <param name="profileName">The profile name to search for credentials for</param>
        /// <param name="profilesLocation">Overrides the location to search for credentials</param>
        public StoredProfileAWSCredentials(string profileName, string profilesLocation)
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            var lookupName = string.IsNullOrEmpty(profileName) ? DEFAULT_PROFILE_NAME : profileName;
            ProfileName = lookupName;
            ProfilesLocation = null;

            // If not overriding the credentials lookup location check the SDK Store for credentials. If an override is being used then
            // assume the intent is to use the credentials file.
            if (string.IsNullOrEmpty(profilesLocation))
            {
                AWSCredentials credentials;
                if (Amazon.Util.ProfileManager.TryGetAWSCredentials(lookupName, out credentials))
                {
                    this._wrappedCredentials = credentials.GetCredentials();
                    var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials));
                    logger.InfoFormat("Credentials found using account name {0} and looking in SDK account store.", lookupName);
                }
            }

            // If credentials weren't found in the SDK store then search the shared credentials file.
            if (this._wrappedCredentials == null)
            {
                var credentialsFilePath = DetermineCredentialsFilePath(profilesLocation);
                if (File.Exists(credentialsFilePath))
                {                    
                    var parser = new CredentialsFileParser(credentialsFilePath);
                    var section = parser.FindSection(lookupName);
                    if (section != null && section.HasValidCredentials)
                    {
                        this._wrappedCredentials = section.Credentials;
                        var logger = Logger.GetLogger(typeof(StoredProfileAWSCredentials));
                        logger.InfoFormat("Credentials found using account name {0} and looking in {1}.", lookupName, credentialsFilePath);
                    }

                    ProfilesLocation = credentialsFilePath;
                }
            }

            // No credentials found so error out.
            if (this._wrappedCredentials == null)
            {
                throw new ArgumentException("App.config does not contain credentials information. Either add the AWSAccessKey and AWSSecretKey or AWSProfileName.");
            }
        }
        /// <summary>
        /// Constructs an instance of EnvironmentAWSCredentials and attempts
        /// to load AccessKey and SecretKey from ConfigurationManager.AppSettings
        /// </summary>
        public EnvironmentAWSCredentials()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            // Use hardcoded credentials
            if (!string.IsNullOrEmpty(appConfig[ACCESSKEY]) && !string.IsNullOrEmpty(appConfig[SECRETKEY]))
            {
                var accessKey = appConfig[ACCESSKEY];
                var secretKey = appConfig[SECRETKEY];
                this._wrappedCredentials = new ImmutableCredentials(accessKey, secretKey, null);
                var logger = Logger.GetLogger(typeof(EnvironmentAWSCredentials));
                logger.InfoFormat("Credentials found with {0} and {1} app settings", ACCESSKEY, SECRETKEY);
            }
            // Fallback to the StoredProfileAWSCredentials provider
            else
            {
                this._wrappedCredentials = new StoredProfileAWSCredentials().GetCredentials();
            }
        }
 public SAMLImmutableCredentials(ImmutableCredentials credentials, DateTime expires, string subject)
     : base(credentials.AccessKey, credentials.SecretKey, credentials.Token)
 {
     Expires = expires;
     Subject = subject;
 }
예제 #38
0
 private static AmazonS3Client GetUsEast1ClientFromCredentials(ImmutableCredentials credentials)
 {
     if (credentials.UseToken)
     {
         return new AmazonS3Client(credentials.AccessKey, credentials.SecretKey, credentials.Token, RegionEndpoint.USEast1);
     }
     else
     {
         return new AmazonS3Client(credentials.AccessKey, credentials.SecretKey, RegionEndpoint.USEast1);
     }
 }
예제 #39
0
 private static string GetHeadBucketPreSignedUrl(string bucketName, ImmutableCredentials credentials)
 {
     // IMPORTANT:
     // This method is called as part of the request pipeline.
     // If the pipeline were to be invoked here it would cause
     // unwanted recursion.
     // As such, the only reason it's OK to use an S3Client here
     // is because this code is using a method that doesn't go
     // through the request pipeline: GetPreSignedURLInternal
     var request = new GetPreSignedUrlRequest
     {
         BucketName = bucketName,
         Expires = DateTime.Now.AddDays(1),
         Verb = HttpVerb.HEAD,
         Protocol = Protocol.HTTP
     };
     // all buckets accessible via USEast1
     using (var s3Client = GetUsEast1ClientFromCredentials(credentials))
     {
         return s3Client.GetPreSignedURLInternal(request, false);
     }
 }
예제 #40
0
 private static void AppendCredentialsSet(StreamWriter writer, string profileName, ImmutableCredentials ic)
 {
     writer.WriteLine();
     writer.WriteLine("; profile {0} and its credentials", profileName);
     writer.WriteLine("# alternative comment marker");
     writer.WriteLine("[{0}]", profileName);
     writer.WriteLine("aws_access_key_id = {0}", ic.AccessKey);
     writer.WriteLine("aws_secret_access_key={0}", ic.SecretKey);
     if (ic.UseToken)
         writer.WriteLine("aws_session_token= {0}", ic.Token);
     writer.WriteLine();
 }
예제 #41
0
 /// <summary>
 /// Constructs a BasicAWSCredentials object for the specified accessKey and secretKey
 /// SecretKey is stored in SecureString
 /// </summary>
 /// <param name="accessKey"></param>
 /// <param name="secretKey"></param>
 public BasicAWSCredentials(string accessKey, SecureString secretKey)
 {
     _credentials = new ImmutableCredentials(accessKey, secretKey, null);
 }
 /// <summary>
 /// Constructs a BasicAWSCredentials object for the specified accessKey and secretKey.
 /// </summary>
 /// <param name="accessKey"></param>
 /// <param name="secretKey"></param>
 public BasicAWSCredentials(string accessKey, string secretKey)
 {
     if (!string.IsNullOrEmpty(accessKey))
     {
         _credentials = new ImmutableCredentials(accessKey, secretKey, null);
     }
 }
 /// <summary>
 /// Returns a copy of the current credentials.
 /// </summary>
 /// <returns></returns>
 public ImmutableCredentials Copy()
 {
     ImmutableCredentials credentials = new ImmutableCredentials
     {
         AccessKey = this.AccessKey,
         SecretKey = this.SecretKey,
         Token = this.Token,
     };
     return credentials;
 }
        /// <summary>
        /// Constructs a SessionAWSCredentials object for the specified accessKey, secretKey.
        /// </summary>
        /// <param name="awsAccessKeyId"></param>
        /// <param name="awsSecretAccessKey"></param>
        /// <param name="token"></param>
        public SessionAWSCredentials(string awsAccessKeyId, string awsSecretAccessKey, string token)
        {
            if (string.IsNullOrEmpty(awsAccessKeyId)) throw new ArgumentNullException("awsAccessKeyId");
            if (string.IsNullOrEmpty(awsSecretAccessKey)) throw new ArgumentNullException("awsSecretAccessKey");
            if (string.IsNullOrEmpty(token)) throw new ArgumentNullException("token");

            _lastCredentials = new ImmutableCredentials(awsAccessKeyId, awsSecretAccessKey, token);
        }
예제 #45
0
 public StoredCredentials(ImmutableCredentials ic)
 {
     credentials = ic;
 }
        /// <summary>
        /// Constructs an instance of EnvironmentVariablesAWSCredentials. If no credentials are found in the environment variables 
        /// then an InvalidOperationException.
        /// </summary>
        public EnvironmentVariablesAWSCredentials()
        {
            string accessKeyId = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_ACCESSKEY);
            string secretKey = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_SECRETKEY);
            if (string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(secretKey))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                    "The environment variables {0} and {1} were not set with AWS credentials.", ENVIRONMENT_VARIABLE_ACCESSKEY, ENVIRONMENT_VARIABLE_SECRETKEY));
            }

            string sessionToken = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_SESSION_TOKEN);

            this._wrappedCredentials = new ImmutableCredentials(accessKeyId, secretKey, sessionToken);
            var logger = Logger.GetLogger(typeof(EnvironmentVariablesAWSCredentials));
            logger.InfoFormat("Credentials found using environment variables.");
        }
예제 #47
0
 /// <summary>
 /// Detects if the signature is malformed, and the requested bucket is in a Region
 /// different from the Region of the request.
 /// </summary>
 /// <param name="requestedBucketUri"></param>
 /// <param name="serviceException"></param>
 /// <param name="credentials"></param>
 /// <returns>the correct region if a mismatch was detected, null otherwise</returns>
 internal static async Task<string> DetectMismatchWithHeadBucketFallbackAsync(AmazonS3Uri requestedBucketUri, AmazonServiceException serviceException, ImmutableCredentials credentials)
 {
     return GetCorrectRegion(requestedBucketUri, serviceException) ??
         CheckRegionAndUpdateCache(requestedBucketUri, await GetBucketRegionNoPipelineAsync(requestedBucketUri.Bucket, credentials));
 }
 public CredentialsRefreshState(ImmutableCredentials credentials, DateTime expiration)
 {
     Credentials = credentials;
     Expiration = expiration;
 }
 public CredentialsRefreshState(ImmutableCredentials credentials, DateTime expiration)
 {
     Credentials = credentials;
     Expiration  = expiration;
 }
 /// <summary>
 /// Returns a copy of ImmutableCredentials corresponding to these credentials
 /// </summary>
 /// <returns></returns>
 public override ImmutableCredentials GetCredentials()
 {
     if (_credentials == null)
         _credentials = new ImmutableCredentials(AccessKeyId, SecretKey, SessionToken);
     return _credentials.Copy();
 }
예제 #51
0
 /// <summary>
 /// Constructs a BasicAWSCredentials object for the specified accessKey and secretKey,
 /// with the useSecureString flag to signal if the secretKey should be stored as SecureString
 /// </summary>
 /// <param name="accessKey"></param>
 /// <param name="secretKey"></param>
 /// <param name="useSecureString">
 /// True if secretKey should be stored in SecureString. False if secretKey should be stored as clear string.
 /// </param>
 public BasicAWSCredentials(string accessKey, string secretKey, bool useSecureString)
 {
     _credentials = new ImmutableCredentials(accessKey, secretKey, null, useSecureString);
 }
예제 #52
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_lastCredentials != null)
                    {
                        _lastCredentials.Dispose();
                        _lastCredentials = null;
                    }
                }

                _disposed = true;
            }
        }
예제 #53
0
 /// <summary>
 /// Constructs a BasicAWSCredentials object for the specified accessKey and secretKey
 /// SecretKey is stored in SecureString
 /// </summary>
 /// <param name="accessKey"></param>
 /// <param name="secretKey"></param>
 public BasicAWSCredentials(string accessKey, SecureString secretKey)
 {
     _credentials = new ImmutableCredentials(accessKey, secretKey, null);
 }
        /// <summary>
        /// Returns a copy of the most recent instance profile credentials.
        /// </summary>
        public override ImmutableCredentials GetCredentials()
        {
            CheckIsIMDSEnabled();
            ImmutableCredentials credentials = null;

            // Try to acquire read lock. The thread would be blocked if another thread has write lock.
            if (_credentialsLock.TryEnterReadLock(_credentialsLockTimeout))
            {
                try
                {
                    if (null != _lastRetrievedCredentials)
                    {
                        // if credentials are expired, we'll still return them, but log a message about
                        // them being expired.
                        if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero))
                        {
                            _logger.InfoFormat(_usingExpiredCredentialsFromIMDS);
                        }

                        return(_lastRetrievedCredentials?.Credentials.Copy());
                    }
                }
                finally
                {
                    _credentialsLock.ExitReadLock();
                }
            }

            // If there's no credentials cached, hit IMDS directly. Try to acquire write lock.
            if (_credentialsLock.TryEnterWriteLock(_credentialsLockTimeout))
            {
                try
                {
                    // Check for last retrieved credentials again in case other thread might have already fetched it.
                    if (null == _lastRetrievedCredentials)
                    {
                        _lastRetrievedCredentials = FetchCredentials();
                    }

                    // if credentials are expired, we'll still return them, but log a message about
                    // them being expired.
                    if (_lastRetrievedCredentials.IsExpiredWithin(TimeSpan.Zero))
                    {
                        _logger.InfoFormat(_usingExpiredCredentialsFromIMDS);
                    }

                    credentials = _lastRetrievedCredentials.Credentials?.Copy();
                }
                finally
                {
                    _credentialsLock.ExitWriteLock();
                }
            }

            if (credentials == null)
            {
                throw new AmazonServiceException(FailedToGetCredentialsMessage);
            }

            return(credentials);
        }
예제 #55
0
 public void AssertWriteProfile(string profileName, ImmutableCredentials credentials, string expectedFileContents)
 {
     if (credentials.UseToken)
     {
         CredentialsFile.AddOrUpdateCredentials(profileName, credentials.AccessKey, credentials.SecretKey, credentials.Token);
     }
     else
     {
         CredentialsFile.AddOrUpdateCredentials(profileName, credentials.AccessKey, credentials.SecretKey);
     }
     CredentialsFile.Persist();
     AssertFileContents(expectedFileContents);
 }