aws-sdk-cpp How to decrypt a password encrypted by kms using KMSCLIENT of c++ sdk - c++

im trying to found any example to how decrypt a password encrypted by KMS, for example i have a RDS database password encrypted by KMS, i want to decrypt it in my aws-cpp-lambda function to connect to the database.
i see that for call client Decrypt i need a DecryptRequest;
but i don't know how to initialize it and where set my "encriptedPassword" in the DecryptedRequest to call client.Decrypt()
this is base64
encriptedPassword = "GPK0ujdAAAAZzBlBgkqhkiG"
Aws::SDKOptions options;
InitAPI(options);
{
Aws::Client::ClientConfiguration awsConfig;
awsConfig.region = Aws::Environment::GetEnv("AWS_REGION");
Aws::KMS::KMSClient client(awsConfig);
// Aws::KMS::Model::DecryptRequest decryptRequest;
// client.Decrypt(decryptRequest);
}
// shutdown the aws api
std::cout << "shutdown api" << "\n";
ShutdownAPI(options);
all the credentials are managed and storage by the aws administrator so i don't have access to that configuration, i only have the encrypted db password. when i make the lambda i publish it a git repository after that a jenkins process build and deploy the lambda to aws, jenkins has the credentials etc and i suppose that also is saved in the ec2 or aws config, they only give me a example of how to do that but its in nodejs i need to do a c++ version of that for example this is the nodejs example
use strict'
const AWS = require('aws-sdk');
module.exports.decrypt = (key) => {
return new Promise((resolve, reject) => {
const kms = new AWS.KMS();
console.log('Attempting to decrypt: ' + key);
const params = {CiphertextBlob: new Buffer(key, 'base64')};
console.log(params);
kms.decrypt(params, function (err, data) {
if (err) {
console.log('Error while decrypting key: ' + err);
reject(err)
} else {
console.log('Decrypted key');
resolve(data.Plaintext.toString('ascii'));
}
});
});
what nodejs version do is decrypt the password using sdk kms client after that is passed as simple string to the db connection lib and connect to the database using host, port, db name, etc.
what i need to do is decrypt the password using the KMSCLIENT for c++ like the node version.
anyone cant write a small example please. Thanks to all!!

Related

Where is my database password in Altostra project?

I’ve created a project in Altostra. I've created a Lambda function in the vscode extension and connected it to an RDS instance. The password is apparently auto-generated and “accessible to any lambda”, but where do I access it?
When you connect lambda to the database resource, you will have connection details provided for you into lambda's environment variable.
Here you have DB_SECRET_RDS02, representing the "secret" you need.
Then, in the Lambda code, you will have access to the variable through process.env
const aws = require('aws-sdk')
// retrieving host and port
const [host, port] = process.env.DB_RDS02.split(':')
// retrieving secret from SecretManager
const secretManager = new aws.SecretsManager()
const secret = await secretManager.getSecretValue({
SecretId: process.env.DB_SECRET_RDS02
}).promise()
// retrieving data from secret
const { username, password } = JSON.parse(secret.SecretString)

AWS Assume Role via .Net SDK gives Access Denied but works with CLI

I am trying to upload a file in S3 by AWS Assume Role. When I am trying to access it from CLI it works fine but from .Net SDK it gives me Access Denied error.
Here are the steps I followed in CLI -
Setup the access key/secret key for user using aws configure
Assume the Role - “aws sts assume-role --role-arn "arn:aws:iam::1010101010:role/Test-Account-Role" --role-session-name AWSCLI-Session”
Take the access key / secret key / session token from the assumed role and setup an AWS profile. The credentials are printed out/returned from the assumed role.
Switch to the assume role profile: “set AWS_PROFILE=”
Verify that the user has the role: “aws sts get-caller-identity”
Access the bucket using ls or cp or rm command - Works Successfully.
Now I am trying to access it from .Net core App -
Here is the code snippet- Note that I am using same Access and Secret key as CLI from my local.
try
{
var region = RegionEndpoint.GetBySystemName(awsRegion);
SessionAWSCredentials tempCredentials = await GetTemporaryCredentialsAsync(awsAccessKey, awsSecretKey, region, roleARN);
//Use the temp credentials received to create the new client
IAmazonS3 client = new AmazonS3Client(tempCredentials, region);
TransferUtility utility = new TransferUtility(client);
// making a TransferUtilityUploadRequest instance
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest
{
BucketName = bucketName,
Key = $"{subFolder}/{fileName}",
FilePath = localFilePath
utility.Upload(request); //transfer
fileUploadedSuccessfully = true;
}
catch (AmazonS3Exception ex)
{
// HandleException
}
catch (Exception ex)
{
// HandleException
}
The method to get temp credentials is as follow - GetTemporaryCredentialsAsync
private static async Task<SessionAWSCredentials> GetTemporaryCredentialsAsync(string awsAccessKey, string awsSecretKey, RegionEndpoint region, string roleARN)
{
using (var stsClient = new AmazonSecurityTokenServiceClient(awsAccessKey, awsSecretKey, region))
{
var getSessionTokenRequest = new GetSessionTokenRequest
{
DurationSeconds = 7200
};
await stsClient.AssumeRoleAsync(
new AssumeRoleRequest()
{
RoleArn = roleARN,
RoleSessionName = "mySession"
});
GetSessionTokenResponse sessionTokenResponse =
await stsClient.GetSessionTokenAsync(getSessionTokenRequest);
Credentials credentials = sessionTokenResponse.Credentials;
var sessionCredentials =
new SessionAWSCredentials(credentials.AccessKeyId,
credentials.SecretAccessKey,
credentials.SessionToken);
return sessionCredentials;
}
}
I am getting back the temp credentials but it gives me Access Denied while uploading the file. Not sure if I am missing anything here.
Also noted that the token generated via SDK is shorter than that from CLI. I tried pasting these temp credentials to local profile and then tried to access the bucket and getting the Access Denied error then too.
There is an AWS .NET V3 example that shows this exact use case. To assume a role, you use a AmazonSecurityTokenServiceClient. In this example, the user assumes the role that allows the role to be used to list all S3 buckets. See this .NET scenario here.
https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/dotnetv3/IAM/IAM_Basics_Scenario/IAM_Basics_Scenario/IAM_Basics.cs

How to invoke secrets from AWS Secrets Manager into code to get the data from an Amazon DyanmoDB table

I have stored AWS IAM user Access key's and Secret keys in a secret of AWS Secrets Manager.
This secret is helpful to get the data from an Amazon DynamoDB table, and keys's having full access to the Amazon DynamoDB table. I need to use this secret in java/.Net code to retrieve the data from DynamoDB table.
Secretname: dynamodbtesting
Below is the sample key names which I used while creating secret.
{
"aws_access_key_id": "value",
"aws_secret_access_key": "secret value"
}
How to use secret in java/.Net code to get the date from DynamoDB table?
Note: I could see one sample code after creation of secret in secret manager, is it helpful?
When using the AWS Java SDK, when you build the client which accesses dynamodb, you can pass credentials explicitly:
https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-explicit
For example:
BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
AmazonS3 dynamodbClient = AmazonDynamoDBClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
To answer your question: "How to use secret in java"
You can use the Secrets Manager Java API V2 to retrive a secret. The following Java code shows you how to perform this use case:
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;
//snippet-end:[secretsmanager.java2.get_secret.import]
/**
* To run this AWS code example, ensure that you have setup your development environment, including your AWS credentials.
*
* For information, see this documentation topic:
*
*https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class GetSecretValue {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" GetSecretValue <secretName> \n\n" +
"Where:\n" +
" secretName - the name of the secret (for example, tutorials/MyFirstSecret). \n";
if (args.length != 1) {
System.out.println(USAGE);
System.exit(1);
}
String secretName = args[0];
Region region = Region.US_EAST_1;
SecretsManagerClient secretsClient = SecretsManagerClient.builder()
.region(region)
.build();
getValue(secretsClient, secretName);
secretsClient.close();
}
//snippet-start:[secretsmanager.java2.get_secret.main]
public static void getValue(SecretsManagerClient secretsClient,String secretName) {
try {
GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
.secretId(secretName)
.build();
GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
String secret = valueResponse.secretString();
System.out.println(secret);
} catch (SecretsManagerException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
//snippet-end:[secretsmanager.java2.get_secret.main]
}
You can find this example and others for this AWS Service here:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/secretsmanager

DynamoDB Connection Biulding using AWS Java SDK by getting Keys from the user at runtime

I'm trying to connect to DynamoDB by getting AccessID and SecretKey from the user. AmazonDynamoDBClient has been depreciated and the replacement don't allow me to get credentials from the user and make a connection to DynamoDB. Here is my code snippet. The solution I'm getting is to keep the keys in a local file. I don't need this.
DynamoDB dynamoDB = null;
try {
System.out.println(1);
BasicAWSCredentials awsCreds = new BasicAWSCredentials(upDoc.getAccID(), upDoc.getAccKey());
System.out.println(2);
//AmazonDynamoDBClient is depreciated
AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCreds).withRegion(Regions.US_EAST_2);
System.out.println(3);
dynamoDB = new DynamoDB(client);
writer.append("Access Granted By AWS DynamoDB \n");
}catch(AmazonDynamoDBException e) {
writer.append("Access Denied By AWS DynamoDB \n");
writer.close();
return "Error occured. Kindly check logs to get the actual cause!";
}
Use AmazonDynamoDBClientBuilder
BasicAWSCredentials awsCreds = new BasicAWSCredentials(upDoc.getAccID(), upDoc.getAccKey());
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_EAST_2).withCredentials(awsCreds).build();

AWS SDK connection - How is this working?? (Beginner)

I am working on my AWS cert and I'm trying to figure out how the following bit of js code works:
var AWS = require('aws-sdk');
var uuid = require('node-uuid');
// Create an S3 client
var s3 = new AWS.S3();
// Create a bucket and upload something into it
var bucketName = 'node-sdk-sample-' + uuid.v4();
var keyName = 'hello_world.txt';
s3.createBucket({Bucket: bucketName}, function() {
var params = {Bucket: bucketName, Key: keyName, Body: 'Hello'};
s3.putObject(params, function(err, data) {
if (err)
console.log(err)
else
console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
});
});
This code successfully loads a txt file containing the words "Hello" in it. I do not understand how this ^ can identify MY AWS account. It does! But how! It somehow is able to determine that I want a new bucket inside MY account, but this code was taken directly from the AWS docs. I don't know how it could figure that out....
As per Class: AWS.CredentialProviderChain, the AWS SDK for JavaScript looks for credentials in the following locations:
AWS.CredentialProviderChain.defaultProviders = [
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); },
function () { return new AWS.SharedIniFileCredentials(); },
function () {
// if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set
return new AWS.ECSCredentials();
// else
return new AWS.EC2MetadataCredentials();
}
]
Environment Variables (useful for testing, or when running code on a local computer)
Local credentials file (useful for running code on a local computer)
ECS credentials (useful when running code in Elastic Container Service)
Amazon EC2 Metadata (useful when running code on an Amazon EC2 instance)
It is highly recommended to never store credentials within an application. If the code is running on an Amazon EC2 instance and a role has been assigned to the instance, the SDK will automatically retrieve credentials from the instance metadata.
The next best method is to store credentials in the ~/.aws/credentials file.