Analyseur de Sécurité Environnement
Détectez secrets, mots de passe et API keys dans les fichiers .env avec masquage automatique
What is Environment File Security Analysis?
Environment file security analysis is the process of scanning .env files and environment
variable configurations to detect exposed secrets, misconfigured credentials, and sensitive data that
should never exist in plaintext within a repository. While environment variables are the standard
mechanism for injecting configuration into applications, they frequently become the weakest link in
a project's security posture — storing database passwords, API keys with billing access, OAuth client
secrets, and private cryptographic keys in files that are one misconfigured .gitignore
away from public exposure.
The consequences of credential leakage are severe and immediate. Exposed AWS access keys are exploited within minutes by automated scanners that monitor public repositories. Leaked database connection strings grant direct access to production data. Compromised OAuth tokens enable account takeover across connected services. An environment security analyzer applies pattern-based detection to identify these risks before they reach version control, CI/CD logs, or container images — shifting secret management left into the development workflow where remediation cost is lowest.
Secret Detection Patterns and Techniques
Effective secret detection relies on a combination of regex-based pattern matching, entropy analysis, and structural recognition. Each technique catches a different class of leaked credential:
-
AWS access keys: AWS keys follow a predictable format — access key IDs start with
AKIA(long-term) orASIA(temporary) followed by 16 alphanumeric characters. Secret access keys are 40-character Base64 strings. Pattern:/AKIA[0-9A-Z]{16}/for key IDs and/[A-Za-z0-9/+=]{40}/for secrets paired with an AWS context variable name. -
Database connection strings: Connection URLs contain credentials inline:
postgres://user:password@host:5432/db,mongodb+srv://admin:s3cret@cluster.mongodb.net, ormysql://root:pass@localhost/app. The pattern matches URI schemes followed byuser:password@segments, catching credentials embedded inDATABASE_URL,MONGO_URI, and similar variables. -
OAuth and API tokens: Platform-specific token formats are highly recognizable —
GitHub tokens start with
ghp_,gho_, orghs_; Slack tokens begin withxoxb-orxoxp-; Stripe keys usesk_live_orsk_test_prefixes. These fixed prefixes make regex detection highly reliable with near-zero false positives. -
Private keys and certificates: PEM-encoded private keys are delimited by
-----BEGIN RSA PRIVATE KEY-----or-----BEGIN EC PRIVATE KEY-----markers. Even when stored as single-line values with\nescapes, the BEGIN/END markers remain detectable in environment variable values. - High-entropy strings: When no known pattern matches, Shannon entropy analysis identifies values with randomness levels consistent with cryptographic secrets. A 32+ character string with entropy above 4.5 bits per character is statistically unlikely to be a human-readable configuration value and warrants manual review.
Credential Exposure Risk Vectors
Understanding how secrets leak is essential for building effective prevention strategies. Each exposure vector has distinct characteristics and mitigation requirements:
-
Committed
.envfiles in version control: The most common exposure path. A missing or incorrectly configured.gitignoreentry causes.envto be tracked by Git. Even if removed later, the secrets persist in Git history indefinitely — accessible viagit logor repository clones. Public repositories on GitHub are continuously scanned by automated secret-harvesting bots that exploit credentials within seconds of exposure. -
Secrets baked into Docker images: Multi-stage builds that copy
.envfiles or useENVdirectives embed secrets into image layers. Even if the file is deleted in a subsequent layer, the intermediate layer retains the data. Anyone withdocker historyordiveaccess can extract secrets from published images on Docker Hub or private registries. - CI/CD pipeline log exposure: Build systems that echo environment variables during debugging, log command arguments containing secrets, or print configuration summaries inadvertently expose credentials in build logs. These logs are often retained for weeks and accessible to anyone with repository read access.
-
Client-side bundle inclusion: Frontend build tools that replace
process.env.VARIABLEat compile time can embed server-side secrets into JavaScript bundles served to browsers. Variables without aNEXT_PUBLIC_,VITE_, orREACT_APP_prefix should never be referenced in client-side code, yet misconfigured bundlers sometimes expose them. -
Backup and snapshot leakage: Database backups, VM snapshots, and server images that
include application directories carry
.envfiles. When these backups are stored in less-secured locations (S3 buckets with overly permissive policies, shared NAS drives), secrets become accessible to broader audiences than intended.
Severity Classification of Exposed Secrets
Not all exposed environment variables carry equal risk. A security analyzer classifies findings by potential impact to prioritize remediation efforts:
- Critical severity: Credentials that grant direct access to production data or billing-enabled services. Includes database connection strings with write access, AWS root account keys, Stripe live secret keys, payment processor credentials, and private signing keys used for authentication tokens. Immediate rotation required upon detection.
- High severity: Credentials providing access to sensitive systems but with limited blast radius. Includes API keys for third-party services with rate limits, OAuth client secrets for non-admin scopes, SMTP credentials, and service account tokens with restricted permissions. Rotation recommended within hours.
-
Medium severity: Tokens for development or staging environments, test API keys (e.g.,
Stripe
sk_test_), internal service URLs that reveal infrastructure topology, and webhook signing secrets. While not immediately exploitable in production, they provide reconnaissance value to attackers. - Informational: Non-secret configuration that nonetheless should not be hardcoded — application names, port numbers, feature flags, logging levels, and public-facing URLs. These carry no direct security risk but indicate configuration management patterns that may coexist with more dangerous secrets in the same file.
Mitigation Strategies and Secret Management
Preventing credential exposure requires layered defenses spanning development workflows, infrastructure configuration, and runtime secret injection:
-
Secret managers: Replace plaintext
.envfiles with dedicated secret management services — AWS Secrets Manager, HashiCorp Vault, Google Secret Manager, or Azure Key Vault. These services provide encryption at rest, access auditing, automatic rotation, and fine-grained IAM policies. Applications retrieve secrets at runtime via SDK calls rather than filesystem reads. -
Git pre-commit hooks: Install hooks that scan staged files for secret patterns before
allowing commits. Tools like
git-secrets,detect-secrets, andgitleaksintegrate into the commit workflow and block accidental secret commits at the source. Combine with CI-side scanning for defense in depth. - Environment variable injection: Inject secrets at deployment time through platform mechanisms — Kubernetes Secrets mounted as environment variables, Docker Swarm secrets, AWS ECS task definition secrets from Parameter Store, or Heroku config vars. Secrets never touch the filesystem or source code.
-
Template-based
.env.examplefiles: Commit a.env.examplefile containing variable names with placeholder values (DB_PASSWORD=changeme). This documents required configuration without exposing actual credentials. Developers copy to.envlocally and populate with real values that are never committed. -
Encryption at rest: When
.envfiles must exist on disk (local development), use encrypted environment tools likesops(Mozilla),age, orgit-cryptthat encrypt secret values while keeping variable names readable. Decryption happens at application startup using keys stored in hardware security modules or developer keychains.
Code Examples
Regex-Based Secret Detection Patterns in JavaScript
// Environment variable secret detection patterns
const SECRET_PATTERNS = [
{
name: 'AWS Access Key ID',
pattern: /(?:^|\s)(?:AWS_ACCESS_KEY_ID|aws_access_key_id)\s*=\s*(AKIA[0-9A-Z]{16})/,
severity: 'critical',
description: 'Long-term AWS access key — grants API access to AWS services'
},
{
name: 'AWS Secret Access Key',
pattern: /(?:^|\s)(?:AWS_SECRET_ACCESS_KEY|aws_secret_access_key)\s*=\s*([A-Za-z0-9/+=]{40})/,
severity: 'critical',
description: 'AWS secret key paired with access key ID'
},
{
name: 'Database Connection String',
pattern: /(?:DATABASE_URL|MONGO_URI|DB_URL|REDIS_URL)\s*=\s*\w+:\/\/[^:]+:[^@]+@/,
severity: 'critical',
description: 'Connection string with inline credentials'
},
{
name: 'GitHub Personal Access Token',
pattern: /(?:GITHUB_TOKEN|GH_TOKEN)\s*=\s*(ghp_[A-Za-z0-9]{36})/,
severity: 'high',
description: 'GitHub PAT with repository or organization access'
},
{
name: 'Stripe Secret Key',
pattern: /(?:STRIPE_SECRET_KEY|STRIPE_KEY)\s*=\s*(sk_live_[A-Za-z0-9]{24,})/,
severity: 'critical',
description: 'Stripe live secret key — grants billing and payment access'
},
{
name: 'Slack Bot Token',
pattern: /(?:SLACK_TOKEN|SLACK_BOT_TOKEN)\s*=\s*(xoxb-[0-9]+-[A-Za-z0-9]+)/,
severity: 'high',
description: 'Slack bot token with workspace messaging access'
},
{
name: 'Private Key (PEM)',
pattern: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/,
severity: 'critical',
description: 'PEM-encoded private key — cryptographic signing material'
},
{
name: 'JWT Secret',
pattern: /(?:JWT_SECRET|TOKEN_SECRET|AUTH_SECRET)\s*=\s*(.{8,})/,
severity: 'high',
description: 'JWT signing secret — compromise enables token forgery'
}
];
// Analyze a .env file content for exposed secrets
function analyzeEnvSecurity(envContent) {
const lines = envContent.split('\n');
const findings = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (!line || line.startsWith('#')) continue;
for (const rule of SECRET_PATTERNS) {
if (rule.pattern.test(line)) {
const [key] = line.split('=');
findings.push({
line: i + 1,
variable: key.trim(),
rule: rule.name,
severity: rule.severity,
description: rule.description
});
break; // One finding per line
}
}
}
// Calculate risk score
const weights = { critical: 30, high: 20, medium: 10, informational: 2 };
const totalRisk = findings.reduce((sum, f) => sum + (weights[f.severity] || 5), 0);
const score = Math.max(0, 100 - totalRisk);
return { score, findings, totalVariables: lines.filter(l => l.includes('=')).length };
}
// Example usage
const envFile = `
DATABASE_URL=postgres://admin:s3cretP4ss@prod-db.example.com:5432/myapp
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
STRIPE_SECRET_KEY=sk_live_4eC39HqLyjWDarjtT1zdp7dc
APP_NAME=my-application
PORT=3000
`.trim();
const result = analyzeEnvSecurity(envFile);
// → { score: 10, findings: [4 critical secrets detected], totalVariables: 6 }Standards & Specifications
- CWE-798 — Use of Hard-coded Credentials — MITRE weakness classification covering secrets stored in source code and configuration files
- OWASP Secrets Management Cheat Sheet — Comprehensive guide covering secret lifecycle management, storage, rotation, and access control best practices
- CWE-522 — Insufficiently Protected Credentials — covers scenarios where credentials are transmitted or stored without adequate protection