Secure Coding Practices
Credential Security Framework
graph TD
A[Secure Coding Practices] --> B[Input Validation]
A --> C[Secure Configuration]
A --> D[Code Review]
A --> E[Static Analysis]
A --> F[Dependency Management]
Preventing Credential Exposure
## Insecure Example
def authenticate(username, password):
## Dangerous: Direct string concatenation
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
## Secure Example
def secure_authenticate(username, password):
## Use parameterized queries
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s",
(username, hash_password(password)))
2. Secure Configuration Management
Environment-based Configuration
## Ubuntu 22.04 - Secure Configuration Example
## Use .env files with restricted permissions
touch .env
chmod 600 .env
## Content of .env file
DB_USERNAME=secure_user
DB_PASSWORD=complex_password_here
API_KEY=encrypted_key
3. Credential Handling Best Practices
Practice |
Description |
Recommendation |
No Hardcoding |
Avoid embedding credentials |
Use environment variables |
Encryption |
Protect sensitive data |
Use strong encryption methods |
Minimal Exposure |
Limit credential visibility |
Use short-lived tokens |
4. Automated Security Scanning
## Install and run security scanning tools
sudo apt-get update
sudo apt-get install -y python3-pip
## Install security scanning tools
pip3 install bandit safety
## Run security scan on project
bandit -r /path/to/your/project
safety check
5. Dependency Security
Managing Third-party Risks
## Check and update dependencies
pip3 install pip-audit
## Audit Python dependencies
pip-audit
## Update vulnerable packages
pip3 list --outdated
pip3 install --upgrade package_name
6. Secure Logging Practices
## Secure Logging Example
import logging
import re
def sanitize_log_message(message):
## Remove sensitive information
return re.sub(r'(password|secret|token)=\S+', r'\1=***', message)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def log_authentication_attempt(username):
## Avoid logging sensitive details
logger.info(f"Authentication attempt for user: {username}")
7. Code Review Checklist
graph LR
A[Code Review] --> B{Credential Checks}
B --> |Pass| C[Approve]
B --> |Fail| D[Reject]
Key Review Points
- No hardcoded credentials
- Proper input validation
- Secure error handling
- Minimal privilege principles
Practical Recommendations
At LabEx, we emphasize:
- Continuous security education
- Regular security audits
- Automated vulnerability detection
- Implementing multi-layered security strategies