added aws_lambda code

This commit is contained in:
2026-08-16 16:59:37 +05:30
parent 50fded9d06
commit 220b261263
6 changed files with 326 additions and 74 deletions
+62
View File
@@ -0,0 +1,62 @@
"""
This module contains a Lambda function that checks if domains are reachable and retrieves SSL information.
Amazon will bill for the wait time of this function, timeout is set to 10 seconds.
TODO: Implement a loop with asynchronous checking of multiple domains.
"""
import requests
import ssl
import socket
from datetime import datetime
def lambda_handler(event, context):
"""
Args:
event (dict):
The event data passed to the Lambda function. Expects a dictionary
with a "hostnames" key containing a list of all hosts to be checked.
context (LambdaContext):
The runtime information of the Lambda function.
"""
max_timeout = 10
remaining_time_in_seconds = context.get_remaining_time_in_millis() / 1000
timeout_in_seconds = min(remaining_time_in_seconds - 1, max_timeout)
results = {}
for hostname in event["hostnames"]:
url = f"https://{hostname}/"
host_result = {}
host_result["https_get_request"] = get_request(url, timeout=timeout_in_seconds)
if host_result["https_get_request"].get("reachable"):
host_result["ssl"] = ssl_info(hostname)
results[hostname] = host_result
return results
def get_request(url, timeout=10):
result = {}
try:
resp = requests.get(url, timeout=timeout)
result["status_code"] = resp.status_code
result["reason"] = resp.reason
result["reachable"] = resp.status_code == 200
except requests.exceptions.RequestException as e:
result["error"] = str(e)
result["reachable"] = False
return result
def ssl_info(hostname, port=443):
try:
ctx = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=10) as sock:
with ctx.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
issuer = dict(x[0] for x in cert['issuer'])
not_after = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y %Z")
return {
"issuer": issuer.get("organizationName", "Unknown"),
"expiry": not_after.strftime("%Y-%m-%d %H:%M:%S"),
"valid": not_after > datetime.utcnow()
}
except Exception as e:
return {"error": str(e)}
+11
View File
@@ -0,0 +1,11 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowInvokeDomainCheckLambda",
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:eu-west-1:458835642486:function:domainCheck"
}
]
}
+99
View File
@@ -0,0 +1,99 @@
# This script sets up AWS Roles Anywhere with a custom CA and an IAM role for Lambda invocation.
# Prerequisites:
# - AWS CLI v2 installed, configured and logged in
# - OpenSSL
#
# https://docs.aws.amazon.com/pdfs/rolesanywhere/latest/userguide/rolesanywhere-guide.pdf
#
# Variables (replace with your own values)
$AccountId = "458835642486"
$Region = "eu-west-1"
$LambdaArn = "arn:aws:lambda:eu-west-1:$AccountId:function:domainCheck"
# Paths for certs
$CertDir = Join-Path $PSScriptRoot "rolesanywhere"
New-Item -ItemType Directory -Force -Path $CertDir | Out-Null
#
$TrustPolicyFile = Join-Path $PSScriptRoot "trust-policy.json"
$LambdaPolicyFile = Join-Path $PSScriptRoot "lambda-policy.json"
function Convert-ToAwsFileUrl {
param(
[Parameter(Mandatory)]
[string]$Path
)
# Expand relative paths and resolve directory separators
$full = (Resolve-Path -LiteralPath $Path).Path
# Convert backslashes to forward slashes
$normalized = $full -replace '\\','/'
# Prepend AWS-style file scheme
"file://$normalized"
}
# Generate CA key + certificate
openssl genrsa -out "$CertDir\ca.key" 2048
openssl req -x509 -new -nodes -key "$CertDir\ca.key" -sha256 -days 365 `
-out "$CertDir\ca.pem" -subj "/CN=MyTestCA" `
-addext "basicConstraints=CA:TRUE" `
-addext "keyUsage=keyCertSign,cRLSign"
# Generate client key + certificate signed by CA
openssl genrsa -out "$CertDir\client.key" 2048
openssl req -new -key "$CertDir\client.key" -out "$CertDir\client.csr" -subj "/CN=MyPC"
openssl x509 -req -in "$CertDir\client.csr" -CA "$CertDir\ca.pem" -CAkey "$CertDir\ca.key" `
-CAcreateserial -out "$CertDir\client.pem" -days 365 -sha256
Write-Host "Certificates generated in $CertDir"
# Create Trust Anchor
$TrustAnchorArn = aws rolesanywhere create-trust-anchor `
--region $Region `
--name MyPCCA `
--source "sourceData={x509CertificateData=$(Get-Content -Raw $CertDir\ca.pem)},sourceType=CERTIFICATE_BUNDLE" `
--query 'trustAnchor.trustAnchorArn' --output text
Write-Host "Trust Anchor ARN: $TrustAnchorArn"
# Create IAM Role
$TrustPolicUrl = Convert-ToAwsFileUrl -Path $TrustPolicyFile
aws iam create-role `
--role-name DomainCheckInvokerRole `
--assume-role-policy-document $TrustPolicUrl
Write-Host "IAM Role created: DomainCheckInvokerRole"
# Attach Lambda policy
$LambdaPolicyUrl = Convert-ToAwsFileUrl -Path $LambdaPolicyFile
aws iam put-role-policy `
--role-name DomainCheckInvokerRole `
--policy-name LambdaInvokeDomainCheck `
--policy-document $LambdaPolicyUrl
Write-Host "Policy attached to role: LambdaInvokeDomainCheck"
# Create Profile
$ProfileArn = aws rolesanywhere create-profile `
--region eu-west-1 `
--name DomainCheckProfile `
--role-arns '["arn:aws:iam::458835642486:role/DomainCheckInvokerRole"]' `
--query "profile.profileArn" `
--output text
Write-Host "Profile ARN: $ProfileArn"
# Step 5: Print AWS config block
Write-Host ""
Write-Host "`nPaste the following into your AWS config (~/.aws/config):`n"
Write-Host "[profile rolesanywhere]"
Write-Host "credential_process = `"C:\path\to\aws_signing_helper.exe`" credential-process ^"
Write-Host " --certificate C:\rolesanywhere\client.pem ^"
Write-Host " --private-key C:\rolesanywhere\client.key ^"
Write-Host " --trust-anchor-arn $TrustAnchorArn ^"
Write-Host " --profile-arn $ProfileArn ^"
Write-Host " --role-arn arn:aws:iam::$AccountId:role/$RoleName"
Write-Host "region = $Region"
+12
View File
@@ -0,0 +1,12 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "rolesanywhere.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}