Install
$ agentstack add skill-harperaa-secure-claude-skills-information-leakage Open-source listing, not yet scanned by AgentStack. Follow the source repository for install instructions.
Security review
⚠ Flagged1 finding(s); flagged for manual review. · v0.1.0 How review works →
- • Prompt-injection patterns
- • Secret / credential exfiltration
- • Dangerous shell & filesystem operations
- • Untrusted network calls
- • Known-malicious package signatures
- high Reads credentials/environment and may exfiltrate them.
What it can access
- ● Network access Used
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ● Environment & secrets Used
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
Sensitive Information Exposure in AI-Generated Code
The Pervasiveness of Hardcoded Secrets
A comprehensive analysis by WebProNews found:
> "AI models trained on public repositories frequently suggest hardcoding API keys and credentials, as these patterns appear millions of times in their training data."
The problem is exacerbated by the fact that many developers using vibe coding are non-technical and unaware of the security implications.
1.3.1 Hardcoded Credentials
The Real-World Incident
Research from Analytics India Magazine documented a real-world incident:
> "A developer used Cursor to build a SaaS app and accidentally committed hardcoded AWS credentials. Within days, attackers had discovered the exposed keys and racked up thousands of dollars in charges."
This is not theoretical—it's happening regularly.
AI-Generated Vulnerable Code
# Prompt: "Connect to AWS S3 and upload files"
import boto3
import stripe
import requests
class CloudStorage:
def __init__(self):
# ❌ CRITICAL: Hardcoded AWS credentials
self.aws_key = "AKIAIOSFODNN7EXAMPLE"
self.aws_secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
# ❌ CRITICAL: Hardcoded API keys
self.stripe_key = "sk_live_EXAMPLE_DO_NOT_USE_HARDCODED_KEYS"
self.sendgrid_key = "SG.EXAMPLE_KEY_DO_NOT_HARDCODE"
# ❌ CRITICAL: Database credentials in code
self.db_config = {
'host': 'prod-db.company.com',
'user': 'admin',
'password': 'SuperSecretPass123!',
'database': 'production'
}
def upload_to_s3(self, file_path, bucket_name):
# ❌ VULNERABLE: Using hardcoded credentials
s3 = boto3.client(
's3',
aws_access_key_id=self.aws_key,
aws_secret_access_key=self.aws_secret
)
s3.upload_file(file_path, bucket_name, file_path)
# Prompt: "Send API request with authentication"
def fetch_user_data(user_id):
# ❌ VULNERABLE: API key in URL
response = requests.get(
f"https://api.service.com/users/{user_id}?api_key=abc123def456"
)
return response.json()
Why This Is Critically Dangerous
1. Committed to Version Control:
- Code pushed to GitHub/GitLab
- Secrets now in git history forever
- Even if removed in later commit, still in history
- Public repos = instant compromise
- Private repos = compromised if repo breached
2. Bots Scan for Exposed Secrets:
- Automated bots scan GitHub 24/7
- Find exposed AWS keys within minutes
- Immediately start using them
- Rack up charges before you notice
3. Difficult to Rotate:
- Once exposed, must rotate all keys
- May require updating multiple services
- Downtime during rotation
- Some keys can't be rotated easily
Secure Implementation
import os
import boto3
import stripe
from dotenv import load_dotenv
from aws_secretsmanager import get_secret
import logging
# ✅ SECURE: Load environment variables from .env file (not in version control)
load_dotenv()
class CloudStorageSecure:
def __init__(self):
# ✅ SECURE: Retrieve credentials from environment variables
self.aws_key = os.getenv('AWS_ACCESS_KEY_ID')
self.aws_secret = os.getenv('AWS_SECRET_ACCESS_KEY')
# ✅ SECURE: Use AWS Secrets Manager for production
if os.getenv('ENVIRONMENT') == 'production':
secrets = self._get_secrets_from_aws()
self.stripe_key = secrets['stripe_key']
self.sendgrid_key = secrets['sendgrid_key']
else:
self.stripe_key = os.getenv('STRIPE_KEY')
self.sendgrid_key = os.getenv('SENDGRID_KEY')
# ✅ SECURE: Database connection from environment
self.db_config = {
'host': os.getenv('DB_HOST'),
'user': os.getenv('DB_USER'),
'password': os.getenv('DB_PASSWORD'),
'database': os.getenv('DB_NAME'),
'ssl_ca': os.getenv('DB_SSL_CA'), # SSL for production
'ssl_verify_cert': True
}
# ✅ SECURE: Validate all credentials are present
self._validate_configuration()
def _get_secrets_from_aws(self):
"""Retrieve secrets from AWS Secrets Manager"""
session = boto3.session.Session()
client = session.client(service_name='secretsmanager')
try:
response = client.get_secret_value(SecretId='prod/api-keys')
return json.loads(response['SecretString'])
except Exception as e:
logging.error(f"Failed to retrieve secrets: {e}")
raise
def _validate_configuration(self):
"""Ensure all required configuration is present"""
required_vars = [
'aws_key', 'aws_secret', 'stripe_key',
'sendgrid_key', 'db_config'
]
for var in required_vars:
if not getattr(self, var, None):
raise ValueError(f"Missing required configuration: {var}")
def upload_to_s3(self, file_path, bucket_name):
# ✅ SECURE: Use IAM roles in production instead of keys
if os.getenv('ENVIRONMENT') == 'production':
s3 = boto3.client('s3') # Uses IAM role
else:
s3 = boto3.client(
's3',
aws_access_key_id=self.aws_key,
aws_secret_access_key=self.aws_secret
)
# ✅ SECURE: Add encryption and access logging
s3.upload_file(
file_path,
bucket_name,
file_path,
ExtraArgs={
'ServerSideEncryption': 'AES256',
'Metadata': {
'uploaded_by': os.getenv('APP_NAME', 'unknown'),
'upload_time': str(datetime.utcnow())
}
}
)
def fetch_user_data_secure(user_id):
# ✅ SECURE: Use headers for API authentication
headers = {
'Authorization': f"Bearer {os.getenv('API_TOKEN')}",
'X-API-Key': os.getenv('API_KEY'),
'X-Request-ID': str(uuid.uuid4()) # For tracking
}
# ✅ SECURE: Never put secrets in URLs
response = requests.get(
f"https://api.service.com/users/{user_id}",
headers=headers,
timeout=10 # Always set timeouts
)
# ✅ SECURE: Log requests without exposing secrets
logging.info(f"API request to /users/{user_id} - Status: {response.status_code}")
return response.json()
Why AI Hardcodes Credentials
1. Prevalence in Training Data:
- Millions of code examples on GitHub with hardcoded keys
- Tutorial code uses placeholder keys for simplicity
- AI learns this as "normal" pattern
2. Simplicity:
- Hardcoding is fewer lines of code
- No need to explain environment variables
- "Works" immediately in example
3. Context Blindness:
- AI doesn't distinguish between:
- Example/tutorial code (hardcoded OK)
- Production code (hardcoded NEVER OK)
- Treats all prompts the same way
Where AI Hardcodes Secrets
1. Direct Variable Assignment:
API_KEY = "sk_live_abc123def456"
AWS_SECRET = "wJalrXUtn..."
DATABASE_PASSWORD = "SuperSecret123!"
2. In Configuration Objects:
const config = {
stripeKey: 'sk_live_...',
dbPassword: 'password123'
};
3. In URLs:
fetch(`https://api.example.com/data?key=abc123def456`)
4. In Connection Strings:
conn = mysql.connector.connect(
host='prod.db.com',
user='admin',
password='SuperSecret123!'
)
Attack Timeline
T+0 minutes: Developer commits code with hardcoded AWS keys T+5 minutes: Bots detect exposed keys, begin using T+30 minutes: $500 in unauthorized EC2 instances spun up T+2 hours: Developer notices unusual AWS bill T+4 hours: $10,000 in charges, keys finally rotated T+1 week: Final bill: $50,000+
This is a real timeline from documented incidents.
How to Find Hardcoded Secrets
Scan your code:
# Search for common secret patterns
grep -r "sk_live_" .
grep -r "AKIA" . # AWS access keys
grep -r "api_key.*=" .
grep -r "password.*=" .
grep -r "secret.*=" .
# Use automated tools
npx secretlint "**/*"
truffleHog --regex --entropy=True .
git-secrets --scan
1.3.2 Information Leakage Through Logging
The Problem
According to a report from Aikido Security:
> "Verbose logging in AI-generated code frequently exposes sensitive data, creating audit trails that become goldmines for attackers."
AI-Generated Vulnerable Code
// Prompt: "Add logging to payment processing"
const winston = require('winston');
const logger = winston.createLogger({
level: 'debug',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'app.log' }),
new winston.transports.Console()
]
});
async function processPayment(paymentData) {
// ❌ VULNERABLE: Logging sensitive payment information
logger.info('Processing payment:', {
cardNumber: paymentData.cardNumber,
cvv: paymentData.cvv,
expiryDate: paymentData.expiryDate,
amount: paymentData.amount,
customerName: paymentData.customerName,
billingAddress: paymentData.billingAddress
});
try {
const result = await paymentGateway.charge(paymentData);
// ❌ VULNERABLE: Logging full response including tokens
logger.info('Payment successful:', result);
return result;
} catch (error) {
// ❌ VULNERABLE: Logging full error with stack trace
logger.error('Payment failed:', {
error: error.message,
stack: error.stack,
paymentData: paymentData,
systemInfo: {
nodeVersion: process.version,
platform: process.platform,
env: process.env // This could expose ALL environment variables!
}
});
throw error;
}
}
What's Wrong With This Logging
1. Logging Full Payment Card Data:
cardNumber: paymentData.cardNumber, // Full card number in logs
cvv: paymentData.cvv, // CVV in logs
expiryDate: paymentData.expiryDate // Expiry in logs
Consequences:
- PCI-DSS violation (cannot store CVV ever)
- Log files now contain full card details
- If logs leaked/hacked, cards compromised
- Massive fines under PCI-DSS
2. Logging process.env:
env: process.env // ALL environment variables
Consequences:
- Exposes ALL secrets (AWS keys, DB passwords, API tokens)
- One log file leak = complete compromise
- Environment variables should NEVER be logged
3. Logging Stack Traces:
stack: error.stack
Consequences:
- Reveals file paths, internal structure
- Shows technology stack
- Helps attackers understand system
4. Logging Full API Responses:
logger.info('Payment successful:', result);
Consequences:
- May contain tokens, sensitive user data
- Full response may have internal IDs
- Excessive data retention
Secure Implementation
const winston = require('winston');
const crypto = require('crypto');
// ✅ SECURE: Configure logging with security in mind
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: false }), // Don't log stack traces in production
winston.format.json()
),
defaultMeta: { service: 'payment-service' },
transports: [
new winston.transports.File({
filename: 'error.log',
level: 'error',
maxsize: 5242880, // 5MB
maxFiles: 5
}),
new winston.transports.File({
filename: 'combined.log',
maxsize: 5242880, // 5MB
maxFiles: 5
})
]
});
// ✅ SECURE: Add console logging only in development
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// ✅ SECURE: Utility functions for data sanitization
function maskCardNumber(cardNumber) {
if (!cardNumber) return 'N/A';
const cleaned = cardNumber.replace(/\D/g, '');
return `${cleaned.slice(0, 4)}****${cleaned.slice(-4)}`;
}
function generateTransactionId() {
return crypto.randomBytes(16).toString('hex');
}
function sanitizeError(error) {
return {
code: error.code || 'UNKNOWN',
message: error.message?.replace(/[0-9]{4,}/g, '****') || 'An error occurred',
type: error.constructor.name
};
}
async function processPaymentSecure(paymentData) {
const transactionId = generateTransactionId();
// ✅ SECURE: Log only non-sensitive information
logger.info('Payment initiated', {
transactionId,
amount: paymentData.amount,
currency: paymentData.currency,
cardType: detectCardType(paymentData.cardNumber),
cardLast4: paymentData.cardNumber.slice(-4),
timestamp: new Date().toISOString()
});
try {
const result = await paymentGateway.charge(paymentData);
// ✅ SECURE: Log only transaction metadata
logger.info('Payment processed', {
transactionId,
status: 'success',
processorTransactionId: result.transactionId,
processingTime: result.processingTime
});
// ✅ SECURE: Never return sensitive data in response
return {
success: true,
transactionId,
maskedCard: maskCardNumber(paymentData.cardNumber),
amount: paymentData.amount
};
} catch (error) {
// ✅ SECURE: Log sanitized error information
logger.error('Payment failed', {
transactionId,
errorCode: error.code,
errorType: sanitizeError(error).type,
cardLast4: paymentData.cardNumber.slice(-4),
amount: paymentData.amount
});
// ✅ SECURE: Store detailed error in secure audit log
if (process.env.AUDIT_LOG_ENABLED === 'true') {
await secureAuditLog.write({
transactionId,
error: sanitizeError(error),
timestamp: new Date().toISOString(),
userId: paymentData.userId
});
}
// ✅ SECURE: Return generic error to client
throw new Error('Payment processing failed. Please try again or contact support.');
}
}
// ✅ SECURE: Implement structured audit logging
class SecureAuditLog {
async write(entry) {
const encrypted = this.encrypt(JSON.stringify(entry));
await this.storage.save({
id: crypto.randomUUID(),
data: encrypted,
timestamp: new Date().toISOString(),
checksum: this.generateChecksum(encrypted)
});
}
encrypt(data) {
const algorithm = 'aes-256-gcm';
const key = Buffer.from(process.env.AUDIT_LOG_KEY, 'hex');
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return {
encrypted,
iv: iv.toString('hex'),
authTag: authTag.toString('hex')
};
}
generateChecksum(data) {
return crypto
.createHash('sha256')
.update(JSON.stringify(data))
.digest('hex');
}
}
Why AI Generates Verbose Logging
1. Debugging Habit:
- Training data includes debug logging
- Developers log everything during development
- AI assumes this is good practice
2. "More is Better" Assumption:
- Detailed logs seem helpful
- AI doesn't understand sensitive vs non-sensitive data
- Logs
…
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: harperaa
- Source: harperaa/secure-claude-skills
- License: MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.