moved docs
Switching to using vendored shell framework moved SafeDownload to vendored shell framework repo
This commit is contained in:
279
ProjectDocs/CODE-REVIEW-FINDINGS.md
Normal file
279
ProjectDocs/CODE-REVIEW-FINDINGS.md
Normal file
@@ -0,0 +1,279 @@
|
||||
# TSYS FetchApply Code Review Findings
|
||||
|
||||
**Review Date:** July 14, 2025
|
||||
**Reviewer:** Claude (Anthropic)
|
||||
**Repository:** TSYS Group Infrastructure Provisioning Scripts
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The repository shows good architectural structure with centralized framework components, but has several performance, security, and maintainability issues that require attention. The codebase is functional but needs optimization for production reliability.
|
||||
|
||||
## Critical Issues (High Priority)
|
||||
|
||||
### 1. Package Installation Performance ⚠️
|
||||
**Location:** `ProjectCode/SetupNewSystem.sh:27` and `Lines 117-183`
|
||||
**Issue:** Multiple separate package installation commands causing performance bottlenecks
|
||||
```bash
|
||||
# Current inefficient pattern
|
||||
apt-get -y install git sudo dmidecode curl
|
||||
# ... later in script ...
|
||||
DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes install virt-what auditd ...
|
||||
```
|
||||
**Impact:** Significantly slower deployment, multiple package cache updates
|
||||
**Fix:** Combine all package installations into single command
|
||||
|
||||
### 2. Network Operations Lack Error Handling 🔴
|
||||
**Location:** `ProjectCode/SetupNewSystem.sh:61-63`, multiple modules
|
||||
**Issue:** curl commands without timeout or error handling
|
||||
```bash
|
||||
# Vulnerable pattern
|
||||
curl --silent ${DL_ROOT}/path/file >/etc/config
|
||||
```
|
||||
**Impact:** Deployment failures in poor network conditions
|
||||
**Fix:** Add timeout, error handling, and retry logic
|
||||
|
||||
### 3. Unquoted Variable Expansions 🔴
|
||||
**Location:** Multiple files, including `ProjectCode/SetupNewSystem.sh:244`
|
||||
**Issue:** Variables used without proper quoting creating security risks
|
||||
```bash
|
||||
# Risky pattern
|
||||
chsh -s $(which zsh) root
|
||||
```
|
||||
**Impact:** Potential command injection, script failures
|
||||
**Fix:** Quote all variable expansions consistently
|
||||
|
||||
## Security Concerns
|
||||
|
||||
### 4. No Download Integrity Verification 🔴
|
||||
**Issue:** All remote downloads lack checksum verification
|
||||
**Impact:** Supply chain attack vulnerability
|
||||
**Recommendation:** Implement SHA256 checksum validation
|
||||
|
||||
### 5. Excessive Root Privilege Usage ⚠️
|
||||
**Issue:** All operations run as root without privilege separation
|
||||
**Impact:** Unnecessary security exposure
|
||||
**Recommendation:** Delegate non-privileged operations when possible
|
||||
|
||||
## Performance Optimization Opportunities
|
||||
|
||||
### 6. Individual File Downloads 🟡
|
||||
**Location:** `ProjectCode/Modules/Security/secharden-scap-stig.sh:66-77`
|
||||
**Issue:** 12+ individual curl commands for config files
|
||||
```bash
|
||||
curl --silent ${DL_ROOT}/path1 > /etc/file1
|
||||
curl --silent ${DL_ROOT}/path2 > /etc/file2
|
||||
# ... repeated 12+ times
|
||||
```
|
||||
**Impact:** Network overhead, slower deployment
|
||||
**Fix:** Batch download operations
|
||||
|
||||
### 7. Missing Connection Pooling ⚠️
|
||||
**Issue:** No connection reuse for multiple downloads from same host
|
||||
**Impact:** Unnecessary connection overhead
|
||||
**Fix:** Use curl with connection reuse or wget with keep-alive
|
||||
|
||||
## Code Quality Issues
|
||||
|
||||
### 8. Inconsistent Framework Usage 🟡
|
||||
**Issue:** Not all modules use established error handling framework
|
||||
**Impact:** Inconsistent error reporting, debugging difficulties
|
||||
**Fix:** Standardize framework usage across all modules
|
||||
|
||||
### 9. Incomplete Function Implementations 🟡
|
||||
**Location:** `Framework-Includes/LookupKv.sh`
|
||||
**Issue:** Stubbed functions with no implementation
|
||||
**Impact:** Technical debt, confusion
|
||||
**Fix:** Implement or remove unused functions
|
||||
|
||||
### 10. Missing Input Validation 🟡
|
||||
**Location:** `Project-Includes/pi-detect.sh`
|
||||
**Issue:** Functions lack proper input validation and quoting
|
||||
**Impact:** Potential script failures
|
||||
**Fix:** Add comprehensive input validation
|
||||
|
||||
## Recommended Immediate Actions
|
||||
|
||||
### Phase 1: Critical Fixes (Week 1)
|
||||
1. **Fix variable quoting** throughout codebase
|
||||
2. **Add error handling** to all network operations
|
||||
3. **Combine package installations** for performance
|
||||
4. **Implement download integrity verification**
|
||||
|
||||
### Phase 2: Performance Optimization (Week 2)
|
||||
1. **Batch file download operations**
|
||||
2. **Add connection timeouts and retries**
|
||||
3. **Implement bulk configuration deployment**
|
||||
4. **Optimize service restart procedures**
|
||||
|
||||
### Phase 3: Code Quality (Week 3-4)
|
||||
1. **Standardize framework usage**
|
||||
2. **Add comprehensive input validation**
|
||||
3. **Implement proper logging with timestamps**
|
||||
4. **Remove or complete stubbed functions**
|
||||
|
||||
## Specific Code Improvements
|
||||
|
||||
### Enhanced Error Handling Pattern
|
||||
```bash
|
||||
function safe_download() {
|
||||
local url="$1"
|
||||
local dest="$2"
|
||||
local max_attempts=3
|
||||
local attempt=1
|
||||
|
||||
while [[ $attempt -le $max_attempts ]]; do
|
||||
if curl --silent --connect-timeout 30 --max-time 60 --fail "$url" > "$dest"; then
|
||||
print_success "Downloaded: $(basename "$dest")"
|
||||
return 0
|
||||
else
|
||||
print_warning "Download attempt $attempt failed: $url"
|
||||
((attempt++))
|
||||
sleep 5
|
||||
fi
|
||||
done
|
||||
|
||||
print_error "Failed to download after $max_attempts attempts: $url"
|
||||
return 1
|
||||
}
|
||||
```
|
||||
|
||||
### Bulk Package Installation Pattern
|
||||
```bash
|
||||
function install_all_packages() {
|
||||
print_info "Installing all required packages..."
|
||||
|
||||
local packages=(
|
||||
# Core system packages
|
||||
git sudo dmidecode curl wget
|
||||
|
||||
# Security packages
|
||||
auditd fail2ban aide
|
||||
|
||||
# Monitoring packages
|
||||
snmpd snmp-mibs-downloader
|
||||
|
||||
# Additional packages
|
||||
virt-what net-tools htop
|
||||
)
|
||||
|
||||
if DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install "${packages[@]}"; then
|
||||
print_success "All packages installed successfully"
|
||||
else
|
||||
print_error "Package installation failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
### Batch Configuration Download
|
||||
```bash
|
||||
function download_configurations() {
|
||||
print_info "Downloading configuration files..."
|
||||
|
||||
local -A configs=(
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/ZSH/tsys-zshrc"]="/etc/zshrc"
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/SMTP/aliases"]="/etc/aliases"
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/Syslog/rsyslog.conf"]="/etc/rsyslog.conf"
|
||||
)
|
||||
|
||||
for url in "${!configs[@]}"; do
|
||||
local dest="${configs[$url]}"
|
||||
if ! safe_download "$url" "$dest"; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
|
||||
print_success "All configurations downloaded"
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Recommendations
|
||||
|
||||
### Add Performance Tests
|
||||
```bash
|
||||
function test_package_installation_performance() {
|
||||
local start_time=$(date +%s)
|
||||
install_all_packages
|
||||
local end_time=$(date +%s)
|
||||
local duration=$((end_time - start_time))
|
||||
|
||||
echo "✅ Package installation completed in ${duration}s"
|
||||
|
||||
if [[ $duration -gt 300 ]]; then
|
||||
echo "⚠️ Installation took longer than expected (>5 minutes)"
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
### Add Network Resilience Tests
|
||||
```bash
|
||||
function test_network_error_handling() {
|
||||
# Test with invalid URL
|
||||
if safe_download "https://invalid.example.com/file" "/tmp/test"; then
|
||||
echo "❌ Error handling test failed - should have failed"
|
||||
return 1
|
||||
else
|
||||
echo "✅ Error handling test passed"
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
## Monitoring and Metrics
|
||||
|
||||
### Deployment Performance Metrics
|
||||
- **Package installation time:** Should complete in <5 minutes
|
||||
- **Configuration download time:** Should complete in <2 minutes
|
||||
- **Service restart time:** Should complete in <30 seconds
|
||||
- **Total deployment time:** Should complete in <15 minutes
|
||||
|
||||
### Error Rate Monitoring
|
||||
- **Network operation failures:** Should be <1%
|
||||
- **Package installation failures:** Should be <0.1%
|
||||
- **Service restart failures:** Should be <0.1%
|
||||
|
||||
## Compliance Assessment
|
||||
|
||||
### Development Guidelines Adherence
|
||||
✅ **Good:** Single package commands in newer modules
|
||||
✅ **Good:** Framework integration patterns
|
||||
✅ **Good:** Function documentation in recent code
|
||||
|
||||
❌ **Needs Work:** Variable quoting consistency
|
||||
❌ **Needs Work:** Error handling standardization
|
||||
❌ **Needs Work:** Input validation coverage
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
**Current Risk Level:** Medium
|
||||
|
||||
**Key Risks:**
|
||||
1. **Deployment failures** due to network issues
|
||||
2. **Security vulnerabilities** from unvalidated downloads
|
||||
3. **Performance issues** in production deployments
|
||||
4. **Maintenance challenges** from code inconsistencies
|
||||
|
||||
**Mitigation Priority:**
|
||||
1. Network error handling (High)
|
||||
2. Download integrity verification (High)
|
||||
3. Performance optimization (Medium)
|
||||
4. Code standardization (Medium)
|
||||
|
||||
## Conclusion
|
||||
|
||||
The TSYS FetchApply repository has a solid foundation but requires systematic improvements to meet production reliability standards. The recommended fixes will significantly enhance:
|
||||
|
||||
- **Deployment reliability** through better error handling
|
||||
- **Security posture** through integrity verification
|
||||
- **Performance** through optimized operations
|
||||
- **Maintainability** through code standardization
|
||||
|
||||
Implementing these improvements in the suggested phases will create a robust, production-ready infrastructure provisioning system.
|
||||
|
||||
---
|
||||
|
||||
**Next Steps:**
|
||||
1. Review and prioritize findings with development team
|
||||
2. Create implementation plan for critical fixes
|
||||
3. Establish testing procedures for improvements
|
||||
4. Set up monitoring for deployment metrics
|
93
ProjectDocs/Claude-Review.md
Normal file
93
ProjectDocs/Claude-Review.md
Normal file
@@ -0,0 +1,93 @@
|
||||
# Claude Code Review - TSYS FetchApply Infrastructure
|
||||
|
||||
**Review Date:** July 14, 2025 (Updated)
|
||||
**Reviewed by:** Claude (Anthropic)
|
||||
**Repository:** TSYS Group Infrastructure Provisioning Scripts
|
||||
**Previous Review:** July 12, 2025
|
||||
|
||||
## Project Overview
|
||||
|
||||
This repository contains infrastructure-as-code for provisioning Linux servers in the TSYS Group environment. The codebase includes 32 shell scripts (~2,800 lines) organized into a modular framework for system hardening, security configuration, and operational tooling deployment.
|
||||
|
||||
## Strengths ✅
|
||||
|
||||
### Security Hardening
|
||||
- **SSH Security:** Comprehensive SSH hardening with key-only authentication, disabled password login, and secure cipher configurations
|
||||
- **Security Agents:** Automated deployment of Wazuh SIEM agents, audit tools, and SCAP-STIG compliance checking
|
||||
- **File Permissions:** Proper restrictive permissions (400 for SSH keys, 644 for configs)
|
||||
- **Network Security:** Firewall configuration, network discovery tools (LLDP), and monitoring agents
|
||||
|
||||
### Code Quality
|
||||
- **Error Handling:** Robust bash strict mode implementation (`set -euo pipefail`) with custom error trapping and line number reporting
|
||||
- **Modular Design:** Well-organized structure separating framework components, configuration files, and functional modules
|
||||
- **Environment Awareness:** Intelligent detection of physical vs virtual hosts, distribution-specific logic, and hardware-specific optimizations
|
||||
- **Logging:** Centralized logging with timestamp-based log files and colored output for debugging
|
||||
|
||||
### Operational Excellence
|
||||
- **Package Management:** Automated repository setup for security tools (Lynis, Webmin, Tailscale, Wazuh)
|
||||
- **System Tuning:** Performance optimizations for physical hosts, virtualization-aware configurations
|
||||
- **Monitoring Integration:** LibreNMS agents, SNMP configuration, and system metrics collection
|
||||
|
||||
## Security Concerns ⚠️
|
||||
|
||||
### Critical Issues
|
||||
1. **~~Insecure Deployment Method~~** ✅ **RESOLVED:** Now uses `git clone` + local script execution instead of `curl | bash`
|
||||
2. **No Integrity Verification:** Downloaded scripts lack checksum validation or cryptographic signatures
|
||||
3. **~~HTTP Downloads~~** ✅ **RESOLVED:** All HTTP URLs converted to HTTPS (Dell OMSA, Proxmox, Apache sources)
|
||||
|
||||
### Moderate Risks
|
||||
4. **Exposed SSH Keys:** Public SSH keys committed directly to repository without rotation mechanism
|
||||
5. **Hard-coded Credentials:** Server hostnames and domain names embedded in scripts
|
||||
6. **Missing Secrets Management:** No current implementation of Bitwarden/Vault integration (noted in TODO comments)
|
||||
|
||||
## Improvement Recommendations 🔧
|
||||
|
||||
### High Priority (Security Critical)
|
||||
1. **~~Secure Deployment Pipeline~~** ✅ **RESOLVED:** Now uses git clone-based deployment
|
||||
2. **~~HTTPS Enforcement~~** ✅ **RESOLVED:** All HTTP downloads converted to HTTPS
|
||||
3. **Script Integrity:** Implement SHA256 checksum verification for all downloaded components
|
||||
4. **Secrets Management:** Deploy proper secrets handling for SSH keys and sensitive configurations
|
||||
|
||||
### Medium Priority (Operational)
|
||||
5. **Testing Framework:** Add integration tests for provisioning workflows
|
||||
6. **Documentation Enhancement:** Expand security considerations and deployment procedures
|
||||
7. **Configuration Validation:** Add pre-deployment validation of system requirements
|
||||
8. **Rollback Capability:** Implement configuration backup and rollback mechanisms
|
||||
|
||||
### Low Priority (Quality of Life)
|
||||
9. **Error Recovery:** Enhanced error recovery and partial deployment resumption
|
||||
10. **Monitoring Integration:** Centralized logging and deployment status reporting
|
||||
11. **User Interface:** Consider web-based deployment dashboard for non-technical users
|
||||
|
||||
## Risk Assessment 📊
|
||||
|
||||
**Overall Risk Level:** Low-Medium ⬇️ (Reduced from Medium-Low)
|
||||
|
||||
The repository contains well-architected defensive security tools with strong error handling and modular design. **Major security improvement:** The insecure `curl | bash` deployment method has been replaced with git-based deployment. Remaining concerns are primarily around hardening the provisioning scripts themselves rather than the deployment method.
|
||||
|
||||
**Recommendation:** Continue addressing remaining security issues (HTTPS enforcement, secrets management) but the critical deployment risk has been mitigated. The codebase is much safer for production use.
|
||||
|
||||
## Update Summary (July 14, 2025)
|
||||
|
||||
**✅ Resolved Issues:**
|
||||
- Insecure deployment method replaced with git clone approach
|
||||
- README.md updated with project management and community links
|
||||
- Deployment security risk significantly reduced
|
||||
- All HTTP URLs converted to HTTPS (Dell OMSA, Proxmox, Apache sources)
|
||||
|
||||
**🔄 Remaining Priorities:**
|
||||
1. ~~HTTPS enforcement for internal downloads~~ ✅ **RESOLVED:** All HTTP URLs converted to HTTPS
|
||||
2. Secrets management implementation
|
||||
3. Script integrity verification
|
||||
4. SSH key rotation from repository
|
||||
|
||||
## Files Reviewed
|
||||
|
||||
- 32 shell scripts across Framework-Includes, Project-Includes, and ProjectCode directories
|
||||
- Configuration files for SSH, SNMP, logging, and system services
|
||||
- Security modules for hardening, authentication, and monitoring
|
||||
- Documentation and framework configuration files
|
||||
|
||||
## Next Steps
|
||||
|
||||
See `charles-todo.md` and `claude-todo.md` for detailed action items prioritized for human operators and AI assistants respectively.
|
336
ProjectDocs/DEPLOYMENT.md
Normal file
336
ProjectDocs/DEPLOYMENT.md
Normal file
@@ -0,0 +1,336 @@
|
||||
# TSYS FetchApply Deployment Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This guide provides comprehensive instructions for deploying the TSYS FetchApply infrastructure provisioning system on Linux servers.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### System Requirements
|
||||
- **Operating System:** Ubuntu 18.04+ or Debian 10+ (recommended)
|
||||
- **RAM:** Minimum 2GB, recommended 4GB
|
||||
- **Disk Space:** Minimum 10GB free space
|
||||
- **Network:** Internet connectivity for package downloads
|
||||
- **Privileges:** Root or sudo access required
|
||||
|
||||
### Required Tools
|
||||
- `git` - Version control system
|
||||
- `curl` - HTTP client for downloads
|
||||
- `wget` - Alternative download tool
|
||||
- `systemctl` - System service management
|
||||
- `apt-get` - Package management (Debian/Ubuntu)
|
||||
|
||||
### Network Requirements
|
||||
- **HTTPS access** to:
|
||||
- `https://archive.ubuntu.com` (Ubuntu packages)
|
||||
- `https://linux.dell.com` (Dell hardware support)
|
||||
- `https://download.proxmox.com` (Proxmox packages)
|
||||
- `https://github.com` (Git repositories)
|
||||
|
||||
## Pre-Deployment Validation
|
||||
|
||||
### 1. System Compatibility Check
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone [repository-url]
|
||||
cd FetchApply
|
||||
|
||||
# Run system validation
|
||||
./Project-Tests/validation/system-requirements.sh
|
||||
```
|
||||
|
||||
### 2. Network Connectivity Test
|
||||
```bash
|
||||
# Test network connectivity
|
||||
curl -I https://archive.ubuntu.com
|
||||
curl -I https://linux.dell.com
|
||||
curl -I https://download.proxmox.com
|
||||
```
|
||||
|
||||
### 3. Permission Verification
|
||||
```bash
|
||||
# Verify write permissions
|
||||
test -w /etc && echo "✅ /etc writable" || echo "❌ /etc not writable"
|
||||
test -w /usr/local/bin && echo "✅ /usr/local/bin writable" || echo "❌ /usr/local/bin not writable"
|
||||
```
|
||||
|
||||
## Deployment Methods
|
||||
|
||||
### Method 1: Standard Deployment (Recommended)
|
||||
```bash
|
||||
# 1. Clone repository
|
||||
git clone [repository-url]
|
||||
cd FetchApply
|
||||
|
||||
# 2. Run pre-deployment tests
|
||||
./Project-Tests/run-tests.sh validation
|
||||
|
||||
# 3. Execute deployment
|
||||
cd ProjectCode
|
||||
sudo bash SetupNewSystem.sh
|
||||
```
|
||||
|
||||
### Method 2: Dry Run Mode
|
||||
```bash
|
||||
# 1. Clone repository
|
||||
git clone [repository-url]
|
||||
cd FetchApply
|
||||
|
||||
# 2. Review configuration
|
||||
cat ProjectCode/SetupNewSystem.sh
|
||||
|
||||
# 3. Execute with manual review
|
||||
cd ProjectCode
|
||||
sudo bash -x SetupNewSystem.sh # Debug mode
|
||||
```
|
||||
|
||||
## Deployment Process
|
||||
|
||||
### Phase 1: Framework Initialization
|
||||
1. **Environment Setup**
|
||||
- Load framework variables
|
||||
- Source framework includes
|
||||
- Initialize logging system
|
||||
|
||||
2. **System Detection**
|
||||
- Detect physical vs virtual hardware
|
||||
- Identify operating system
|
||||
- Check for existing users
|
||||
|
||||
### Phase 2: Base System Configuration
|
||||
1. **Package Installation**
|
||||
- Update package repositories
|
||||
- Install essential packages
|
||||
- Configure package sources
|
||||
|
||||
2. **User Management**
|
||||
- Create required user accounts
|
||||
- Configure SSH access
|
||||
- Set up sudo permissions
|
||||
|
||||
### Phase 3: Security Hardening
|
||||
1. **SSH Configuration**
|
||||
- Deploy hardened SSH configuration
|
||||
- Install SSH keys
|
||||
- Disable password authentication
|
||||
|
||||
2. **System Hardening**
|
||||
- Configure firewall rules
|
||||
- Enable audit logging
|
||||
- Install security tools
|
||||
|
||||
### Phase 4: Monitoring and Management
|
||||
1. **Monitoring Agents**
|
||||
- Deploy LibreNMS agents
|
||||
- Configure SNMP
|
||||
- Set up system monitoring
|
||||
|
||||
2. **Management Tools**
|
||||
- Install Cockpit dashboard
|
||||
- Configure remote access
|
||||
- Set up maintenance scripts
|
||||
|
||||
## Post-Deployment Verification
|
||||
|
||||
### 1. Security Validation
|
||||
```bash
|
||||
# Run security tests
|
||||
./Project-Tests/run-tests.sh security
|
||||
|
||||
# Verify SSH configuration
|
||||
ssh -T [server-ip] # Should work with key authentication
|
||||
```
|
||||
|
||||
### 2. Service Status Check
|
||||
```bash
|
||||
# Check critical services
|
||||
sudo systemctl status ssh
|
||||
sudo systemctl status auditd
|
||||
sudo systemctl status snmpd
|
||||
```
|
||||
|
||||
### 3. Network Connectivity
|
||||
```bash
|
||||
# Test internal services
|
||||
curl -k https://localhost:9090 # Cockpit
|
||||
snmpwalk -v2c -c public localhost system
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### 1. Permission Denied Errors
|
||||
```bash
|
||||
# Solution: Run with sudo
|
||||
sudo bash SetupNewSystem.sh
|
||||
```
|
||||
|
||||
#### 2. Network Connectivity Issues
|
||||
```bash
|
||||
# Check DNS resolution
|
||||
nslookup archive.ubuntu.com
|
||||
|
||||
# Test direct IP access
|
||||
curl -I 91.189.91.26 # Ubuntu archive IP
|
||||
```
|
||||
|
||||
#### 3. Package Installation Failures
|
||||
```bash
|
||||
# Update package cache
|
||||
sudo apt-get update
|
||||
|
||||
# Fix broken packages
|
||||
sudo apt-get -f install
|
||||
```
|
||||
|
||||
#### 4. SSH Key Issues
|
||||
```bash
|
||||
# Verify key permissions
|
||||
ls -la ~/.ssh/
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
chmod 644 ~/.ssh/id_rsa.pub
|
||||
```
|
||||
|
||||
### Debug Mode
|
||||
```bash
|
||||
# Enable debug logging
|
||||
export DEBUG=1
|
||||
bash -x SetupNewSystem.sh
|
||||
```
|
||||
|
||||
### Log Analysis
|
||||
```bash
|
||||
# Check deployment logs
|
||||
tail -f /var/log/fetchapply/deployment.log
|
||||
|
||||
# Review system logs
|
||||
journalctl -u ssh
|
||||
journalctl -u auditd
|
||||
```
|
||||
|
||||
## Environment-Specific Configurations
|
||||
|
||||
### Physical Dell Servers
|
||||
- **OMSA Installation:** Dell OpenManage Server Administrator
|
||||
- **Hardware Monitoring:** iDRAC configuration
|
||||
- **Performance Tuning:** CPU and memory optimizations
|
||||
|
||||
### Virtual Machines
|
||||
- **Guest Additions:** VMware tools or VirtualBox additions
|
||||
- **Resource Limits:** Memory and CPU constraints
|
||||
- **Network Configuration:** Bridge vs NAT settings
|
||||
|
||||
### Development Environments
|
||||
- **SSH Configuration:** Less restrictive settings
|
||||
- **Development Tools:** Additional packages for development
|
||||
- **Testing Access:** Enhanced logging and debugging
|
||||
|
||||
## Maintenance and Updates
|
||||
|
||||
### Regular Maintenance
|
||||
```bash
|
||||
# Update system packages
|
||||
sudo apt-get update && sudo apt-get upgrade
|
||||
|
||||
# Update monitoring scripts
|
||||
cd /usr/local/bin
|
||||
sudo wget https://[repository]/scripts/up2date.sh
|
||||
sudo chmod +x up2date.sh
|
||||
```
|
||||
|
||||
### Security Updates
|
||||
```bash
|
||||
# Check for security updates
|
||||
sudo apt-get update
|
||||
sudo apt list --upgradable | grep -i security
|
||||
|
||||
# Apply security patches
|
||||
sudo apt-get upgrade
|
||||
```
|
||||
|
||||
### Configuration Updates
|
||||
```bash
|
||||
# Update FetchApply
|
||||
cd FetchApply
|
||||
git pull origin main
|
||||
|
||||
# Re-run specific modules
|
||||
cd ProjectCode/Modules/Security
|
||||
sudo bash secharden-ssh.sh
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Pre-Deployment
|
||||
- Always test in non-production environment first
|
||||
- Review all scripts before execution
|
||||
- Validate network connectivity
|
||||
- Ensure proper backup procedures
|
||||
|
||||
### 2. During Deployment
|
||||
- Monitor deployment progress
|
||||
- Check for errors and warnings
|
||||
- Document any customizations
|
||||
- Validate each phase completion
|
||||
|
||||
### 3. Post-Deployment
|
||||
- Run full security test suite
|
||||
- Verify all services are running
|
||||
- Test remote access
|
||||
- Document deployment specifics
|
||||
|
||||
### 4. Ongoing Operations
|
||||
- Regular security updates
|
||||
- Monitor system performance
|
||||
- Review audit logs
|
||||
- Maintain deployment documentation
|
||||
|
||||
## Support and Resources
|
||||
|
||||
### Documentation
|
||||
- **README.md:** Basic usage instructions
|
||||
- **SECURITY.md:** Security architecture and guidelines
|
||||
- **Project-Tests/README.md:** Testing framework documentation
|
||||
|
||||
### Community Support
|
||||
- **Issues:** https://projects.knownelement.com/project/reachableceo-vptechnicaloperations/timeline
|
||||
- **Discussion:** https://community.turnsys.com/c/chieftechnologyandproductofficer/26
|
||||
|
||||
### Professional Support
|
||||
- **Technical Support:** [Contact information to be added]
|
||||
- **Consulting Services:** [Contact information to be added]
|
||||
|
||||
## Deployment Checklist
|
||||
|
||||
### Pre-Deployment
|
||||
- [ ] System requirements validated
|
||||
- [ ] Network connectivity tested
|
||||
- [ ] Backup procedures in place
|
||||
- [ ] Security review completed
|
||||
|
||||
### Deployment
|
||||
- [ ] Repository cloned successfully
|
||||
- [ ] Pre-deployment tests passed
|
||||
- [ ] Deployment executed without errors
|
||||
- [ ] Post-deployment verification completed
|
||||
|
||||
### Post-Deployment
|
||||
- [ ] Security tests passed
|
||||
- [ ] All services running
|
||||
- [ ] Remote access verified
|
||||
- [ ] Documentation updated
|
||||
|
||||
### Maintenance
|
||||
- [ ] Update schedule established
|
||||
- [ ] Monitoring configured
|
||||
- [ ] Backup procedures tested
|
||||
- [ ] Incident response plan activated
|
||||
|
||||
## Version History
|
||||
|
||||
- **v1.0:** Initial deployment framework
|
||||
- **v1.1:** Added security hardening and secrets management
|
||||
- **v1.2:** Enhanced testing framework and documentation
|
||||
|
||||
Last updated: July 14, 2025
|
406
ProjectDocs/DEVELOPMENT-GUIDELINES.md
Normal file
406
ProjectDocs/DEVELOPMENT-GUIDELINES.md
Normal file
@@ -0,0 +1,406 @@
|
||||
# TSYS FetchApply Development Guidelines
|
||||
|
||||
## Overview
|
||||
|
||||
This document contains development standards and best practices for the TSYS FetchApply infrastructure provisioning system.
|
||||
|
||||
## Package Management Best Practices
|
||||
|
||||
### Combine apt-get Install Commands
|
||||
|
||||
**Rule:** Always combine multiple package installations into a single `apt-get install` command for performance.
|
||||
|
||||
**Rationale:** Single command execution is significantly faster than multiple separate commands due to:
|
||||
- Reduced package cache processing
|
||||
- Single dependency resolution
|
||||
- Fewer network connections
|
||||
- Optimized package download ordering
|
||||
|
||||
#### ✅ Correct Implementation
|
||||
```bash
|
||||
# Install all packages in one command
|
||||
apt-get install -y package1 package2 package3 package4
|
||||
|
||||
# Real example from 2FA script
|
||||
apt-get install -y libpam-google-authenticator qrencode
|
||||
```
|
||||
|
||||
#### ❌ Incorrect Implementation
|
||||
```bash
|
||||
# Don't use separate commands for each package
|
||||
apt-get install -y package1
|
||||
apt-get install -y package2
|
||||
apt-get install -y package3
|
||||
```
|
||||
|
||||
#### Complex Package Installation Pattern
|
||||
```bash
|
||||
function install_security_packages() {
|
||||
print_info "Installing security packages..."
|
||||
|
||||
# Update package cache once
|
||||
apt-get update
|
||||
|
||||
# Install all packages in single command
|
||||
apt-get install -y \
|
||||
auditd \
|
||||
fail2ban \
|
||||
libpam-google-authenticator \
|
||||
lynis \
|
||||
rkhunter \
|
||||
aide \
|
||||
chkrootkit \
|
||||
clamav \
|
||||
clamav-daemon
|
||||
|
||||
print_success "Security packages installed successfully"
|
||||
}
|
||||
```
|
||||
|
||||
## Script Development Standards
|
||||
|
||||
### Error Handling
|
||||
- Always use `set -euo pipefail` at script start
|
||||
- Implement proper error trapping
|
||||
- Use framework error handling functions
|
||||
- Return appropriate exit codes
|
||||
|
||||
### Function Structure
|
||||
```bash
|
||||
function function_name() {
|
||||
print_info "Description of what function does..."
|
||||
|
||||
# Local variables
|
||||
local var1="value"
|
||||
local var2="value"
|
||||
|
||||
# Function logic
|
||||
if [[ condition ]]; then
|
||||
print_success "Success message"
|
||||
return 0
|
||||
else
|
||||
print_error "Error message"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
### Framework Integration
|
||||
- Source framework includes at script start
|
||||
- Use framework logging and pretty print functions
|
||||
- Follow existing patterns for consistency
|
||||
- Include proper PROJECT_ROOT path resolution
|
||||
|
||||
```bash
|
||||
# Standard framework sourcing pattern
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../.."
|
||||
source "$PROJECT_ROOT/Framework-Includes/PrettyPrint.sh"
|
||||
source "$PROJECT_ROOT/Framework-Includes/Logging.sh"
|
||||
source "$PROJECT_ROOT/Framework-Includes/ErrorHandling.sh"
|
||||
```
|
||||
|
||||
## Code Quality Standards
|
||||
|
||||
### ShellCheck Compliance
|
||||
- All scripts must pass shellcheck validation
|
||||
- Address shellcheck warnings appropriately
|
||||
- Use proper quoting for variables
|
||||
- Handle edge cases and error conditions
|
||||
|
||||
### Variable Naming
|
||||
- Use UPPERCASE for global constants
|
||||
- Use lowercase for local variables
|
||||
- Use descriptive names
|
||||
- Quote all variable expansions
|
||||
|
||||
```bash
|
||||
# Global constants
|
||||
declare -g BACKUP_DIR="/root/backup"
|
||||
declare -g CONFIG_FILE="/etc/ssh/sshd_config"
|
||||
|
||||
# Local variables
|
||||
local user_name="localuser"
|
||||
local temp_file="/tmp/config.tmp"
|
||||
|
||||
# Proper quoting
|
||||
if [[ -f "$CONFIG_FILE" ]]; then
|
||||
cp "$CONFIG_FILE" "$BACKUP_DIR/"
|
||||
fi
|
||||
```
|
||||
|
||||
### Function Documentation
|
||||
- Include purpose description
|
||||
- Document parameters if any
|
||||
- Document return values
|
||||
- Include usage examples for complex functions
|
||||
|
||||
```bash
|
||||
# Configure SSH hardening settings
|
||||
# Parameters: none
|
||||
# Returns: 0 on success, 1 on failure
|
||||
# Usage: configure_ssh_hardening
|
||||
function configure_ssh_hardening() {
|
||||
print_info "Configuring SSH hardening..."
|
||||
# Implementation
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Test Coverage
|
||||
- Every new module must include corresponding tests
|
||||
- Test both success and failure scenarios
|
||||
- Validate configurations after changes
|
||||
- Include integration tests for complex workflows
|
||||
|
||||
### Test Categories
|
||||
1. **Unit Tests:** Individual function validation
|
||||
2. **Integration Tests:** Module interaction testing
|
||||
3. **Security Tests:** Security configuration validation
|
||||
4. **Validation Tests:** System requirement checking
|
||||
|
||||
### Test Implementation Pattern
|
||||
```bash
|
||||
function test_function_name() {
|
||||
echo "🔍 Testing specific functionality..."
|
||||
|
||||
local failed=0
|
||||
|
||||
# Test implementation
|
||||
if [[ condition ]]; then
|
||||
echo "✅ Test passed"
|
||||
else
|
||||
echo "❌ Test failed"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
```
|
||||
|
||||
## Security Standards
|
||||
|
||||
### Configuration Backup
|
||||
- Always backup configurations before modification
|
||||
- Use timestamped backup directories
|
||||
- Provide restore instructions
|
||||
- Test backup/restore procedures
|
||||
|
||||
### Service Management
|
||||
- Test configurations before restarting services
|
||||
- Provide rollback procedures
|
||||
- Validate service status after changes
|
||||
- Include service dependency handling
|
||||
|
||||
### User Safety
|
||||
- Use `nullok` for gradual 2FA rollout
|
||||
- Provide clear setup instructions
|
||||
- Include emergency access procedures
|
||||
- Test all access methods before enforcement
|
||||
|
||||
## Documentation Standards
|
||||
|
||||
### Script Headers
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
# TSYS Module Name - Brief Description
|
||||
# Longer description of what this script does
|
||||
# Author: TSYS Development Team
|
||||
# Version: 1.0
|
||||
# Last Updated: YYYY-MM-DD
|
||||
|
||||
set -euo pipefail
|
||||
```
|
||||
|
||||
### Inline Documentation
|
||||
- Comment complex logic
|
||||
- Explain non-obvious decisions
|
||||
- Document external dependencies
|
||||
- Include troubleshooting notes
|
||||
|
||||
### User Documentation
|
||||
- Create comprehensive guides for complex features
|
||||
- Include step-by-step procedures
|
||||
- Provide troubleshooting sections
|
||||
- Include examples and use cases
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Package Management
|
||||
- Single apt-get commands (as noted above)
|
||||
- Cache package lists appropriately
|
||||
- Use specific package versions when stability required
|
||||
- Clean up package cache when appropriate
|
||||
|
||||
### Network Operations
|
||||
- Use connection timeouts for external requests
|
||||
- Implement retry logic with backoff
|
||||
- Cache downloaded resources when possible
|
||||
- Validate download integrity
|
||||
|
||||
### File Operations
|
||||
- Use efficient file processing tools
|
||||
- Minimize file system operations
|
||||
- Use appropriate file permissions
|
||||
- Clean up temporary files
|
||||
|
||||
## Version Control Practices
|
||||
|
||||
### Commit Messages
|
||||
- Use descriptive commit messages
|
||||
- Include scope of changes
|
||||
- Reference related issues/requirements
|
||||
- Follow established commit message format
|
||||
|
||||
### Branch Management
|
||||
- Test changes in feature branches
|
||||
- Use pull requests for review
|
||||
- Maintain clean commit history
|
||||
- Tag releases appropriately
|
||||
|
||||
### Code Review Requirements
|
||||
- All changes require review
|
||||
- Security changes require security team review
|
||||
- Test coverage must be maintained
|
||||
- Documentation must be updated
|
||||
|
||||
## Deployment Practices
|
||||
|
||||
### Pre-Deployment
|
||||
- Run full test suite
|
||||
- Validate in test environment
|
||||
- Review security implications
|
||||
- Update documentation
|
||||
|
||||
### Deployment Process
|
||||
- Use configuration validation
|
||||
- Implement gradual rollout when possible
|
||||
- Monitor for issues during deployment
|
||||
- Have rollback procedures ready
|
||||
|
||||
### Post-Deployment
|
||||
- Validate deployment success
|
||||
- Monitor system performance
|
||||
- Update operational documentation
|
||||
- Gather feedback for improvements
|
||||
|
||||
## Example Implementation
|
||||
|
||||
### Complete Module Template
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
# TSYS Security Module - Template
|
||||
# Template for creating new security modules
|
||||
# Author: TSYS Development Team
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Source framework functions
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../.."
|
||||
source "$PROJECT_ROOT/Framework-Includes/PrettyPrint.sh"
|
||||
source "$PROJECT_ROOT/Framework-Includes/Logging.sh"
|
||||
source "$PROJECT_ROOT/Framework-Includes/ErrorHandling.sh"
|
||||
|
||||
# Module configuration
|
||||
BACKUP_DIR="/root/backup/module-$(date +%Y%m%d-%H%M%S)"
|
||||
CONFIG_FILE="/etc/example.conf"
|
||||
|
||||
# Create backup directory
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
print_header "TSYS Module Template"
|
||||
|
||||
function backup_configs() {
|
||||
print_info "Creating configuration backup..."
|
||||
|
||||
if [[ -f "$CONFIG_FILE" ]]; then
|
||||
cp "$CONFIG_FILE" "$BACKUP_DIR/"
|
||||
print_success "Configuration backed up"
|
||||
fi
|
||||
}
|
||||
|
||||
function install_packages() {
|
||||
print_info "Installing required packages..."
|
||||
|
||||
# Update package cache
|
||||
apt-get update
|
||||
|
||||
# Install all packages in single command
|
||||
apt-get install -y package1 package2 package3
|
||||
|
||||
print_success "Packages installed successfully"
|
||||
}
|
||||
|
||||
function configure_module() {
|
||||
print_info "Configuring module..."
|
||||
|
||||
# Configuration logic here
|
||||
|
||||
print_success "Module configured successfully"
|
||||
}
|
||||
|
||||
function validate_configuration() {
|
||||
print_info "Validating configuration..."
|
||||
|
||||
local failed=0
|
||||
|
||||
# Validation logic here
|
||||
|
||||
if [[ $failed -eq 0 ]]; then
|
||||
print_success "Configuration validation passed"
|
||||
return 0
|
||||
else
|
||||
print_error "Configuration validation failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function main() {
|
||||
# Check if running as root
|
||||
if [[ $EUID -ne 0 ]]; then
|
||||
print_error "This script must be run as root"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Execute module steps
|
||||
backup_configs
|
||||
install_packages
|
||||
configure_module
|
||||
validate_configuration
|
||||
|
||||
print_success "Module setup completed successfully!"
|
||||
}
|
||||
|
||||
# Run main function
|
||||
main "$@"
|
||||
```
|
||||
|
||||
## Continuous Improvement
|
||||
|
||||
### Regular Reviews
|
||||
- Review guidelines quarterly
|
||||
- Update based on lessons learned
|
||||
- Incorporate new best practices
|
||||
- Gather team feedback
|
||||
|
||||
### Tool Updates
|
||||
- Keep development tools current
|
||||
- Adopt new security practices
|
||||
- Update testing frameworks
|
||||
- Improve automation
|
||||
|
||||
### Knowledge Sharing
|
||||
- Document lessons learned
|
||||
- Share best practices
|
||||
- Provide training materials
|
||||
- Maintain knowledge base
|
||||
|
||||
---
|
||||
|
||||
**Last Updated:** July 14, 2025
|
||||
**Version:** 1.0
|
||||
**Author:** TSYS Development Team
|
||||
|
||||
**Note:** These guidelines are living documents and should be updated as the project evolves and new best practices are identified.
|
534
ProjectDocs/REFACTORING-EXAMPLES.md
Normal file
534
ProjectDocs/REFACTORING-EXAMPLES.md
Normal file
@@ -0,0 +1,534 @@
|
||||
# Code Refactoring Examples
|
||||
|
||||
This document provides specific examples of how to apply the code review findings to improve performance, security, and reliability.
|
||||
|
||||
## Package Installation Optimization
|
||||
|
||||
### Before (Current - Multiple Commands)
|
||||
```bash
|
||||
# Line 27 in SetupNewSystem.sh
|
||||
apt-get -y install git sudo dmidecode curl
|
||||
|
||||
# Lines 117-183 (later in script)
|
||||
DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install \
|
||||
virt-what \
|
||||
auditd \
|
||||
aide \
|
||||
# ... many more packages
|
||||
```
|
||||
|
||||
### After (Optimized - Single Command)
|
||||
```bash
|
||||
function install_all_packages() {
|
||||
print_info "Installing all required packages..."
|
||||
|
||||
# All packages in logical groups for better readability
|
||||
local packages=(
|
||||
# Core system tools
|
||||
git sudo dmidecode curl wget net-tools htop
|
||||
|
||||
# Security and auditing
|
||||
auditd aide fail2ban lynis rkhunter
|
||||
|
||||
# Monitoring and SNMP
|
||||
snmpd snmp-mibs-downloader libsnmp-dev
|
||||
|
||||
# Virtualization detection
|
||||
virt-what
|
||||
|
||||
# System utilities
|
||||
rsyslog logrotate ntp ntpdate
|
||||
cockpit cockpit-ws cockpit-system
|
||||
|
||||
# Development and debugging
|
||||
build-essential dkms
|
||||
|
||||
# Network services
|
||||
openssh-server ufw
|
||||
)
|
||||
|
||||
# Single package installation command with retry logic
|
||||
local max_attempts=3
|
||||
local attempt=1
|
||||
|
||||
while [[ $attempt -le $max_attempts ]]; do
|
||||
if DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install "${packages[@]}"; then
|
||||
print_success "All packages installed successfully"
|
||||
return 0
|
||||
else
|
||||
print_warning "Package installation attempt $attempt failed"
|
||||
if [[ $attempt -lt $max_attempts ]]; then
|
||||
print_info "Retrying in 10 seconds..."
|
||||
sleep 10
|
||||
apt-get update # Refresh package cache before retry
|
||||
fi
|
||||
((attempt++))
|
||||
fi
|
||||
done
|
||||
|
||||
print_error "Package installation failed after $max_attempts attempts"
|
||||
return 1
|
||||
}
|
||||
```
|
||||
|
||||
## Safe Download Implementation
|
||||
|
||||
### Before (Current - Unsafe Downloads)
|
||||
```bash
|
||||
# Lines 61-63 in SetupNewSystem.sh
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ZSH/tsys-zshrc >/etc/zshrc
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/SMTP/aliases >/etc/aliases
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/Syslog/rsyslog.conf >/etc/rsyslog.conf
|
||||
```
|
||||
|
||||
### After (Safe Downloads with Error Handling)
|
||||
```bash
|
||||
function download_system_configs() {
|
||||
print_info "Downloading system configuration files..."
|
||||
|
||||
# Source the safe download framework
|
||||
source "$PROJECT_ROOT/Framework-Includes/SafeDownload.sh"
|
||||
|
||||
# Define configuration downloads with checksums (optional)
|
||||
declare -A config_downloads=(
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/ZSH/tsys-zshrc"]="/etc/zshrc"
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/SMTP/aliases"]="/etc/aliases"
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/Syslog/rsyslog.conf"]="/etc/rsyslog.conf"
|
||||
["${DL_ROOT}/ProjectCode/ConfigFiles/SSH/Configs/tsys-sshd-config"]="/etc/ssh/sshd_config.tsys"
|
||||
)
|
||||
|
||||
# Validate all URLs are accessible before starting
|
||||
local urls=()
|
||||
for url in "${!config_downloads[@]}"; do
|
||||
urls+=("$url")
|
||||
done
|
||||
|
||||
if ! validate_required_urls "${urls[@]}"; then
|
||||
print_error "Some configuration URLs are not accessible"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Perform batch download with backup
|
||||
local failed_downloads=0
|
||||
for url in "${!config_downloads[@]}"; do
|
||||
local dest="${config_downloads[$url]}"
|
||||
if ! safe_config_download "$url" "$dest"; then
|
||||
((failed_downloads++))
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $failed_downloads -eq 0 ]]; then
|
||||
print_success "All configuration files downloaded successfully"
|
||||
return 0
|
||||
else
|
||||
print_error "$failed_downloads configuration downloads failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
## Variable Quoting Fixes
|
||||
|
||||
### Before (Unsafe Variable Usage)
|
||||
```bash
|
||||
# Line 244 in SetupNewSystem.sh
|
||||
chsh -s $(which zsh) root
|
||||
|
||||
# Multiple instances throughout codebase
|
||||
if [ -f $CONFIG_FILE ]; then
|
||||
cp $CONFIG_FILE $BACKUP_DIR
|
||||
fi
|
||||
```
|
||||
|
||||
### After (Proper Variable Quoting)
|
||||
```bash
|
||||
# Safe variable usage with proper quoting
|
||||
chsh -s "$(which zsh)" root
|
||||
|
||||
# Consistent quoting pattern
|
||||
if [[ -f "$CONFIG_FILE" ]]; then
|
||||
cp "$CONFIG_FILE" "$BACKUP_DIR/"
|
||||
fi
|
||||
|
||||
# Function parameter handling
|
||||
function configure_service() {
|
||||
local service_name="$1"
|
||||
local config_file="$2"
|
||||
|
||||
if [[ -z "$service_name" || -z "$config_file" ]]; then
|
||||
print_error "configure_service: service name and config file required"
|
||||
return 1
|
||||
fi
|
||||
|
||||
print_info "Configuring service: $service_name"
|
||||
# Safe operations with quoted variables
|
||||
}
|
||||
```
|
||||
|
||||
## Service Management with Error Handling
|
||||
|
||||
### Before (Basic Service Operations)
|
||||
```bash
|
||||
# Current pattern in various modules
|
||||
systemctl restart snmpd
|
||||
systemctl enable snmpd
|
||||
```
|
||||
|
||||
### After (Robust Service Management)
|
||||
```bash
|
||||
function safe_service_restart() {
|
||||
local service="$1"
|
||||
local config_test_cmd="${2:-}"
|
||||
|
||||
if [[ -z "$service" ]]; then
|
||||
print_error "safe_service_restart: service name required"
|
||||
return 1
|
||||
fi
|
||||
|
||||
print_info "Managing service: $service"
|
||||
|
||||
# Test configuration if test command provided
|
||||
if [[ -n "$config_test_cmd" ]]; then
|
||||
print_info "Testing $service configuration..."
|
||||
if ! eval "$config_test_cmd"; then
|
||||
print_error "$service configuration test failed"
|
||||
return 1
|
||||
fi
|
||||
print_success "$service configuration test passed"
|
||||
fi
|
||||
|
||||
# Check if service exists
|
||||
if ! systemctl list-unit-files "$service.service" >/dev/null 2>&1; then
|
||||
print_error "Service $service does not exist"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Stop service if running
|
||||
if systemctl is-active "$service" >/dev/null 2>&1; then
|
||||
print_info "Stopping $service..."
|
||||
if ! systemctl stop "$service"; then
|
||||
print_error "Failed to stop $service"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Start and enable service
|
||||
print_info "Starting and enabling $service..."
|
||||
if systemctl start "$service" && systemctl enable "$service"; then
|
||||
print_success "$service started and enabled successfully"
|
||||
|
||||
# Verify service is running
|
||||
sleep 2
|
||||
if systemctl is-active "$service" >/dev/null 2>&1; then
|
||||
print_success "$service is running properly"
|
||||
return 0
|
||||
else
|
||||
print_error "$service failed to start properly"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
print_error "Failed to start or enable $service"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Usage examples
|
||||
safe_service_restart "sshd" "sshd -t"
|
||||
safe_service_restart "snmpd"
|
||||
safe_service_restart "rsyslog"
|
||||
```
|
||||
|
||||
## Batch Configuration Deployment
|
||||
|
||||
### Before (Individual File Operations)
|
||||
```bash
|
||||
# Lines 66-77 in secharden-scap-stig.sh
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/usb_storage.conf > /etc/modprobe.d/usb_storage.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/dccp.conf > /etc/modprobe.d/dccp.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/rds.conf > /etc/modprobe.d/rds.conf
|
||||
# ... 12 more individual downloads
|
||||
```
|
||||
|
||||
### After (Batch Operations with Error Handling)
|
||||
```bash
|
||||
function deploy_modprobe_configs() {
|
||||
print_info "Deploying modprobe security configurations..."
|
||||
|
||||
source "$PROJECT_ROOT/Framework-Includes/SafeDownload.sh"
|
||||
|
||||
local modprobe_configs=(
|
||||
"usb_storage" "dccp" "rds" "sctp" "tipc"
|
||||
"cramfs" "freevxfs" "hfs" "hfsplus"
|
||||
"jffs2" "squashfs" "udf"
|
||||
)
|
||||
|
||||
# Create download map
|
||||
declare -A config_downloads=()
|
||||
for config in "${modprobe_configs[@]}"; do
|
||||
local url="${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/${config}.conf"
|
||||
local dest="/etc/modprobe.d/${config}.conf"
|
||||
config_downloads["$url"]="$dest"
|
||||
done
|
||||
|
||||
# Validate URLs first
|
||||
local urls=()
|
||||
for url in "${!config_downloads[@]}"; do
|
||||
urls+=("$url")
|
||||
done
|
||||
|
||||
if ! validate_required_urls "${urls[@]}"; then
|
||||
print_error "Some modprobe configuration URLs are not accessible"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Perform batch download
|
||||
if batch_download config_downloads; then
|
||||
print_success "All modprobe configurations deployed"
|
||||
|
||||
# Update initramfs to apply changes
|
||||
if update-initramfs -u; then
|
||||
print_success "Initramfs updated with new module configurations"
|
||||
else
|
||||
print_warning "Failed to update initramfs - reboot may be required"
|
||||
fi
|
||||
|
||||
return 0
|
||||
else
|
||||
print_error "Failed to deploy some modprobe configurations"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
## Input Validation and Error Handling
|
||||
|
||||
### Before (Minimal Validation)
|
||||
```bash
|
||||
# pi-detect.sh current implementation
|
||||
function pi-detect() {
|
||||
print_info Now running "$FUNCNAME"....
|
||||
if [ -f /sys/firmware/devicetree/base/model ] ; then
|
||||
export IS_RASPI="1"
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
### After (Comprehensive Validation)
|
||||
```bash
|
||||
function pi-detect() {
|
||||
print_info "Now running $FUNCNAME..."
|
||||
|
||||
# Initialize variables with default values
|
||||
export IS_RASPI="0"
|
||||
export PI_MODEL=""
|
||||
export PI_REVISION=""
|
||||
|
||||
# Check for Raspberry Pi detection file
|
||||
local device_tree_model="/sys/firmware/devicetree/base/model"
|
||||
local cpuinfo_file="/proc/cpuinfo"
|
||||
|
||||
if [[ -f "$device_tree_model" ]]; then
|
||||
# Try device tree method first (most reliable)
|
||||
local model_info
|
||||
model_info=$(tr -d '\0' < "$device_tree_model" 2>/dev/null)
|
||||
|
||||
if [[ "$model_info" =~ [Rr]aspberry.*[Pp]i ]]; then
|
||||
export IS_RASPI="1"
|
||||
export PI_MODEL="$model_info"
|
||||
print_success "Raspberry Pi detected via device tree: $PI_MODEL"
|
||||
fi
|
||||
elif [[ -f "$cpuinfo_file" ]]; then
|
||||
# Fallback to cpuinfo method
|
||||
if grep -qi "raspberry" "$cpuinfo_file"; then
|
||||
export IS_RASPI="1"
|
||||
PI_MODEL=$(grep "^Model" "$cpuinfo_file" | cut -d: -f2 | sed 's/^[[:space:]]*//' 2>/dev/null || echo "Unknown Pi Model")
|
||||
PI_REVISION=$(grep "^Revision" "$cpuinfo_file" | cut -d: -f2 | sed 's/^[[:space:]]*//' 2>/dev/null || echo "Unknown")
|
||||
export PI_MODEL
|
||||
export PI_REVISION
|
||||
print_success "Raspberry Pi detected via cpuinfo: $PI_MODEL (Rev: $PI_REVISION)"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "$IS_RASPI" == "1" ]]; then
|
||||
print_info "Raspberry Pi specific optimizations will be applied"
|
||||
else
|
||||
print_info "Standard x86/x64 system detected"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
```
|
||||
|
||||
## Function Framework Integration
|
||||
|
||||
### Before (Inconsistent Framework Usage)
|
||||
```bash
|
||||
# Mixed patterns throughout codebase
|
||||
function some_function() {
|
||||
echo "Doing something..."
|
||||
command_that_might_fail
|
||||
echo "Done"
|
||||
}
|
||||
```
|
||||
|
||||
### After (Standardized Framework Integration)
|
||||
```bash
|
||||
function some_function() {
|
||||
print_info "Now running $FUNCNAME..."
|
||||
|
||||
# Local variables
|
||||
local config_file="/etc/example.conf"
|
||||
local backup_dir="/root/backup"
|
||||
local failed=0
|
||||
|
||||
# Validate prerequisites
|
||||
if [[ ! -d "$backup_dir" ]]; then
|
||||
if ! mkdir -p "$backup_dir"; then
|
||||
print_error "Failed to create backup directory: $backup_dir"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Backup existing configuration
|
||||
if [[ -f "$config_file" ]]; then
|
||||
if cp "$config_file" "$backup_dir/$(basename "$config_file").bak.$(date +%Y%m%d-%H%M%S)"; then
|
||||
print_info "Backed up existing configuration"
|
||||
else
|
||||
print_error "Failed to backup existing configuration"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Perform main operation with error handling
|
||||
if command_that_might_fail; then
|
||||
print_success "Operation completed successfully"
|
||||
else
|
||||
print_error "Operation failed"
|
||||
return 1
|
||||
fi
|
||||
|
||||
print_success "Completed $FUNCNAME"
|
||||
return 0
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Monitoring Integration
|
||||
|
||||
### Enhanced Deployment with Metrics
|
||||
```bash
|
||||
function deploy_with_metrics() {
|
||||
local start_time end_time duration
|
||||
local operation_name="$1"
|
||||
shift
|
||||
local operation_function="$1"
|
||||
shift
|
||||
|
||||
print_info "Starting $operation_name..."
|
||||
start_time=$(date +%s)
|
||||
|
||||
# Execute the operation
|
||||
if "$operation_function" "$@"; then
|
||||
end_time=$(date +%s)
|
||||
duration=$((end_time - start_time))
|
||||
|
||||
print_success "$operation_name completed in ${duration}s"
|
||||
|
||||
# Log performance metrics
|
||||
echo "$(date '+%Y-%m-%d %H:%M:%S') - $operation_name: ${duration}s" >> /var/log/fetchapply-performance.log
|
||||
|
||||
# Alert if operation took too long
|
||||
case "$operation_name" in
|
||||
"Package Installation")
|
||||
if [[ $duration -gt 300 ]]; then
|
||||
print_warning "Package installation took longer than expected (${duration}s > 300s)"
|
||||
fi
|
||||
;;
|
||||
"Configuration Download")
|
||||
if [[ $duration -gt 120 ]]; then
|
||||
print_warning "Configuration download took longer than expected (${duration}s > 120s)"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
return 0
|
||||
else
|
||||
end_time=$(date +%s)
|
||||
duration=$((end_time - start_time))
|
||||
|
||||
print_error "$operation_name failed after ${duration}s"
|
||||
echo "$(date '+%Y-%m-%d %H:%M:%S') - $operation_name: FAILED after ${duration}s" >> /var/log/fetchapply-performance.log
|
||||
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Usage example
|
||||
deploy_with_metrics "Package Installation" install_all_packages
|
||||
deploy_with_metrics "Configuration Download" download_system_configs
|
||||
deploy_with_metrics "SSH Hardening" configure_ssh_hardening
|
||||
```
|
||||
|
||||
## Testing Integration
|
||||
|
||||
### Comprehensive Validation Function
|
||||
```bash
|
||||
function validate_deployment() {
|
||||
print_header "Deployment Validation"
|
||||
|
||||
local validation_failures=0
|
||||
|
||||
# Test package installation
|
||||
local required_packages=("git" "curl" "wget" "snmpd" "auditd" "fail2ban")
|
||||
for package in "${required_packages[@]}"; do
|
||||
if dpkg -l | grep -q "^ii.*$package"; then
|
||||
print_success "Package installed: $package"
|
||||
else
|
||||
print_error "Package missing: $package"
|
||||
((validation_failures++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Test service status
|
||||
local required_services=("sshd" "snmpd" "auditd" "rsyslog")
|
||||
for service in "${required_services[@]}"; do
|
||||
if systemctl is-active "$service" >/dev/null 2>&1; then
|
||||
print_success "Service running: $service"
|
||||
else
|
||||
print_error "Service not running: $service"
|
||||
((validation_failures++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Test configuration files
|
||||
local required_configs=("/etc/ssh/sshd_config" "/etc/snmp/snmpd.conf" "/etc/rsyslog.conf")
|
||||
for config in "${required_configs[@]}"; do
|
||||
if [[ -f "$config" && -s "$config" ]]; then
|
||||
print_success "Configuration exists: $(basename "$config")"
|
||||
else
|
||||
print_error "Configuration missing or empty: $(basename "$config")"
|
||||
((validation_failures++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Run security tests
|
||||
if command -v lynis >/dev/null 2>&1; then
|
||||
print_info "Running basic security audit..."
|
||||
if lynis audit system --quick --quiet; then
|
||||
print_success "Security audit completed"
|
||||
else
|
||||
print_warning "Security audit found issues"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Summary
|
||||
if [[ $validation_failures -eq 0 ]]; then
|
||||
print_success "All deployment validation checks passed"
|
||||
return 0
|
||||
else
|
||||
print_error "$validation_failures deployment validation checks failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
||||
These refactoring examples demonstrate how to apply the code review findings to create more robust, performant, and maintainable infrastructure provisioning scripts.
|
190
ProjectDocs/SECURITY.md
Normal file
190
ProjectDocs/SECURITY.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# TSYS FetchApply Security Documentation
|
||||
|
||||
## Security Architecture
|
||||
|
||||
The TSYS FetchApply infrastructure provisioning system is designed with security-first principles, implementing multiple layers of protection for server deployment and management.
|
||||
|
||||
## Current Security Features
|
||||
|
||||
### 1. Secure Deployment Method ✅
|
||||
- **Git-based deployment:** Uses `git clone` instead of `curl | bash`
|
||||
- **Local execution:** Scripts run locally after inspection
|
||||
- **Version control:** Full audit trail of changes
|
||||
- **Code review:** Changes require explicit approval
|
||||
|
||||
### 2. HTTPS Enforcement ✅
|
||||
- **All downloads use HTTPS:** Eliminates man-in-the-middle attacks
|
||||
- **SSL certificate validation:** Automatic certificate checking
|
||||
- **Secure repositories:** Ubuntu archive, Dell, Proxmox all use HTTPS
|
||||
- **No HTTP fallbacks:** No insecure download methods
|
||||
|
||||
### 3. SSH Hardening
|
||||
- **Key-only authentication:** Password login disabled
|
||||
- **Secure ciphers:** Modern encryption algorithms only
|
||||
- **Fail2ban protection:** Automated intrusion prevention
|
||||
- **Custom SSH configuration:** Hardened sshd_config
|
||||
|
||||
### 4. System Security
|
||||
- **Firewall configuration:** Automated iptables rules
|
||||
- **Audit logging:** auditd with custom rules
|
||||
- **SIEM integration:** Wazuh agent deployment
|
||||
- **Compliance scanning:** SCAP-STIG automated checks
|
||||
|
||||
### 5. Error Handling
|
||||
- **Bash strict mode:** `set -euo pipefail` prevents errors
|
||||
- **Centralized logging:** All operations logged with timestamps
|
||||
- **Graceful failures:** Proper cleanup on errors
|
||||
- **Line-level debugging:** Error reporting with line numbers
|
||||
|
||||
## Security Testing
|
||||
|
||||
### Automated Security Validation
|
||||
```bash
|
||||
# Run security test suite
|
||||
./Project-Tests/run-tests.sh security
|
||||
|
||||
# Specific security tests
|
||||
./Project-Tests/security/https-enforcement.sh
|
||||
```
|
||||
|
||||
### Security Test Categories
|
||||
1. **HTTPS Enforcement:** Validates all URLs use HTTPS
|
||||
2. **Deployment Security:** Checks for secure deployment methods
|
||||
3. **SSL Certificate Validation:** Tests certificate authenticity
|
||||
4. **Permission Validation:** Verifies proper file permissions
|
||||
|
||||
## Threat Model
|
||||
|
||||
### Mitigated Threats
|
||||
- **Supply Chain Attacks:** Git-based deployment with review
|
||||
- **Man-in-the-Middle:** HTTPS-only downloads
|
||||
- **Privilege Escalation:** Proper permission models
|
||||
- **Unauthorized Access:** SSH hardening and key management
|
||||
|
||||
### Remaining Risks
|
||||
- **Secrets in Repository:** SSH keys stored in git (planned for removal)
|
||||
- **No Integrity Verification:** Downloads lack checksum validation
|
||||
- **No Backup/Recovery:** No rollback capability implemented
|
||||
|
||||
## Security Recommendations
|
||||
|
||||
### High Priority
|
||||
1. **Implement Secrets Management**
|
||||
- Remove SSH keys from repository
|
||||
- Use Bitwarden/Vault for secret storage
|
||||
- Implement key rotation procedures
|
||||
|
||||
2. **Add Download Integrity Verification**
|
||||
- SHA256 checksum validation for all downloads
|
||||
- GPG signature verification where available
|
||||
- Fail-safe on integrity check failures
|
||||
|
||||
3. **Enhance Audit Logging**
|
||||
- Centralized log collection
|
||||
- Real-time security monitoring
|
||||
- Automated threat detection
|
||||
|
||||
### Medium Priority
|
||||
1. **Configuration Backup**
|
||||
- System state snapshots before changes
|
||||
- Rollback capability for failed deployments
|
||||
- Configuration drift detection
|
||||
|
||||
2. **Network Security**
|
||||
- VPN-based deployment (where applicable)
|
||||
- Network segmentation for management
|
||||
- Encrypted communication channels
|
||||
|
||||
## Compliance
|
||||
|
||||
### Security Standards
|
||||
- **CIS Benchmarks:** Automated compliance checking
|
||||
- **STIG Guidelines:** SCAP-based validation
|
||||
- **Industry Best Practices:** Following NIST cybersecurity framework
|
||||
|
||||
### Audit Requirements
|
||||
- **Change Tracking:** All modifications logged
|
||||
- **Access Control:** Permission-based system access
|
||||
- **Vulnerability Management:** Regular security assessments
|
||||
|
||||
## Incident Response
|
||||
|
||||
### Security Event Handling
|
||||
1. **Detection:** Automated monitoring and alerting
|
||||
2. **Containment:** Immediate isolation procedures
|
||||
3. **Investigation:** Log analysis and forensics
|
||||
4. **Recovery:** System restoration procedures
|
||||
5. **Lessons Learned:** Process improvement
|
||||
|
||||
### Contact Information
|
||||
- **Security Team:** [To be defined]
|
||||
- **Incident Response:** [To be defined]
|
||||
- **Escalation Path:** [To be defined]
|
||||
|
||||
## Security Development Lifecycle
|
||||
|
||||
### Code Review Process
|
||||
1. **Static Analysis:** Automated security scanning
|
||||
2. **Peer Review:** Manual code inspection
|
||||
3. **Security Testing:** Automated security test suite
|
||||
4. **Approval:** Security team sign-off
|
||||
|
||||
### Deployment Security
|
||||
1. **Pre-deployment Validation:** Security test execution
|
||||
2. **Secure Deployment:** Authorized personnel only
|
||||
3. **Post-deployment Verification:** Security configuration validation
|
||||
4. **Monitoring:** Continuous security monitoring
|
||||
|
||||
## Security Tools and Integrations
|
||||
|
||||
### Current Tools
|
||||
- **Wazuh:** SIEM and security monitoring
|
||||
- **Lynis:** Security auditing
|
||||
- **auditd:** System call auditing
|
||||
- **Fail2ban:** Intrusion prevention
|
||||
|
||||
### Planned Integrations
|
||||
- **Vault/Bitwarden:** Secrets management
|
||||
- **OSSEC:** Host-based intrusion detection
|
||||
- **Nessus/OpenVAS:** Vulnerability scanning
|
||||
- **ELK Stack:** Log aggregation and analysis
|
||||
|
||||
## Vulnerability Management
|
||||
|
||||
### Vulnerability Scanning
|
||||
- **Regular scans:** Monthly vulnerability assessments
|
||||
- **Automated patching:** Security update automation
|
||||
- **Exception handling:** Risk-based patch management
|
||||
- **Reporting:** Executive security dashboards
|
||||
|
||||
### Disclosure Process
|
||||
1. **Internal Discovery:** Report to security team
|
||||
2. **Assessment:** Risk and impact evaluation
|
||||
3. **Remediation:** Patch development and testing
|
||||
4. **Deployment:** Coordinated security updates
|
||||
5. **Verification:** Post-patch validation
|
||||
|
||||
## Security Metrics
|
||||
|
||||
### Key Performance Indicators
|
||||
- **Deployment Success Rate:** Percentage of successful secure deployments
|
||||
- **Vulnerability Response Time:** Time to patch critical vulnerabilities
|
||||
- **Security Test Coverage:** Percentage of code covered by security tests
|
||||
- **Incident Response Time:** Time to detect and respond to security events
|
||||
|
||||
### Monitoring and Reporting
|
||||
- **Real-time Dashboards:** Security status monitoring
|
||||
- **Executive Reports:** Monthly security summaries
|
||||
- **Compliance Reports:** Quarterly compliance assessments
|
||||
- **Trend Analysis:** Security posture improvement tracking
|
||||
|
||||
## Contact and Support
|
||||
|
||||
For security-related questions or incidents:
|
||||
- **Repository Issues:** https://projects.knownelement.com/project/reachableceo-vptechnicaloperations/timeline
|
||||
- **Community Discussion:** https://community.turnsys.com/c/chieftechnologyandproductofficer/26
|
||||
- **Security Team:** [Contact information to be added]
|
||||
|
||||
## Security Updates
|
||||
|
||||
This document is updated as security features are implemented and threats evolve. Last updated: July 14, 2025.
|
329
ProjectDocs/TSYS-2FA-GUIDE.md
Normal file
329
ProjectDocs/TSYS-2FA-GUIDE.md
Normal file
@@ -0,0 +1,329 @@
|
||||
# TSYS Two-Factor Authentication Implementation Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This guide provides complete instructions for implementing and managing two-factor authentication (2FA) on TSYS servers using Google Authenticator (TOTP).
|
||||
|
||||
## What This Implementation Provides
|
||||
|
||||
### Services Protected by 2FA
|
||||
- **SSH Access:** Requires SSH key + 2FA token
|
||||
- **Cockpit Web Interface:** Requires password + 2FA token
|
||||
- **Webmin Administration:** Requires password + 2FA token (if installed)
|
||||
|
||||
### Security Features
|
||||
- **Time-based One-Time Passwords (TOTP):** Standard 6-digit codes
|
||||
- **Backup Codes:** Emergency access codes
|
||||
- **Gradual Rollout:** Optional nullok mode for phased deployment
|
||||
- **Configuration Backup:** Automatic backup of all configs
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Run the 2FA Setup Script
|
||||
```bash
|
||||
# Navigate to the security modules directory
|
||||
cd ProjectCode/Modules/Security
|
||||
|
||||
# Run the 2FA setup script as root
|
||||
sudo bash secharden-2fa.sh
|
||||
```
|
||||
|
||||
### Step 2: Validate Installation
|
||||
```bash
|
||||
# Run 2FA validation tests
|
||||
./Project-Tests/security/2fa-validation.sh
|
||||
|
||||
# Run specific 2FA security test
|
||||
./Project-Tests/run-tests.sh security
|
||||
```
|
||||
|
||||
### Step 3: Setup Individual Users
|
||||
For each user that needs 2FA access:
|
||||
|
||||
```bash
|
||||
# Check setup instructions
|
||||
cat /home/username/2fa-setup-instructions.txt
|
||||
|
||||
# Run user setup script
|
||||
sudo /tmp/setup-2fa-username.sh
|
||||
```
|
||||
|
||||
### Step 4: Test 2FA Access
|
||||
1. **Test SSH access** from another terminal
|
||||
2. **Test Cockpit access** via web browser
|
||||
3. **Test Webmin access** if installed
|
||||
|
||||
## User Setup Process
|
||||
|
||||
### Installing Authenticator Apps
|
||||
Users need one of these apps on their phone:
|
||||
- **Google Authenticator** (Android/iOS)
|
||||
- **Authy** (Android/iOS)
|
||||
- **Microsoft Authenticator** (Android/iOS)
|
||||
- **1Password** (with TOTP support)
|
||||
|
||||
### Setting Up 2FA for a User
|
||||
1. **Run setup script:**
|
||||
```bash
|
||||
sudo /tmp/setup-2fa-username.sh
|
||||
```
|
||||
|
||||
2. **Follow prompts:**
|
||||
- Answer "y" to update time-based token
|
||||
- Scan QR code with authenticator app
|
||||
- Save emergency backup codes securely
|
||||
- Answer "y" to remaining security questions
|
||||
|
||||
3. **Test immediately:**
|
||||
```bash
|
||||
# Test SSH from another terminal
|
||||
ssh username@server-ip
|
||||
# You'll be prompted for 6-digit code
|
||||
```
|
||||
|
||||
## Configuration Details
|
||||
|
||||
### SSH Configuration Changes
|
||||
File: `/etc/ssh/sshd_config`
|
||||
```
|
||||
ChallengeResponseAuthentication yes
|
||||
UsePAM yes
|
||||
AuthenticationMethods publickey,keyboard-interactive
|
||||
```
|
||||
|
||||
### PAM Configuration
|
||||
File: `/etc/pam.d/sshd`
|
||||
```
|
||||
auth required pam_google_authenticator.so nullok
|
||||
```
|
||||
|
||||
### Cockpit Configuration
|
||||
File: `/etc/cockpit/cockpit.conf`
|
||||
```
|
||||
[WebService]
|
||||
LoginTitle = TSYS Server Management
|
||||
LoginTo = 300
|
||||
RequireHost = true
|
||||
|
||||
[Session]
|
||||
Banner = /etc/cockpit/issue.cockpit
|
||||
IdleTimeout = 15
|
||||
```
|
||||
|
||||
### Webmin Configuration
|
||||
File: `/etc/webmin/miniserv.conf`
|
||||
```
|
||||
twofactor_provider=totp
|
||||
twofactor=1
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Gradual vs Strict Enforcement
|
||||
|
||||
#### Gradual Enforcement (Default)
|
||||
- Uses `nullok` option in PAM
|
||||
- Users without 2FA can still log in
|
||||
- Allows phased rollout
|
||||
- Good for initial deployment
|
||||
|
||||
#### Strict Enforcement
|
||||
- Remove `nullok` from PAM configuration
|
||||
- All users must have 2FA configured
|
||||
- Immediate security enforcement
|
||||
- Risk of lockout if misconfigured
|
||||
|
||||
### Backup and Recovery
|
||||
|
||||
#### Emergency Access
|
||||
- **Backup codes:** Generated during setup
|
||||
- **Root access:** Can disable 2FA if needed
|
||||
- **Console access:** Physical/virtual console bypasses SSH
|
||||
|
||||
#### Configuration Backup
|
||||
- Automatic backup to `/root/backup/2fa-TIMESTAMP/`
|
||||
- Includes all modified configuration files
|
||||
- Can be restored if needed
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### 1. User Cannot Generate QR Code
|
||||
```bash
|
||||
# Ensure qrencode is installed
|
||||
sudo apt-get install qrencode
|
||||
|
||||
# Re-run user setup
|
||||
sudo /tmp/setup-2fa-username.sh
|
||||
```
|
||||
|
||||
#### 2. SSH Connection Fails
|
||||
```bash
|
||||
# Check SSH service status
|
||||
sudo systemctl status sshd
|
||||
|
||||
# Test SSH configuration
|
||||
sudo sshd -t
|
||||
|
||||
# Check logs
|
||||
sudo journalctl -u sshd -f
|
||||
```
|
||||
|
||||
#### 3. 2FA Code Not Accepted
|
||||
- **Check time synchronization** on server and phone
|
||||
- **Verify app setup** - rescan QR code if needed
|
||||
- **Try backup codes** if available
|
||||
|
||||
#### 4. Locked Out of Server
|
||||
```bash
|
||||
# Access via console (physical/virtual)
|
||||
# Disable 2FA temporarily
|
||||
sudo cp /root/backup/2fa-*/pam.d.bak/sshd /etc/pam.d/sshd
|
||||
sudo systemctl restart sshd
|
||||
```
|
||||
|
||||
### Debug Commands
|
||||
|
||||
```bash
|
||||
# Check 2FA status
|
||||
./Project-Tests/security/2fa-validation.sh
|
||||
|
||||
# Check SSH configuration
|
||||
sudo sshd -T | grep -E "(Challenge|PAM|Authentication)"
|
||||
|
||||
# Check PAM configuration
|
||||
cat /etc/pam.d/sshd | grep google-authenticator
|
||||
|
||||
# Check user 2FA status
|
||||
ls -la ~/.google_authenticator
|
||||
```
|
||||
|
||||
## Management and Maintenance
|
||||
|
||||
### Adding New Users
|
||||
1. Ensure user account exists
|
||||
2. Run setup script for new user
|
||||
3. Provide setup instructions
|
||||
4. Test access
|
||||
|
||||
### Removing User 2FA
|
||||
```bash
|
||||
# Remove user's 2FA configuration
|
||||
sudo rm /home/username/.google_authenticator
|
||||
|
||||
# User will need to re-setup 2FA
|
||||
```
|
||||
|
||||
### Disabling 2FA System-Wide
|
||||
```bash
|
||||
# Restore original configurations
|
||||
sudo cp /root/backup/2fa-*/sshd_config.bak /etc/ssh/sshd_config
|
||||
sudo cp /root/backup/2fa-*/pam.d.bak/sshd /etc/pam.d/sshd
|
||||
sudo systemctl restart sshd
|
||||
```
|
||||
|
||||
### Updating 2FA Configuration
|
||||
```bash
|
||||
# Re-run setup script
|
||||
sudo bash secharden-2fa.sh
|
||||
|
||||
# Validate changes
|
||||
./Project-Tests/security/2fa-validation.sh
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Deployment Strategy
|
||||
1. **Test in non-production** environment first
|
||||
2. **Enable gradual rollout** (nullok) initially
|
||||
3. **Train users** on 2FA setup process
|
||||
4. **Test emergency procedures** before strict enforcement
|
||||
5. **Monitor logs** for authentication issues
|
||||
|
||||
### Security Recommendations
|
||||
- **Enforce strict mode** after successful rollout
|
||||
- **Regular backup code rotation**
|
||||
- **Monitor failed authentication attempts**
|
||||
- **Document emergency procedures**
|
||||
- **Regular security audits**
|
||||
|
||||
### User Training
|
||||
- **Provide clear instructions**
|
||||
- **Demonstrate setup process**
|
||||
- **Explain backup code importance**
|
||||
- **Test login process with users**
|
||||
- **Establish support procedures**
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
### Authentication Logs
|
||||
```bash
|
||||
# SSH authentication logs
|
||||
sudo journalctl -u sshd | grep -i "authentication"
|
||||
|
||||
# PAM authentication logs
|
||||
sudo journalctl | grep -i "pam_google_authenticator"
|
||||
|
||||
# Failed login attempts
|
||||
sudo journalctl | grep -i "failed"
|
||||
```
|
||||
|
||||
### Security Monitoring
|
||||
- Monitor for repeated failed 2FA attempts
|
||||
- Alert on successful logins without 2FA (during gradual rollout)
|
||||
- Track user 2FA setup completion
|
||||
- Monitor for emergency access usage
|
||||
|
||||
## Integration with Existing Systems
|
||||
|
||||
### LDAP/Active Directory
|
||||
- 2FA works with existing authentication systems
|
||||
- Users still need local 2FA setup
|
||||
- Consider centralized 2FA solutions for large deployments
|
||||
|
||||
### Monitoring Systems
|
||||
- LibreNMS: Will continue to work with SNMP
|
||||
- Wazuh: Will log 2FA authentication events
|
||||
- Cockpit: Enhanced with 2FA protection
|
||||
|
||||
### Backup Systems
|
||||
- Ensure backup procedures account for 2FA
|
||||
- Test restore procedures with 2FA enabled
|
||||
- Document emergency access procedures
|
||||
|
||||
## Support and Resources
|
||||
|
||||
### Files Created by Setup
|
||||
- `/tmp/setup-2fa-*.sh` - User setup scripts
|
||||
- `/home/*/2fa-setup-instructions.txt` - User instructions
|
||||
- `/root/backup/2fa-*/` - Configuration backups
|
||||
|
||||
### Validation Tools
|
||||
- `./Project-Tests/security/2fa-validation.sh` - Complete 2FA validation
|
||||
- `./Project-Tests/run-tests.sh security` - Security test suite
|
||||
|
||||
### Emergency Contacts
|
||||
- System Administrator: [Contact Info]
|
||||
- Security Team: [Contact Info]
|
||||
- 24/7 Support: [Contact Info]
|
||||
|
||||
## Compliance and Audit
|
||||
|
||||
### Security Benefits
|
||||
- Significantly reduces risk of unauthorized access
|
||||
- Meets multi-factor authentication requirements
|
||||
- Provides audit trail of authentication events
|
||||
- Complies with security frameworks (NIST, ISO 27001)
|
||||
|
||||
### Audit Trail
|
||||
- All authentication attempts logged
|
||||
- 2FA setup events recorded
|
||||
- Configuration changes tracked
|
||||
- Emergency access documented
|
||||
|
||||
---
|
||||
|
||||
**Last Updated:** July 14, 2025
|
||||
**Version:** 1.0
|
||||
**Author:** TSYS Security Team
|
117
ProjectDocs/charles-todo.md
Normal file
117
ProjectDocs/charles-todo.md
Normal file
@@ -0,0 +1,117 @@
|
||||
# Charles TODO - TSYS FetchApply Security Improvements
|
||||
|
||||
**Priority Order:** High → Medium → Low
|
||||
**Target:** Address security vulnerabilities and operational improvements
|
||||
|
||||
## 🚨 HIGH PRIORITY (Security Critical)
|
||||
|
||||
### ✅ 1. Replace Insecure Deployment Method - RESOLVED
|
||||
**Previous Issue:** `curl https://dl.knownelement.com/KNEL/FetchApply/SetupNewSystem.sh | bash`
|
||||
**Status:** Fixed in README.md - now uses secure git clone approach
|
||||
**Current Method:** `git clone this repo` → `cd FetchApply/ProjectCode` → `bash SetupNewSystem.sh`
|
||||
|
||||
**Remaining considerations:**
|
||||
- Consider implementing GPG signature verification for tagged releases
|
||||
- Add cryptographic checksums for external downloads within scripts
|
||||
|
||||
### ✅ 2. Enforce HTTPS for All Downloads - RESOLVED
|
||||
**Previous Issue:** HTTP URLs in Dell OMSA and some repository setups
|
||||
**Status:** All HTTP URLs converted to HTTPS across:
|
||||
- `ProjectCode/Dell/Server/omsa.sh` - Ubuntu archive and Dell repo URLs
|
||||
- `ProjectCode/legacy/prox7.sh` - Proxmox download URLs
|
||||
- `ProjectCode/Modules/RandD/sslStackFromSource.sh` - Apache source URLs
|
||||
|
||||
**Remaining considerations:**
|
||||
- SSL certificate validation is enabled by default in wget/curl
|
||||
- Consider adding retry logic for certificate failures
|
||||
|
||||
### 3. Implement Secrets Management
|
||||
**Current Issue:** SSH keys committed to repository, no secrets rotation
|
||||
**Action Required:**
|
||||
- Deploy Bitwarden CLI or HashiCorp Vault integration
|
||||
- Remove SSH public keys from repository
|
||||
- Create secure key distribution mechanism
|
||||
- Implement key rotation procedures
|
||||
- Add environment variable support for sensitive data
|
||||
|
||||
**Files to secure:**
|
||||
- `ProjectCode/ConfigFiles/SSH/AuthorizedKeys/` (entire directory)
|
||||
- Hard-coded hostnames in various scripts
|
||||
|
||||
## 🔶 MEDIUM PRIORITY (Operational Security)
|
||||
|
||||
### 4. Add Script Integrity Verification
|
||||
**Action Required:**
|
||||
- Generate SHA256 checksums for all scripts
|
||||
- Create checksum verification function in Framework-Includes
|
||||
- Add signature verification for external downloads
|
||||
- Implement rollback capability on verification failure
|
||||
|
||||
### 5. Enhanced Error Recovery
|
||||
**Action Required:**
|
||||
- Add state tracking for partial deployments
|
||||
- Implement resume functionality for interrupted installations
|
||||
- Create system restoration points before major changes
|
||||
- Add dependency checking before module execution
|
||||
|
||||
### 6. Security Testing Framework
|
||||
**Action Required:**
|
||||
- Create integration tests for security configurations
|
||||
- Add compliance validation (CIS benchmarks, STIG)
|
||||
- Implement automated security scanning post-deployment
|
||||
- Create test environments for validation
|
||||
|
||||
### 7. Configuration Validation
|
||||
**Action Required:**
|
||||
- Add pre-flight checks for system compatibility
|
||||
- Validate network connectivity to required services
|
||||
- Check for conflicting software before installation
|
||||
- Verify sufficient disk space and system resources
|
||||
|
||||
## 🔹 LOW PRIORITY (Quality Improvements)
|
||||
|
||||
### 8. Documentation Enhancement
|
||||
**Action Required:**
|
||||
- Create detailed security architecture documentation
|
||||
- Add troubleshooting guides for common issues
|
||||
- Document security implications of each module
|
||||
- Create deployment runbooks for different environments
|
||||
|
||||
### 9. Monitoring and Alerting
|
||||
**Action Required:**
|
||||
- Add deployment success/failure reporting
|
||||
- Implement centralized logging for all installations
|
||||
- Create dashboards for deployment status
|
||||
- Add alerting for security configuration drift
|
||||
|
||||
### 10. User Experience Improvements
|
||||
**Action Required:**
|
||||
- Create web-based deployment interface
|
||||
- Add progress indicators for long-running operations
|
||||
- Implement dry-run mode for testing configurations
|
||||
- Add interactive configuration selection
|
||||
|
||||
## Implementation Timeline
|
||||
|
||||
**✅ COMPLETED:** Item 1 (Secure deployment method)
|
||||
**✅ COMPLETED:** Item 2 (HTTPS enforcement)
|
||||
**Week 1:** Item 3 (Secrets management)
|
||||
**Week 2-3:** Items 4-5 (Operational improvements)
|
||||
**Month 2:** Items 6-10 (Quality and monitoring)
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] No plaintext secrets in repository
|
||||
- [x] All downloads use HTTPS with verification ✅
|
||||
- [x] Deployment method is cryptographically secure ✅
|
||||
- [ ] Automated testing validates security configurations
|
||||
- [ ] Rollback capability exists for all changes
|
||||
- [ ] Comprehensive documentation covers security implications
|
||||
|
||||
## Resources Needed
|
||||
|
||||
- Access to package repository for signed distributions
|
||||
- GPG key infrastructure for signing
|
||||
- Secrets management service (Vault/Bitwarden)
|
||||
- Test environment infrastructure
|
||||
- Security scanning tools integration
|
162
ProjectDocs/claude-todo.md
Normal file
162
ProjectDocs/claude-todo.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Claude TODO - TSYS FetchApply Automation Tasks
|
||||
|
||||
**Purpose:** Actionable items optimized for AI assistant implementation
|
||||
**Priority:** Critical → High → Medium → Low
|
||||
|
||||
## 🚨 CRITICAL (Immediate Security Fixes)
|
||||
|
||||
### ✅ RESOLVED: Secure Deployment Method
|
||||
**Previous Issue:** `curl | bash` deployment method
|
||||
**Status:** Fixed in README.md - now uses `git clone` + local script execution
|
||||
|
||||
### ✅ RESOLVED: Replace HTTP URLs with HTTPS
|
||||
**Files modified:**
|
||||
- `ProjectCode/Dell/Server/omsa.sh` - Converted 11 HTTP URLs to HTTPS (Ubuntu archive, Dell repo)
|
||||
- `ProjectCode/legacy/prox7.sh` - Converted 2 HTTP URLs to HTTPS (Proxmox downloads)
|
||||
- `ProjectCode/Modules/RandD/sslStackFromSource.sh` - Converted 3 HTTP URLs to HTTPS (Apache sources)
|
||||
|
||||
**Status:** All HTTP URLs in active scripts converted to HTTPS. Only remaining HTTP references are in comments and LibreNMS agent files (external dependencies).
|
||||
|
||||
### TASK-002: Add Download Integrity Verification
|
||||
**Create new function in:** `Framework-Includes/VerifyDownload.sh`
|
||||
**Function to implement:**
|
||||
```bash
|
||||
function verify_download() {
|
||||
local url="$1"
|
||||
local expected_hash="$2"
|
||||
local output_file="$3"
|
||||
|
||||
curl -fsSL "$url" -o "$output_file"
|
||||
local actual_hash=$(sha256sum "$output_file" | cut -d' ' -f1)
|
||||
|
||||
if [ "$actual_hash" != "$expected_hash" ]; then
|
||||
print_error "Hash verification failed for $output_file"
|
||||
rm -f "$output_file"
|
||||
return 1
|
||||
fi
|
||||
print_info "Download verified: $output_file"
|
||||
}
|
||||
```
|
||||
|
||||
### TASK-003: Create Secure Deployment Script
|
||||
**Create:** `ProjectCode/SecureSetupNewSystem.sh`
|
||||
**Features to implement:**
|
||||
- GPG signature verification
|
||||
- SHA256 checksum validation
|
||||
- HTTPS-only downloads
|
||||
- Rollback capability
|
||||
|
||||
## 🔶 HIGH (Security Enhancements)
|
||||
|
||||
### TASK-004: Remove Hardcoded SSH Keys
|
||||
**Files to modify:**
|
||||
- `ProjectCode/ConfigFiles/SSH/AuthorizedKeys/root-ssh-authorized-keys`
|
||||
- `ProjectCode/ConfigFiles/SSH/AuthorizedKeys/localuser-ssh-authorized-keys`
|
||||
- `ProjectCode/Modules/Security/secharden-ssh.sh:31,40,51`
|
||||
|
||||
**Implementation approach:**
|
||||
1. Create environment variable support: `SSH_KEYS_URL` or `SSH_KEYS_VAULT_PATH`
|
||||
2. Modify secharden-ssh.sh to fetch keys from secure source
|
||||
3. Add key validation before deployment
|
||||
|
||||
### TASK-005: Add Secrets Management Framework
|
||||
**Create:** `Framework-Includes/SecretsManager.sh`
|
||||
**Functions to implement:**
|
||||
```bash
|
||||
function get_secret() { } # Retrieve secret from vault
|
||||
function validate_secret() { } # Validate secret format
|
||||
function rotate_secret() { } # Trigger secret rotation
|
||||
```
|
||||
|
||||
### TASK-006: Enhanced Preflight Checks
|
||||
**Modify:** `Framework-Includes/PreflightCheck.sh`
|
||||
**Add checks for:**
|
||||
- Network connectivity to required hosts
|
||||
- Disk space requirements
|
||||
- Existing conflicting software
|
||||
- Required system capabilities
|
||||
|
||||
## 🔹 MEDIUM (Operational Improvements)
|
||||
|
||||
### TASK-007: Add Configuration Backup
|
||||
**Create:** `Framework-Includes/ConfigBackup.sh`
|
||||
**Functions:**
|
||||
```bash
|
||||
function backup_config() { } # Create timestamped backup
|
||||
function restore_config() { } # Restore from backup
|
||||
function list_backups() { } # Show available backups
|
||||
```
|
||||
|
||||
### TASK-008: Implement State Tracking
|
||||
**Create:** `Framework-Includes/StateManager.sh`
|
||||
**Track:**
|
||||
- Deployment progress
|
||||
- Module completion status
|
||||
- Rollback points
|
||||
- System changes made
|
||||
|
||||
### TASK-009: Add Retry Logic
|
||||
**Enhance existing scripts with:**
|
||||
- Configurable retry attempts for network operations
|
||||
- Exponential backoff for failed operations
|
||||
- Circuit breaker for repeatedly failing services
|
||||
|
||||
## 🔸 LOW (Quality of Life)
|
||||
|
||||
### TASK-010: Enhanced Logging
|
||||
**Modify:** `Framework-Includes/Logging.sh`
|
||||
**Add:**
|
||||
- Structured logging (JSON format option)
|
||||
- Log levels (DEBUG, INFO, WARN, ERROR)
|
||||
- Remote logging capability
|
||||
- Log rotation management
|
||||
|
||||
### TASK-011: Progress Indicators
|
||||
**Add to:** `Framework-Includes/PrettyPrint.sh`
|
||||
```bash
|
||||
function show_progress() { } # Display progress bar
|
||||
function update_status() { } # Update current operation
|
||||
```
|
||||
|
||||
### TASK-012: Dry Run Mode
|
||||
**Add to:** `ProjectCode/SetupNewSystem.sh`
|
||||
**Implementation:**
|
||||
- `--dry-run` flag support
|
||||
- Preview of changes without execution
|
||||
- Dependency analysis output
|
||||
|
||||
## Implementation Order for Claude
|
||||
|
||||
**Updated Priority After Security Fix (July 14, 2025):**
|
||||
1. **Start with TASK-001** (HTTPS enforcement - simple find/replace operations)
|
||||
2. **Create framework functions** (TASK-002, TASK-005, TASK-007)
|
||||
3. **Enhance existing modules** (TASK-004, TASK-006)
|
||||
4. **Add operational features** (TASK-008, TASK-009)
|
||||
5. **Improve user experience** (TASK-010, TASK-011, TASK-012)
|
||||
|
||||
**Note:** Major deployment security risk resolved - remaining tasks focus on hardening internal operations.
|
||||
|
||||
## File Location Patterns
|
||||
|
||||
- **Framework components:** `Framework-Includes/*.sh`
|
||||
- **Security modules:** `ProjectCode/Modules/Security/*.sh`
|
||||
- **Configuration files:** `ProjectCode/ConfigFiles/*/`
|
||||
- **Main entry point:** `ProjectCode/SetupNewSystem.sh`
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
For each task:
|
||||
1. Create backup of original files
|
||||
2. Implement changes incrementally
|
||||
3. Test with `bash -n` for syntax validation
|
||||
4. Verify functionality with controlled test runs
|
||||
5. Document changes made
|
||||
|
||||
## Error Handling Requirements
|
||||
|
||||
All new functions must:
|
||||
- Use `set -euo pipefail` compatibility
|
||||
- Integrate with existing error handling framework
|
||||
- Log errors to `$LOGFILENAME`
|
||||
- Return appropriate exit codes
|
||||
- Clean up temporary files on failure
|
Reference in New Issue
Block a user