Compare commits
228 Commits
c365d232fa
...
main
Author | SHA1 | Date | |
---|---|---|---|
2930eeaf27 | |||
870540840c | |||
5e2eaff55d | |||
8f19c9fb6e | |||
40ab4608e2 | |||
47ddb93fef | |||
e73b81e229 | |||
39e37d0f76 | |||
31e66864ad | |||
0006eefcf1 | |||
abfaf765e6 | |||
1f2bd31380 | |||
93cea874a8 | |||
a898ebc59d | |||
78cc8cbcf3 | |||
495d0bb03b | |||
7a7d23f36c | |||
84f3ca3b0e | |||
f9f32612bb | |||
09063bfee4 | |||
5bbaff89e9 | |||
5a8561ea84 | |||
2fa32a5eb7 | |||
83d5cf2f8d | |||
49e57ff846 | |||
47b5a976c2 | |||
a710fc7b4e | |||
c6e458de8b | |||
e31bab4162 | |||
86740b8c7d | |||
f585f90b7f | |||
24c10b6f35 | |||
634a998d7e | |||
e3685f68ad | |||
ac857c91c3 | |||
a632e7d514 | |||
f6acf660f6 | |||
0c736c7295 | |||
273e7fe674 | |||
6609d7d9e3 | |||
0588b2dd60 | |||
f399308b2d | |||
45b53efe11 | |||
b0d1ae0a3e | |||
a2ff47e5d2 | |||
b5d09e64f0 | |||
edc3ca26ad | |||
a272764d66 | |||
97b67ea1fc | |||
a86b2ea09b | |||
54cfcf669f | |||
28c18a2bda | |||
168456ee7f | |||
d6364eac7a | |||
d2100d1146 | |||
5c20f167b2 | |||
3b705a23ba | |||
319cd61ad4 | |||
1e458f0fae | |||
0bf88e3d8c | |||
bf4efcdf5a | |||
f9f556111b | |||
7e5302b5e6 | |||
885487fce5 | |||
ba8efdfa0b | |||
1d14c9c9a2 | |||
d3e4fb5014 | |||
001faf76a3 | |||
52e8ecf779 | |||
24946292e7 | |||
cb10cdf1cc | |||
f2dc2ce29e | |||
d1ef7118d5 | |||
160d1b26cc | |||
ce5bb0be6f | |||
ce1bf7d220 | |||
0175a00458 | |||
0f52d19229 | |||
0937036155 | |||
02a874f713 | |||
259a4f07b7 | |||
f06d8b1fe5 | |||
d76613c0dc | |||
5deaecd79f | |||
c58c3f116e | |||
e4e1c66111 | |||
d60c03b116 | |||
6cdc7bbba7 | |||
ba384498c0 | |||
8669b64adc | |||
13e2678be4 | |||
1e3c7a97af | |||
b7c329ddb8 | |||
3207f1a870 | |||
0041e95d59 | |||
c476f84943 | |||
8c38bcc57c | |||
7431c1eb4e | |||
38b779f054 | |||
197d8e2d27 | |||
0ee847f556 | |||
7457db098f | |||
109acf07be | |||
7ad5a2a8e7 | |||
86cded93c5 | |||
ce45ec1684 | |||
15074a99f4 | |||
982389fb63 | |||
7b3549c617 | |||
a9318aee60 | |||
ede6aa0562 | |||
445cbbefde | |||
89ac84c4e1 | |||
5eb2f6b3d5 | |||
adc57c1e37 | |||
29dca6241e | |||
a38eac2e77 | |||
0016e1aaeb | |||
80dd021217 | |||
4e3368156c | |||
46020fecf5 | |||
e3683db3cf | |||
c77d932dd2 | |||
ffdef9500c | |||
363c845ead | |||
df7f369f8c | |||
63536f2684 | |||
063cfc2262 | |||
1887920f52 | |||
c1791eaa43 | |||
94eed1ab9d | |||
55178257ef | |||
486a150e5e | |||
8c68a975e0 | |||
066708f101 | |||
9be83022e6 | |||
66976c2ed0 | |||
03abf42065 | |||
6df6aba2dd | |||
d80dd973e4 | |||
fe89e56e4a | |||
0773dcb372 | |||
6e6a57f61b | |||
ccb24fe403 | |||
c75d0e39a6 | |||
f3070de151 | |||
d82c8733fa | |||
d64d75cb3b | |||
f0654723e5 | |||
fd9c50d151 | |||
4375b82f55 | |||
8d16f8e8f7 | |||
6d5732964c | |||
10ce9ca724 | |||
a277a36b39 | |||
87b31b845d | |||
a8a07b7c5d | |||
f0e8482e71 | |||
17924e8f88 | |||
a458c39ddc | |||
7e4aa53c33 | |||
0c75da8b08 | |||
db6643c825 | |||
7a5b90ae84 | |||
23cba4713b | |||
dc40896af0 | |||
396891af1c | |||
89814e2113 | |||
5549409dcc | |||
8c14f7823b | |||
012fcb1698 | |||
93dcd9fc92 | |||
ef50e10cba | |||
eeea9a98de | |||
a5f0cba15c | |||
e9874c75a5 | |||
fe830a1ad9 | |||
4c20af7fb9 | |||
ae147b7cd0 | |||
178c4068c2 | |||
8009651e1e | |||
4f416b9748 | |||
cf68f49b17 | |||
bc955b0bb2 | |||
ffd4f74c4a | |||
09be6ebfb7 | |||
3f0bf60b44 | |||
8f76bd1ad1 | |||
47b651ac15 | |||
e77c972787 | |||
f2b46b7b97 | |||
b82f16bfb6 | |||
cfa08ec8f5 | |||
d0d9db84b2 | |||
f4cfe89fa1 | |||
82c93f4190 | |||
61009a4158 | |||
8b83dbac4b | |||
8de1a76003 | |||
31532c9f44 | |||
18c5e4495d | |||
ed347d83dc | |||
39c7e4d36f | |||
f8bc62b329 | |||
f7f0eb6c9d | |||
b2844f8bad | |||
1a8980afc6 | |||
4a38cd404f | |||
cbe446b115 | |||
83c8fc02a9 | |||
3730e7ac54 | |||
b79fcc0e5a | |||
400644f281 | |||
bb93cd7ee2 | |||
9c659f8a4d | |||
459da206bf | |||
d78409315f | |||
bde664f38f | |||
d53b4fd5ef | |||
1093db16c0 | |||
aef7bb1e18 | |||
fdbf33d3b9 | |||
5e83e5ca68 | |||
8385dc1e4d | |||
7c30abb120 | |||
fc5e8288e1 | |||
27f2ab1c29 | |||
97aedd1467 |
6
.vscode/settings.json
vendored
Normal file
6
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"debug.javascript.defaultRuntimeExecutable": {
|
||||
"pwa-node": "/home/localuser/.local/share/mise/shims/node"
|
||||
},
|
||||
"python.defaultInterpreterPath": "/home/localuser/.local/share/mise/installs/python/3.11.13/bin/python"
|
||||
}
|
3
Project-ConfigFiles/CONFIG_VARS
Normal file
3
Project-ConfigFiles/CONFIG_VARS
Normal file
@@ -0,0 +1,3 @@
|
||||
|
||||
export DL_ROOT
|
||||
DL_ROOT="https://dl.knownelement.com/KNEL/FetchApply/"
|
13
Project-Includes/LocalHelp.sh
Normal file
13
Project-Includes/LocalHelp.sh
Normal file
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
|
||||
function LocalHelp()
|
||||
{
|
||||
echo "$0 is <description here>"
|
||||
echo "$0 takes <num> arguments: "
|
||||
echo "1) <stuff>"
|
||||
echo "2) <other stuff>"
|
||||
echo "<additional info on arguments...>:"
|
||||
echo "<put>"
|
||||
echo "<stuff>"
|
||||
echo "<here>"
|
||||
}
|
19
Project-Includes/PreflightCheck.sh
Normal file
19
Project-Includes/PreflightCheck.sh
Normal file
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
|
||||
function PreflightCheck()
|
||||
{
|
||||
|
||||
export curr_user="$USER"
|
||||
export user_check
|
||||
|
||||
user_check="$(echo "$curr_user" | grep -c root)"
|
||||
|
||||
|
||||
if [ $user_check -ne 1 ]; then
|
||||
print_error "Must run as root."
|
||||
error_out
|
||||
fi
|
||||
|
||||
echo "All checks passed...."
|
||||
|
||||
}
|
13
Project-Includes/pi-detect.sh
Normal file
13
Project-Includes/pi-detect.sh
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
function pi-detect()
|
||||
{
|
||||
print_info Now running "$FUNCNAME"....
|
||||
if [ -f /sys/firmware/devicetree/base/model ] ; then
|
||||
export IS_RASPI="1"
|
||||
fi
|
||||
|
||||
if [ ! -f /sys/firmware/devicetree/base/model ] ; then
|
||||
export IS_RASPI="0"
|
||||
fi
|
||||
print_info Completed running "$FUNCNAME"
|
||||
}
|
176
Project-Tests/README.md
Normal file
176
Project-Tests/README.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# TSYS FetchApply Testing Framework
|
||||
|
||||
## Overview
|
||||
|
||||
This testing framework provides comprehensive validation for the TSYS FetchApply infrastructure provisioning system. It includes unit tests, integration tests, security tests, and system validation.
|
||||
|
||||
## Test Categories
|
||||
|
||||
### 1. Unit Tests (`unit/`)
|
||||
- **Purpose:** Test individual framework functions and components
|
||||
- **Scope:** Framework includes, helper functions, syntax validation
|
||||
- **Example:** `framework-functions.sh` - Tests logging, pretty print, and error handling functions
|
||||
|
||||
### 2. Integration Tests (`integration/`)
|
||||
- **Purpose:** Test complete workflows and module interactions
|
||||
- **Scope:** End-to-end deployment scenarios, module integration
|
||||
- **Future:** Module interaction testing, deployment workflow validation
|
||||
|
||||
### 3. Security Tests (`security/`)
|
||||
- **Purpose:** Validate security configurations and practices
|
||||
- **Scope:** HTTPS enforcement, deployment security, SSH hardening
|
||||
- **Example:** `https-enforcement.sh` - Validates all URLs use HTTPS
|
||||
|
||||
### 4. Validation Tests (`validation/`)
|
||||
- **Purpose:** System compatibility and pre-flight checks
|
||||
- **Scope:** System requirements, network connectivity, permissions
|
||||
- **Example:** `system-requirements.sh` - Validates minimum system requirements
|
||||
|
||||
## Usage
|
||||
|
||||
### Run All Tests
|
||||
```bash
|
||||
./Project-Tests/run-tests.sh
|
||||
```
|
||||
|
||||
### Run Specific Test Categories
|
||||
```bash
|
||||
./Project-Tests/run-tests.sh unit # Unit tests only
|
||||
./Project-Tests/run-tests.sh integration # Integration tests only
|
||||
./Project-Tests/run-tests.sh security # Security tests only
|
||||
./Project-Tests/run-tests.sh validation # Validation tests only
|
||||
```
|
||||
|
||||
### Run Individual Tests
|
||||
```bash
|
||||
./Project-Tests/validation/system-requirements.sh
|
||||
./Project-Tests/security/https-enforcement.sh
|
||||
./Project-Tests/unit/framework-functions.sh
|
||||
```
|
||||
|
||||
## Test Results
|
||||
|
||||
- **Console Output:** Real-time test results with color-coded status
|
||||
- **JSON Reports:** Detailed test reports saved to `logs/tests/`
|
||||
- **Exit Codes:** 0 for success, 1 for failures
|
||||
|
||||
## Configuration Validation
|
||||
|
||||
The validation framework performs pre-flight checks to ensure system compatibility:
|
||||
|
||||
### System Requirements
|
||||
- **Memory:** Minimum 2GB RAM
|
||||
- **Disk Space:** Minimum 10GB available
|
||||
- **OS Compatibility:** Ubuntu/Debian (tested), others (may work)
|
||||
|
||||
### Network Connectivity
|
||||
- Tests connection to required download sources
|
||||
- Validates HTTPS endpoints are accessible
|
||||
- Checks for firewall/proxy issues
|
||||
|
||||
### Command Dependencies
|
||||
- Verifies required tools are installed (`curl`, `wget`, `git`, `systemctl`, `apt-get`)
|
||||
- Checks for proper versions where applicable
|
||||
|
||||
### Permissions
|
||||
- Validates write access to system directories
|
||||
- Checks for required administrative privileges
|
||||
|
||||
## Adding New Tests
|
||||
|
||||
### Test File Structure
|
||||
```bash
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
function test_something() {
|
||||
echo "🔍 Testing something..."
|
||||
|
||||
if [[ condition ]]; then
|
||||
echo "✅ Test passed"
|
||||
return 0
|
||||
else
|
||||
echo "❌ Test failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function main() {
|
||||
echo "🧪 Running Test Suite Name"
|
||||
echo "=========================="
|
||||
|
||||
local total_failures=0
|
||||
test_something || ((total_failures++))
|
||||
|
||||
echo "=========================="
|
||||
if [[ $total_failures -eq 0 ]]; then
|
||||
echo "✅ All tests passed"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ $total_failures tests failed"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
||||
```
|
||||
|
||||
### Test Categories Guidelines
|
||||
|
||||
- **Unit Tests:** Focus on individual functions, fast execution
|
||||
- **Integration Tests:** Test module interactions, longer execution
|
||||
- **Security Tests:** Validate security configurations
|
||||
- **Validation Tests:** Pre-flight system checks
|
||||
|
||||
## Continuous Integration
|
||||
|
||||
The testing framework is designed to integrate with CI/CD pipelines:
|
||||
|
||||
```bash
|
||||
# Example CI script
|
||||
./Project-Tests/run-tests.sh all
|
||||
test_exit_code=$?
|
||||
|
||||
if [[ $test_exit_code -eq 0 ]]; then
|
||||
echo "All tests passed - deployment approved"
|
||||
else
|
||||
echo "Tests failed - deployment blocked"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
## Test Development Best Practices
|
||||
|
||||
1. **Clear Test Names:** Use descriptive function names
|
||||
2. **Proper Exit Codes:** Return 0 for success, 1 for failure
|
||||
3. **Informative Output:** Use emoji and clear messages
|
||||
4. **Timeout Protection:** Use timeout for network operations
|
||||
5. **Cleanup:** Remove temporary files and resources
|
||||
6. **Error Handling:** Use `set -euo pipefail` for strict error handling
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
- **Permission Denied:** Run tests with appropriate privileges
|
||||
- **Network Timeouts:** Check firewall and proxy settings
|
||||
- **Missing Dependencies:** Install required tools before testing
|
||||
- **Script Errors:** Validate syntax with `bash -n script.sh`
|
||||
|
||||
### Debug Mode
|
||||
```bash
|
||||
# Enable debug output
|
||||
export DEBUG=1
|
||||
./Project-Tests/run-tests.sh
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
When adding new functionality to FetchApply:
|
||||
|
||||
1. Add corresponding tests in appropriate category
|
||||
2. Run full test suite before committing
|
||||
3. Update documentation for new test cases
|
||||
4. Ensure tests pass in clean environment
|
128
Project-Tests/run-tests.sh
Executable file
128
Project-Tests/run-tests.sh
Executable file
@@ -0,0 +1,128 @@
|
||||
#!/bin/bash
|
||||
|
||||
# TSYS FetchApply Testing Framework
|
||||
# Main test runner script
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Source framework includes
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/.."
|
||||
source "$PROJECT_ROOT/Framework-Includes/Logging.sh"
|
||||
source "$PROJECT_ROOT/Framework-Includes/PrettyPrint.sh"
|
||||
|
||||
# Test configuration
|
||||
TEST_LOG_DIR="$PROJECT_ROOT/logs/tests"
|
||||
TEST_RESULTS_FILE="$TEST_LOG_DIR/test-results-$(date +%Y%m%d-%H%M%S).json"
|
||||
|
||||
# Ensure test log directory exists
|
||||
mkdir -p "$TEST_LOG_DIR"
|
||||
|
||||
# Test counters
|
||||
declare -g TESTS_PASSED=0
|
||||
declare -g TESTS_FAILED=0
|
||||
declare -g TESTS_SKIPPED=0
|
||||
|
||||
# Test runner functions
|
||||
function run_test_suite() {
|
||||
local suite_name="$1"
|
||||
local test_dir="$2"
|
||||
|
||||
print_header "Running $suite_name Tests"
|
||||
|
||||
if [[ ! -d "$test_dir" ]]; then
|
||||
print_warning "Test directory $test_dir not found, skipping"
|
||||
return 0
|
||||
fi
|
||||
|
||||
for test_file in "$test_dir"/*.sh; do
|
||||
if [[ -f "$test_file" ]]; then
|
||||
run_single_test "$test_file"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
function run_single_test() {
|
||||
local test_file="$1"
|
||||
local test_name="$(basename "$test_file" .sh)"
|
||||
|
||||
print_info "Running test: $test_name"
|
||||
|
||||
if timeout 300 bash "$test_file"; then
|
||||
print_success "✅ $test_name PASSED"
|
||||
((TESTS_PASSED++))
|
||||
else
|
||||
print_error "❌ $test_name FAILED"
|
||||
((TESTS_FAILED++))
|
||||
fi
|
||||
}
|
||||
|
||||
function generate_test_report() {
|
||||
local total_tests=$((TESTS_PASSED + TESTS_FAILED + TESTS_SKIPPED))
|
||||
|
||||
print_header "Test Results Summary"
|
||||
print_info "Total Tests: $total_tests"
|
||||
print_success "Passed: $TESTS_PASSED"
|
||||
print_error "Failed: $TESTS_FAILED"
|
||||
print_warning "Skipped: $TESTS_SKIPPED"
|
||||
|
||||
# Generate JSON report
|
||||
cat > "$TEST_RESULTS_FILE" <<EOF
|
||||
{
|
||||
"timestamp": "$(date -Iseconds)",
|
||||
"total_tests": $total_tests,
|
||||
"passed": $TESTS_PASSED,
|
||||
"failed": $TESTS_FAILED,
|
||||
"skipped": $TESTS_SKIPPED,
|
||||
"success_rate": $(awk "BEGIN {printf \"%.2f\", ($TESTS_PASSED/$total_tests)*100}")
|
||||
}
|
||||
EOF
|
||||
|
||||
print_info "Test report saved to: $TEST_RESULTS_FILE"
|
||||
}
|
||||
|
||||
# Main execution
|
||||
function main() {
|
||||
print_header "TSYS FetchApply Test Suite"
|
||||
|
||||
# Parse command line arguments
|
||||
local test_type="${1:-all}"
|
||||
|
||||
case "$test_type" in
|
||||
"unit")
|
||||
run_test_suite "Unit" "$(dirname "$0")/unit"
|
||||
;;
|
||||
"integration")
|
||||
run_test_suite "Integration" "$(dirname "$0")/integration"
|
||||
;;
|
||||
"security")
|
||||
run_test_suite "Security" "$(dirname "$0")/security"
|
||||
;;
|
||||
"validation")
|
||||
run_test_suite "Validation" "$(dirname "$0")/validation"
|
||||
;;
|
||||
"all")
|
||||
run_test_suite "Unit" "$(dirname "$0")/unit"
|
||||
run_test_suite "Integration" "$(dirname "$0")/integration"
|
||||
run_test_suite "Security" "$(dirname "$0")/security"
|
||||
run_test_suite "Validation" "$(dirname "$0")/validation"
|
||||
;;
|
||||
*)
|
||||
print_error "Usage: $0 [unit|integration|security|validation|all]"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
generate_test_report
|
||||
|
||||
# Exit with appropriate code
|
||||
if [[ $TESTS_FAILED -gt 0 ]]; then
|
||||
exit 1
|
||||
else
|
||||
exit 0
|
||||
fi
|
||||
}
|
||||
|
||||
# Run main if executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
310
Project-Tests/security/2fa-validation.sh
Executable file
310
Project-Tests/security/2fa-validation.sh
Executable file
@@ -0,0 +1,310 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Two-Factor Authentication Validation Test
|
||||
# Validates 2FA configuration for SSH, Cockpit, and Webmin
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../.."
|
||||
|
||||
function test_2fa_packages() {
|
||||
echo "🔍 Testing 2FA package installation..."
|
||||
|
||||
local packages=("libpam-google-authenticator" "qrencode")
|
||||
local failed=0
|
||||
|
||||
for package in "${packages[@]}"; do
|
||||
if dpkg -l | grep -q "^ii.*$package"; then
|
||||
echo "✅ Package installed: $package"
|
||||
else
|
||||
echo "❌ Package missing: $package"
|
||||
((failed++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Check if google-authenticator command exists
|
||||
if command -v google-authenticator >/dev/null 2>&1; then
|
||||
echo "✅ Google Authenticator command available"
|
||||
else
|
||||
echo "❌ Google Authenticator command not found"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_ssh_2fa_config() {
|
||||
echo "🔍 Testing SSH 2FA configuration..."
|
||||
|
||||
local ssh_config="/etc/ssh/sshd_config"
|
||||
local failed=0
|
||||
|
||||
# Check required SSH settings
|
||||
if grep -q "^ChallengeResponseAuthentication yes" "$ssh_config"; then
|
||||
echo "✅ ChallengeResponseAuthentication enabled"
|
||||
else
|
||||
echo "❌ ChallengeResponseAuthentication not enabled"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
if grep -q "^UsePAM yes" "$ssh_config"; then
|
||||
echo "✅ UsePAM enabled"
|
||||
else
|
||||
echo "❌ UsePAM not enabled"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
if grep -q "^AuthenticationMethods publickey,keyboard-interactive" "$ssh_config"; then
|
||||
echo "✅ AuthenticationMethods configured for 2FA"
|
||||
else
|
||||
echo "❌ AuthenticationMethods not configured for 2FA"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_pam_2fa_config() {
|
||||
echo "🔍 Testing PAM 2FA configuration..."
|
||||
|
||||
local pam_sshd="/etc/pam.d/sshd"
|
||||
local failed=0
|
||||
|
||||
# Check if PAM includes Google Authenticator
|
||||
if grep -q "pam_google_authenticator.so" "$pam_sshd"; then
|
||||
echo "✅ PAM Google Authenticator module configured"
|
||||
else
|
||||
echo "❌ PAM Google Authenticator module not configured"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Check if nullok is present (allows users without 2FA setup)
|
||||
if grep -q "pam_google_authenticator.so nullok" "$pam_sshd"; then
|
||||
echo "✅ PAM nullok option configured (allows gradual rollout)"
|
||||
else
|
||||
echo "⚠️ PAM nullok option not configured (immediate enforcement)"
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_cockpit_2fa_config() {
|
||||
echo "🔍 Testing Cockpit 2FA configuration..."
|
||||
|
||||
local cockpit_config="/etc/cockpit/cockpit.conf"
|
||||
local cockpit_pam="/etc/pam.d/cockpit"
|
||||
local failed=0
|
||||
|
||||
# Check if Cockpit is installed
|
||||
if ! command -v cockpit-ws >/dev/null 2>&1; then
|
||||
echo "⚠️ Cockpit not installed, skipping test"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check Cockpit configuration
|
||||
if [[ -f "$cockpit_config" ]]; then
|
||||
echo "✅ Cockpit configuration file exists"
|
||||
else
|
||||
echo "❌ Cockpit configuration file missing"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Check Cockpit PAM configuration
|
||||
if [[ -f "$cockpit_pam" ]] && grep -q "pam_google_authenticator.so" "$cockpit_pam"; then
|
||||
echo "✅ Cockpit PAM 2FA configured"
|
||||
else
|
||||
echo "❌ Cockpit PAM 2FA not configured"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_webmin_2fa_config() {
|
||||
echo "🔍 Testing Webmin 2FA configuration..."
|
||||
|
||||
local webmin_config="/etc/webmin/miniserv.conf"
|
||||
local failed=0
|
||||
|
||||
# Check if Webmin is installed
|
||||
if [[ ! -f "$webmin_config" ]]; then
|
||||
echo "⚠️ Webmin not installed, skipping test"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check Webmin 2FA settings
|
||||
if grep -q "^twofactor_provider=totp" "$webmin_config"; then
|
||||
echo "✅ Webmin TOTP provider configured"
|
||||
else
|
||||
echo "❌ Webmin TOTP provider not configured"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
if grep -q "^twofactor=1" "$webmin_config"; then
|
||||
echo "✅ Webmin 2FA enabled"
|
||||
else
|
||||
echo "❌ Webmin 2FA not enabled"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_user_2fa_setup() {
|
||||
echo "🔍 Testing user 2FA setup preparation..."
|
||||
|
||||
local users=("localuser" "root")
|
||||
local failed=0
|
||||
|
||||
for user in "${users[@]}"; do
|
||||
if id "$user" &>/dev/null; then
|
||||
# Check if setup script exists
|
||||
if [[ -f "/tmp/setup-2fa-$user.sh" ]]; then
|
||||
echo "✅ 2FA setup script exists for user: $user"
|
||||
else
|
||||
echo "❌ 2FA setup script missing for user: $user"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Check if instructions exist
|
||||
if [[ -f "/home/$user/2fa-setup-instructions.txt" ]]; then
|
||||
echo "✅ 2FA instructions exist for user: $user"
|
||||
else
|
||||
echo "❌ 2FA instructions missing for user: $user"
|
||||
((failed++))
|
||||
fi
|
||||
else
|
||||
echo "⚠️ User $user not found, skipping"
|
||||
fi
|
||||
done
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_service_status() {
|
||||
echo "🔍 Testing service status..."
|
||||
|
||||
local failed=0
|
||||
|
||||
# Test SSH service
|
||||
if systemctl is-active sshd >/dev/null 2>&1; then
|
||||
echo "✅ SSH service is running"
|
||||
else
|
||||
echo "❌ SSH service is not running"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Test SSH configuration
|
||||
if sshd -t 2>/dev/null; then
|
||||
echo "✅ SSH configuration is valid"
|
||||
else
|
||||
echo "❌ SSH configuration is invalid"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Test Cockpit service if installed
|
||||
if systemctl is-enabled cockpit.socket >/dev/null 2>&1; then
|
||||
if systemctl is-active cockpit.socket >/dev/null 2>&1; then
|
||||
echo "✅ Cockpit service is running"
|
||||
else
|
||||
echo "❌ Cockpit service is not running"
|
||||
((failed++))
|
||||
fi
|
||||
fi
|
||||
|
||||
# Test Webmin service if installed
|
||||
if systemctl is-enabled webmin >/dev/null 2>&1; then
|
||||
if systemctl is-active webmin >/dev/null 2>&1; then
|
||||
echo "✅ Webmin service is running"
|
||||
else
|
||||
echo "❌ Webmin service is not running"
|
||||
((failed++))
|
||||
fi
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_backup_existence() {
|
||||
echo "🔍 Testing backup existence..."
|
||||
|
||||
local backup_dir="/root/backup"
|
||||
local failed=0
|
||||
|
||||
if [[ -d "$backup_dir" ]]; then
|
||||
# Look for recent 2FA backups
|
||||
local recent_backups=$(find "$backup_dir" -name "2fa-*" -type d -newer /etc/ssh/sshd_config 2>/dev/null | wc -l)
|
||||
|
||||
if [[ $recent_backups -gt 0 ]]; then
|
||||
echo "✅ Recent 2FA backup found in $backup_dir"
|
||||
else
|
||||
echo "⚠️ No recent 2FA backups found"
|
||||
fi
|
||||
else
|
||||
echo "❌ Backup directory does not exist"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_2fa_enforcement() {
|
||||
echo "🔍 Testing 2FA enforcement level..."
|
||||
|
||||
local pam_sshd="/etc/pam.d/sshd"
|
||||
|
||||
# Check if nullok is used (allows users without 2FA)
|
||||
if grep -q "pam_google_authenticator.so nullok" "$pam_sshd"; then
|
||||
echo "⚠️ 2FA enforcement: GRADUAL (nullok allows users without 2FA)"
|
||||
echo " Users can log in without 2FA during setup phase"
|
||||
else
|
||||
echo "✅ 2FA enforcement: STRICT (all users must have 2FA)"
|
||||
echo " All users must have 2FA configured to log in"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# Main test execution
|
||||
function main() {
|
||||
echo "🔒 Running Two-Factor Authentication Validation Tests"
|
||||
echo "=================================================="
|
||||
|
||||
local total_failures=0
|
||||
|
||||
# Run all 2FA validation tests
|
||||
test_2fa_packages || ((total_failures++))
|
||||
test_ssh_2fa_config || ((total_failures++))
|
||||
test_pam_2fa_config || ((total_failures++))
|
||||
test_cockpit_2fa_config || ((total_failures++))
|
||||
test_webmin_2fa_config || ((total_failures++))
|
||||
test_user_2fa_setup || ((total_failures++))
|
||||
test_service_status || ((total_failures++))
|
||||
test_backup_existence || ((total_failures++))
|
||||
test_2fa_enforcement || ((total_failures++))
|
||||
|
||||
echo "=================================================="
|
||||
|
||||
if [[ $total_failures -eq 0 ]]; then
|
||||
echo "✅ All 2FA validation tests passed"
|
||||
echo ""
|
||||
echo "📋 Next Steps:"
|
||||
echo "1. Run user setup scripts: /tmp/setup-2fa-*.sh"
|
||||
echo "2. Test 2FA login from another terminal"
|
||||
echo "3. Remove nullok from PAM config for strict enforcement"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ $total_failures 2FA validation tests failed"
|
||||
echo ""
|
||||
echo "🔧 Troubleshooting:"
|
||||
echo "1. Re-run secharden-2fa.sh script"
|
||||
echo "2. Check system logs: journalctl -u sshd"
|
||||
echo "3. Verify package installation"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run main if executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
143
Project-Tests/security/https-enforcement.sh
Executable file
143
Project-Tests/security/https-enforcement.sh
Executable file
@@ -0,0 +1,143 @@
|
||||
#!/bin/bash
|
||||
|
||||
# HTTPS Enforcement Security Test
|
||||
# Validates that all scripts use HTTPS instead of HTTP
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../.."
|
||||
|
||||
function test_no_http_urls() {
|
||||
echo "🔍 Checking for HTTP URLs in scripts..."
|
||||
|
||||
local http_violations=0
|
||||
local script_dirs=("ProjectCode" "Framework-Includes" "Project-Includes")
|
||||
|
||||
for dir in "${script_dirs[@]}"; do
|
||||
if [[ -d "$PROJECT_ROOT/$dir" ]]; then
|
||||
# Find HTTP URLs in shell scripts (excluding comments)
|
||||
while IFS= read -r -d '' file; do
|
||||
if grep -n "http://" "$file" | grep -v "^[[:space:]]*#" | grep -v "schema.org" | grep -v "xmlns"; then
|
||||
echo "❌ HTTP URL found in: $file"
|
||||
((http_violations++))
|
||||
fi
|
||||
done < <(find "$PROJECT_ROOT/$dir" -name "*.sh" -type f -print0)
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ $http_violations -eq 0 ]]; then
|
||||
echo "✅ No HTTP URLs found in active scripts"
|
||||
return 0
|
||||
else
|
||||
echo "❌ Found $http_violations HTTP URL violations"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function test_https_urls_valid() {
|
||||
echo "🔍 Validating HTTPS URLs are accessible..."
|
||||
|
||||
local script_dirs=("ProjectCode" "Framework-Includes" "Project-Includes")
|
||||
local https_failures=0
|
||||
|
||||
# Extract HTTPS URLs from scripts
|
||||
for dir in "${script_dirs[@]}"; do
|
||||
if [[ -d "$PROJECT_ROOT/$dir" ]]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
# Extract HTTPS URLs from non-comment lines
|
||||
grep -o "https://[^[:space:]\"']*" "$file" | grep -v "schema.org" | while read -r url; do
|
||||
# Test connectivity with timeout
|
||||
if timeout 30 curl -s --head --fail "$url" >/dev/null 2>&1; then
|
||||
echo "✅ HTTPS URL accessible: $url"
|
||||
else
|
||||
echo "❌ HTTPS URL not accessible: $url"
|
||||
((https_failures++))
|
||||
fi
|
||||
done
|
||||
done < <(find "$PROJECT_ROOT/$dir" -name "*.sh" -type f -print0)
|
||||
fi
|
||||
done
|
||||
|
||||
return $https_failures
|
||||
}
|
||||
|
||||
function test_ssl_certificate_validation() {
|
||||
echo "🔍 Testing SSL certificate validation..."
|
||||
|
||||
local test_urls=(
|
||||
"https://archive.ubuntu.com"
|
||||
"https://linux.dell.com"
|
||||
"https://download.proxmox.com"
|
||||
)
|
||||
|
||||
local ssl_failures=0
|
||||
|
||||
for url in "${test_urls[@]}"; do
|
||||
# Test with strict SSL verification
|
||||
if curl -s --fail --ssl-reqd --cert-status "$url" >/dev/null 2>&1; then
|
||||
echo "✅ SSL certificate valid: $url"
|
||||
else
|
||||
echo "❌ SSL certificate validation failed: $url"
|
||||
((ssl_failures++))
|
||||
fi
|
||||
done
|
||||
|
||||
return $ssl_failures
|
||||
}
|
||||
|
||||
function test_deployment_security() {
|
||||
echo "🔍 Testing deployment method security..."
|
||||
|
||||
local readme_file="$PROJECT_ROOT/README.md"
|
||||
|
||||
if [[ -f "$readme_file" ]]; then
|
||||
# Check for insecure curl | bash patterns
|
||||
if grep -q "curl.*|.*bash" "$readme_file" || grep -q "wget.*|.*bash" "$readme_file"; then
|
||||
echo "❌ Insecure deployment method found in README.md"
|
||||
return 1
|
||||
else
|
||||
echo "✅ Secure deployment method in README.md"
|
||||
fi
|
||||
|
||||
# Check for git clone method
|
||||
if grep -q "git clone" "$readme_file"; then
|
||||
echo "✅ Git clone deployment method found"
|
||||
return 0
|
||||
else
|
||||
echo "⚠️ No git clone method found in README.md"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
echo "❌ README.md not found"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Main test execution
|
||||
function main() {
|
||||
echo "🔒 Running HTTPS Enforcement Security Tests"
|
||||
echo "=========================================="
|
||||
|
||||
local total_failures=0
|
||||
|
||||
# Run all security tests
|
||||
test_no_http_urls || ((total_failures++))
|
||||
test_https_urls_valid || ((total_failures++))
|
||||
test_ssl_certificate_validation || ((total_failures++))
|
||||
test_deployment_security || ((total_failures++))
|
||||
|
||||
echo "=========================================="
|
||||
|
||||
if [[ $total_failures -eq 0 ]]; then
|
||||
echo "✅ All HTTPS enforcement security tests passed"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ $total_failures HTTPS enforcement security tests failed"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run main if executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
176
Project-Tests/unit/framework-functions.sh
Executable file
176
Project-Tests/unit/framework-functions.sh
Executable file
@@ -0,0 +1,176 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Framework Functions Unit Tests
|
||||
# Tests core framework functionality
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../.."
|
||||
|
||||
# Source framework functions
|
||||
source "$PROJECT_ROOT/Framework-Includes/Logging.sh" 2>/dev/null || echo "Warning: Logging.sh not found"
|
||||
source "$PROJECT_ROOT/Framework-Includes/PrettyPrint.sh" 2>/dev/null || echo "Warning: PrettyPrint.sh not found"
|
||||
source "$PROJECT_ROOT/Framework-Includes/ErrorHandling.sh" 2>/dev/null || echo "Warning: ErrorHandling.sh not found"
|
||||
|
||||
function test_logging_functions() {
|
||||
echo "🔍 Testing logging functions..."
|
||||
|
||||
local test_log="/tmp/test-log-$$"
|
||||
|
||||
# Test if logging functions exist and work
|
||||
if command -v log_info >/dev/null 2>&1; then
|
||||
log_info "Test info message" 2>/dev/null || true
|
||||
echo "✅ log_info function exists"
|
||||
else
|
||||
echo "❌ log_info function missing"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if command -v log_error >/dev/null 2>&1; then
|
||||
log_error "Test error message" 2>/dev/null || true
|
||||
echo "✅ log_error function exists"
|
||||
else
|
||||
echo "❌ log_error function missing"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f "$test_log"
|
||||
return 0
|
||||
}
|
||||
|
||||
function test_pretty_print_functions() {
|
||||
echo "🔍 Testing pretty print functions..."
|
||||
|
||||
# Test if pretty print functions exist
|
||||
if command -v print_info >/dev/null 2>&1; then
|
||||
print_info "Test info message" >/dev/null 2>&1 || true
|
||||
echo "✅ print_info function exists"
|
||||
else
|
||||
echo "❌ print_info function missing"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if command -v print_error >/dev/null 2>&1; then
|
||||
print_error "Test error message" >/dev/null 2>&1 || true
|
||||
echo "✅ print_error function exists"
|
||||
else
|
||||
echo "❌ print_error function missing"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if command -v print_success >/dev/null 2>&1; then
|
||||
print_success "Test success message" >/dev/null 2>&1 || true
|
||||
echo "✅ print_success function exists"
|
||||
else
|
||||
echo "❌ print_success function missing"
|
||||
return 1
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
function test_error_handling() {
|
||||
echo "🔍 Testing error handling..."
|
||||
|
||||
# Test if error handling functions exist
|
||||
if command -v handle_error >/dev/null 2>&1; then
|
||||
echo "✅ handle_error function exists"
|
||||
else
|
||||
echo "❌ handle_error function missing"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Test bash strict mode is set
|
||||
if [[ "$-" == *e* ]]; then
|
||||
echo "✅ Bash strict mode (set -e) is enabled"
|
||||
else
|
||||
echo "❌ Bash strict mode (set -e) not enabled"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [[ "$-" == *u* ]]; then
|
||||
echo "✅ Bash unset variable checking (set -u) is enabled"
|
||||
else
|
||||
echo "❌ Bash unset variable checking (set -u) not enabled"
|
||||
return 1
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
function test_framework_includes_exist() {
|
||||
echo "🔍 Testing framework includes exist..."
|
||||
|
||||
local required_includes=(
|
||||
"Logging.sh"
|
||||
"PrettyPrint.sh"
|
||||
"ErrorHandling.sh"
|
||||
"PreflightCheck.sh"
|
||||
)
|
||||
|
||||
local missing_files=0
|
||||
|
||||
for include_file in "${required_includes[@]}"; do
|
||||
if [[ -f "$PROJECT_ROOT/Framework-Includes/$include_file" ]]; then
|
||||
echo "✅ Framework include exists: $include_file"
|
||||
else
|
||||
echo "❌ Framework include missing: $include_file"
|
||||
((missing_files++))
|
||||
fi
|
||||
done
|
||||
|
||||
return $missing_files
|
||||
}
|
||||
|
||||
function test_syntax_validation() {
|
||||
echo "🔍 Testing script syntax validation..."
|
||||
|
||||
local syntax_errors=0
|
||||
local script_dirs=("Framework-Includes" "Project-Includes" "ProjectCode")
|
||||
|
||||
for dir in "${script_dirs[@]}"; do
|
||||
if [[ -d "$PROJECT_ROOT/$dir" ]]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
if bash -n "$file" 2>/dev/null; then
|
||||
echo "✅ Syntax valid: $(basename "$file")"
|
||||
else
|
||||
echo "❌ Syntax error in: $(basename "$file")"
|
||||
((syntax_errors++))
|
||||
fi
|
||||
done < <(find "$PROJECT_ROOT/$dir" -name "*.sh" -type f -print0)
|
||||
fi
|
||||
done
|
||||
|
||||
return $syntax_errors
|
||||
}
|
||||
|
||||
# Main test execution
|
||||
function main() {
|
||||
echo "🧪 Running Framework Functions Unit Tests"
|
||||
echo "========================================"
|
||||
|
||||
local total_failures=0
|
||||
|
||||
# Run all unit tests
|
||||
test_framework_includes_exist || ((total_failures++))
|
||||
test_logging_functions || ((total_failures++))
|
||||
test_pretty_print_functions || ((total_failures++))
|
||||
test_error_handling || ((total_failures++))
|
||||
test_syntax_validation || ((total_failures++))
|
||||
|
||||
echo "========================================"
|
||||
|
||||
if [[ $total_failures -eq 0 ]]; then
|
||||
echo "✅ All framework function unit tests passed"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ $total_failures framework function unit tests failed"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run main if executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
286
Project-Tests/unit/safe-download.sh
Executable file
286
Project-Tests/unit/safe-download.sh
Executable file
@@ -0,0 +1,286 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Safe Download Framework Unit Tests
|
||||
# Tests the SafeDownload.sh framework functionality
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_ROOT="$(dirname "$(realpath "${BASH_SOURCE[0]}")")/../.."
|
||||
|
||||
# Source framework functions
|
||||
source "$PROJECT_ROOT/Framework-Includes/SafeDownload.sh"
|
||||
|
||||
function test_network_connectivity() {
|
||||
echo "🔍 Testing network connectivity..."
|
||||
|
||||
if test_network_connectivity; then
|
||||
echo "✅ Network connectivity test passed"
|
||||
return 0
|
||||
else
|
||||
echo "❌ Network connectivity test failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function test_url_accessibility() {
|
||||
echo "🔍 Testing URL accessibility..."
|
||||
|
||||
local test_urls=(
|
||||
"https://archive.ubuntu.com"
|
||||
"https://github.com"
|
||||
)
|
||||
|
||||
local failed=0
|
||||
|
||||
for url in "${test_urls[@]}"; do
|
||||
if check_url_accessibility "$url"; then
|
||||
echo "✅ URL accessible: $url"
|
||||
else
|
||||
echo "❌ URL not accessible: $url"
|
||||
((failed++))
|
||||
fi
|
||||
done
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_safe_download() {
|
||||
echo "🔍 Testing safe download functionality..."
|
||||
|
||||
local test_url="https://raw.githubusercontent.com/torvalds/linux/master/README"
|
||||
local test_dest="/tmp/test-download-$$"
|
||||
local failed=0
|
||||
|
||||
# Test successful download
|
||||
if safe_download "$test_url" "$test_dest"; then
|
||||
echo "✅ Safe download successful"
|
||||
|
||||
# Verify file exists and has content
|
||||
if [[ -f "$test_dest" && -s "$test_dest" ]]; then
|
||||
echo "✅ Downloaded file exists and has content"
|
||||
else
|
||||
echo "❌ Downloaded file is missing or empty"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f "$test_dest"
|
||||
else
|
||||
echo "❌ Safe download failed"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Test download with invalid URL
|
||||
if safe_download "https://invalid.example.com/nonexistent" "/tmp/test-invalid-$$" 2>/dev/null; then
|
||||
echo "❌ Invalid URL download should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Invalid URL download failed as expected"
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_checksum_verification() {
|
||||
echo "🔍 Testing checksum verification..."
|
||||
|
||||
local test_file="/tmp/test-checksum-$$"
|
||||
local test_content="Hello, World!"
|
||||
local expected_checksum="dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"
|
||||
local failed=0
|
||||
|
||||
# Create test file with known content
|
||||
echo -n "$test_content" > "$test_file"
|
||||
|
||||
# Test correct checksum
|
||||
if verify_checksum "$test_file" "$expected_checksum"; then
|
||||
echo "✅ Correct checksum verification passed"
|
||||
else
|
||||
echo "❌ Correct checksum verification failed"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
# Test incorrect checksum
|
||||
if verify_checksum "$test_file" "invalid_checksum" 2>/dev/null; then
|
||||
echo "❌ Incorrect checksum should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Incorrect checksum verification failed as expected"
|
||||
fi
|
||||
|
||||
# Test missing file
|
||||
if verify_checksum "/tmp/nonexistent-file-$$" "$expected_checksum" 2>/dev/null; then
|
||||
echo "❌ Missing file checksum should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Missing file checksum verification failed as expected"
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f "$test_file"
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_batch_download() {
|
||||
echo "🔍 Testing batch download functionality..."
|
||||
|
||||
# Create test download map
|
||||
declare -A test_downloads=(
|
||||
["https://raw.githubusercontent.com/torvalds/linux/master/README"]="/tmp/batch-test-1-$$"
|
||||
["https://raw.githubusercontent.com/torvalds/linux/master/COPYING"]="/tmp/batch-test-2-$$"
|
||||
)
|
||||
|
||||
local failed=0
|
||||
|
||||
# Test batch download
|
||||
if batch_download test_downloads; then
|
||||
echo "✅ Batch download successful"
|
||||
|
||||
# Verify all files were downloaded
|
||||
for file in "${test_downloads[@]}"; do
|
||||
if [[ -f "$file" && -s "$file" ]]; then
|
||||
echo "✅ Batch file downloaded: $(basename "$file")"
|
||||
else
|
||||
echo "❌ Batch file missing: $(basename "$file")"
|
||||
((failed++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Cleanup
|
||||
for file in "${test_downloads[@]}"; do
|
||||
rm -f "$file"
|
||||
done
|
||||
else
|
||||
echo "❌ Batch download failed"
|
||||
((failed++))
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_config_backup_and_restore() {
|
||||
echo "🔍 Testing config backup and restore..."
|
||||
|
||||
local test_config="/tmp/test-config-$$"
|
||||
local original_content="Original configuration"
|
||||
local failed=0
|
||||
|
||||
# Create original config file
|
||||
echo "$original_content" > "$test_config"
|
||||
|
||||
# Test safe config download (this will fail with invalid URL, triggering restore)
|
||||
if safe_config_download "https://invalid.example.com/config" "$test_config" ".test-backup" 2>/dev/null; then
|
||||
echo "❌ Invalid config download should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Invalid config download failed as expected"
|
||||
|
||||
# Verify original file was restored
|
||||
if [[ -f "$test_config" ]] && grep -q "$original_content" "$test_config"; then
|
||||
echo "✅ Original config was restored after failed download"
|
||||
else
|
||||
echo "❌ Original config was not restored properly"
|
||||
((failed++))
|
||||
fi
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f "$test_config" "$test_config.test-backup"
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_download_error_handling() {
|
||||
echo "🔍 Testing download error handling..."
|
||||
|
||||
local failed=0
|
||||
|
||||
# Test download with missing parameters
|
||||
if safe_download "" "/tmp/test" 2>/dev/null; then
|
||||
echo "❌ Download with empty URL should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Download with empty URL failed as expected"
|
||||
fi
|
||||
|
||||
if safe_download "https://example.com" "" 2>/dev/null; then
|
||||
echo "❌ Download with empty destination should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Download with empty destination failed as expected"
|
||||
fi
|
||||
|
||||
# Test download to read-only location (should fail)
|
||||
if safe_download "https://github.com" "/test-readonly-$$" 2>/dev/null; then
|
||||
echo "❌ Download to read-only location should have failed"
|
||||
((failed++))
|
||||
else
|
||||
echo "✅ Download to read-only location failed as expected"
|
||||
fi
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_download_performance() {
|
||||
echo "🔍 Testing download performance..."
|
||||
|
||||
local test_url="https://raw.githubusercontent.com/torvalds/linux/master/README"
|
||||
local test_dest="/tmp/perf-test-$$"
|
||||
local start_time end_time duration
|
||||
|
||||
start_time=$(date +%s)
|
||||
|
||||
if safe_download "$test_url" "$test_dest"; then
|
||||
end_time=$(date +%s)
|
||||
duration=$((end_time - start_time))
|
||||
|
||||
echo "✅ Download completed in ${duration}s"
|
||||
|
||||
if [[ $duration -gt 30 ]]; then
|
||||
echo "⚠️ Download took longer than expected (>30s)"
|
||||
else
|
||||
echo "✅ Download performance acceptable"
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f "$test_dest"
|
||||
return 0
|
||||
else
|
||||
echo "❌ Performance test download failed"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Main test execution
|
||||
function main() {
|
||||
echo "🧪 Running Safe Download Framework Unit Tests"
|
||||
echo "==========================================="
|
||||
|
||||
local total_failures=0
|
||||
|
||||
# Run all tests
|
||||
test_network_connectivity || ((total_failures++))
|
||||
test_url_accessibility || ((total_failures++))
|
||||
test_safe_download || ((total_failures++))
|
||||
test_checksum_verification || ((total_failures++))
|
||||
test_batch_download || ((total_failures++))
|
||||
test_config_backup_and_restore || ((total_failures++))
|
||||
test_download_error_handling || ((total_failures++))
|
||||
test_download_performance || ((total_failures++))
|
||||
|
||||
echo "==========================================="
|
||||
|
||||
if [[ $total_failures -eq 0 ]]; then
|
||||
echo "✅ All safe download framework tests passed"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ $total_failures safe download framework tests failed"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run main if executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
142
Project-Tests/validation/system-requirements.sh
Executable file
142
Project-Tests/validation/system-requirements.sh
Executable file
@@ -0,0 +1,142 @@
|
||||
#!/bin/bash
|
||||
|
||||
# System Requirements Validation Test
|
||||
# Validates minimum system requirements before deployment
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Test configuration
|
||||
MIN_RAM_GB=2
|
||||
MIN_DISK_GB=10
|
||||
REQUIRED_COMMANDS=("curl" "wget" "git" "systemctl" "apt-get")
|
||||
|
||||
# Test functions
|
||||
function test_memory_requirements() {
|
||||
local total_mem_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}')
|
||||
local total_mem_gb=$((total_mem_kb / 1024 / 1024))
|
||||
|
||||
if [[ $total_mem_gb -ge $MIN_RAM_GB ]]; then
|
||||
echo "✅ Memory requirement met: ${total_mem_gb}GB >= ${MIN_RAM_GB}GB"
|
||||
return 0
|
||||
else
|
||||
echo "❌ Memory requirement not met: ${total_mem_gb}GB < ${MIN_RAM_GB}GB"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function test_disk_space() {
|
||||
local available_gb=$(df / | tail -1 | awk '{print int($4/1024/1024)}')
|
||||
|
||||
if [[ $available_gb -ge $MIN_DISK_GB ]]; then
|
||||
echo "✅ Disk space requirement met: ${available_gb}GB >= ${MIN_DISK_GB}GB"
|
||||
return 0
|
||||
else
|
||||
echo "❌ Disk space requirement not met: ${available_gb}GB < ${MIN_DISK_GB}GB"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function test_required_commands() {
|
||||
local failed=0
|
||||
|
||||
for cmd in "${REQUIRED_COMMANDS[@]}"; do
|
||||
if command -v "$cmd" >/dev/null 2>&1; then
|
||||
echo "✅ Required command available: $cmd"
|
||||
else
|
||||
echo "❌ Required command missing: $cmd"
|
||||
((failed++))
|
||||
fi
|
||||
done
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_os_compatibility() {
|
||||
if [[ -f /etc/os-release ]]; then
|
||||
local os_id=$(grep "^ID=" /etc/os-release | cut -d'=' -f2 | tr -d '"')
|
||||
local os_version=$(grep "^VERSION_ID=" /etc/os-release | cut -d'=' -f2 | tr -d '"')
|
||||
|
||||
case "$os_id" in
|
||||
ubuntu|debian)
|
||||
echo "✅ OS compatibility: $os_id $os_version (supported)"
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
echo "⚠️ OS compatibility: $os_id $os_version (may work, not fully tested)"
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
else
|
||||
echo "❌ Cannot determine OS version"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
function test_network_connectivity() {
|
||||
local test_urls=(
|
||||
"https://archive.ubuntu.com"
|
||||
"https://linux.dell.com"
|
||||
"https://download.proxmox.com"
|
||||
"https://github.com"
|
||||
)
|
||||
|
||||
local failed=0
|
||||
|
||||
for url in "${test_urls[@]}"; do
|
||||
if curl -s --connect-timeout 10 --max-time 30 "$url" >/dev/null 2>&1; then
|
||||
echo "✅ Network connectivity: $url"
|
||||
else
|
||||
echo "❌ Network connectivity failed: $url"
|
||||
((failed++))
|
||||
fi
|
||||
done
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
function test_permissions() {
|
||||
local test_dirs=("/etc" "/usr/local/bin" "/var/log")
|
||||
local failed=0
|
||||
|
||||
for dir in "${test_dirs[@]}"; do
|
||||
if [[ -w "$dir" ]]; then
|
||||
echo "✅ Write permission: $dir"
|
||||
else
|
||||
echo "❌ Write permission denied: $dir"
|
||||
((failed++))
|
||||
fi
|
||||
done
|
||||
|
||||
return $failed
|
||||
}
|
||||
|
||||
# Main test execution
|
||||
function main() {
|
||||
echo "🔍 Running System Requirements Validation"
|
||||
echo "========================================"
|
||||
|
||||
local total_failures=0
|
||||
|
||||
# Run all validation tests
|
||||
test_memory_requirements || ((total_failures++))
|
||||
test_disk_space || ((total_failures++))
|
||||
test_required_commands || ((total_failures++))
|
||||
test_os_compatibility || ((total_failures++))
|
||||
test_network_connectivity || ((total_failures++))
|
||||
test_permissions || ((total_failures++))
|
||||
|
||||
echo "========================================"
|
||||
|
||||
if [[ $total_failures -eq 0 ]]; then
|
||||
echo "✅ All system requirements validation tests passed"
|
||||
exit 0
|
||||
else
|
||||
echo "❌ $total_failures system requirements validation tests failed"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run main if executed directly
|
||||
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||
main "$@"
|
||||
fi
|
9
ProjectCode/Agents/librenms/check_mk.socket
Normal file
9
ProjectCode/Agents/librenms/check_mk.socket
Normal file
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Check_MK LibreNMS Agent Socket
|
||||
|
||||
[Socket]
|
||||
ListenStream=6556
|
||||
Accept=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=sockets.target
|
7
ProjectCode/Agents/librenms/check_mk@.service
Normal file
7
ProjectCode/Agents/librenms/check_mk@.service
Normal file
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Check_MK LibreNMS Agent Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/check_mk_agent
|
||||
StandardOutput=socket
|
659
ProjectCode/Agents/librenms/check_mk_agent
Normal file
659
ProjectCode/Agents/librenms/check_mk_agent
Normal file
@@ -0,0 +1,659 @@
|
||||
#!/bin/bash
|
||||
# +------------------------------------------------------------------+
|
||||
# | ____ _ _ __ __ _ __ |
|
||||
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
|
||||
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
|
||||
# | | |___| | | | __/ (__| < | | | | . \ |
|
||||
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
|
||||
# | |
|
||||
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
|
||||
# +------------------------------------------------------------------+
|
||||
#
|
||||
# This file is part of Check_MK.
|
||||
# The official homepage is at http://mathias-kettner.de/check_mk.
|
||||
#
|
||||
# check_mk is free software; you can redistribute it and/or modify it
|
||||
# under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation in version 2. check_mk is distributed
|
||||
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
|
||||
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
|
||||
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
|
||||
# ails. You should have received a copy of the GNU General Public
|
||||
# License along with GNU Make; see the file COPYING. If not, write
|
||||
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
|
||||
# Boston, MA 02110-1301 USA.
|
||||
|
||||
# Remove locale settings to eliminate localized outputs where possible
|
||||
export LC_ALL=C
|
||||
unset LANG
|
||||
|
||||
export MK_LIBDIR="/usr/lib/check_mk_agent"
|
||||
export MK_CONFDIR="/etc/check_mk"
|
||||
export MK_VARDIR="/var/lib/check_mk_agent"
|
||||
|
||||
# Provide information about the remote host. That helps when data
|
||||
# is being sent only once to each remote host.
|
||||
if [ "$REMOTE_HOST" ] ; then
|
||||
export REMOTE=$REMOTE_HOST
|
||||
elif [ "$SSH_CLIENT" ] ; then
|
||||
export REMOTE=${SSH_CLIENT%% *}
|
||||
fi
|
||||
|
||||
# Make sure, locally installed binaries are found
|
||||
PATH=$PATH:/usr/local/bin
|
||||
|
||||
# All executables in PLUGINSDIR will simply be executed and their
|
||||
# ouput appended to the output of the agent. Plugins define their own
|
||||
# sections and must output headers with '<<<' and '>>>'
|
||||
PLUGINSDIR=$MK_LIBDIR/plugins
|
||||
|
||||
# All executables in LOCALDIR will by executabled and their
|
||||
# output inserted into the section <<<local>>>. Please
|
||||
# refer to online documentation for details about local checks.
|
||||
LOCALDIR=$MK_LIBDIR/local
|
||||
|
||||
# All files in SPOOLDIR will simply appended to the agent
|
||||
# output if they are not outdated (see below)
|
||||
SPOOLDIR=$MK_VARDIR/spool
|
||||
|
||||
# close standard input (for security reasons) and stderr
|
||||
if [ "$1" = -d ]
|
||||
then
|
||||
set -xv
|
||||
else
|
||||
exec </dev/null 2>/dev/null
|
||||
fi
|
||||
|
||||
# Runs a command asynchronous by use of a cache file
|
||||
function run_cached () {
|
||||
local section=
|
||||
if [ "$1" = -s ] ; then local section="echo '<<<$2>>>' ; " ; shift ; fi
|
||||
local NAME=$1
|
||||
local MAXAGE=$2
|
||||
shift 2
|
||||
local CMDLINE="$section$@"
|
||||
|
||||
if [ ! -d $MK_VARDIR/cache ]; then mkdir -p $MK_VARDIR/cache ; fi
|
||||
CACHEFILE="$MK_VARDIR/cache/$NAME.cache"
|
||||
|
||||
# Check if the creation of the cache takes suspiciously long and return
|
||||
# nothing if the age (access time) of $CACHEFILE.new is twice the MAXAGE
|
||||
local NOW=$(date +%s)
|
||||
if [ -e "$CACHEFILE.new" ] ; then
|
||||
local CF_ATIME=$(stat -c %X "$CACHEFILE.new")
|
||||
if [ $((NOW - CF_ATIME)) -ge $((MAXAGE * 2)) ] ; then
|
||||
# Kill the process still accessing that file in case
|
||||
# it is still running. This avoids overlapping processes!
|
||||
fuser -k -9 "$CACHEFILE.new" >/dev/null 2>&1
|
||||
rm -f "$CACHEFILE.new"
|
||||
return
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if cache file exists and is recent enough
|
||||
if [ -s "$CACHEFILE" ] ; then
|
||||
local MTIME=$(stat -c %Y "$CACHEFILE")
|
||||
if [ $((NOW - MTIME)) -le $MAXAGE ] ; then local USE_CACHEFILE=1 ; fi
|
||||
# Output the file in any case, even if it is
|
||||
# outdated. The new file will not yet be available
|
||||
cat "$CACHEFILE"
|
||||
fi
|
||||
|
||||
# Cache file outdated and new job not yet running? Start it
|
||||
if [ -z "$USE_CACHEFILE" -a ! -e "$CACHEFILE.new" ] ; then
|
||||
echo "set -o noclobber ; exec > \"$CACHEFILE.new\" || exit 1 ; $CMDLINE && mv \"$CACHEFILE.new\" \"$CACHEFILE\" || rm -f \"$CACHEFILE\" \"$CACHEFILE.new\"" | nohup bash >/dev/null 2>&1 &
|
||||
fi
|
||||
}
|
||||
|
||||
# Make run_cached available for subshells (plugins, local checks, etc.)
|
||||
export -f run_cached
|
||||
|
||||
echo '<<<check_mk>>>'
|
||||
echo Version: 1.2.6b5
|
||||
echo AgentOS: linux
|
||||
echo AgentDirectory: $MK_CONFDIR
|
||||
echo DataDirectory: $MK_VARDIR
|
||||
echo SpoolDirectory: $SPOOLDIR
|
||||
echo PluginsDirectory: $PLUGINSDIR
|
||||
echo LocalDirectory: $LOCALDIR
|
||||
|
||||
# If we are called via xinetd, try to find only_from configuration
|
||||
if [ -n "$REMOTE_HOST" ]
|
||||
then
|
||||
echo -n 'OnlyFrom: '
|
||||
echo $(sed -n '/^service[[:space:]]*check_mk/,/}/s/^[[:space:]]*only_from[[:space:]]*=[[:space:]]*\(.*\)/\1/p' /etc/xinetd.d/* | head -n1)
|
||||
fi
|
||||
|
||||
# Print out Partitions / Filesystems. (-P gives non-wrapped POSIXed output)
|
||||
# Heads up: NFS-mounts are generally supressed to avoid agent hangs.
|
||||
# If hard NFS mounts are configured or you have too large nfs retry/timeout
|
||||
# settings, accessing those mounts from the agent would leave you with
|
||||
# thousands of agent processes and, ultimately, a dead monitored system.
|
||||
# These should generally be monitored on the NFS server, not on the clients.
|
||||
|
||||
echo '<<<df>>>'
|
||||
# The exclusion list is getting a bit of a problem. -l should hide any remote FS but seems
|
||||
# to be all but working.
|
||||
excludefs="-x smbfs -x cifs -x iso9660 -x udf -x nfsv4 -x nfs -x mvfs -x zfs"
|
||||
df -PTlk $excludefs | sed 1d
|
||||
|
||||
# df inodes information
|
||||
echo '<<<df>>>'
|
||||
echo '[df_inodes_start]'
|
||||
df -PTli $excludefs | sed 1d
|
||||
echo '[df_inodes_end]'
|
||||
|
||||
# Filesystem usage for ZFS
|
||||
if type zfs > /dev/null 2>&1 ; then
|
||||
echo '<<<zfsget>>>'
|
||||
zfs get -Hp name,quota,used,avail,mountpoint,type -t filesystem,volume || \
|
||||
zfs get -Hp name,quota,used,avail,mountpoint,type
|
||||
echo '[df]'
|
||||
df -PTlk -t zfs | sed 1d
|
||||
fi
|
||||
|
||||
# Check NFS mounts by accessing them with stat -f (System
|
||||
# call statfs()). If this lasts more then 2 seconds we
|
||||
# consider it as hanging. We need waitmax.
|
||||
if type waitmax >/dev/null
|
||||
then
|
||||
STAT_VERSION=$(stat --version | head -1 | cut -d" " -f4)
|
||||
STAT_BROKE="5.3.0"
|
||||
|
||||
echo '<<<nfsmounts>>>'
|
||||
sed -n '/ nfs4\? /s/[^ ]* \([^ ]*\) .*/\1/p' < /proc/mounts |
|
||||
sed 's/\\040/ /g' |
|
||||
while read MP
|
||||
do
|
||||
if [ $STAT_VERSION != $STAT_BROKE ]; then
|
||||
waitmax -s 9 2 stat -f -c "$MP ok %b %f %a %s" "$MP" || \
|
||||
echo "$MP hanging 0 0 0 0"
|
||||
else
|
||||
waitmax -s 9 2 stat -f -c "$MP ok %b %f %a %s" "$MP" && \
|
||||
printf '\n'|| echo "$MP hanging 0 0 0 0"
|
||||
fi
|
||||
done
|
||||
|
||||
echo '<<<cifsmounts>>>'
|
||||
sed -n '/ cifs\? /s/[^ ]* \([^ ]*\) .*/\1/p' < /proc/mounts |
|
||||
sed 's/\\040/ /g' |
|
||||
while read MP
|
||||
do
|
||||
if [ $STAT_VERSION != $STAT_BROKE ]; then
|
||||
waitmax -s 9 2 stat -f -c "$MP ok %b %f %a %s" "$MP" || \
|
||||
echo "$MP hanging 0 0 0 0"
|
||||
else
|
||||
waitmax -s 9 2 stat -f -c "$MP ok %b %f %a %s" "$MP" && \
|
||||
printf '\n'|| echo "$MP hanging 0 0 0 0"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Check mount options. Filesystems may switch to 'ro' in case
|
||||
# of a read error.
|
||||
echo '<<<mounts>>>'
|
||||
grep ^/dev < /proc/mounts
|
||||
|
||||
# processes including username, without kernel processes
|
||||
echo '<<<ps>>>'
|
||||
ps ax -o user,vsz,rss,cputime,pid,command --columns 10000 | sed -e 1d -e 's/ *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) */(\1,\2,\3,\4,\5) /'
|
||||
|
||||
# Memory usage
|
||||
echo '<<<mem>>>'
|
||||
egrep -v '^Swap:|^Mem:|total:' < /proc/meminfo
|
||||
|
||||
# Load and number of processes
|
||||
echo '<<<cpu>>>'
|
||||
echo "$(cat /proc/loadavg) $(grep -E '^CPU|^processor' < /proc/cpuinfo | wc -l)"
|
||||
|
||||
# Uptime
|
||||
echo '<<<uptime>>>'
|
||||
cat /proc/uptime
|
||||
|
||||
|
||||
# New variant: Information about speed and state in one section
|
||||
echo '<<<lnx_if:sep(58)>>>'
|
||||
sed 1,2d /proc/net/dev
|
||||
if type ethtool > /dev/null
|
||||
then
|
||||
for eth in $(sed -e 1,2d < /proc/net/dev | cut -d':' -f1 | sort)
|
||||
do
|
||||
echo "[$eth]"
|
||||
ethtool $eth | egrep '(Speed|Duplex|Link detected|Auto-negotiation):'
|
||||
echo -en "\tAddress: " ; cat /sys/class/net/$eth/address ; echo
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Current state of bonding interfaces
|
||||
if [ -e /proc/net/bonding ] ; then
|
||||
echo '<<<lnx_bonding:sep(58)>>>'
|
||||
pushd /proc/net/bonding > /dev/null ; head -v -n 1000 * ; popd
|
||||
fi
|
||||
|
||||
# Same for Open vSwitch bonding
|
||||
if type ovs-appctl > /dev/null ; then
|
||||
echo '<<<ovs_bonding:sep(58)>>>'
|
||||
for bond in $(ovs-appctl bond/list | sed -e 1d | cut -f2) ; do
|
||||
echo "[$bond]"
|
||||
ovs-appctl bond/show $bond
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Number of TCP connections in the various states
|
||||
echo '<<<tcp_conn_stats>>>'
|
||||
# waitmax 10 netstat -nt | awk ' /^tcp/ { c[$6]++; } END { for (x in c) { print x, c[x]; } }'
|
||||
# New implementation: netstat is very slow for large TCP tables
|
||||
cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk ' /:/ { c[$4]++; } END { for (x in c) { print x, c[x]; } }'
|
||||
|
||||
# Linux Multipathing
|
||||
if type multipath >/dev/null ; then
|
||||
echo '<<<multipath>>>'
|
||||
multipath -l
|
||||
fi
|
||||
|
||||
# Performancecounter Platten
|
||||
echo '<<<diskstat>>>'
|
||||
date +%s
|
||||
egrep ' (x?[shv]d[a-z]*|cciss/c[0-9]+d[0-9]+|emcpower[a-z]+|dm-[0-9]+|VxVM.*|mmcblk.*) ' < /proc/diskstats
|
||||
if type dmsetup >/dev/null ; then
|
||||
echo '[dmsetup_info]'
|
||||
dmsetup info -c --noheadings --separator ' ' -o name,devno,vg_name,lv_name
|
||||
fi
|
||||
if [ -d /dev/vx/dsk ] ; then
|
||||
echo '[vx_dsk]'
|
||||
stat -c "%t %T %n" /dev/vx/dsk/*/*
|
||||
fi
|
||||
|
||||
|
||||
# Performancecounter Kernel
|
||||
echo '<<<kernel>>>'
|
||||
date +%s
|
||||
cat /proc/vmstat /proc/stat
|
||||
|
||||
# Hardware sensors via IPMI (need ipmitool)
|
||||
if type ipmitool > /dev/null
|
||||
then
|
||||
run_cached -s ipmi 300 "ipmitool sensor list | grep -v 'command failed' | sed -e 's/ *| */|/g' -e 's/ /_/g' -e 's/_*"'$'"//' -e 's/|/ /g' | egrep -v '^[^ ]+ na ' | grep -v ' discrete '"
|
||||
fi
|
||||
|
||||
|
||||
# IPMI data via ipmi-sensors (of freeipmi). Please make sure, that if you
|
||||
# have installed freeipmi that IPMI is really support by your hardware.
|
||||
if type ipmi-sensors >/dev/null
|
||||
then
|
||||
echo '<<<ipmi_sensors>>>'
|
||||
# Newer ipmi-sensors version have new output format; Legacy format can be used
|
||||
if ipmi-sensors --help | grep -q legacy-output; then
|
||||
IPMI_FORMAT="--legacy-output"
|
||||
else
|
||||
IPMI_FORMAT=""
|
||||
fi
|
||||
# At least with ipmi-sensoirs 0.7.16 this group is Power_Unit instead of "Power Unit"
|
||||
run_cached -s ipmi_sensors 300 "for class in Temperature Power_Unit Fan
|
||||
do
|
||||
ipmi-sensors $IPMI_FORMAT --sdr-cache-directory /var/cache -g "$class" | sed -e 's/ /_/g' -e 's/:_\?/ /g' -e 's@ \([^(]*\)_(\([^)]*\))@ \2_\1@'
|
||||
# In case of a timeout immediately leave loop.
|
||||
if [ $? = 255 ] ; then break ; fi
|
||||
done"
|
||||
fi
|
||||
|
||||
# RAID status of Linux software RAID
|
||||
echo '<<<md>>>'
|
||||
cat /proc/mdstat
|
||||
|
||||
# RAID status of Linux RAID via device mapper
|
||||
if type dmraid >/dev/null && DMSTATUS=$(dmraid -r)
|
||||
then
|
||||
echo '<<<dmraid>>>'
|
||||
|
||||
# Output name and status
|
||||
dmraid -s | grep -e ^name -e ^status
|
||||
|
||||
# Output disk names of the RAID disks
|
||||
DISKS=$(echo "$DMSTATUS" | cut -f1 -d\:)
|
||||
|
||||
for disk in $DISKS ; do
|
||||
device=$(cat /sys/block/$(basename $disk)/device/model )
|
||||
status=$(echo "$DMSTATUS" | grep ^${disk})
|
||||
echo "$status Model: $device"
|
||||
done
|
||||
fi
|
||||
|
||||
# RAID status of LSI controllers via cfggen
|
||||
if type cfggen > /dev/null ; then
|
||||
echo '<<<lsi>>>'
|
||||
cfggen 0 DISPLAY | egrep '(Target ID|State|Volume ID|Status of volume)[[:space:]]*:' | sed -e 's/ *//g' -e 's/:/ /'
|
||||
fi
|
||||
|
||||
# RAID status of LSI MegaRAID controller via MegaCli. You can download that tool from:
|
||||
# http://www.lsi.com/downloads/Public/MegaRAID%20Common%20Files/8.02.16_MegaCLI.zip
|
||||
if type MegaCli >/dev/null ; then
|
||||
MegaCli_bin="MegaCli"
|
||||
elif type MegaCli64 >/dev/null ; then
|
||||
MegaCli_bin="MegaCli64"
|
||||
elif type megacli >/dev/null ; then
|
||||
MegaCli_bin="megacli"
|
||||
else
|
||||
MegaCli_bin="unknown"
|
||||
fi
|
||||
|
||||
if [ "$MegaCli_bin" != "unknown" ]; then
|
||||
echo '<<<megaraid_pdisks>>>'
|
||||
for part in $($MegaCli_bin -EncInfo -aALL -NoLog < /dev/null \
|
||||
| sed -rn 's/:/ /g; s/[[:space:]]+/ /g; s/^ //; s/ $//; s/Number of enclosures on adapter ([0-9]+).*/adapter \1/g; /^(Enclosure|Device ID|adapter) [0-9]+$/ p'); do
|
||||
[ $part = adapter ] && echo ""
|
||||
[ $part = 'Enclosure' ] && echo -ne "\ndev2enc"
|
||||
echo -n " $part"
|
||||
done
|
||||
echo
|
||||
$MegaCli_bin -PDList -aALL -NoLog < /dev/null | egrep 'Enclosure|Raw Size|Slot Number|Device Id|Firmware state|Inquiry|Adapter'
|
||||
echo '<<<megaraid_ldisks>>>'
|
||||
$MegaCli_bin -LDInfo -Lall -aALL -NoLog < /dev/null | egrep 'Size|State|Number|Adapter|Virtual'
|
||||
echo '<<<megaraid_bbu>>>'
|
||||
$MegaCli_bin -AdpBbuCmd -GetBbuStatus -aALL -NoLog < /dev/null | grep -v Exit
|
||||
fi
|
||||
|
||||
# RAID status of 3WARE disk controller (by Radoslaw Bak)
|
||||
if type tw_cli > /dev/null ; then
|
||||
for C in $(tw_cli show | awk 'NR < 4 { next } { print $1 }'); do
|
||||
echo '<<<3ware_info>>>'
|
||||
tw_cli /$C show all | egrep 'Model =|Firmware|Serial'
|
||||
echo '<<<3ware_disks>>>'
|
||||
tw_cli /$C show drivestatus | egrep 'p[0-9]' | sed "s/^/$C\//"
|
||||
echo '<<<3ware_units>>>'
|
||||
tw_cli /$C show unitstatus | egrep 'u[0-9]' | sed "s/^/$C\//"
|
||||
done
|
||||
fi
|
||||
|
||||
# RAID controllers from areca (Taiwan)
|
||||
# cli64 can be found at ftp://ftp.areca.com.tw/RaidCards/AP_Drivers/Linux/CLI/
|
||||
if type cli64 >/dev/null ; then
|
||||
run_cached -s arc_raid_status 300 "cli64 rsf info | tail -n +3 | head -n -2"
|
||||
fi
|
||||
|
||||
# VirtualBox Guests. Section must always been output. Otherwise the
|
||||
# check would not be executed in case no guest additions are installed.
|
||||
# And that is something the check wants to detect
|
||||
echo '<<<vbox_guest>>>'
|
||||
if type VBoxControl >/dev/null 2>&1 ; then
|
||||
VBoxControl -nologo guestproperty enumerate | cut -d, -f1,2
|
||||
[ ${PIPESTATUS[0]} = 0 ] || echo "ERROR"
|
||||
fi
|
||||
|
||||
# OpenVPN Clients. Currently we assume that the configuration # is in
|
||||
# /etc/openvpn. We might find a safer way to find the configuration later.
|
||||
if [ -e /etc/openvpn/openvpn-status.log ] ; then
|
||||
echo '<<<openvpn_clients:sep(44)>>>'
|
||||
sed -n -e '/CLIENT LIST/,/ROUTING TABLE/p' < /etc/openvpn/openvpn-status.log | sed -e 1,3d -e '$d'
|
||||
fi
|
||||
|
||||
# Time synchronization with NTP
|
||||
if type ntpq > /dev/null 2>&1 ; then
|
||||
# remove heading, make first column space separated
|
||||
run_cached -s ntp 30 "waitmax 5 ntpq -np | sed -e 1,2d -e 's/^\(.\)/\1 /' -e 's/^ /%/'"
|
||||
fi
|
||||
|
||||
# Time synchronization with Chrony
|
||||
if type chronyc > /dev/null 2>&1 ; then
|
||||
# Force successful exit code. Otherwise section will be missing if daemon not running
|
||||
run_cached -s chrony 30 "waitmax 5 chronyc tracking || true"
|
||||
fi
|
||||
|
||||
if type nvidia-settings >/dev/null && [ -S /tmp/.X11-unix/X0 ]
|
||||
then
|
||||
echo '<<<nvidia>>>'
|
||||
for var in GPUErrors GPUCoreTemp
|
||||
do
|
||||
DISPLAY=:0 waitmax 2 nvidia-settings -t -q $var | sed "s/^/$var: /"
|
||||
done
|
||||
fi
|
||||
|
||||
if [ -e /proc/drbd ]; then
|
||||
echo '<<<drbd>>>'
|
||||
cat /proc/drbd
|
||||
fi
|
||||
|
||||
# Status of CUPS printer queues
|
||||
if type lpstat > /dev/null 2>&1; then
|
||||
if pgrep cups > /dev/null 2>&1; then
|
||||
echo '<<<cups_queues>>>'
|
||||
CPRINTCONF=/etc/cups/printers.conf
|
||||
if [ -r "$CPRINTCONF" ] ; then
|
||||
LOCAL_PRINTERS=$(grep -E "<(Default)?Printer .*>" $CPRINTCONF | awk '{print $2}' | sed -e 's/>//')
|
||||
lpstat -p | while read LINE
|
||||
do
|
||||
PRINTER=$(echo $LINE | awk '{print $2}')
|
||||
if echo "$LOCAL_PRINTERS" | grep -q "$PRINTER"; then
|
||||
echo $LINE
|
||||
fi
|
||||
done
|
||||
echo '---'
|
||||
lpstat -o | while read LINE
|
||||
do
|
||||
PRINTER=${LINE%%-*}
|
||||
if echo "$LOCAL_PRINTERS" | grep -q "$PRINTER"; then
|
||||
echo $LINE
|
||||
fi
|
||||
done
|
||||
else
|
||||
lpstat -p
|
||||
echo '---'
|
||||
lpstat -o | sort
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Heartbeat monitoring
|
||||
# Different handling for heartbeat clusters with and without CRM
|
||||
# for the resource state
|
||||
if [ -S /var/run/heartbeat/crm/cib_ro -o -S /var/run/crm/cib_ro ] || pgrep crmd > /dev/null 2>&1; then
|
||||
echo '<<<heartbeat_crm>>>'
|
||||
crm_mon -1 -r | grep -v ^$ | sed 's/^ //; /^\sResource Group:/,$ s/^\s//; s/^\s/_/g'
|
||||
fi
|
||||
if type cl_status > /dev/null 2>&1; then
|
||||
echo '<<<heartbeat_rscstatus>>>'
|
||||
cl_status rscstatus
|
||||
|
||||
echo '<<<heartbeat_nodes>>>'
|
||||
for NODE in $(cl_status listnodes); do
|
||||
if [ $NODE != $(echo $HOSTNAME | tr 'A-Z' 'a-z') ]; then
|
||||
STATUS=$(cl_status nodestatus $NODE)
|
||||
echo -n "$NODE $STATUS"
|
||||
for LINK in $(cl_status listhblinks $NODE 2>/dev/null); do
|
||||
echo -n " $LINK $(cl_status hblinkstatus $NODE $LINK)"
|
||||
done
|
||||
echo
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Postfix mailqueue monitoring
|
||||
#
|
||||
# Only handle mailq when postfix user is present. The mailq command is also
|
||||
# available when postfix is not installed. But it produces different outputs
|
||||
# which are not handled by the check at the moment. So try to filter out the
|
||||
# systems not using postfix by searching for the postfix user.a
|
||||
#
|
||||
# Cannot take the whole outout. This could produce several MB of agent output
|
||||
# on blocking queues.
|
||||
# Only handle the last 6 lines (includes the summary line at the bottom and
|
||||
# the last message in the queue. The last message is not used at the moment
|
||||
# but it could be used to get the timestamp of the last message.
|
||||
if type postconf >/dev/null ; then
|
||||
echo '<<<postfix_mailq>>>'
|
||||
postfix_queue_dir=$(postconf -h queue_directory)
|
||||
postfix_count=$(find $postfix_queue_dir/deferred -type f | wc -l)
|
||||
postfix_size=$(du -ks $postfix_queue_dir/deferred | awk '{print $1 }')
|
||||
if [ $postfix_count -gt 0 ]
|
||||
then
|
||||
echo -- $postfix_size Kbytes in $postfix_count Requests.
|
||||
else
|
||||
echo Mail queue is empty
|
||||
fi
|
||||
elif [ -x /usr/sbin/ssmtp ] ; then
|
||||
echo '<<<postfix_mailq>>>'
|
||||
mailq 2>&1 | sed 's/^[^:]*: \(.*\)/\1/' | tail -n 6
|
||||
fi
|
||||
|
||||
#Check status of qmail mailqueue
|
||||
if type qmail-qstat >/dev/null
|
||||
then
|
||||
echo "<<<qmail_stats>>>"
|
||||
qmail-qstat
|
||||
fi
|
||||
|
||||
# Check status of OMD sites
|
||||
if type omd >/dev/null
|
||||
then
|
||||
run_cached -s omd_status 60 "omd status --bare --auto"
|
||||
fi
|
||||
|
||||
|
||||
# Welcome the ZFS check on Linux
|
||||
# We do not endorse running ZFS on linux if your vendor doesnt support it ;)
|
||||
# check zpool status
|
||||
if type zpool >/dev/null; then
|
||||
echo "<<<zpool_status>>>"
|
||||
zpool status -x
|
||||
fi
|
||||
|
||||
|
||||
# Fileinfo-Check: put patterns for files into /etc/check_mk/fileinfo.cfg
|
||||
if [ -r "$MK_CONFDIR/fileinfo.cfg" ] ; then
|
||||
echo '<<<fileinfo:sep(124)>>>'
|
||||
date +%s
|
||||
stat -c "%n|%s|%Y" $(cat "$MK_CONFDIR/fileinfo.cfg")
|
||||
fi
|
||||
|
||||
# Get stats about OMD monitoring cores running on this machine.
|
||||
# Since cd is a shell builtin the check does not affect the performance
|
||||
# on non-OMD machines.
|
||||
if cd /omd/sites
|
||||
then
|
||||
echo '<<<livestatus_status:sep(59)>>>'
|
||||
for site in *
|
||||
do
|
||||
if [ -S "/omd/sites/$site/tmp/run/live" ] ; then
|
||||
echo "[$site]"
|
||||
echo -e "GET status" | waitmax 3 /omd/sites/$site/bin/unixcat /omd/sites/$site/tmp/run/live
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Get statistics about monitored jobs. Below the job directory there
|
||||
# is a sub directory per user that ran a job. That directory must be
|
||||
# owned by the user so that a symlink or hardlink attack for reading
|
||||
# arbitrary files can be avoided.
|
||||
if pushd $MK_VARDIR/job >/dev/null; then
|
||||
echo '<<<job>>>'
|
||||
for username in *
|
||||
do
|
||||
if [ -d "$username" ] && cd "$username" ; then
|
||||
su "$username" -c "head -n -0 -v *"
|
||||
cd ..
|
||||
fi
|
||||
done
|
||||
popd > /dev/null
|
||||
fi
|
||||
|
||||
# Gather thermal information provided e.g. by acpi
|
||||
# At the moment only supporting thermal sensors
|
||||
if ls /sys/class/thermal/thermal_zone* >/dev/null 2>&1; then
|
||||
echo '<<<lnx_thermal>>>'
|
||||
for F in /sys/class/thermal/thermal_zone*; do
|
||||
echo -n "${F##*/} "
|
||||
if [ ! -e $F/mode ] ; then echo -n "- " ; fi
|
||||
cat $F/{mode,type,temp,trip_point_*} | tr \\n " "
|
||||
echo
|
||||
done
|
||||
fi
|
||||
|
||||
# Libelle Business Shadow
|
||||
if type trd >/dev/null; then
|
||||
echo "<<<libelle_business_shadow:sep(58)>>>"
|
||||
trd -s
|
||||
fi
|
||||
|
||||
# MK's Remote Plugin Executor
|
||||
if [ -e "$MK_CONFDIR/mrpe.cfg" ]
|
||||
then
|
||||
echo '<<<mrpe>>>'
|
||||
grep -Ev '^[[:space:]]*($|#)' "$MK_CONFDIR/mrpe.cfg" | \
|
||||
while read descr cmdline
|
||||
do
|
||||
PLUGIN=${cmdline%% *}
|
||||
OUTPUT=$(eval "$cmdline")
|
||||
echo -n "(${PLUGIN##*/}) $descr $? $OUTPUT" | tr \\n \\1
|
||||
echo
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Local checks
|
||||
echo '<<<local>>>'
|
||||
if cd $LOCALDIR ; then
|
||||
for skript in $(ls) ; do
|
||||
if [ -f "$skript" -a -x "$skript" ] ; then
|
||||
./$skript
|
||||
fi
|
||||
done
|
||||
# Call some plugins only every X'th minute
|
||||
for skript in [1-9]*/* ; do
|
||||
if [ -x "$skript" ] ; then
|
||||
run_cached local_${skript//\//\\} ${skript%/*} "$skript"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Plugins
|
||||
if cd $PLUGINSDIR ; then
|
||||
for skript in $(ls) ; do
|
||||
if [ -f "$skript" -a -x "$skript" ] ; then
|
||||
./$skript
|
||||
fi
|
||||
done
|
||||
# Call some plugins only every Xth minute
|
||||
for skript in [1-9]*/* ; do
|
||||
if [ -x "$skript" ] ; then
|
||||
run_cached plugins_${skript//\//\\} ${skript%/*} "$skript"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Agent output snippets created by cronjobs, etc.
|
||||
if [ -d "$SPOOLDIR" ]
|
||||
then
|
||||
pushd "$SPOOLDIR" > /dev/null
|
||||
now=$(date +%s)
|
||||
|
||||
for file in *
|
||||
do
|
||||
# output every file in this directory. If the file is prefixed
|
||||
# with a number, then that number is the maximum age of the
|
||||
# file in seconds. If the file is older than that, it is ignored.
|
||||
maxage=""
|
||||
part="$file"
|
||||
|
||||
# Each away all digits from the front of the filename and
|
||||
# collect them in the variable maxage.
|
||||
while [ "${part/#[0-9]/}" != "$part" ]
|
||||
do
|
||||
maxage=$maxage${part:0:1}
|
||||
part=${part:1}
|
||||
done
|
||||
|
||||
# If there is at least one digit, than we honor that.
|
||||
if [ "$maxage" ] ; then
|
||||
mtime=$(stat -c %Y "$file")
|
||||
if [ $((now - mtime)) -gt $maxage ] ; then
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
|
||||
# Output the file
|
||||
cat "$file"
|
||||
done
|
||||
popd > /dev/null
|
||||
fi
|
9
ProjectCode/Agents/librenms/dmi.sh
Normal file
9
ProjectCode/Agents/librenms/dmi.sh
Normal file
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
echo '<<<dmi>>>'
|
||||
|
||||
# requires dmidecode
|
||||
for FIELD in bios-vendor bios-version bios-release-date system-manufacturer system-product-name system-version system-serial-number system-uuid baseboard-manufacturer baseboard-product-name baseboard-version baseboard-serial-number baseboard-asset-tag chassis-manufacturer chassis-type chassis-version chassis-serial-number chassis-asset-tag processor-family processor-manufacturer processor-version processor-frequency
|
||||
do
|
||||
echo $FIELD="$(dmidecode -s $FIELD | grep -v '^#')"
|
||||
done
|
22
ProjectCode/Agents/librenms/dpkg.sh
Normal file
22
ProjectCode/Agents/librenms/dpkg.sh
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
# Cache the file for 30 minutes
|
||||
# If you want to override this, put the command in cron.
|
||||
# We cache because it is a 1sec delay, which is painful for the poller
|
||||
if [ -x /usr/bin/dpkg-query ]; then
|
||||
DATE=$(date +%s)
|
||||
FILE=/var/cache/librenms/agent-local-dpkg
|
||||
|
||||
[ -d /var/cache/librenms ] || mkdir -p /var/cache/librenms
|
||||
|
||||
if [ ! -e $FILE ]; then
|
||||
dpkg-query -W --showformat='${Status} ${Package} ${Version} ${Architecture} ${Installed-Size}\n'|grep " installed "|cut -d\ -f4- > $FILE
|
||||
fi
|
||||
FILEMTIME=$(stat -c %Y $FILE)
|
||||
FILEAGE=$(($DATE-$FILEMTIME))
|
||||
if [ $FILEAGE -gt 1800 ]; then
|
||||
dpkg-query -W --showformat='${Status} ${Package} ${Version} ${Architecture} ${Installed-Size}\n'|grep " installed "|cut -d\ -f4- > $FILE
|
||||
fi
|
||||
echo "<<<dpkg>>>"
|
||||
cat $FILE
|
||||
fi
|
||||
|
1438
ProjectCode/Agents/librenms/mysql.sh
Normal file
1438
ProjectCode/Agents/librenms/mysql.sh
Normal file
File diff suppressed because it is too large
Load Diff
34
ProjectCode/Agents/librenms/ntp-client
Normal file
34
ProjectCode/Agents/librenms/ntp-client
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
# Please make sure the paths below are correct.
|
||||
# Alternatively you can put them in $0.conf, meaning if you've named
|
||||
# this script ntp-client then it must go in ntp-client.conf .
|
||||
#
|
||||
# NTPQV output version of "ntpq -c rv"
|
||||
# Version 4 is the most common and up to date version.
|
||||
#
|
||||
# If you are unsure, which to set, run this script and make sure that
|
||||
# the JSON output variables match that in "ntpq -c rv".
|
||||
#
|
||||
################################################################
|
||||
# Don't change anything unless you know what are you doing #
|
||||
################################################################
|
||||
BIN_NTPQ='/usr/bin/env ntpq'
|
||||
BIN_GREP='/usr/bin/env grep'
|
||||
BIN_AWK='/usr/bin/env awk'
|
||||
|
||||
CONFIG=$0".conf"
|
||||
if [ -f "$CONFIG" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
. "$CONFIG"
|
||||
fi
|
||||
|
||||
NTP_OFFSET=$($BIN_NTPQ -c rv | $BIN_GREP "offset" | $BIN_AWK -Foffset= '{print $2}' | $BIN_AWK -F, '{print $1}')
|
||||
NTP_FREQUENCY=$($BIN_NTPQ -c rv | $BIN_GREP "frequency" | $BIN_AWK -Ffrequency= '{print $2}' | $BIN_AWK -F, '{print $1}')
|
||||
NTP_SYS_JITTER=$($BIN_NTPQ -c rv | $BIN_GREP "sys_jitter" | $BIN_AWK -Fsys_jitter= '{print $2}' | $BIN_AWK -F, '{print $1}')
|
||||
NTP_CLK_JITTER=$($BIN_NTPQ -c rv | $BIN_GREP "clk_jitter" | $BIN_AWK -Fclk_jitter= '{print $2}' | $BIN_AWK -F, '{print $1}')
|
||||
NTP_WANDER=$($BIN_NTPQ -c rv | $BIN_GREP "clk_wander" | $BIN_AWK -Fclk_wander= '{print $2}' | $BIN_AWK -F, '{print $1}')
|
||||
NTP_VERSION=$($BIN_NTPQ -c rv | $BIN_GREP "version" | $BIN_AWK -F'ntpd ' '{print $2}' | $BIN_AWK -F. '{print $1}')
|
||||
|
||||
echo '{"data":{"offset":"'"$NTP_OFFSET"'","frequency":"'"$NTP_FREQUENCY"'","sys_jitter":"'"$NTP_SYS_JITTER"'","clk_jitter":"'"$NTP_CLK_JITTER"'","clk_wander":"'"$NTP_WANDER"'"},"version":"'"$NTP_VERSION"'","error":"0","errorString":""}'
|
||||
|
||||
exit 0
|
@@ -8,6 +8,6 @@
|
||||
QUEUES="incoming active deferred hold"
|
||||
|
||||
for i in $QUEUES; do
|
||||
COUNT=`qshape $i | grep TOTAL | awk '{print $2}'`
|
||||
COUNT=$(qshape "$i" | grep TOTAL | awk '{print $2}')
|
||||
printf "$COUNT\n"
|
||||
done
|
@@ -86,10 +86,10 @@ my ( $received,
|
||||
$rardnf,
|
||||
$rarnfqa,
|
||||
$iuscp,
|
||||
$msefl,
|
||||
$sce,
|
||||
$scp,
|
||||
$urr) = split ( /\n/, $old );
|
||||
$urr,
|
||||
$msefl) = split ( /\n/, $old );
|
||||
|
||||
if ( ! defined( $received ) ){ $received=0; }
|
||||
if ( ! defined( $delivered ) ){ $delivered=0; }
|
||||
@@ -142,7 +142,6 @@ my $recipientsC=0;
|
||||
my $recipienthdC=0;
|
||||
my $deferralcrC=0;
|
||||
my $deferralhidC=0;
|
||||
my $chrC=0;
|
||||
my $hcrnfqhC=0;
|
||||
my $sardnfC=0;
|
||||
my $sarnobuC=0;
|
||||
@@ -193,14 +192,15 @@ sub newValue{
|
||||
}
|
||||
|
||||
|
||||
my $output=`$pflogsumm /var/log/mail.log`;
|
||||
|
||||
#holds client host rejected values till the end when it is compared to the old one
|
||||
my $chrNew=0;
|
||||
my $output=`$pflogsumm /var/log/maillog`;
|
||||
|
||||
#holds RBL values till the end when it is compared to the old one
|
||||
my $buNew=0;
|
||||
|
||||
|
||||
#holds client host rejected values till the end when it is compared to the old one
|
||||
my $chrNew=0;
|
||||
|
||||
# holds recipient address rejected values till the end when it is compared to the old one
|
||||
my $raruuNew=0;
|
||||
|
||||
@@ -353,6 +353,7 @@ while ( defined( $outputA[$int] ) ){
|
||||
# deferrals Host is down
|
||||
if ( ( $line =~ /Host is down$/ ) && ( ! $handled ) ){
|
||||
$line=~s/ .*//;
|
||||
$deferralcrC=$line;
|
||||
$deferralhidC=$line;
|
||||
$deferralhid=newValue( $deferralhid, $line );
|
||||
$handled=1;
|
||||
@@ -429,8 +430,8 @@ while ( defined( $outputA[$int] ) ){
|
||||
#Improper use of SMTP command pipelining
|
||||
if ( ( $line =~ /Improper use of SMTP command pipelining/ ) && ( ! $handled ) ){
|
||||
$line=~s/.*\: //g;
|
||||
$iuoscpC=$line;
|
||||
$iuoscp=newValue( $iuoscp, $line );
|
||||
$iuscpC=$line;
|
||||
$iuscp=newValue( $iuscp, $line );
|
||||
}
|
||||
|
||||
#Message size exceeds fixed limit
|
||||
@@ -453,16 +454,18 @@ while ( defined( $outputA[$int] ) ){
|
||||
$scpC=$line;
|
||||
$scp=newValue( $scp, $line );
|
||||
}
|
||||
|
||||
|
||||
#unknown reject reason
|
||||
if ( ( $line =~ /unknown reject reason/ ) && ( ! $handled ) ){
|
||||
$line=~s/.*\: //g;
|
||||
$urrC=$line;
|
||||
$urr=newValue( $urr, $line );
|
||||
}
|
||||
|
||||
$int++;
|
||||
}
|
||||
|
||||
|
||||
# final client host rejected total
|
||||
$chr=newValue( $chr, $chrNew );
|
||||
|
||||
@@ -502,8 +505,8 @@ my $data=$received."\n".
|
||||
$iuscp."\n".
|
||||
$sce."\n".
|
||||
$scp."\n".
|
||||
$urr."\n";
|
||||
$msefl."\n".
|
||||
$urr."\n".
|
||||
$msefl."\n";
|
||||
|
||||
print $data;
|
||||
|
||||
@@ -535,10 +538,10 @@ my $current=$receivedC."\n".
|
||||
$rardnfC."\n".
|
||||
$rarnfqaC."\n".
|
||||
$iuscpC."\n".
|
||||
$mseflC."\n".
|
||||
$sceC."\n".
|
||||
$scpC."\n".
|
||||
$urrC."\n";
|
||||
$urrC."\n".
|
||||
$mseflC."\n";
|
||||
|
||||
open(my $fh, ">", $cache) or die "Can't open '".$cache."'";
|
||||
print $fh $current;
|
46
ProjectCode/Agents/librenms/raspberry.sh
Normal file
46
ProjectCode/Agents/librenms/raspberry.sh
Normal file
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
#######################################
|
||||
# please read DOCS to succesfully get #
|
||||
# raspberry sensors into your host #
|
||||
#######################################
|
||||
picmd='/usr/bin/vcgencmd'
|
||||
pised='/bin/sed'
|
||||
getTemp='measure_temp'
|
||||
getVoltsCore='measure_volts core'
|
||||
getVoltsRamC='measure_volts sdram_c'
|
||||
getVoltsRamI='measure_volts sdram_i'
|
||||
getVoltsRamP='measure_volts sdram_p'
|
||||
getFreqArm='measure_clock arm'
|
||||
getFreqCore='measure_clock core'
|
||||
getStatusH264='codec_enabled H264'
|
||||
getStatusMPG2='codec_enabled MPG2'
|
||||
getStatusWVC1='codec_enabled WVC1'
|
||||
getStatusMPG4='codec_enabled MPG4'
|
||||
getStatusMJPG='codec_enabled MJPG'
|
||||
getStatusWMV9='codec_enabled WMV9'
|
||||
|
||||
$picmd $getTemp | $pised 's|[^0-9.]||g'
|
||||
$picmd "$getVoltsCore" | $pised 's|[^0-9.]||g'
|
||||
$picmd "$getVoltsRamC" | $pised 's|[^0-9.]||g'
|
||||
$picmd "$getVoltsRamI" | $pised 's|[^0-9.]||g'
|
||||
$picmd "$getVoltsRamP" | $pised 's|[^0-9.]||g'
|
||||
$picmd "$getFreqArm" | $pised 's/frequency([0-9]*)=//g'
|
||||
$picmd "$getFreqCore" | $pised 's/frequency([0-9]*)=//g'
|
||||
$picmd "$getStatusH264" | $pised 's/H264=//g'
|
||||
$picmd "$getStatusMPG2" | $pised 's/MPG2=//g'
|
||||
$picmd "$getStatusWVC1" | $pised 's/WVC1=//g'
|
||||
$picmd "$getStatusMPG4" | $pised 's/MPG4=//g'
|
||||
$picmd "$getStatusMJPG" | $pised 's/MJPG=//g'
|
||||
$picmd "$getStatusWMV9" | $pised 's/WMV9=//g'
|
||||
$picmd "$getStatusH264" | $pised 's/enabled/2/g'
|
||||
$picmd "$getStatusMPG2" | $pised 's/enabled/2/g'
|
||||
$picmd "$getStatusWVC1" | $pised 's/enabled/2/g'
|
||||
$picmd "$getStatusMPG4" | $pised 's/enabled/2/g'
|
||||
$picmd "$getStatusMJPG" | $pised 's/enabled/2/g'
|
||||
$picmd "$getStatusWMV9" | $pised 's/enabled/2/g'
|
||||
$picmd "$getStatusH264" | $pised 's/disabled/1/g'
|
||||
$picmd "$getStatusMPG2" | $pised 's/disabled/1/g'
|
||||
$picmd "$getStatusWVC1" | $pised 's/disabled/1/g'
|
||||
$picmd "$getStatusMPG4" | $pised 's/disabled/1/g'
|
||||
$picmd "$getStatusMJPG" | $pised 's/disabled/1/g'
|
||||
$picmd "$getStatusWMV9" | $pised 's/disabled/1/g'
|
929
ProjectCode/Agents/librenms/smart
Normal file
929
ProjectCode/Agents/librenms/smart
Normal file
@@ -0,0 +1,929 @@
|
||||
#!/usr/bin/env perl
|
||||
#Copyright (c) 2024, Zane C. Bowers-Hadley
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source and binary forms, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
#IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
#OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
|
||||
#THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
=for comment
|
||||
|
||||
Add this to snmpd.conf like below.
|
||||
|
||||
extend smart /etc/snmp/smart
|
||||
|
||||
Then add to root's cron tab, if you have more than a few disks.
|
||||
|
||||
*/5 * * * * /etc/snmp/extends/smart -u
|
||||
|
||||
You will also need to create the config file, which defaults to the same path as the script,
|
||||
but with .config appended. So if the script is located at /etc/snmp/smart, the config file
|
||||
will be /etc/snmp/extends/smart.config. Alternatively you can also specific a config via -c.
|
||||
|
||||
Anything starting with a # is comment. The format for variables is $variable=$value. Empty
|
||||
lines are ignored. Spaces and tabes at either the start or end of a line are ignored. Any
|
||||
line with out a matched variable or # are treated as a disk.
|
||||
|
||||
#This is a comment
|
||||
cache=/var/cache/smart
|
||||
smartctl=/usr/local/sbin/smartctl
|
||||
useSN=0
|
||||
ada0
|
||||
da5 /dev/da5 -d sat
|
||||
twl0,0 /dev/twl0 -d 3ware,0
|
||||
twl0,1 /dev/twl0 -d 3ware,1
|
||||
twl0,2 /dev/twl0 -d 3ware,2
|
||||
|
||||
The variables are as below.
|
||||
|
||||
cache = The path to the cache file to use. Default: /var/cache/smart
|
||||
smartctl = The path to use for smartctl. Default: /usr/bin/env smartctl
|
||||
useSN = If set to 1, it will use the disks SN for reporting instead of the device name.
|
||||
1 is the default. 0 will use the device name.
|
||||
|
||||
A disk line is can be as simple as just a disk name under /dev/. Such as in the config above
|
||||
The line "ada0" would resolve to "/dev/ada0" and would be called with no special argument. If
|
||||
a line has a space in it, everything before the space is treated as the disk name and is what
|
||||
used for reporting and everything after that is used as the argument to be passed to smartctl.
|
||||
|
||||
If you want to guess at the configuration, call it with -g and it will print out what it thinks
|
||||
it should be.
|
||||
|
||||
|
||||
Switches:
|
||||
|
||||
-c <config> The config file to use.
|
||||
-u Update
|
||||
-p Pretty print the JSON.
|
||||
-Z GZip+Base64 compress the results.
|
||||
|
||||
-g Guess at the config and print it to STDOUT
|
||||
-C Enable manual checking for guess and cciss.
|
||||
-S Set useSN to 0 when using -g
|
||||
-t <test> Run the specified smart self test on all the devices.
|
||||
-U When calling cciss_vol_status, call it with -u.
|
||||
-G <modes> Guess modes to use. This is a comma seperated list.
|
||||
Default :: scan-open,cciss-vol-status
|
||||
|
||||
Guess Modes:
|
||||
|
||||
- scan :: Use "--scan" with smartctl. "scan-open" will take presidence.
|
||||
|
||||
- scan-open :: Call smartctl with "--scan-open".
|
||||
|
||||
- cciss-vol-status :: Freebsd/Linux specific and if it sees /dev/sg0(on Linux) or
|
||||
/dev/ciss0(on FreebSD) it will attempt to find drives via cciss-vol-status,
|
||||
and then optionally checking for disks via smrtctl if -C is given. Should be noted
|
||||
though that -C will not find drives that are currently missing/failed. If -U is given,
|
||||
cciss_vol_status will be called with -u.
|
||||
|
||||
=cut
|
||||
|
||||
##
|
||||
## You should not need to touch anything below here.
|
||||
##
|
||||
use warnings;
|
||||
use strict;
|
||||
use Getopt::Std;
|
||||
use JSON;
|
||||
use MIME::Base64;
|
||||
use IO::Compress::Gzip qw(gzip $GzipError);
|
||||
|
||||
my $cache = '/var/cache/smart';
|
||||
my $smartctl = '/usr/bin/env smartctl';
|
||||
my @disks;
|
||||
my $useSN = 1;
|
||||
|
||||
$Getopt::Std::STANDARD_HELP_VERSION = 1;
|
||||
|
||||
sub main::VERSION_MESSAGE {
|
||||
print "SMART SNMP extend 0.3.2\n";
|
||||
}
|
||||
|
||||
sub main::HELP_MESSAGE {
|
||||
&VERSION_MESSAGE;
|
||||
print "\n" . "-u Update '" . $cache . "'\n" . '-g Guess at the config and print it to STDOUT
|
||||
-c <config> The config file to use.
|
||||
-p Pretty print the JSON.
|
||||
-Z GZip+Base64 compress the results.
|
||||
-C Enable manual checking for guess and cciss.
|
||||
-S Set useSN to 0 when using -g
|
||||
-t <test> Run the specified smart self test on all the devices.
|
||||
-U When calling cciss_vol_status, call it with -u.
|
||||
-G <modes> Guess modes to use. This is a comma seperated list.
|
||||
Default :: scan-open,cciss-vol-status
|
||||
|
||||
|
||||
Scan Modes:
|
||||
|
||||
- scan :: Use "--scan" with smartctl. "scan-open" will take presidence.
|
||||
|
||||
- scan-open :: Call smartctl with "--scan-open".
|
||||
|
||||
- cciss-vol-status :: Freebsd/Linux specific and if it sees /dev/sg0(on Linux) or
|
||||
/dev/ciss0(on FreebSD) it will attempt to find drives via cciss-vol-status,
|
||||
and then optionally checking for disks via smrtctl if -C is given. Should be noted
|
||||
though that -C will not find drives that are currently missing/failed. If -U is given,
|
||||
cciss_vol_status will be called with -u.
|
||||
';
|
||||
|
||||
} ## end sub main::HELP_MESSAGE
|
||||
|
||||
#gets the options
|
||||
my %opts = ();
|
||||
getopts( 'ugc:pZhvCSGt:U', \%opts );
|
||||
|
||||
if ( $opts{h} ) {
|
||||
&HELP_MESSAGE;
|
||||
exit;
|
||||
}
|
||||
if ( $opts{v} ) {
|
||||
&VERSION_MESSAGE;
|
||||
exit;
|
||||
}
|
||||
|
||||
#
|
||||
# figure out what scan modes to use if -g specified
|
||||
#
|
||||
my $scan_modes = {
|
||||
'scan-open' => 0,
|
||||
'scan' => 0,
|
||||
'cciss_vol_status' => 0,
|
||||
};
|
||||
if ( $opts{g} ) {
|
||||
if ( !defined( $opts{G} ) ) {
|
||||
$opts{G} = 'scan-open,cciss_vol_status';
|
||||
}
|
||||
$opts{G} =~ s/[\ \t]//g;
|
||||
my @scan_modes_split = split( /,/, $opts{G} );
|
||||
foreach my $mode (@scan_modes_split) {
|
||||
if ( !defined $scan_modes->{$mode} ) {
|
||||
die( '"' . $mode . '" is not a recognized scan mode' );
|
||||
}
|
||||
$scan_modes->{$mode} = 1;
|
||||
}
|
||||
} ## end if ( $opts{g} )
|
||||
|
||||
# configure JSON for later usage
|
||||
# only need to do this if actually running as in -g is not specified
|
||||
my $json;
|
||||
if ( !$opts{g} ) {
|
||||
|
||||
$json = JSON->new->allow_nonref->canonical(1);
|
||||
if ( $opts{p} ) {
|
||||
$json->pretty;
|
||||
}
|
||||
}
|
||||
|
||||
#
|
||||
#
|
||||
# guess if asked
|
||||
#
|
||||
#
|
||||
if ( defined( $opts{g} ) ) {
|
||||
|
||||
#get what path to use for smartctl
|
||||
$smartctl = `which smartctl`;
|
||||
chomp($smartctl);
|
||||
if ( $? != 0 ) {
|
||||
warn("'which smartctl' failed with a exit code of $?");
|
||||
exit 1;
|
||||
}
|
||||
|
||||
#try to touch the default cache location and warn if it can't be done
|
||||
system( 'touch ' . $cache . '>/dev/null' );
|
||||
if ( $? != 0 ) {
|
||||
$cache = '#Could not touch ' . $cache . "You will need to manually set it\n" . "cache=?\n";
|
||||
} else {
|
||||
system( 'rm -f ' . $cache . '>/dev/null' );
|
||||
$cache = 'cache=' . $cache . "\n";
|
||||
}
|
||||
|
||||
my $drive_lines = '';
|
||||
|
||||
#
|
||||
#
|
||||
# scan-open and scan guess mode handling
|
||||
#
|
||||
#
|
||||
if ( $scan_modes->{'scan-open'} || $scan_modes->{'scan'} ) {
|
||||
# used for checking if a disk has been found more than once
|
||||
my %found_disks_names;
|
||||
my @argumentsA;
|
||||
|
||||
# use scan-open if it is set, overriding scan if it is also set
|
||||
my $mode = 'scan';
|
||||
if ( $scan_modes->{'scan-open'} ) {
|
||||
$mode = 'scan-open';
|
||||
}
|
||||
|
||||
#have smartctl scan and see if it finds anythings not get found
|
||||
my $scan_output = `$smartctl --$mode`;
|
||||
my @scan_outputA = split( /\n/, $scan_output );
|
||||
|
||||
# remove non-SMART devices sometimes returned
|
||||
@scan_outputA = grep( !/ses[0-9]/, @scan_outputA ); # not a disk, but may or may not have SMART attributes
|
||||
@scan_outputA = grep( !/pass[0-9]/, @scan_outputA ); # very likely a duplicate and a disk under another name
|
||||
@scan_outputA = grep( !/cd[0-9]/, @scan_outputA ); # CD drive
|
||||
if ( $^O eq 'freebsd' ) {
|
||||
@scan_outputA = grep( !/sa[0-9]/, @scan_outputA ); # tape drive
|
||||
@scan_outputA = grep( !/ctl[0-9]/, @scan_outputA ); # CAM target layer
|
||||
} elsif ( $^O eq 'linux' ) {
|
||||
@scan_outputA = grep( !/st[0-9]/, @scan_outputA ); # SCSI tape drive
|
||||
@scan_outputA = grep( !/ht[0-9]/, @scan_outputA ); # ATA tape drive
|
||||
}
|
||||
|
||||
# make the first pass, figuring out what all we have and trimming comments
|
||||
foreach my $arguments (@scan_outputA) {
|
||||
my $name = $arguments;
|
||||
|
||||
$arguments =~ s/ \#.*//; # trim the comment out of the argument
|
||||
$name =~ s/ .*//;
|
||||
$name =~ s/\/dev\///;
|
||||
if ( defined( $found_disks_names{$name} ) ) {
|
||||
$found_disks_names{$name}++;
|
||||
} else {
|
||||
$found_disks_names{$name} = 0;
|
||||
}
|
||||
|
||||
push( @argumentsA, $arguments );
|
||||
|
||||
} ## end foreach my $arguments (@scan_outputA)
|
||||
|
||||
# second pass, putting the lines together
|
||||
my %current_disk;
|
||||
foreach my $arguments (@argumentsA) {
|
||||
my $not_virt = 1;
|
||||
|
||||
# check to see if we have a virtual device
|
||||
my @virt_check = split( /\n/, `smartctl -i $arguments 2> /dev/null` );
|
||||
foreach my $virt_check_line (@virt_check) {
|
||||
if ( $virt_check_line =~ /(?i)Product\:.*LOGICAL VOLUME/ ) {
|
||||
$not_virt = 0;
|
||||
}
|
||||
}
|
||||
|
||||
my $name = $arguments;
|
||||
$name =~ s/ .*//;
|
||||
$name =~ s/\/dev\///;
|
||||
|
||||
# only add it if not a virtual RAID drive
|
||||
# HP RAID virtual disks will show up with very basical but totally useless smart data
|
||||
if ($not_virt) {
|
||||
if ( $found_disks_names{$name} == 0 ) {
|
||||
# If no other devices, just name it after the base device.
|
||||
$drive_lines = $drive_lines . $name . " " . $arguments . "\n";
|
||||
} else {
|
||||
# if more than one, start at zero and increment, apennding comma number to the base device name
|
||||
if ( defined( $current_disk{$name} ) ) {
|
||||
$current_disk{$name}++;
|
||||
} else {
|
||||
$current_disk{$name} = 0;
|
||||
}
|
||||
$drive_lines = $drive_lines . $name . "," . $current_disk{$name} . " " . $arguments . "\n";
|
||||
}
|
||||
} ## end if ($not_virt)
|
||||
|
||||
} ## end foreach my $arguments (@argumentsA)
|
||||
} ## end if ( $scan_modes->{'scan-open'} || $scan_modes...)
|
||||
|
||||
#
|
||||
#
|
||||
# scan mode handler for cciss_vol_status
|
||||
# /dev/sg* devices for cciss on Linux
|
||||
# /dev/ccis* devices for cciss on FreeBSD
|
||||
#
|
||||
#
|
||||
if ( $scan_modes->{'cciss_vol_status'} && ( $^O eq 'linux' || $^O eq 'freebsd' ) ) {
|
||||
my $cciss;
|
||||
if ( $^O eq 'freebsd' ) {
|
||||
$cciss = 'ciss';
|
||||
} elsif ( $^O eq 'linux' ) {
|
||||
$cciss = 'sg';
|
||||
}
|
||||
|
||||
my $uarg = '';
|
||||
if ( $opts{U} ) {
|
||||
$uarg = '-u';
|
||||
}
|
||||
|
||||
# generate the initial device path that will be checked
|
||||
my $sg_int = 0;
|
||||
my $device = '/dev/' . $cciss . $sg_int;
|
||||
|
||||
my $sg_process = 1;
|
||||
if ( -e $device ) {
|
||||
my $output = `which cciss_vol_status 2> /dev/null`;
|
||||
if ( $? != 0 && !$opts{C} ) {
|
||||
$sg_process = 0;
|
||||
$drive_lines
|
||||
= $drive_lines
|
||||
. "# -C not given, but "
|
||||
. $device
|
||||
. " exists and cciss_vol_status is not present\n"
|
||||
. "# in path or 'ccis_vol_status -V "
|
||||
. $device
|
||||
. "' is failing\n";
|
||||
} ## end if ( $? != 0 && !$opts{C} )
|
||||
} ## end if ( -e $device )
|
||||
my $seen_lines = {};
|
||||
my $ignore_lines = {};
|
||||
while ( -e $device && $sg_process ) {
|
||||
my $output = `cciss_vol_status -V $uarg $device 2> /dev/null`;
|
||||
if ( $? != 0 && $output eq '' && !$opts{C} ) {
|
||||
# just empty here as we just want to skip it if it fails and there is no C
|
||||
# warning is above
|
||||
} elsif ( $? != 0 && $output eq '' && $opts{C} ) {
|
||||
my $drive_count = 0;
|
||||
my $continue = 1;
|
||||
while ($continue) {
|
||||
my $output = `$smartctl -i $device -d cciss,$drive_count 2> /dev/null`;
|
||||
if ( $? != 0 ) {
|
||||
$continue = 0;
|
||||
} else {
|
||||
my $add_it = 0;
|
||||
my $id;
|
||||
while ( $output =~ /(?i)Serial Number:(.*)/g ) {
|
||||
$id = $1;
|
||||
$id =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
if ( defined($id) && !defined( $seen_lines->{$id} ) ) {
|
||||
$add_it = 1;
|
||||
$seen_lines->{$id} = 1;
|
||||
}
|
||||
if ( $continue && $add_it ) {
|
||||
$drive_lines
|
||||
= $drive_lines
|
||||
. $cciss . '0-'
|
||||
. $drive_count . ' '
|
||||
. $device
|
||||
. ' -d cciss,'
|
||||
. $drive_count . "\n";
|
||||
}
|
||||
} ## end else [ if ( $? != 0 ) ]
|
||||
$drive_count++;
|
||||
} ## end while ($continue)
|
||||
} else {
|
||||
my $drive_count = 0;
|
||||
# count the connector lines, this will make sure failed are founded as well
|
||||
my $seen_conectors = {};
|
||||
while ( $output =~ /(connector +\d+[IA]\ +box +\d+\ +bay +\d+.*)/g ) {
|
||||
my $cciss_drive_line = $1;
|
||||
my $connector = $cciss_drive_line;
|
||||
$connector =~ s/(.*\ bay +\d+).*/$1/;
|
||||
if ( !defined( $seen_lines->{$cciss_drive_line} )
|
||||
&& !defined( $seen_conectors->{$connector} )
|
||||
&& !defined( $ignore_lines->{$cciss_drive_line} ) )
|
||||
{
|
||||
$seen_lines->{$cciss_drive_line} = 1;
|
||||
$seen_conectors->{$connector} = 1;
|
||||
$drive_count++;
|
||||
} else {
|
||||
# going to be a connector we've already seen
|
||||
# which will happen when it is processing replacement drives
|
||||
# so save this as a device to ignore
|
||||
$ignore_lines->{$cciss_drive_line} = 1;
|
||||
}
|
||||
} ## end while ( $output =~ /(connector +\d+[IA]\ +box +\d+\ +bay +\d+.*)/g)
|
||||
my $drive_int = 0;
|
||||
while ( $drive_int < $drive_count ) {
|
||||
$drive_lines
|
||||
= $drive_lines
|
||||
. $cciss
|
||||
. $sg_int . '-'
|
||||
. $drive_int . ' '
|
||||
. $device
|
||||
. ' -d cciss,'
|
||||
. $drive_int . "\n";
|
||||
|
||||
$drive_int++;
|
||||
} ## end while ( $drive_int < $drive_count )
|
||||
} ## end else [ if ( $? != 0 && $output eq '' && !$opts{C})]
|
||||
|
||||
$sg_int++;
|
||||
$device = '/dev/' . $cciss . $sg_int;
|
||||
} ## end while ( -e $device && $sg_process )
|
||||
} ## end if ( $scan_modes->{'cciss_vol_status'} && ...)
|
||||
|
||||
my $useSN = 1;
|
||||
if ( $opts{S} ) {
|
||||
$useSN = 0;
|
||||
}
|
||||
|
||||
print '# scan_modes='
|
||||
. $opts{G}
|
||||
. "\nuseSN="
|
||||
. $useSN . "\n"
|
||||
. 'smartctl='
|
||||
. $smartctl . "\n"
|
||||
. $cache
|
||||
. $drive_lines;
|
||||
|
||||
exit 0;
|
||||
} ## end if ( defined( $opts{g} ) )
|
||||
|
||||
#get which config file to use
|
||||
my $config = $0 . '.config';
|
||||
if ( defined( $opts{c} ) ) {
|
||||
$config = $opts{c};
|
||||
}
|
||||
|
||||
#reads the config file, optionally
|
||||
my $config_file = '';
|
||||
open( my $readfh, "<", $config ) or die "Can't open '" . $config . "'";
|
||||
read( $readfh, $config_file, 1000000 );
|
||||
close($readfh);
|
||||
|
||||
#
|
||||
#
|
||||
# parse the config file and remove comments and empty lines
|
||||
#
|
||||
#
|
||||
my @configA = split( /\n/, $config_file );
|
||||
@configA = grep( !/^$/, @configA );
|
||||
@configA = grep( !/^\#/, @configA );
|
||||
@configA = grep( !/^[\s\t]*$/, @configA );
|
||||
my $configA_int = 0;
|
||||
while ( defined( $configA[$configA_int] ) ) {
|
||||
my $line = $configA[$configA_int];
|
||||
chomp($line);
|
||||
$line =~ s/^[\t\s]+//;
|
||||
$line =~ s/[\t\s]+$//;
|
||||
|
||||
my ( $var, $val ) = split( /=/, $line, 2 );
|
||||
|
||||
my $matched;
|
||||
if ( $var eq 'cache' ) {
|
||||
$cache = $val;
|
||||
$matched = 1;
|
||||
}
|
||||
|
||||
if ( $var eq 'smartctl' ) {
|
||||
$smartctl = $val;
|
||||
$matched = 1;
|
||||
}
|
||||
|
||||
if ( $var eq 'useSN' ) {
|
||||
$useSN = $val;
|
||||
$matched = 1;
|
||||
}
|
||||
|
||||
if ( !defined($val) ) {
|
||||
push( @disks, $line );
|
||||
}
|
||||
|
||||
$configA_int++;
|
||||
} ## end while ( defined( $configA[$configA_int] ) )
|
||||
|
||||
#
|
||||
#
|
||||
# run the specified self test on all disks if asked
|
||||
#
|
||||
#
|
||||
if ( defined( $opts{t} ) ) {
|
||||
|
||||
# make sure we have something that atleast appears sane for the test name
|
||||
my $valid_tesks = {
|
||||
'offline' => 1,
|
||||
'short' => 1,
|
||||
'long' => 1,
|
||||
'conveyance' => 1,
|
||||
'afterselect,on' => 1,
|
||||
};
|
||||
if ( !defined( $valid_tesks->{ $opts{t} } ) && $opts{t} !~ /select,(\d+[\-\+]\d+|next|next\+\d+|redo\+\d+)/ ) {
|
||||
print '"' . $opts{t} . "\" does not appear to be a valid test\n";
|
||||
exit 1;
|
||||
}
|
||||
|
||||
print "Running the SMART $opts{t} on all devices in the config...\n\n";
|
||||
|
||||
foreach my $line (@disks) {
|
||||
my $disk;
|
||||
my $name;
|
||||
if ( $line =~ /\ / ) {
|
||||
( $name, $disk ) = split( /\ /, $line, 2 );
|
||||
} else {
|
||||
$disk = $line;
|
||||
$name = $line;
|
||||
}
|
||||
if ( $disk !~ /\// ) {
|
||||
$disk = '/dev/' . $disk;
|
||||
}
|
||||
|
||||
print "\n------------------------------------------------------------------\nDoing "
|
||||
. $smartctl . ' -t '
|
||||
. $opts{t} . ' '
|
||||
. $disk
|
||||
. " ...\n\n";
|
||||
print `$smartctl -t $opts{t} $disk` . "\n";
|
||||
|
||||
} ## end foreach my $line (@disks)
|
||||
|
||||
exit 0;
|
||||
} ## end if ( defined( $opts{t} ) )
|
||||
|
||||
#if set to 1, no cache will be written and it will be printed instead
|
||||
my $noWrite = 0;
|
||||
|
||||
#
|
||||
#
|
||||
# if no -u, it means we are being called from snmped
|
||||
#
|
||||
#
|
||||
if ( !defined( $opts{u} ) ) {
|
||||
# if the cache file exists, print it, otherwise assume one is not being used
|
||||
if ( -f $cache ) {
|
||||
my $old = '';
|
||||
open( my $readfh, "<", $cache ) or die "Can't open '" . $cache . "'";
|
||||
read( $readfh, $old, 1000000 );
|
||||
close($readfh);
|
||||
print $old;
|
||||
exit 0;
|
||||
} else {
|
||||
$opts{u} = 1;
|
||||
$noWrite = 1;
|
||||
}
|
||||
} ## end if ( !defined( $opts{u} ) )
|
||||
|
||||
#
|
||||
#
|
||||
# Process each disk
|
||||
#
|
||||
#
|
||||
my $to_return = {
|
||||
data => { disks => {}, exit_nonzero => 0, unhealthy => 0, useSN => $useSN },
|
||||
version => 1,
|
||||
error => 0,
|
||||
errorString => '',
|
||||
};
|
||||
foreach my $line (@disks) {
|
||||
my $disk;
|
||||
my $name;
|
||||
if ( $line =~ /\ / ) {
|
||||
( $name, $disk ) = split( /\ /, $line, 2 );
|
||||
} else {
|
||||
$disk = $line;
|
||||
$name = $line;
|
||||
}
|
||||
if ( $disk !~ /\// ) {
|
||||
$disk = '/dev/' . $disk;
|
||||
}
|
||||
|
||||
my $output = `$smartctl -A $disk`;
|
||||
my %IDs = (
|
||||
'5' => 'null',
|
||||
'10' => 'null',
|
||||
'173' => 'null',
|
||||
'177' => 'null',
|
||||
'183' => 'null',
|
||||
'184' => 'null',
|
||||
'187' => 'null',
|
||||
'188' => 'null',
|
||||
'190' => 'null',
|
||||
'194' => 'null',
|
||||
'196' => 'null',
|
||||
'197' => 'null',
|
||||
'198' => 'null',
|
||||
'199' => 'null',
|
||||
'231' => 'null',
|
||||
'232' => 'null',
|
||||
'233' => 'null',
|
||||
'9' => 'null',
|
||||
'disk' => $disk,
|
||||
'serial' => undef,
|
||||
'selftest_log' => undef,
|
||||
'health_pass' => 0,
|
||||
max_temp => 'null',
|
||||
exit => $?,
|
||||
);
|
||||
$IDs{'disk'} =~ s/^\/dev\///;
|
||||
|
||||
# if polling exited non-zero above, no reason running the rest of the checks
|
||||
my $disk_id = $name;
|
||||
if ( $IDs{exit} != 0 ) {
|
||||
$to_return->{data}{exit_nonzero}++;
|
||||
} else {
|
||||
my @outputA;
|
||||
|
||||
if ( $output =~ /NVMe Log/ ) {
|
||||
# we have an NVMe drive with annoyingly different output
|
||||
my %mappings = (
|
||||
'Temperature' => 194,
|
||||
'Power Cycles' => 12,
|
||||
'Power On Hours' => 9,
|
||||
'Percentage Used' => 231,
|
||||
);
|
||||
foreach ( split( /\n/, $output ) ) {
|
||||
if (/:/) {
|
||||
my ( $key, $val ) = split(/:/);
|
||||
$val =~ s/^\s+|\s+$|\D+//g;
|
||||
if ( exists( $mappings{$key} ) ) {
|
||||
if ( $mappings{$key} == 231 ) {
|
||||
$IDs{ $mappings{$key} } = 100 - $val;
|
||||
} else {
|
||||
$IDs{ $mappings{$key} } = $val;
|
||||
}
|
||||
}
|
||||
} ## end if (/:/)
|
||||
} ## end foreach ( split( /\n/, $output ) )
|
||||
|
||||
} else {
|
||||
@outputA = split( /\n/, $output );
|
||||
my $outputAint = 0;
|
||||
while ( defined( $outputA[$outputAint] ) ) {
|
||||
my $line = $outputA[$outputAint];
|
||||
$line =~ s/^ +//;
|
||||
$line =~ s/ +/ /g;
|
||||
|
||||
if ( $line =~ /^[0123456789]+ / ) {
|
||||
my @lineA = split( /\ /, $line, 10 );
|
||||
my $raw = $lineA[9];
|
||||
my $normalized = $lineA[3];
|
||||
my $id = $lineA[0];
|
||||
|
||||
# Crucial SSD
|
||||
# 202, Percent_Lifetime_Remain, same as 231, SSD Life Left
|
||||
if ( $id == 202
|
||||
&& $line =~ /Percent_Lifetime_Remain/ )
|
||||
{
|
||||
$IDs{231} = $raw;
|
||||
}
|
||||
|
||||
# single int raw values
|
||||
if ( ( $id == 5 )
|
||||
|| ( $id == 10 )
|
||||
|| ( $id == 173 )
|
||||
|| ( $id == 183 )
|
||||
|| ( $id == 184 )
|
||||
|| ( $id == 187 )
|
||||
|| ( $id == 196 )
|
||||
|| ( $id == 197 )
|
||||
|| ( $id == 198 )
|
||||
|| ( $id == 199 ) )
|
||||
{
|
||||
my @rawA = split( /\ /, $raw );
|
||||
$IDs{$id} = $rawA[0];
|
||||
} ## end if ( ( $id == 5 ) || ( $id == 10 ) || ( $id...))
|
||||
|
||||
# single int normalized values
|
||||
if ( ( $id == 177 )
|
||||
|| ( $id == 230 )
|
||||
|| ( $id == 231 )
|
||||
|| ( $id == 232 )
|
||||
|| ( $id == 233 ) )
|
||||
{
|
||||
# annoying non-standard disk
|
||||
# WDC WDS500G2B0A
|
||||
# 230 Media_Wearout_Indicator 0x0032 100 100 --- Old_age Always - 0x002e000a002e
|
||||
# 232 Available_Reservd_Space 0x0033 100 100 004 Pre-fail Always - 100
|
||||
# 233 NAND_GB_Written_TLC 0x0032 100 100 --- Old_age Always - 9816
|
||||
|
||||
if ( $id == 230
|
||||
&& $line =~ /Media_Wearout_Indicator/ )
|
||||
{
|
||||
$IDs{233} = int($normalized);
|
||||
} elsif ( $id == 232
|
||||
&& $line =~ /Available_Reservd_Space/ )
|
||||
{
|
||||
$IDs{232} = int($normalized);
|
||||
} else {
|
||||
# only set 233 if it has not been set yet
|
||||
# if it was set already then the above did it and we don't want
|
||||
# to overwrite it
|
||||
if ( $id == 233 && $IDs{233} eq "null" ) {
|
||||
$IDs{$id} = int($normalized);
|
||||
} elsif ( $id != 233 ) {
|
||||
$IDs{$id} = int($normalized);
|
||||
}
|
||||
} ## end else [ if ( $id == 230 && $line =~ /Media_Wearout_Indicator/)]
|
||||
} ## end if ( ( $id == 177 ) || ( $id == 230 ) || (...))
|
||||
|
||||
# 9, power on hours
|
||||
if ( $id == 9 ) {
|
||||
my @runtime = split( /[\ h]/, $raw );
|
||||
$IDs{$id} = $runtime[0];
|
||||
}
|
||||
|
||||
# 188, Command_Timeout
|
||||
if ( $id == 188 ) {
|
||||
my $total = 0;
|
||||
my @rawA = split( /\ /, $raw );
|
||||
my $rawAint = 0;
|
||||
while ( defined( $rawA[$rawAint] ) ) {
|
||||
$total = $total + $rawA[$rawAint];
|
||||
$rawAint++;
|
||||
}
|
||||
$IDs{$id} = $total;
|
||||
} ## end if ( $id == 188 )
|
||||
|
||||
# 190, airflow temp
|
||||
# 194, temp
|
||||
if ( ( $id == 190 )
|
||||
|| ( $id == 194 ) )
|
||||
{
|
||||
my ($temp) = split( /\ /, $raw );
|
||||
$IDs{$id} = $temp;
|
||||
}
|
||||
} ## end if ( $line =~ /^[0123456789]+ / )
|
||||
|
||||
# SAS Wrapping
|
||||
# Section by Cameron Munroe (munroenet[at]gmail.com)
|
||||
|
||||
# Elements in Grown Defect List.
|
||||
# Marking as 5 Reallocated_Sector_Ct
|
||||
if ( $line =~ "Elements in grown defect list:" ) {
|
||||
|
||||
my @lineA = split( /\ /, $line, 10 );
|
||||
my $raw = $lineA[5];
|
||||
|
||||
# Reallocated Sector Count ID
|
||||
$IDs{5} = $raw;
|
||||
|
||||
}
|
||||
|
||||
# Current Drive Temperature
|
||||
# Marking as 194 Temperature_Celsius
|
||||
if ( $line =~ "Current Drive Temperature:" ) {
|
||||
|
||||
my @lineA = split( /\ /, $line, 10 );
|
||||
my $raw = $lineA[3];
|
||||
|
||||
# Temperature C ID
|
||||
$IDs{194} = $raw;
|
||||
|
||||
}
|
||||
|
||||
# End of SAS Wrapper
|
||||
|
||||
$outputAint++;
|
||||
} ## end while ( defined( $outputA[$outputAint] ) )
|
||||
} ## end else [ if ( $output =~ /NVMe Log/ ) ]
|
||||
|
||||
#get the selftest logs
|
||||
$output = `$smartctl -l selftest $disk`;
|
||||
@outputA = split( /\n/, $output );
|
||||
my @completed = grep( /Completed/, @outputA );
|
||||
$IDs{'completed'} = scalar @completed;
|
||||
my @interrupted = grep( /Interrupted/, @outputA );
|
||||
$IDs{'interrupted'} = scalar @interrupted;
|
||||
my @read_failure = grep( /read failure/, @outputA );
|
||||
$IDs{'read_failure'} = scalar @read_failure;
|
||||
my @read_failure2 = grep( /Failed in segment/, @outputA );
|
||||
$IDs{'read_failure'} = $IDs{'read_failure'} + scalar @read_failure2;
|
||||
my @unknown_failure = grep( /unknown failure/, @outputA );
|
||||
$IDs{'unknown_failure'} = scalar @unknown_failure;
|
||||
my @extended = grep( /\d.*\ ([Ee]xtended|[Ll]ong).*(?![Dd]uration)/, @outputA );
|
||||
$IDs{'extended'} = scalar @extended;
|
||||
my @short = grep( /[Ss]hort/, @outputA );
|
||||
$IDs{'short'} = scalar @short;
|
||||
my @conveyance = grep( /[Cc]onveyance/, @outputA );
|
||||
$IDs{'conveyance'} = scalar @conveyance;
|
||||
my @selective = grep( /[Ss]elective/, @outputA );
|
||||
$IDs{'selective'} = scalar @selective;
|
||||
my @offline = grep( /(\d|[Bb]ackground|[Ff]oreground)+\ +[Oo]ffline/, @outputA );
|
||||
$IDs{'offline'} = scalar @offline;
|
||||
|
||||
# if we have logs, actually grab the log output
|
||||
if ( $IDs{'completed'} > 0
|
||||
|| $IDs{'interrupted'} > 0
|
||||
|| $IDs{'read_failure'} > 0
|
||||
|| $IDs{'extended'} > 0
|
||||
|| $IDs{'short'} > 0
|
||||
|| $IDs{'conveyance'} > 0
|
||||
|| $IDs{'selective'} > 0
|
||||
|| $IDs{'offline'} > 0 )
|
||||
{
|
||||
my @headers = grep( /(Num\ +Test.*LBA| Description .*[Hh]ours)/, @outputA );
|
||||
|
||||
my @log_lines;
|
||||
push( @log_lines, @extended, @short, @conveyance, @selective, @offline );
|
||||
$IDs{'selftest_log'} = join( "\n", @headers, sort(@log_lines) );
|
||||
} ## end if ( $IDs{'completed'} > 0 || $IDs{'interrupted'...})
|
||||
|
||||
# get the drive serial number, if needed
|
||||
$disk_id = $name;
|
||||
$output = `$smartctl -i $disk`;
|
||||
# generally upper case, HP branded drives seem to report with lower case n
|
||||
while ( $output =~ /(?i)Serial Number:(.*)/g ) {
|
||||
$IDs{'serial'} = $1;
|
||||
$IDs{'serial'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
if ($useSN) {
|
||||
$disk_id = $IDs{'serial'};
|
||||
}
|
||||
|
||||
while ( $output =~ /(?i)Model Family:(.*)/g ) {
|
||||
$IDs{'model_family'} = $1;
|
||||
$IDs{'model_family'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
while ( $output =~ /(?i)Device Model:(.*)/g ) {
|
||||
$IDs{'device_model'} = $1;
|
||||
$IDs{'device_model'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
while ( $output =~ /(?i)Model Number:(.*)/g ) {
|
||||
$IDs{'model_number'} = $1;
|
||||
$IDs{'model_number'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
while ( $output =~ /(?i)Firmware Version:(.*)/g ) {
|
||||
$IDs{'fw_version'} = $1;
|
||||
$IDs{'fw_version'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
# mainly HP drives
|
||||
while ( $output =~ /(?i)Vendor:(.*)/g ) {
|
||||
$IDs{'vendor'} = $1;
|
||||
$IDs{'vendor'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
# mainly HP drives
|
||||
while ( $output =~ /(?i)Product:(.*)/g ) {
|
||||
$IDs{'product'} = $1;
|
||||
$IDs{'product'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
# mainly HP drives
|
||||
while ( $output =~ /(?i)Revision:(.*)/g ) {
|
||||
$IDs{'revision'} = $1;
|
||||
$IDs{'revision'} =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
|
||||
# figure out what to use for the max temp, if there is one
|
||||
if ( $IDs{'190'} =~ /^\d+$/ ) {
|
||||
$IDs{max_temp} = $IDs{'190'};
|
||||
} elsif ( $IDs{'194'} =~ /^\d+$/ ) {
|
||||
$IDs{max_temp} = $IDs{'194'};
|
||||
}
|
||||
if ( $IDs{'194'} =~ /^\d+$/ && defined( $IDs{max_temp} ) && $IDs{'194'} > $IDs{max_temp} ) {
|
||||
$IDs{max_temp} = $IDs{'194'};
|
||||
}
|
||||
|
||||
$output = `$smartctl -H $disk`;
|
||||
if ( $output =~ /SMART\ overall\-health\ self\-assessment\ test\ result\:\ PASSED/ ) {
|
||||
$IDs{'health_pass'} = 1;
|
||||
} elsif ( $output =~ /SMART\ Health\ Status\:\ OK/ ) {
|
||||
$IDs{'health_pass'} = 1;
|
||||
}
|
||||
|
||||
if ( !$IDs{'health_pass'} ) {
|
||||
$to_return->{data}{unhealthy}++;
|
||||
}
|
||||
} ## end else [ if ( $IDs{exit} != 0 ) ]
|
||||
|
||||
# only bother to save this if useSN is not being used
|
||||
if ( !$useSN ) {
|
||||
$to_return->{data}{disks}{$disk_id} = \%IDs;
|
||||
} elsif ( $IDs{exit} == 0 && defined($disk_id) ) {
|
||||
$to_return->{data}{disks}{$disk_id} = \%IDs;
|
||||
}
|
||||
|
||||
# smartctl will in some cases exit zero when it can't pull data for cciss
|
||||
# so if we get a zero exit, but no serial then it means something errored
|
||||
# and the device is likely dead
|
||||
if ( $IDs{exit} == 0 && !defined( $IDs{serial} ) ) {
|
||||
$to_return->{data}{unhealthy}++;
|
||||
}
|
||||
} ## end foreach my $line (@disks)
|
||||
|
||||
my $toReturn = $json->encode($to_return);
|
||||
|
||||
if ( !$opts{p} ) {
|
||||
$toReturn = $toReturn . "\n";
|
||||
}
|
||||
|
||||
if ( $opts{Z} ) {
|
||||
my $toReturnCompressed;
|
||||
gzip \$toReturn => \$toReturnCompressed;
|
||||
my $compressed = encode_base64($toReturnCompressed);
|
||||
$compressed =~ s/\n//g;
|
||||
$compressed = $compressed . "\n";
|
||||
if ( length($compressed) < length($toReturn) ) {
|
||||
$toReturn = $compressed;
|
||||
}
|
||||
} ## end if ( $opts{Z} )
|
||||
|
||||
if ( !$noWrite ) {
|
||||
open( my $writefh, ">", $cache ) or die "Can't open '" . $cache . "'";
|
||||
print $writefh $toReturn;
|
||||
close($writefh);
|
||||
} else {
|
||||
print $toReturn;
|
||||
}
|
2048
ProjectCode/Agents/librenms/ss.py
Normal file
2048
ProjectCode/Agents/librenms/ss.py
Normal file
File diff suppressed because one or more lines are too long
45
ProjectCode/Agents/librenms/ups-nut.sh
Normal file
45
ProjectCode/Agents/librenms/ups-nut.sh
Normal file
@@ -0,0 +1,45 @@
|
||||
#!/bin/sh
|
||||
################################################################
|
||||
# Instructions: #
|
||||
# 1. copy this script to /etc/snmp/ and make it executable: #
|
||||
# chmod +x ups-nut.sh #
|
||||
# 2. make sure UPS_NAME below matches the name of your UPS #
|
||||
# 3. edit your snmpd.conf to include this line: #
|
||||
# extend ups-nut /etc/snmp/ups-nut.sh #
|
||||
# 4. restart snmpd on the host #
|
||||
# 5. activate the app for the desired host in LibreNMS #
|
||||
################################################################
|
||||
UPS_NAME="${1:-APCUPS}"
|
||||
|
||||
PATH=$PATH:/usr/bin:/bin
|
||||
TMP=$(upsc $UPS_NAME 2>/dev/null)
|
||||
|
||||
for value in "battery\.charge: [0-9.]+" "battery\.(runtime\.)?low: [0-9]+" "battery\.runtime: [0-9]+" "battery\.voltage: [0-9.]+" "battery\.voltage\.nominal: [0-9]+" "input\.voltage\.nominal: [0-9.]+" "input\.voltage: [0-9.]+" "ups\.load: [0-9.]+"
|
||||
do
|
||||
OUT=$(echo "$TMP" | grep -Eo "$value" | awk '{print $2}' | LANG=C sort | head -n 1)
|
||||
if [ -n "$OUT" ]; then
|
||||
echo "$OUT"
|
||||
else
|
||||
echo "Unknown"
|
||||
fi
|
||||
done
|
||||
|
||||
for value in "ups\.status:[A-Z ]{0,}OL" "ups\.status:[A-Z ]{0,}OB" "ups\.status:[A-Z ]{0,}LB" "ups\.status:[A-Z ]{0,}HB" "ups\.status:[A-Z ]{0,}RB" "ups\.status:[A-Z ]{0,}CHRG" "ups\.status:[A-Z ]{0,}DISCHRG" "ups\.status:[A-Z ]{0,}BYPASS" "ups\.status:[A-Z ]{0,}CAL" "ups\.status:[A-Z ]{0,}OFF" "ups\.status:[A-Z ]{0,}OVER" "ups\.status:[A-Z ]{0,}TRIM" "ups\.status:[A-Z ]{0,}BOOST" "ups\.status:[A-Z ]{0,}FSD" "ups\.alarm:[A-Z ]"
|
||||
do
|
||||
UNKNOWN=$(echo "$TMP" | grep -Eo "ups\.status:")
|
||||
if [ -z "$UNKNOWN" ]; then
|
||||
echo "Unknown"
|
||||
else
|
||||
OUT=$(echo "$TMP" | grep -Eo "$value")
|
||||
if [ -n "$OUT" ]; then
|
||||
echo "1"
|
||||
else
|
||||
echo "0"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
UPSTEMP="ups\.temperature: [0-9.]+"
|
||||
OUT=$(echo "$TMP" | grep -Eo "$UPSTEMP" | awk '{print $2}' | LANG=C sort | head -n 1)
|
||||
[ -n "$OUT" ] && echo "$OUT" || echo "Unknown"
|
||||
|
46
ProjectCode/ConfigFiles/AuditD/auditd.conf
Normal file
46
ProjectCode/ConfigFiles/AuditD/auditd.conf
Normal file
@@ -0,0 +1,46 @@
|
||||
#
|
||||
# Known Element Enterprises Customized Config File
|
||||
# auditd
|
||||
# Initial version 2025-06-27
|
||||
#
|
||||
|
||||
local_events = yes
|
||||
write_logs = yes
|
||||
log_file = /var/log/audit/audit.log
|
||||
log_group = adm
|
||||
log_format = ENRICHED
|
||||
flush = INCREMENTAL_ASYNC
|
||||
freq = 50
|
||||
max_log_file = 8
|
||||
num_logs = 5
|
||||
priority_boost = 4
|
||||
name_format = NONE
|
||||
max_log_file_action = keep_logs
|
||||
space_left = 75
|
||||
space_left_action = email
|
||||
action_mail_acct = root
|
||||
|
||||
admin_space_left_action = halt
|
||||
disk_full_action = SUSPEND
|
||||
disk_error_action = SUSPEND
|
||||
admin_space_left = 50
|
||||
|
||||
verify_email = yes
|
||||
use_libwrap = yes
|
||||
tcp_listen_queue = 5
|
||||
tcp_max_per_addr = 1
|
||||
tcp_client_max_idle = 0
|
||||
transport = TCP
|
||||
distribute_network = no
|
||||
q_depth = 2000
|
||||
overflow_action = SYSLOG
|
||||
max_restarts = 10
|
||||
plugin_dir = /etc/audit/plugins.d
|
||||
end_of_event_timeout = 2
|
||||
##tcp_client_ports = 1024-65535
|
||||
##tcp_listen_port = 60
|
||||
|
||||
##krb5_key_file = /etc/audit/audit.key
|
||||
krb5_principal = auditd
|
||||
|
||||
##name = mydomain
|
5
ProjectCode/ConfigFiles/BANNERS/issue
Normal file
5
ProjectCode/ConfigFiles/BANNERS/issue
Normal file
@@ -0,0 +1,5 @@
|
||||
This system is the property of Known Element Enterprises LLC.
|
||||
|
||||
Authorized uses only. All activity may be monitored and reported.
|
||||
|
||||
All activities subject to monitoring/recording/review in real time and/or at a later time.
|
5
ProjectCode/ConfigFiles/BANNERS/issue.net
Normal file
5
ProjectCode/ConfigFiles/BANNERS/issue.net
Normal file
@@ -0,0 +1,5 @@
|
||||
This system is the property of Known Element Enterprises LLC.
|
||||
|
||||
Authorized uses only. All activity may be monitored and reported.
|
||||
|
||||
All activities subject to monitoring/recording/review in real time and/or at a later time.
|
5
ProjectCode/ConfigFiles/BANNERS/motd
Normal file
5
ProjectCode/ConfigFiles/BANNERS/motd
Normal file
@@ -0,0 +1,5 @@
|
||||
This system is the property of Known Element Enterprises LLC.
|
||||
|
||||
Authorized uses only. All activity may be monitored and reported.
|
||||
|
||||
All activities subject to monitoring/recording/review in real time and/or at a later time.
|
2
ProjectCode/ConfigFiles/Cockpit/disallowed-users
Normal file
2
ProjectCode/ConfigFiles/Cockpit/disallowed-users
Normal file
@@ -0,0 +1,2 @@
|
||||
#/etc/cockpit/disallowed-users
|
||||
# List of users which are not allowed to login to Cockpit
|
6
ProjectCode/ConfigFiles/DHCP/dhclient.conf
Normal file
6
ProjectCode/ConfigFiles/DHCP/dhclient.conf
Normal file
@@ -0,0 +1,6 @@
|
||||
option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
|
||||
|
||||
send host-name = gethostname();
|
||||
request subnet-mask, broadcast-address, time-offset, routers,
|
||||
domain-name, host-name,
|
||||
rfc3442-classless-static-routes;
|
23
ProjectCode/ConfigFiles/Logrotate/logrotate.conf
Normal file
23
ProjectCode/ConfigFiles/Logrotate/logrotate.conf
Normal file
@@ -0,0 +1,23 @@
|
||||
# see "man logrotate" for details
|
||||
|
||||
# global options do not affect preceding include directives
|
||||
|
||||
# rotate log files weekly
|
||||
weekly
|
||||
|
||||
# keep 4 weeks worth of backlogs
|
||||
rotate 4
|
||||
|
||||
# create new (empty) log files after rotating old ones
|
||||
create 0640 root utmp
|
||||
|
||||
# use date as a suffix of the rotated file
|
||||
#dateext
|
||||
|
||||
# uncomment this if you want your log files compressed
|
||||
#compress
|
||||
|
||||
# packages drop log rotation information into this directory
|
||||
include /etc/logrotate.d
|
||||
|
||||
# system-specific logs may also be configured here.
|
1
ProjectCode/ConfigFiles/ModProbe/cramfs.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/cramfs.conf
Normal file
@@ -0,0 +1 @@
|
||||
install cramfs /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/dccp.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/dccp.conf
Normal file
@@ -0,0 +1 @@
|
||||
install dccp /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/freevxfs.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/freevxfs.conf
Normal file
@@ -0,0 +1 @@
|
||||
install freevxfs /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/hfs.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/hfs.conf
Normal file
@@ -0,0 +1 @@
|
||||
install hfs /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/hfsplus.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/hfsplus.conf
Normal file
@@ -0,0 +1 @@
|
||||
install hfsplus /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/jffs2.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/jffs2.conf
Normal file
@@ -0,0 +1 @@
|
||||
install jffs2 /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/rds.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/rds.conf
Normal file
@@ -0,0 +1 @@
|
||||
install rds /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/sctp.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/sctp.conf
Normal file
@@ -0,0 +1 @@
|
||||
install sctp /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/squashfs.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/squashfs.conf
Normal file
@@ -0,0 +1 @@
|
||||
install squashfs /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/tipc.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/tipc.conf
Normal file
@@ -0,0 +1 @@
|
||||
install tipc /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/udf.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/udf.conf
Normal file
@@ -0,0 +1 @@
|
||||
install udf /bin/true
|
1
ProjectCode/ConfigFiles/ModProbe/usb_storage.conf
Normal file
1
ProjectCode/ConfigFiles/ModProbe/usb_storage.conf
Normal file
@@ -0,0 +1 @@
|
||||
install usb-storage /bin/true
|
@@ -1,6 +1,7 @@
|
||||
driftfile /var/lib/ntp/ntp.drift
|
||||
leapfile /usr/share/zoneinfo/leap-seconds.list
|
||||
server 10.251.33.6
|
||||
server 10.251.33.7
|
||||
server pfv-netboot.knel.net
|
||||
restrict 127.0.0.1
|
||||
restrict ::1
|
||||
interface ignore wildcard
|
||||
interface listen 127.0.0.1
|
2
ProjectCode/ConfigFiles/NetworkDiscovery/lldpd
Normal file
2
ProjectCode/ConfigFiles/NetworkDiscovery/lldpd
Normal file
@@ -0,0 +1,2 @@
|
||||
# Uncomment to start SNMP subagent and enable CDP, SONMP and EDP protocol
|
||||
DAEMON_ARGS="-x -c -s -e"
|
1
ProjectCode/ConfigFiles/SMTP/postfix_generic
Normal file
1
ProjectCode/ConfigFiles/SMTP/postfix_generic
Normal file
@@ -0,0 +1 @@
|
||||
/.*/ tsysrootaccount@knel.net
|
1
ProjectCode/ConfigFiles/SNMP/snmp-sudo.conf
Normal file
1
ProjectCode/ConfigFiles/SNMP/snmp-sudo.conf
Normal file
@@ -0,0 +1 @@
|
||||
Debian-snmp ALL = NOPASSWD: /bin/cat
|
46
ProjectCode/ConfigFiles/SNMP/snmpd-physicalhost.conf
Normal file
46
ProjectCode/ConfigFiles/SNMP/snmpd-physicalhost.conf
Normal file
@@ -0,0 +1,46 @@
|
||||
##########################################################################
|
||||
# snmpd.conf
|
||||
# Created by CNW on 11/3/2018 via snmpconf wizard and manual post tweaks
|
||||
###########################################################################
|
||||
# SECTION: Monitor Various Aspects of the Running Host
|
||||
#
|
||||
|
||||
# disk: Check for disk space usage of a partition.
|
||||
# The agent can check the amount of available disk space, and make
|
||||
# sure it is above a set limit.
|
||||
#
|
||||
load 3 3 3
|
||||
rocommunity kn3lmgmt
|
||||
sysservices 76
|
||||
|
||||
#syslocation Rack, Room, Building, City, Country [Lat, Lon]
|
||||
syslocation R4, Server Room, SITER, Pflugerville, United States
|
||||
syscontact coo@turnsys.com
|
||||
|
||||
#NTP
|
||||
extend ntp-client /usr/lib/check_mk_agent/local/ntp-client
|
||||
|
||||
#SMTP
|
||||
extend mailq /usr/lib/check_mk_agent/local/postfix-queues
|
||||
extend postfixdetailed /usr/lib/check_mk_agent/local/postfixdetailed
|
||||
|
||||
#OS Distribution Detection
|
||||
extend distro /usr/local/bin/distro
|
||||
extend osupdate /usr/lib/check_mk_agent/local/os-updates.sh
|
||||
|
||||
#Hardware Detection
|
||||
extend manufacturer /usr/bin/sudo /usr/bin/cat /sys/devices/virtual/dmi/id/sys_vendor
|
||||
extend hardware /usr/bin/sudo /usr/bin/cat /sys/devices/virtual/dmi/id/product_name
|
||||
extend serial /usr/bin/sudo /usr/bin/cat /sys/devices/virtual/dmi/id/product_serial
|
||||
|
||||
#SMART
|
||||
extend smart /usr/lib/check_mk_agent/local/smart
|
||||
|
||||
#Temperature
|
||||
pass_persist .1.3.6.1.4.1.9.9.13.1.3 /usr/local/bin/temper-snmp
|
||||
|
||||
# Allow Systems Management Data Engine SNMP to connect to snmpd using SMUX
|
||||
# smuxpeer .1.3.6.1.4.1.674.10892.1
|
||||
|
||||
# LLDP collection
|
||||
master agentx
|
@@ -18,15 +18,15 @@ syslocation SITER, Pflugerville, United States
|
||||
syscontact coo@turnsys.com
|
||||
|
||||
#NTP
|
||||
extend ntp-client /usr/local/librenms/ntp-client.sh
|
||||
extend ntp-client /usr/lib/check_mk_agent/local/ntp-client
|
||||
|
||||
#SMTP
|
||||
extend mailq /usr/local/librenms/postfix-queues
|
||||
extend postfixdetailed /usr/local/librenms/postfixdetailed
|
||||
extend mailq /usr/lib/check_mk_agent/local/postfix-queues
|
||||
extend postfixdetailed /usr/lib/check_mk_agent/local/postfixdetailed
|
||||
|
||||
#OS Distribution Detection
|
||||
extend distro /usr/local/bin/distro
|
||||
extend osupdate /usr/local/librenms/os-updates.sh
|
||||
extend osupdate /usr/lib/check_mk_agent/local/os-updates.sh
|
||||
|
||||
|
||||
#Hardware Detection
|
||||
@@ -35,3 +35,6 @@ extend serial /usr/bin/sudo /usr/bin/cat /sys/firmware/devicetree/base/serial-nu
|
||||
|
||||
# Allow Systems Management Data Engine SNMP to connect to snmpd using SMUX
|
||||
# smuxpeer .1.3.6.1.4.1.674.10892.1
|
||||
|
||||
# LLDP collection
|
||||
master agentx
|
@@ -18,16 +18,18 @@ syslocation R4, Server Room, SITER, Pflugerville, United States
|
||||
syscontact coo@turnsys.com
|
||||
|
||||
#NTP
|
||||
extend ntp-client /usr/local/librenms/ntp-client.sh
|
||||
extend ntp-client /usr/lib/check_mk_agent/local/ntp-client
|
||||
|
||||
#SMTP
|
||||
extend mailq /usr/local/librenms/postfix-queues
|
||||
extend postfixdetailed /usr/local/librenms/postfixdetailed
|
||||
extend mailq /usr/lib/check_mk_agent/local/postfix-queues
|
||||
extend postfixdetailed /usr/lib/check_mk_agent/local/postfixdetailed
|
||||
|
||||
#OS Distribution Detection
|
||||
extend distro /usr/local/bin/distro
|
||||
extend osupdate /usr/local/librenms/os-updates.sh
|
||||
extend osupdate /usr/lib/check_mk_agent/local/os-updates.sh
|
||||
|
||||
# Socket statistics
|
||||
extend ss /usr/lib/check_mk_agent/local/ss.py
|
||||
|
||||
#Hardware Detection
|
||||
# (uncomment for x86 platforms)
|
||||
@@ -35,6 +37,8 @@ extend manufacturer /usr/bin/sudo /usr/bin/cat /sys/devices/virtual/dmi/id/sys_v
|
||||
extend hardware /usr/bin/sudo /usr/bin/cat /sys/devices/virtual/dmi/id/product_name
|
||||
extend serial /usr/bin/sudo /usr/bin/cat /sys/devices/virtual/dmi/id/product_serial
|
||||
|
||||
|
||||
# Allow Systems Management Data Engine SNMP to connect to snmpd using SMUX
|
||||
# smuxpeer .1.3.6.1.4.1.674.10892.1
|
||||
|
||||
# LLDP collection
|
||||
master agentx
|
@@ -0,0 +1,2 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDHaBNuLS+GYGRPc9wne63Ocr+R+/Q01Y9V0FTv0RnG3
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPyMR0lFgiMKhQJ5aqy68nR0BQp1cNzi/wIThyuTV4a8 tsyscto@ultix-control
|
@@ -0,0 +1,2 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDHaBNuLS+GYGRPc9wne63Ocr+R+/Q01Y9V0FTv0RnG3
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPyMR0lFgiMKhQJ5aqy68nR0BQp1cNzi/wIThyuTV4a8 tsyscto@ultix-control
|
19
ProjectCode/ConfigFiles/SSH/Configs/ssh-audit-hardening.conf
Normal file
19
ProjectCode/ConfigFiles/SSH/Configs/ssh-audit-hardening.conf
Normal file
@@ -0,0 +1,19 @@
|
||||
# Restrict key exchange, cipher, and MAC algorithms, as per sshaudit.com
|
||||
# hardening guide.
|
||||
KexAlgorithms sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,gss-curve25519-sha256-,diffie-hellman-group16-sha512,gss-group16-sha512-,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256
|
||||
|
||||
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-gcm@openssh.com,aes128-ctr
|
||||
|
||||
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,umac-128-etm@openssh.com
|
||||
|
||||
HostKeyAlgorithms sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256
|
||||
|
||||
RequiredRSASize 3072
|
||||
|
||||
CASignatureAlgorithms sk-ssh-ed25519@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256
|
||||
|
||||
GSSAPIKexAlgorithms gss-curve25519-sha256-,gss-group16-sha512-
|
||||
|
||||
HostbasedAcceptedAlgorithms sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,ssh-ed25519,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-512,rsa-sha2-256-cert-v01@openssh.com,rsa-sha2-256
|
||||
|
||||
PubkeyAcceptedAlgorithms sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,ssh-ed25519,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-512,rsa-sha2-256-cert-v01@openssh.com,rsa-sha2-256
|
20
ProjectCode/ConfigFiles/SSH/Configs/tsys-sshd-config
Normal file
20
ProjectCode/ConfigFiles/SSH/Configs/tsys-sshd-config
Normal file
@@ -0,0 +1,20 @@
|
||||
Include /etc/ssh/sshd_config.d/*.conf
|
||||
HostKey /etc/ssh/ssh_host_rsa_key
|
||||
HostKey /etc/ssh/ssh_host_ed25519_key
|
||||
KbdInteractiveAuthentication no
|
||||
PrintMotd no
|
||||
PasswordAuthentication no
|
||||
AllowTcpForwarding no
|
||||
X11Forwarding no
|
||||
ChallengeResponseAuthentication no
|
||||
AcceptEnv LANG LC_*
|
||||
Subsystem sftp /usr/lib/openssh/sftp-server
|
||||
UsePAM yes
|
||||
Banner /etc/issue.net
|
||||
MaxAuthTries 2
|
||||
MaxStartups 10:30:100
|
||||
PermitRootLogin prohibit-password
|
||||
ClientAliveInterval 300
|
||||
ClientAliveCountMax 3
|
||||
AllowUsers root localuser subodev
|
||||
LoginGraceTime 60
|
6
ProjectCode/ConfigFiles/Syslog/rsyslog.conf
Normal file
6
ProjectCode/ConfigFiles/Syslog/rsyslog.conf
Normal file
@@ -0,0 +1,6 @@
|
||||
module(load="imuxsock") # provides support for local system logging
|
||||
module(load="imklog") # provides kernel logging support
|
||||
#module(load="immark") # provides --MARK-- message capability
|
||||
|
||||
*.* @tsys-librenms.knel.net:514
|
||||
:omusrmsg:EOF
|
31
ProjectCode/ConfigFiles/Systemd/journald.conf
Normal file
31
ProjectCode/ConfigFiles/Systemd/journald.conf
Normal file
@@ -0,0 +1,31 @@
|
||||
[Journal]
|
||||
#Compress=yes
|
||||
#Seal=yes
|
||||
#SplitMode=uid
|
||||
#SyncIntervalSec=5m
|
||||
#RateLimitIntervalSec=30s
|
||||
#RateLimitBurst=10000
|
||||
#SystemMaxUse=
|
||||
#SystemKeepFree=
|
||||
#SystemMaxFileSize=
|
||||
#SystemMaxFiles=100
|
||||
#RuntimeMaxUse=
|
||||
#RuntimeKeepFree=
|
||||
#RuntimeMaxFileSize=
|
||||
#RuntimeMaxFiles=100
|
||||
#MaxRetentionSec=
|
||||
#MaxFileSec=1month
|
||||
#ForwardToSyslog=yes
|
||||
#ForwardToKMsg=no
|
||||
#ForwardToConsole=no
|
||||
#ForwardToWall=yes
|
||||
#TTYPath=/dev/console
|
||||
#MaxLevelStore=debug
|
||||
#MaxLevelSyslog=debug
|
||||
#MaxLevelKMsg=notice
|
||||
#MaxLevelConsole=info
|
||||
#MaxLevelWall=emerg
|
||||
#LineMax=48K
|
||||
#ReadKMsg=yes
|
||||
#Audit=no
|
||||
Storage=persistent
|
258
ProjectCode/ConfigFiles/ZSH/tsys-zshrc
Normal file
258
ProjectCode/ConfigFiles/ZSH/tsys-zshrc
Normal file
@@ -0,0 +1,258 @@
|
||||
# ~/.zshrc file for zsh interactive shells.
|
||||
# see /usr/share/doc/zsh/examples/zshrc for examples
|
||||
|
||||
setopt autocd # change directory just by typing its name
|
||||
#setopt correct # auto correct mistakes
|
||||
setopt interactivecomments # allow comments in interactive mode
|
||||
setopt magicequalsubst # enable filename expansion for arguments of the form ‘anything=expression’
|
||||
setopt nonomatch # hide error message if there is no match for the pattern
|
||||
setopt notify # report the status of background jobs immediately
|
||||
setopt numericglobsort # sort filenames numerically when it makes sense
|
||||
setopt promptsubst # enable command substitution in prompt
|
||||
|
||||
WORDCHARS=${WORDCHARS//\/} # Don't consider certain characters part of the word
|
||||
|
||||
# hide EOL sign ('%')
|
||||
PROMPT_EOL_MARK=""
|
||||
|
||||
# configure key keybindings
|
||||
bindkey -v # emacs key bindings
|
||||
bindkey ' ' magic-space # do history expansion on space
|
||||
bindkey '^U' backward-kill-line # ctrl + U
|
||||
bindkey '^[[3;5~' kill-word # ctrl + Supr
|
||||
bindkey '^[[3~' delete-char # delete
|
||||
bindkey '^[[1;5C' forward-word # ctrl + ->
|
||||
bindkey '^[[1;5D' backward-word # ctrl + <-
|
||||
bindkey '^[[5~' beginning-of-buffer-or-history # page up
|
||||
bindkey '^[[6~' end-of-buffer-or-history # page down
|
||||
bindkey '^[[H' beginning-of-line # home
|
||||
bindkey '^[[F' end-of-line # end
|
||||
bindkey '^[[Z' undo # shift + tab undo last action
|
||||
|
||||
# enable completion features
|
||||
autoload -Uz compinit
|
||||
compinit -d ~/.cache/zcompdump
|
||||
zstyle ':completion:*:*:*:*:*' menu select
|
||||
zstyle ':completion:*' auto-description 'specify: %d'
|
||||
zstyle ':completion:*' completer _expand _complete
|
||||
zstyle ':completion:*' format 'Completing %d'
|
||||
zstyle ':completion:*' group-name ''
|
||||
zstyle ':completion:*' list-colors ''
|
||||
zstyle ':completion:*' list-prompt %SAt %p: Hit TAB for more, or the character to insert%s
|
||||
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
|
||||
zstyle ':completion:*' rehash true
|
||||
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s
|
||||
zstyle ':completion:*' use-compctl false
|
||||
zstyle ':completion:*' verbose true
|
||||
zstyle ':completion:*:kill:*' command 'ps -u $USER -o pid,%cpu,tty,cputime,cmd'
|
||||
|
||||
# History configurations
|
||||
HISTFILE=~/.zsh_history
|
||||
HISTSIZE=10000
|
||||
SAVEHIST=200000
|
||||
setopt hist_expire_dups_first # delete duplicates first when HISTFILE size exceeds HISTSIZE
|
||||
setopt hist_ignore_dups # ignore duplicated commands history list
|
||||
setopt hist_ignore_space # ignore commands that start with space
|
||||
setopt hist_verify # show command with history expansion to user before running it
|
||||
#setopt share_history # share command history data
|
||||
|
||||
# force zsh to show the complete history
|
||||
alias history="history 0"
|
||||
|
||||
# configure `time` format
|
||||
TIMEFMT=$'\nreal\t%E\nuser\t%U\nsys\t%S\ncpu\t%P'
|
||||
|
||||
# make less more friendly for non-text input files, see lesspipe(1)
|
||||
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
|
||||
|
||||
# set variable identifying the chroot you work in (used in the prompt below)
|
||||
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
|
||||
debian_chroot=$(cat /etc/debian_chroot)
|
||||
fi
|
||||
|
||||
# set a fancy prompt (non-color, unless we know we "want" color)
|
||||
case "$TERM" in
|
||||
xterm-color|*-256color) color_prompt=yes;;
|
||||
esac
|
||||
|
||||
# uncomment for a colored prompt, if the terminal has the capability; turned
|
||||
# off by default to not distract the user: the focus in a terminal window
|
||||
# should be on the output of commands, not on the prompt
|
||||
force_color_prompt=yes
|
||||
|
||||
if [ -n "$force_color_prompt" ]; then
|
||||
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
|
||||
# We have color support; assume it's compliant with Ecma-48
|
||||
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
|
||||
# a case would tend to support setf rather than setaf.)
|
||||
color_prompt=yes
|
||||
else
|
||||
color_prompt=
|
||||
fi
|
||||
fi
|
||||
|
||||
configure_prompt() {
|
||||
prompt_symbol=㉿
|
||||
# Skull emoji for root terminal
|
||||
#[ "$EUID" -eq 0 ] && prompt_symbol=💀
|
||||
case "$PROMPT_ALTERNATIVE" in
|
||||
twoline)
|
||||
PROMPT=$'%F{%(#.blue.green)}┌──${debian_chroot:+($debian_chroot)─}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))─}(%B%F{%(#.red.blue)}%n'$prompt_symbol$'%m%b%F{%(#.blue.green)})-[%B%F{reset}%(6~.%-1~/…/%4~.%5~)%b%F{%(#.blue.green)}]\n└─%B%(#.%F{red}#.%F{blue}$)%b%F{reset} '
|
||||
# Right-side prompt with exit codes and background processes
|
||||
#RPROMPT=$'%(?.. %? %F{red}%B⨯%b%F{reset})%(1j. %j %F{yellow}%B⚙%b%F{reset}.)'
|
||||
;;
|
||||
oneline)
|
||||
PROMPT=$'${debian_chroot:+($debian_chroot)}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))}%B%F{%(#.red.blue)}%n@%m%b%F{reset}:%B%F{%(#.blue.green)}%~%b%F{reset}%(#.#.$) '
|
||||
RPROMPT=
|
||||
;;
|
||||
backtrack)
|
||||
PROMPT=$'${debian_chroot:+($debian_chroot)}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))}%B%F{red}%n@%m%b%F{reset}:%B%F{blue}%~%b%F{reset}%(#.#.$) '
|
||||
RPROMPT=
|
||||
;;
|
||||
esac
|
||||
unset prompt_symbol
|
||||
}
|
||||
|
||||
# The following block is surrounded by two delimiters.
|
||||
# These delimiters must not be modified. Thanks.
|
||||
# START KALI CONFIG VARIABLES
|
||||
PROMPT_ALTERNATIVE=twoline
|
||||
NEWLINE_BEFORE_PROMPT=yes
|
||||
# STOP KALI CONFIG VARIABLES
|
||||
|
||||
if [ "$color_prompt" = yes ]; then
|
||||
# override default virtualenv indicator in prompt
|
||||
VIRTUAL_ENV_DISABLE_PROMPT=1
|
||||
|
||||
configure_prompt
|
||||
|
||||
# enable syntax-highlighting
|
||||
if [ -f /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ]; then
|
||||
. /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
|
||||
ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern)
|
||||
ZSH_HIGHLIGHT_STYLES[default]=none
|
||||
ZSH_HIGHLIGHT_STYLES[unknown-token]=underline
|
||||
ZSH_HIGHLIGHT_STYLES[reserved-word]=fg=cyan,bold
|
||||
ZSH_HIGHLIGHT_STYLES[suffix-alias]=fg=green,underline
|
||||
ZSH_HIGHLIGHT_STYLES[global-alias]=fg=green,bold
|
||||
ZSH_HIGHLIGHT_STYLES[precommand]=fg=green,underline
|
||||
ZSH_HIGHLIGHT_STYLES[commandseparator]=fg=blue,bold
|
||||
ZSH_HIGHLIGHT_STYLES[autodirectory]=fg=green,underline
|
||||
ZSH_HIGHLIGHT_STYLES[path]=bold
|
||||
ZSH_HIGHLIGHT_STYLES[path_pathseparator]=
|
||||
ZSH_HIGHLIGHT_STYLES[path_prefix_pathseparator]=
|
||||
ZSH_HIGHLIGHT_STYLES[globbing]=fg=blue,bold
|
||||
ZSH_HIGHLIGHT_STYLES[history-expansion]=fg=blue,bold
|
||||
ZSH_HIGHLIGHT_STYLES[command-substitution]=none
|
||||
ZSH_HIGHLIGHT_STYLES[command-substitution-delimiter]=fg=magenta,bold
|
||||
ZSH_HIGHLIGHT_STYLES[process-substitution]=none
|
||||
ZSH_HIGHLIGHT_STYLES[process-substitution-delimiter]=fg=magenta,bold
|
||||
ZSH_HIGHLIGHT_STYLES[single-hyphen-option]=fg=green
|
||||
ZSH_HIGHLIGHT_STYLES[double-hyphen-option]=fg=green
|
||||
ZSH_HIGHLIGHT_STYLES[back-quoted-argument]=none
|
||||
ZSH_HIGHLIGHT_STYLES[back-quoted-argument-delimiter]=fg=blue,bold
|
||||
ZSH_HIGHLIGHT_STYLES[single-quoted-argument]=fg=yellow
|
||||
ZSH_HIGHLIGHT_STYLES[double-quoted-argument]=fg=yellow
|
||||
ZSH_HIGHLIGHT_STYLES[dollar-quoted-argument]=fg=yellow
|
||||
ZSH_HIGHLIGHT_STYLES[rc-quote]=fg=magenta
|
||||
ZSH_HIGHLIGHT_STYLES[dollar-double-quoted-argument]=fg=magenta,bold
|
||||
ZSH_HIGHLIGHT_STYLES[back-double-quoted-argument]=fg=magenta,bold
|
||||
ZSH_HIGHLIGHT_STYLES[back-dollar-quoted-argument]=fg=magenta,bold
|
||||
ZSH_HIGHLIGHT_STYLES[assign]=none
|
||||
ZSH_HIGHLIGHT_STYLES[redirection]=fg=blue,bold
|
||||
ZSH_HIGHLIGHT_STYLES[comment]=fg=black,bold
|
||||
ZSH_HIGHLIGHT_STYLES[named-fd]=none
|
||||
ZSH_HIGHLIGHT_STYLES[numeric-fd]=none
|
||||
ZSH_HIGHLIGHT_STYLES[arg0]=fg=cyan
|
||||
ZSH_HIGHLIGHT_STYLES[bracket-error]=fg=red,bold
|
||||
ZSH_HIGHLIGHT_STYLES[bracket-level-1]=fg=blue,bold
|
||||
ZSH_HIGHLIGHT_STYLES[bracket-level-2]=fg=green,bold
|
||||
ZSH_HIGHLIGHT_STYLES[bracket-level-3]=fg=magenta,bold
|
||||
ZSH_HIGHLIGHT_STYLES[bracket-level-4]=fg=yellow,bold
|
||||
ZSH_HIGHLIGHT_STYLES[bracket-level-5]=fg=cyan,bold
|
||||
ZSH_HIGHLIGHT_STYLES[cursor-matchingbracket]=standout
|
||||
fi
|
||||
else
|
||||
PROMPT='${debian_chroot:+($debian_chroot)}%n@%m:%~%(#.#.$) '
|
||||
fi
|
||||
unset color_prompt force_color_prompt
|
||||
|
||||
toggle_oneline_prompt(){
|
||||
if [ "$PROMPT_ALTERNATIVE" = oneline ]; then
|
||||
PROMPT_ALTERNATIVE=twoline
|
||||
else
|
||||
PROMPT_ALTERNATIVE=oneline
|
||||
fi
|
||||
configure_prompt
|
||||
zle reset-prompt
|
||||
}
|
||||
zle -N toggle_oneline_prompt
|
||||
bindkey ^P toggle_oneline_prompt
|
||||
|
||||
# If this is an xterm set the title to user@host:dir
|
||||
case "$TERM" in
|
||||
xterm*|rxvt*|Eterm|aterm|kterm|gnome*|alacritty)
|
||||
TERM_TITLE=$'\e]0;${debian_chroot:+($debian_chroot)}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))}%n@%m: %~\a'
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
|
||||
precmd() {
|
||||
# Print the previously configured title
|
||||
print -Pnr -- "$TERM_TITLE"
|
||||
|
||||
# Print a new line before the prompt, but only if it is not the first line
|
||||
if [ "$NEWLINE_BEFORE_PROMPT" = yes ]; then
|
||||
if [ -z "$_NEW_LINE_BEFORE_PROMPT" ]; then
|
||||
_NEW_LINE_BEFORE_PROMPT=1
|
||||
else
|
||||
print ""
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# enable color support of ls, less and man, and also add handy aliases
|
||||
if [ -x /usr/bin/dircolors ]; then
|
||||
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
|
||||
export LS_COLORS="$LS_COLORS:ow=30;44:" # fix ls color for folders with 777 permissions
|
||||
|
||||
alias ls='ls --color=auto'
|
||||
#alias dir='dir --color=auto'
|
||||
#alias vdir='vdir --color=auto'
|
||||
|
||||
alias grep='grep --color=auto'
|
||||
alias fgrep='fgrep --color=auto'
|
||||
alias egrep='egrep --color=auto'
|
||||
alias diff='diff --color=auto'
|
||||
alias ip='ip --color=auto'
|
||||
|
||||
export LESS_TERMCAP_mb=$'\E[1;31m' # begin blink
|
||||
export LESS_TERMCAP_md=$'\E[1;36m' # begin bold
|
||||
export LESS_TERMCAP_me=$'\E[0m' # reset bold/blink
|
||||
export LESS_TERMCAP_so=$'\E[01;33m' # begin reverse video
|
||||
export LESS_TERMCAP_se=$'\E[0m' # reset reverse video
|
||||
export LESS_TERMCAP_us=$'\E[1;32m' # begin underline
|
||||
export LESS_TERMCAP_ue=$'\E[0m' # reset underline
|
||||
|
||||
# Take advantage of $LS_COLORS for completion as well
|
||||
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
|
||||
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'
|
||||
fi
|
||||
|
||||
# some more ls aliases
|
||||
alias ll='ls -l'
|
||||
alias la='ls -A'
|
||||
alias l='ls -CF'
|
||||
|
||||
# enable auto-suggestions based on the history
|
||||
if [ -f /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh ]; then
|
||||
. /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh
|
||||
# change suggestion color
|
||||
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=#999'
|
||||
fi
|
||||
|
||||
# enable command-not-found if installed
|
||||
if [ -f /etc/zsh_command_not_found ]; then
|
||||
. /etc/zsh_command_not_found
|
||||
fi
|
34
ProjectCode/Dell/Server/omsa.sh
Normal file
34
ProjectCode/Dell/Server/omsa.sh
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
|
||||
#curl -s http://dl.turnsys.net/omsa.sh|/bin/bash
|
||||
|
||||
gpg --keyserver hkp://pool.sks-keyservers.net:80 --recv-key 1285491434D8786F
|
||||
gpg -a --export 1285491434D8786F | apt-key add -
|
||||
echo "deb https://linux.dell.com/repo/community/openmanage/930/bionic bionic main" > /etc/apt/sources.list.d/linux.dell.com.sources.list
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman-curl-client-transport1_2.6.5-0ubuntu3_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman-client4_2.6.5-0ubuntu3_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman1_2.6.5-0ubuntu3_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman-server1_2.6.5-0ubuntu3_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/s/sblim-sfcc/libcimcclient0_2.2.8-0ubuntu2_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/openwsman_2.6.5-0ubuntu3_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/multiverse/c/cim-schema/cim-schema_2.48.0-0ubuntu1_all.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/s/sblim-sfc-common/libsfcutil0_1.0.1-0ubuntu4_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/multiverse/s/sblim-sfcb/sfcb_1.4.9-0ubuntu5_amd64.deb
|
||||
wget https://archive.ubuntu.com/ubuntu/pool/universe/s/sblim-cmpi-devel/libcmpicppimpl0_2.0.3-0ubuntu2_amd64.deb
|
||||
dpkg -i libwsman-curl-client-transport1_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libwsman-client4_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libwsman1_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libwsman-server1_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libcimcclient0_2.2.8-0ubuntu2_amd64.deb
|
||||
dpkg -i openwsman_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i cim-schema_2.48.0-0ubuntu1_all.deb
|
||||
dpkg -i libsfcutil0_1.0.1-0ubuntu4_amd64.deb
|
||||
dpkg -i sfcb_1.4.9-0ubuntu5_amd64.deb
|
||||
dpkg -i libcmpicppimpl0_2.0.3-0ubuntu2_amd64.deb
|
||||
|
||||
apt update
|
||||
apt -y install srvadmin-all
|
||||
touch /opt/dell/srvadmin/lib64/openmanage/IGNORE_GENERATION
|
||||
|
||||
#logout,login, then run
|
||||
# srvadmin-services.sh enable && srvadmin-services.sh start
|
0
ProjectCode/Modules/Auth/auth-cloudron-ldap.sh
Normal file
0
ProjectCode/Modules/Auth/auth-cloudron-ldap.sh
Normal file
63
ProjectCode/Modules/OAM/oam-librenms.sh
Normal file
63
ProjectCode/Modules/OAM/oam-librenms.sh
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/bin/bash
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../../../)"
|
||||
|
||||
#Framework variables are read from hee
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../../../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
print_info "Setting up librenms agent..."
|
||||
|
||||
cat ../../Agents/librenms/distro > /usr/local/bin/distro
|
||||
chmod +x /usr/local/bin/distro
|
||||
|
||||
if [ ! -d /usr/lib/check_mk_agent ]; then
|
||||
mkdir -p /usr/lib/check_mk_agent
|
||||
fi
|
||||
|
||||
if [ ! -d /usr/lib/check_mk_agent/plugins ]; then
|
||||
mkdir -p /usr/lib/check_mk_agent/plugins
|
||||
fi
|
||||
|
||||
if [ ! -d /usr/lib/check_mk_agent/local ]; then
|
||||
mkdir -p /usr/lib/check_mk_agent/local
|
||||
fi
|
||||
|
||||
cat ../../Agents/librenms/check_mk_agent > /usr/bin/check_mk_agent
|
||||
chmod +x /usr/bin/check_mk_agent
|
||||
|
||||
cat ../../Agents/librenms/check_mk@.service > /etc/systemd/system/check_mk@.service
|
||||
cat ../../Agents/librenms/check_mk.socket > /etc/systemd/system/check_mk.socket
|
||||
|
||||
systemctl enable check_mk.socket
|
||||
systemctl start check_mk.socket
|
||||
|
||||
#Modules commented out below, we will roll out on systems that use them, most of the fleet doesn't use those modules
|
||||
|
||||
cat ../../Agents/librenms/dmi.sh > /usr/lib/check_mk_agent/local/dmi.sh
|
||||
cat ../../Agents/librenms/dpkg.sh > /usr/lib/check_mk_agent/local/dpkg.sh
|
||||
#cat ../../Agents/librenms/mysql.sh > /usr/lib/check_mk_agent/local/mysql.sh
|
||||
cat ../../Agents/librenms/ntp-client > /usr/lib/check_mk_agent/local/ntp-client
|
||||
#cat ../../Agents/librenms/ntp-server.sh > /usr/lib/check_mk_agent/local/ntp-server.sh
|
||||
cat ../../Agents/librenms/os-updates.sh > /usr/lib/check_mk_agent/local/os-updates.sh
|
||||
cat ../../Agents/librenms/postfixdetailed > /usr/lib/check_mk_agent/local/postfixdetailed
|
||||
cat ../../Agents/librenms/postfix-queues > /usr/lib/check_mk_agent/local/postfix-queues
|
||||
#cat ../../Agents/librenms/smart.sh > /usr/lib/check_mk_agent/local/smart
|
||||
#cat ../../Agents/librenms/smart.sh.config > /usr/lib/check_mk_agent/local/smart.config
|
||||
|
||||
chmod +x /usr/lib/check_mk_agent/local/*
|
@@ -8,13 +8,13 @@ OPENSSL_FILE="openssl-1.1.0h.tar.gz"
|
||||
NGHTTP_URL_BASE="https://github.com/nghttp2/nghttp2/releases/download/v1.31.0/"
|
||||
NGHTTP_FILE="nghttp2-1.31.0.tar.gz"
|
||||
|
||||
APR_URL_BASE="http://mirrors.whoishostingthis.com/apache/apr/"
|
||||
APR_URL_BASE="https://archive.apache.org/dist/apr/"
|
||||
APR_FILE="apr-1.6.3.tar.gz"
|
||||
|
||||
APR_UTIL_URL_BASE="http://mirrors.whoishostingthis.com/apache/apr/"
|
||||
APR_UTIL_URL_BASE="https://archive.apache.org/dist/apr/"
|
||||
APR_UTIL_FILE="apr-util-1.6.1.tar.gz"
|
||||
|
||||
APACHE_URL_BASE="http://mirrors.whoishostingthis.com/apache/httpd/"
|
||||
APACHE_URL_BASE="https://archive.apache.org/dist/httpd/"
|
||||
APACHE_FILE="httpd-2.4.33.tar.gz"
|
||||
|
||||
CURL_URL_BASE="https://curl.haxx.se/download/"
|
410
ProjectCode/Modules/Security/secharden-2fa.sh
Normal file
410
ProjectCode/Modules/Security/secharden-2fa.sh
Normal file
@@ -0,0 +1,410 @@
|
||||
#!/bin/bash
|
||||
|
||||
# TSYS Security Hardening - Two-Factor Authentication
|
||||
# Implements 2FA for SSH, Cockpit, and Webmin services
|
||||
# Uses Google Authenticator (TOTP) for time-based tokens
|
||||
|
||||
|
||||
#####
|
||||
#Core framework functions...
|
||||
#####
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../../../)"
|
||||
|
||||
#Framework variables are read from hee
|
||||
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../../../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
#Framework variables are read from hee
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
# 2FA Configuration
|
||||
BACKUP_DIR="/root/backup/2fa"
|
||||
PAM_CONFIG_DIR="/etc/pam.d"
|
||||
SSH_CONFIG="/etc/ssh/sshd_config"
|
||||
COCKPIT_CONFIG="/etc/cockpit/cockpit.conf"
|
||||
|
||||
# Create backup directory
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
print_info "TSYS Two-Factor Authentication Setup"
|
||||
|
||||
# Backup existing configurations
|
||||
function backup_configs() {
|
||||
print_info "Creating backup of existing configurations..."
|
||||
|
||||
# Backup SSH configuration
|
||||
if [[ -f "$SSH_CONFIG" ]]; then
|
||||
cp "$SSH_CONFIG" "$BACKUP_DIR/sshd_config.bak"
|
||||
print_info "SSH config backed up"
|
||||
fi
|
||||
|
||||
# Backup PAM configurations
|
||||
if [[ -d "$PAM_CONFIG_DIR" ]]; then
|
||||
cp -r "$PAM_CONFIG_DIR" "$BACKUP_DIR/pam.d.bak"
|
||||
print_info "PAM configs backed up"
|
||||
fi
|
||||
|
||||
# Backup Cockpit configuration if exists
|
||||
if [[ -f "$COCKPIT_CONFIG" ]]; then
|
||||
cp "$COCKPIT_CONFIG" "$BACKUP_DIR/cockpit.conf.bak"
|
||||
print_info "Cockpit config backed up"
|
||||
fi
|
||||
|
||||
print_info "Backup completed: $BACKUP_DIR"
|
||||
}
|
||||
|
||||
# Install required packages
|
||||
function install_2fa_packages() {
|
||||
print_info "Installing 2FA packages..."
|
||||
|
||||
# Update package cache
|
||||
apt-get update
|
||||
|
||||
# Install Google Authenticator PAM module
|
||||
# Install QR code generator for terminal display
|
||||
apt-get install -y libpam-google-authenticator qrencode
|
||||
|
||||
print_info "2FA packages installed successfully"
|
||||
}
|
||||
|
||||
# Configure SSH for 2FA
|
||||
function configure_ssh_2fa() {
|
||||
print_info "Configuring SSH for 2FA..."
|
||||
|
||||
# Configure SSH daemon
|
||||
print_info "Updating SSH configuration..."
|
||||
|
||||
# Enable challenge-response authentication
|
||||
if ! grep -q "^ChallengeResponseAuthentication yes" "$SSH_CONFIG"; then
|
||||
sed -i 's/^ChallengeResponseAuthentication.*/ChallengeResponseAuthentication yes/' "$SSH_CONFIG" || \
|
||||
echo "ChallengeResponseAuthentication yes" >> "$SSH_CONFIG"
|
||||
fi
|
||||
|
||||
# Enable PAM authentication
|
||||
if ! grep -q "^UsePAM yes" "$SSH_CONFIG"; then
|
||||
sed -i 's/^UsePAM.*/UsePAM yes/' "$SSH_CONFIG" || \
|
||||
echo "UsePAM yes" >> "$SSH_CONFIG"
|
||||
fi
|
||||
|
||||
# Configure authentication methods (key + 2FA)
|
||||
if ! grep -q "^AuthenticationMethods" "$SSH_CONFIG"; then
|
||||
echo "AuthenticationMethods publickey,keyboard-interactive" >> "$SSH_CONFIG"
|
||||
else
|
||||
sed -i 's/^AuthenticationMethods.*/AuthenticationMethods publickey,keyboard-interactive/' "$SSH_CONFIG"
|
||||
fi
|
||||
|
||||
print_info "SSH configuration updated"
|
||||
}
|
||||
|
||||
# Configure PAM for 2FA
|
||||
function configure_pam_2fa() {
|
||||
print_info "Configuring PAM for 2FA..."
|
||||
|
||||
# Create backup of original PAM SSH config
|
||||
cp "$PAM_CONFIG_DIR/sshd" "$PAM_CONFIG_DIR/sshd.bak.$(date +%Y%m%d)"
|
||||
|
||||
# Configure PAM to use Google Authenticator
|
||||
cat > "$PAM_CONFIG_DIR/sshd" << 'EOF'
|
||||
# PAM configuration for SSH with 2FA
|
||||
# Standard Un*x authentication
|
||||
@include common-auth
|
||||
|
||||
# Google Authenticator 2FA
|
||||
auth required pam_google_authenticator.so nullok
|
||||
|
||||
# Standard Un*x authorization
|
||||
@include common-account
|
||||
|
||||
# SELinux needs to be the first session rule
|
||||
session required pam_selinux.so close
|
||||
session required pam_loginuid.so
|
||||
|
||||
# Standard Un*x session setup and teardown
|
||||
@include common-session
|
||||
|
||||
# Print the message of the day upon successful login
|
||||
session optional pam_motd.so motd=/run/motd.dynamic
|
||||
session optional pam_motd.so noupdate
|
||||
|
||||
# Print the status of the user's mailbox upon successful login
|
||||
session optional pam_mail.so standard noenv
|
||||
|
||||
# Set up user limits from /etc/security/limits.conf
|
||||
session required pam_limits.so
|
||||
|
||||
# SELinux needs to intervene at login time
|
||||
session required pam_selinux.so open
|
||||
|
||||
# Standard Un*x password updating
|
||||
@include common-password
|
||||
EOF
|
||||
|
||||
print_info "PAM configuration updated for SSH 2FA"
|
||||
}
|
||||
|
||||
# Configure Cockpit for 2FA
|
||||
function configure_cockpit_2fa() {
|
||||
print_info "Configuring Cockpit for 2FA..."
|
||||
|
||||
# Create Cockpit config directory if it doesn't exist
|
||||
mkdir -p "$(dirname "$COCKPIT_CONFIG")"
|
||||
|
||||
# Configure Cockpit to use PAM with 2FA
|
||||
cat > "$COCKPIT_CONFIG" << 'EOF'
|
||||
[WebService]
|
||||
# Enable 2FA for Cockpit web interface
|
||||
LoginTitle = TSYS Server Management
|
||||
LoginTo = 300
|
||||
RequireHost = true
|
||||
|
||||
[Session]
|
||||
# Use PAM for authentication (includes 2FA)
|
||||
Banner = /etc/cockpit/issue.cockpit
|
||||
IdleTimeout = 15
|
||||
EOF
|
||||
|
||||
# Create PAM configuration for Cockpit
|
||||
cat > "$PAM_CONFIG_DIR/cockpit" << 'EOF'
|
||||
# PAM configuration for Cockpit with 2FA
|
||||
auth requisite pam_nologin.so
|
||||
auth required pam_env.so
|
||||
auth required pam_faillock.so preauth
|
||||
auth sufficient pam_unix.so try_first_pass
|
||||
auth required pam_google_authenticator.so nullok
|
||||
auth required pam_faillock.so authfail
|
||||
auth required pam_deny.so
|
||||
|
||||
account required pam_nologin.so
|
||||
account include system-auth
|
||||
account required pam_faillock.so
|
||||
|
||||
session required pam_selinux.so close
|
||||
session required pam_loginuid.so
|
||||
session optional pam_keyinit.so force revoke
|
||||
session include system-auth
|
||||
session required pam_selinux.so open
|
||||
session optional pam_motd.so
|
||||
EOF
|
||||
|
||||
print_info "Cockpit 2FA configuration completed"
|
||||
}
|
||||
|
||||
# Configure Webmin for 2FA (if installed)
|
||||
function configure_webmin_2fa() {
|
||||
print_info "Checking for Webmin installation..."
|
||||
|
||||
local webmin_config="/etc/webmin/miniserv.conf"
|
||||
|
||||
if [[ -f "$webmin_config" ]]; then
|
||||
print_info "Webmin found, configuring 2FA..."
|
||||
|
||||
# Stop webmin service
|
||||
systemctl stop webmin || true
|
||||
|
||||
# Enable 2FA in Webmin configuration
|
||||
sed -i 's/^twofactor_provider=.*/twofactor_provider=totp/' "$webmin_config" || \
|
||||
echo "twofactor_provider=totp" >> "$webmin_config"
|
||||
|
||||
# Enable 2FA requirement
|
||||
sed -i 's/^twofactor=.*/twofactor=1/' "$webmin_config" || \
|
||||
echo "twofactor=1" >> "$webmin_config"
|
||||
|
||||
# Start webmin service
|
||||
systemctl start webmin || true
|
||||
|
||||
print_info "Webmin 2FA configuration completed"
|
||||
else
|
||||
print_info "Webmin not found, skipping configuration"
|
||||
fi
|
||||
}
|
||||
|
||||
# Setup 2FA for users
|
||||
function setup_user_2fa() {
|
||||
print_info "Setting up 2FA for system users..."
|
||||
|
||||
local users=("localuser" "root")
|
||||
|
||||
for user in "${users[@]}"; do
|
||||
if id "$user" &>/dev/null; then
|
||||
print_info "Setting up 2FA for user: $user"
|
||||
|
||||
# Create 2FA setup script for user
|
||||
cat > "/tmp/setup-2fa-$user.sh" << 'EOF'
|
||||
#!/bin/bash
|
||||
echo "Setting up Google Authenticator for user: $USER"
|
||||
echo "Please follow the prompts to configure 2FA:"
|
||||
echo "1. Answer 'y' to update your time-based token"
|
||||
echo "2. Scan the QR code with your authenticator app"
|
||||
echo "3. Save the backup codes in a secure location"
|
||||
echo "4. Answer 'y' to the remaining questions for security"
|
||||
echo ""
|
||||
google-authenticator -t -d -f -r 3 -R 30 -W
|
||||
EOF
|
||||
|
||||
chmod +x "/tmp/setup-2fa-$user.sh"
|
||||
|
||||
# Instructions for user setup
|
||||
cat > "~$user/2fa-setup-instructions.txt" << EOF
|
||||
TSYS Two-Factor Authentication Setup Instructions
|
||||
==============================================
|
||||
|
||||
Your system has been configured for 2FA. To complete setup:
|
||||
|
||||
1. Install an authenticator app on your phone:
|
||||
- Google Authenticator
|
||||
- Authy
|
||||
- Microsoft Authenticator
|
||||
|
||||
2. Run the setup command:
|
||||
sudo /tmp/setup-2fa-$user.sh
|
||||
|
||||
3. Follow the prompts:
|
||||
- Scan the QR code with your app
|
||||
- Save the backup codes securely
|
||||
- Answer 'y' to security questions
|
||||
|
||||
4. Test your setup:
|
||||
- SSH to the server
|
||||
- Enter your 6-digit code when prompted
|
||||
|
||||
IMPORTANT: Save backup codes in a secure location!
|
||||
Without them, you may be locked out if you lose your phone.
|
||||
|
||||
For support, contact your system administrator.
|
||||
EOF
|
||||
|
||||
chown "$user:$user" "~$user/2fa-setup-instructions.txt"
|
||||
print_info "2FA setup prepared for user: $user"
|
||||
else
|
||||
print_info "User $user not found, skipping"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Restart services
|
||||
function restart_services() {
|
||||
print_info "Restarting services..."
|
||||
|
||||
# Test SSH configuration
|
||||
if sshd -t; then
|
||||
systemctl restart sshd
|
||||
print_info "SSH service restarted"
|
||||
else
|
||||
print_error "SSH configuration test failed"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Restart Cockpit if installed
|
||||
if systemctl is-enabled cockpit.socket &>/dev/null; then
|
||||
systemctl restart cockpit.socket
|
||||
print_info "Cockpit service restarted"
|
||||
fi
|
||||
|
||||
# Restart Webmin if installed
|
||||
if systemctl is-enabled webmin &>/dev/null; then
|
||||
systemctl restart webmin
|
||||
print_info "Webmin service restarted"
|
||||
fi
|
||||
}
|
||||
|
||||
# Validation and testing
|
||||
function validate_2fa_setup() {
|
||||
print_info "Validating 2FA setup..."
|
||||
|
||||
# Check if Google Authenticator is installed
|
||||
if command -v google-authenticator &>/dev/null; then
|
||||
print_info "Google Authenticator installed"
|
||||
else
|
||||
print_error "Google Authenticator not found"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check SSH configuration
|
||||
if grep -q "AuthenticationMethods publickey,keyboard-interactive" "$SSH_CONFIG"; then
|
||||
print_info "SSH 2FA configuration valid"
|
||||
else
|
||||
print_error "SSH 2FA configuration invalid"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check PAM configuration
|
||||
if grep -q "pam_google_authenticator.so" "$PAM_CONFIG_DIR/sshd"; then
|
||||
print_info "PAM 2FA configuration valid"
|
||||
else
|
||||
print_error "PAM 2FA configuration invalid"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check service status
|
||||
if systemctl is-active sshd &>/dev/null; then
|
||||
print_info "SSH service is running"
|
||||
else
|
||||
print_error "SSH service is not running"
|
||||
return 1
|
||||
fi
|
||||
|
||||
print_info "2FA validation completed successfully"
|
||||
}
|
||||
|
||||
# Display final instructions
|
||||
function show_final_instructions() {
|
||||
print_info "2FA Setup Completed"
|
||||
|
||||
print_info "Two-Factor Authentication has been configured for:"
|
||||
print_info "- SSH (requires key + 2FA token)"
|
||||
print_info "- Cockpit web interface"
|
||||
if [[ -f "/etc/webmin/miniserv.conf" ]]; then
|
||||
print_info "- Webmin administration panel"
|
||||
fi
|
||||
|
||||
print_info "IMPORTANT: Complete user setup immediately!"
|
||||
print_info "1. Check /home/*/2fa-setup-instructions.txt for user setup"
|
||||
print_info "2. Run setup scripts for each user"
|
||||
print_info "3. Test 2FA before logging out"
|
||||
|
||||
print_info "Backup location: $BACKUP_DIR"
|
||||
print_info "To disable 2FA, restore configurations from backup"
|
||||
|
||||
print_info "2FA setup completed successfully!"
|
||||
}
|
||||
|
||||
# Main execution
|
||||
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 setup steps
|
||||
backup_configs
|
||||
install_2fa_packages
|
||||
configure_ssh_2fa
|
||||
configure_pam_2fa
|
||||
configure_cockpit_2fa
|
||||
configure_webmin_2fa
|
||||
setup_user_2fa
|
||||
restart_services
|
||||
validate_2fa_setup
|
||||
show_final_instructions
|
||||
}
|
||||
|
||||
# Run main function
|
||||
main "$@"
|
51
ProjectCode/Modules/Security/secharden-audit-agents.sh
Normal file
51
ProjectCode/Modules/Security/secharden-audit-agents.sh
Normal file
@@ -0,0 +1,51 @@
|
||||
#!/bin/bash
|
||||
|
||||
#####
|
||||
#Core framework functions...
|
||||
#####
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../../)"
|
||||
|
||||
#Framework variables are read from hee
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
|
||||
export DL_ROOT
|
||||
DL_ROOT="https://dl.knownelement.com/KNEL/FetchApply/"
|
||||
|
||||
# Material herein Sourced from
|
||||
|
||||
# https://cisofy.com/documentation/lynis/
|
||||
# https://jbcsec.com/configure-linux-ssh/
|
||||
# https://opensource.com/article/20/5/linux-security-lynis
|
||||
# https://forum.greenbone.net/t/ssh-authentication/13536
|
||||
|
||||
# openvas
|
||||
|
||||
#lynis
|
||||
|
||||
#Auditd
|
||||
|
||||
curl --silent ${DL_ROOT}/ConfigFiles/AudidD/auditd.conf > /etc/audit/auditd.conf
|
||||
|
||||
# Systemd
|
||||
curl --silent ${DL_ROOT}/ConfigFiles/Systemd/journald.conf > /etc/systemd/journald.conf
|
||||
|
||||
# logrotate
|
||||
curl --silent ${DL_ROOT}/ConfigFiles/Logrotate/logrotate.conf > /etc/logrotate.conf
|
3
ProjectCode/Modules/Security/secharden-auto-upgrade.sh
Normal file
3
ProjectCode/Modules/Security/secharden-auto-upgrade.sh
Normal file
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Sourced from https://wiki.debian.org/UnattendedUpgrades
|
127
ProjectCode/Modules/Security/secharden-scap-stig.sh
Normal file
127
ProjectCode/Modules/Security/secharden-scap-stig.sh
Normal file
@@ -0,0 +1,127 @@
|
||||
#!/bin/bash
|
||||
|
||||
|
||||
#########################################
|
||||
#Core framework functions...
|
||||
#########################################
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../../../)"
|
||||
|
||||
#Framework variables are read from hee
|
||||
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../../../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
#Framework variables are read from hee
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
|
||||
#########################################
|
||||
# Core script code begins here
|
||||
#########################################
|
||||
|
||||
# Sourced from
|
||||
|
||||
# https://complianceascode.readthedocs.io/en/latest/manual/developer/01_introduction.html
|
||||
# https://github.com/ComplianceAsCode/content
|
||||
# https://github.com/ComplianceAsCode
|
||||
|
||||
#apparmor
|
||||
#enforcing
|
||||
#enabled in bootloader config
|
||||
|
||||
#aide
|
||||
|
||||
#auditd
|
||||
|
||||
#disable auto mounting
|
||||
#disable usb storage
|
||||
|
||||
|
||||
#motd
|
||||
#remote login warning banner
|
||||
|
||||
#Ensure time sync is working
|
||||
#systemd-timesync
|
||||
#ntp
|
||||
#chrony
|
||||
|
||||
#password complexity
|
||||
#password expiration warning
|
||||
#password expiration time
|
||||
#password hashing algo
|
||||
|
||||
#fix grub perms
|
||||
|
||||
if [ "$IS_RASPI" = 0 ] ; then
|
||||
|
||||
chown root:root /boot/grub/grub.cfg
|
||||
chmod og-rwx /boot/grub/grub.cfg
|
||||
chmod 0400 /boot/grub/grub.cfg
|
||||
|
||||
fi
|
||||
|
||||
|
||||
#disable auto mounting
|
||||
systemctl --now disable autofs || true
|
||||
apt-get -y --purge remove autofs || true
|
||||
|
||||
#disable usb storage
|
||||
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
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/sctp.conf > /etc/modprobe.d/sctp.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/tipc.conf > /etc/modprobe.d/tipc.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/cramfs.conf > /etc/modprobe.d/cramfs.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/freevxfs.conf > /etc/modprobe.d/freevxfs.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/hfs.conf > /etc/modprobe.d/hfs.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/hfsplus.conf > /etc/modprobe.d/hfsplus.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/jffs2.conf > /etc/modprobe.d/jffs2.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/squashfs.conf > /etc/modprobe.d/squashfs.conf
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/ModProbe/udf.conf > /etc/modprobe.d/udf.conf
|
||||
|
||||
#banners
|
||||
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/BANNERS/issue > /etc/issue
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/BANNERS/issue.net > /etc/issue.net
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/BANNERS/motd > /etc/motd
|
||||
|
||||
#Cron perms
|
||||
|
||||
if [ -f /etc/cron.deny ]; then
|
||||
rm /etc/cron.deny || true
|
||||
fi
|
||||
|
||||
touch /etc/cron.allow
|
||||
chmod g-wx,o-rwx /etc/cron.allow
|
||||
chown root:root /etc/cron.allow
|
||||
|
||||
chmod og-rwx /etc/crontab
|
||||
chmod og-rwx /etc/cron.hourly/
|
||||
chmod og-rwx /etc/cron.daily/
|
||||
chmod og-rwx /etc/cron.weekly/
|
||||
chmod og-rwx /etc/cron.monthly/
|
||||
chown root:root /etc/cron.d/
|
||||
chmod og-rwx /etc/cron.d/
|
||||
|
||||
# At perms
|
||||
|
||||
rm -f /etc/at.deny || true
|
||||
touch /etc/at.allow
|
||||
chmod g-wx,o-rwx /etc/at.allow
|
||||
chown root:root /etc/at.allow
|
106
ProjectCode/Modules/Security/secharden-ssh.sh
Normal file
106
ProjectCode/Modules/Security/secharden-ssh.sh
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/bin/bash
|
||||
|
||||
#########################################
|
||||
#Core framework functions...
|
||||
#########################################
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../../../)"
|
||||
|
||||
#Framework variables are read from here
|
||||
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../../../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
#Framework variables are read from hee
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
|
||||
#########################################
|
||||
# Core script code begins here
|
||||
#########################################
|
||||
|
||||
export SUBODEV_CHECK
|
||||
SUBODEV_CHECK="$(getent passwd | grep -c subodev || true)"
|
||||
|
||||
export LOCALUSER_CHECK
|
||||
LOCALUSER_CHECK="$(getent passwd | grep -c localuser || true)"
|
||||
|
||||
export ROOT_SSH_DIR
|
||||
ROOT_SSH_DIR="/root/.ssh"
|
||||
|
||||
export LOCALUSER_SSH_DIR
|
||||
LOCALUSER_SSH_DIR="/home/localuser/.ssh"
|
||||
|
||||
export SUBODEV_SSH_DIR
|
||||
SUBODEV_SSH_DIR="/home/subodev/.ssh"
|
||||
|
||||
|
||||
if [ ! -d $ROOT_SSH_DIR ]; then
|
||||
mkdir /root/.ssh/
|
||||
fi
|
||||
|
||||
cat ../../ConfigFiles/SSH/AuthorizedKeys/root-ssh-authorized-keys >/root/.ssh/authorized_keys
|
||||
chmod 400 /root/.ssh/authorized_keys
|
||||
chown root: /root/.ssh/authorized_keys
|
||||
|
||||
if [ "$LOCALUSER_CHECK" -gt 0 ]; then
|
||||
if [ ! -d $LOCALUSER_SSH_DIR ]; then
|
||||
mkdir -p /home/localuser/.ssh/
|
||||
fi
|
||||
|
||||
cat ../../ConfigFiles/SSH/AuthorizedKeys/localuser-ssh-authorized-keys >/home/localuser/.ssh/authorized_keys
|
||||
chown localuser /home/localuser/.ssh/authorized_keys &&
|
||||
chmod 400 /home/localuser/.ssh/authorized_keys
|
||||
fi
|
||||
|
||||
if [ "$SUBODEV_CHECK" = 1 ]; then
|
||||
|
||||
if [ ! -d $SUBODEV_SSH_DIR ]; then
|
||||
mkdir /home/subodev/.ssh/
|
||||
fi
|
||||
|
||||
cat ../../ConfigFiles/SSH/AuthorizedKeys/localuser-ssh-authorized-keys >/home/subodev/.ssh/authorized_keys
|
||||
chmod 400 /home/subodev/.ssh/authorized_keys &&
|
||||
chown subodev: /home/subodev/.ssh/authorized_keys
|
||||
fi
|
||||
|
||||
export DEV_WORKSTATION_CHECK
|
||||
DEV_WORKSTATION_CHECK="$(hostname | egrep -c 'subopi-dev|CharlesDevServer' || true)"
|
||||
|
||||
if [ "$DEV_WORKSTATION_CHECK" -eq 0 ]; then
|
||||
|
||||
cat ../../ConfigFiles/SSH/Configs/tsys-sshd-config >/etc/ssh/sshd_config
|
||||
fi
|
||||
|
||||
|
||||
#Don't deploy this config to a ubuntu server, it breaks openssh server. Works on kali/debian.
|
||||
|
||||
export UBUNTU_CHECK
|
||||
UBUNTU_CHECK="$(distro | grep -c Ubuntu||true)"
|
||||
|
||||
if [ "$UBUNTU_CHECK" -ne 1 ]; then
|
||||
cat ../../ConfigFiles/SSH/Configs/ssh-audit-hardening.conf >/etc/ssh/sshd_config.d/ssh-audit_hardening.conf
|
||||
chmod og-rwx /etc/ssh/sshd_config.d/*
|
||||
fi
|
||||
|
||||
# Perms on sshd_config
|
||||
chmod og-rwx /etc/ssh/sshd_config
|
||||
|
||||
#todo
|
||||
|
||||
# only strong MAC algos are used
|
60
ProjectCode/Modules/Security/secharden-wazuh.sh
Normal file
60
ProjectCode/Modules/Security/secharden-wazuh.sh
Normal file
@@ -0,0 +1,60 @@
|
||||
#!/bin/bash
|
||||
|
||||
#########################################
|
||||
#Core framework functions...
|
||||
#########################################
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../../../)"
|
||||
|
||||
#Framework variables are read from here
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../../../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
#Framework variables are read from hee
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
|
||||
#########################################
|
||||
# Core script code begins here
|
||||
#########################################
|
||||
|
||||
# We don't want to run this on the wazuh server, otherwise bad things happen...
|
||||
|
||||
export TSYS_NSM_CHECK
|
||||
TSYS_NSM_CHECK="$(hostname |grep -c tsys-nsm ||true)"
|
||||
|
||||
if [ "$TSYS_NSM_CHECK" -eq 0 ]; then
|
||||
|
||||
if [ -f /usr/share/keyrings/wazuh.gpg ]; then
|
||||
rm -f /usr/share/keyrings/wazuh.gpg
|
||||
fi
|
||||
|
||||
curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | gpg --no-default-keyring --keyring gnupg-ring:/usr/share/keyrings/wazuh.gpg --import
|
||||
chmod 644 /usr/share/keyrings/wazuh.gpg
|
||||
echo "deb [signed-by=/usr/share/keyrings/wazuh.gpg] https://packages.wazuh.com/4.x/apt/ stable main" > /etc/apt/sources.list.d/wazuh.list
|
||||
apt-get update
|
||||
|
||||
WAZUH_MANAGER="tsys-nsm.knel.net" apt-get -y install wazuh-agent
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable wazuh-agent
|
||||
systemctl start wazuh-agent
|
||||
|
||||
echo "wazuh-agent hold" | dpkg --set-selections
|
||||
|
||||
fi
|
435
ProjectCode/SetupNewSystem.sh
Normal file
435
ProjectCode/SetupNewSystem.sh
Normal file
@@ -0,0 +1,435 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
#####
|
||||
#Core framework functions...
|
||||
#####
|
||||
|
||||
|
||||
export PROJECT_ROOT_PATH
|
||||
PROJECT_ROOT_PATH="$(realpath ../)"
|
||||
|
||||
#Framework variables are read from hee
|
||||
|
||||
|
||||
export GIT_VENDOR_PATH_ROOT
|
||||
GIT_VENDOR_PATH_ROOT="$PROJECT_ROOT_PATH/vendor/git@git.knownelement.com/29418/"
|
||||
|
||||
export KNELShellFrameworkRoot
|
||||
KNELShellFrameworkRoot="$GIT_VENDOR_PATH_ROOT/KNEL/KNELShellFramework"
|
||||
|
||||
source $KNELShellFrameworkRoot/Framework-ConfigFiles/FrameworkVars
|
||||
|
||||
for framework_include_file in $KNELShellFrameworkRoot/Framework-Includes/*; do
|
||||
source "$framework_include_file"
|
||||
done
|
||||
|
||||
for project_include_file in ../Project-Includes/*; do
|
||||
source "$project_include_file"
|
||||
done
|
||||
|
||||
# Start actual script logic here...
|
||||
|
||||
#################
|
||||
#Global variables
|
||||
#################
|
||||
|
||||
apt-get -y install git sudo dmidecode curl
|
||||
|
||||
export UBUNTU_CHECK
|
||||
UBUNTU_CHECK="$(distro | grep -c Ubuntu || true)"
|
||||
|
||||
export IS_PHYSICAL_HOST
|
||||
IS_PHYSICAL_HOST="$(/usr/sbin/dmidecode -t System | grep -c Dell || true)"
|
||||
|
||||
export SUBODEV_CHECK
|
||||
SUBODEV_CHECK="$(getent passwd | grep -c subodev || true)"
|
||||
|
||||
export LOCALUSER_CHECK
|
||||
LOCALUSER_CHECK="$(getent passwd | grep -c localuser || true)"
|
||||
|
||||
export DL_ROOT
|
||||
DL_ROOT="https://dl.knownelement.com/KNEL/FetchApply/"
|
||||
|
||||
#######################
|
||||
# Support functions
|
||||
#######################
|
||||
|
||||
function global-oam() {
|
||||
print_info "Now running $FUNCNAME...."
|
||||
|
||||
cat ./scripts/up2date.sh >/usr/local/bin/up2date.sh && chmod +x /usr/local/bin/up2date.sh
|
||||
|
||||
cd Modules/OAM || exit
|
||||
bash ./oam-librenms.sh
|
||||
cd - || exit
|
||||
|
||||
print_info "Completed running $FUNCNAME"
|
||||
|
||||
}
|
||||
|
||||
function global-systemServiceConfigurationFiles() {
|
||||
print_info "Now running $FUNCNAME...."
|
||||
|
||||
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
|
||||
|
||||
newaliases
|
||||
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function global-installPackages() {
|
||||
print_info "Now running $FUNCNAME...."
|
||||
|
||||
# Setup webmin repo, used for RBAC/2fa PAM
|
||||
|
||||
curl https://raw.githubusercontent.com/webmin/webmin/master/webmin-setup-repo.sh >/tmp/webmin-setup.sh
|
||||
sh /tmp/webmin-setup.sh -f && rm -f /tmp/webmin-setup.sh
|
||||
|
||||
# Setup lynis repo, used for sec ops/compliance
|
||||
|
||||
if [ -f /etc/apt/trusted.gpg.d/cisofy-software-public.gpg ]; then
|
||||
rm -f /etc/apt/trusted.gpg.d/cisofy-software-public.gpg
|
||||
fi
|
||||
|
||||
curl -fsSL https://packages.cisofy.com/keys/cisofy-software-public.key | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/cisofy-software-public.gpg
|
||||
echo "deb [arch=amd64,arm64 signed-by=/etc/apt/trusted.gpg.d/cisofy-software-public.gpg] https://packages.cisofy.com/community/lynis/deb/ stable main" | sudo tee /etc/apt/sources.list.d/cisofy-lynis.list
|
||||
|
||||
# Setup tailscale
|
||||
|
||||
curl -fsSL https://tailscale.com/install.sh | sh
|
||||
|
||||
#
|
||||
#Patch the system
|
||||
#
|
||||
|
||||
/usr/local/bin/up2date.sh
|
||||
|
||||
#Remove stuff we don't want
|
||||
|
||||
export DEBIAN_FRONTEND="noninteractive" \
|
||||
&& apt-get -qq --yes --purge \
|
||||
remove \
|
||||
systemd-timesyncd \
|
||||
chrony \
|
||||
telnet \
|
||||
inetutils-telnet \
|
||||
nano \
|
||||
multipath-tools \
|
||||
|| true
|
||||
|
||||
# add stuff we want
|
||||
|
||||
print_info ""Now installing all the packages...""
|
||||
|
||||
DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install \
|
||||
virt-what \
|
||||
auditd \
|
||||
audispd-plugins \
|
||||
cloud-guest-utils \
|
||||
aide \
|
||||
htop \
|
||||
snmpd \
|
||||
ncdu \
|
||||
iftop \
|
||||
iotop \
|
||||
cockpit \
|
||||
cockpit-bridge \
|
||||
cockpit-doc \
|
||||
cockpit-networkmanager \
|
||||
cockpit-packagekit \
|
||||
cockpit-pcp \
|
||||
cockpit-sosreport \
|
||||
cockpit-storaged \
|
||||
cockpit-system \
|
||||
cockpit-ws \
|
||||
nethogs \
|
||||
sysstat \
|
||||
ngrep \
|
||||
acct \
|
||||
lsb-release \
|
||||
screen \
|
||||
tailscale \
|
||||
tmux \
|
||||
vim \
|
||||
command-not-found \
|
||||
lldpd \
|
||||
ansible-core \
|
||||
net-tools \
|
||||
dos2unix \
|
||||
gpg \
|
||||
molly-guard \
|
||||
lshw \
|
||||
fzf \
|
||||
ripgrep \
|
||||
sudo \
|
||||
mailutils \
|
||||
clamav \
|
||||
sl \
|
||||
logwatch \
|
||||
git \
|
||||
net-tools \
|
||||
tshark \
|
||||
tcpdump \
|
||||
lynis \
|
||||
glances \
|
||||
zsh \
|
||||
zsh-autosuggestions \
|
||||
zsh-syntax-highlighting \
|
||||
fonts-powerline \
|
||||
webmin \
|
||||
usermin \
|
||||
ntpsec \
|
||||
ntpsec-ntpdate \
|
||||
tuned \
|
||||
cockpit \
|
||||
iptables \
|
||||
netfilter-persistent \
|
||||
iptables-persistent \
|
||||
pflogsumm \
|
||||
postfix
|
||||
|
||||
export KALI_CHECK
|
||||
KALI_CHECK="$(distro | grep -c kali || true)"
|
||||
|
||||
export VIRT_TYPE
|
||||
VIRT_TYPE="$(virt-what)"
|
||||
|
||||
export IS_VIRT_GUEST
|
||||
IS_VIRT_GUEST="$(echo "$VIRT_TYPE" | egrep -c 'hyperv|kvm' || true)"
|
||||
|
||||
export IS_KVM_GUEST
|
||||
IS_KVM_GUEST="$(echo "$VIRT_TYPE" | grep -c 'kvm' || true)"
|
||||
|
||||
if [[ $IS_KVM_GUEST = 1 ]]; then
|
||||
apt -y install qemu-guest-agent
|
||||
fi
|
||||
|
||||
if [[ $KALI_CHECK -eq 0 ]];then
|
||||
DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install \
|
||||
latencytop \
|
||||
cockpit-tests
|
||||
fi
|
||||
|
||||
if [[ $IS_PHYSICAL_HOST -gt 0 ]]; then
|
||||
export DEBIAN_FRONTEND="noninteractive" && apt-get -qq --yes -o Dpkg::Options::="--force-confold" install \
|
||||
i7z \
|
||||
thermald \
|
||||
cpufrequtils \
|
||||
linux-cpupower
|
||||
# power-profiles-daemon
|
||||
fi
|
||||
|
||||
############################
|
||||
# Secrets agents
|
||||
############################
|
||||
|
||||
# bitwarden cli
|
||||
|
||||
# vault cli
|
||||
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function global-postPackageConfiguration() {
|
||||
|
||||
print_info "Now running $FUNCNAME"
|
||||
|
||||
systemctl --now enable auditd
|
||||
|
||||
systemctl stop postfix
|
||||
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/SMTP/postfix_generic >/etc/postfix/generic
|
||||
postmap /etc/postfix/generic
|
||||
|
||||
postconf -e "inet_protocols = ipv4"
|
||||
postconf -e "inet_interfaces = 127.0.0.1"
|
||||
postconf -e "mydestination= 127.0.0.1"
|
||||
postconf -e "relayhost = tsys-cloudron.knel.net"
|
||||
postconf -e "smtp_generic_maps = hash:/etc/postfix/generic"
|
||||
# smtp_generic_maps = hash:/etc/postfix/generic
|
||||
|
||||
systemctl restart postfix
|
||||
|
||||
#This is under test/dev and may fail
|
||||
echo "hi from root to root" | mail -s "hi directly to root from $(hostname)" root
|
||||
|
||||
chsh -s $(which zsh) root
|
||||
|
||||
if [ "$LOCALUSER_CHECK" -gt 0 ]; then
|
||||
chsh -s "$(which zsh)" localuser
|
||||
fi
|
||||
|
||||
if [ "$SUBODEV_CHECK" -gt 0 ]; then
|
||||
chsh -s "$(which zsh)" subodev
|
||||
fi
|
||||
|
||||
###Post package deployment bits
|
||||
|
||||
curl --silent ${DL_ROOT}/ProjectCode/ConfigFiles/DHCP/dhclient.conf >/etc/dhcp/dhclient.conf
|
||||
|
||||
systemctl stop snmpd && /etc/init.d/snmpd stop
|
||||
|
||||
cat ./ConfigFiles/SNMP/snmp-sudo.conf >/etc/sudoers.d/Debian-snmp
|
||||
sed -i "s|-Lsd|-LS6d|" /lib/systemd/system/snmpd.service
|
||||
|
||||
pi-detect
|
||||
|
||||
if [ "$IS_RASPI" = 1 ]; then
|
||||
cat ./ConfigFiles/SNMP/snmpd-rpi.conf >/etc/snmp/snmpd.conf || true
|
||||
fi
|
||||
|
||||
if [ "$IS_PHYSICAL_HOST" = 1 ]; then
|
||||
cat ./ConfigFiles/SNMP/snmpd-physicalhost.conf >/etc/snmp/snmpd.conf || true
|
||||
fi
|
||||
|
||||
if [ "$IS_VIRT_GUEST" = 1 ]; then
|
||||
cat ./ConfigFiles/SNMP/snmpd.conf >/etc/snmp/snmpd.conf || true
|
||||
fi
|
||||
|
||||
systemctl daemon-reload && systemctl restart snmpd && /etc/init.d/snmpd restart
|
||||
|
||||
cat ./ConfigFiles/NetworkDiscovery/lldpd >/etc/default/lldpd
|
||||
systemctl restart lldpd
|
||||
|
||||
cat ./ConfigFiles/Cockpit/disallowed-users >/etc/cockpit/disallowed-users
|
||||
systemctl restart cockpit
|
||||
|
||||
export LIBRENMS_CHECK
|
||||
LIBRENMS_CHECK="$(hostname | grep -c tsys-librenms || true)"
|
||||
|
||||
if [ "$LIBRENMS_CHECK" -eq 0 ]; then
|
||||
DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install rsyslog
|
||||
systemctl stop rsyslog
|
||||
systemctl start rsyslog
|
||||
fi
|
||||
|
||||
export NTP_SERVER_CHECK
|
||||
NTP_SERVER_CHECK="$(hostname | egrep -c 'pfv-netboot|pfvsvrpi' || true)"
|
||||
|
||||
if [ "$NTP_SERVER_CHECK" -eq 0 ]; then
|
||||
|
||||
cat ./ConfigFiles/NTP/ntp.conf >/etc/ntpsec/ntp.conf
|
||||
systemctl restart ntpsec.service
|
||||
fi
|
||||
|
||||
systemctl stop postfix
|
||||
systemctl start postfix
|
||||
|
||||
/usr/sbin/accton on
|
||||
|
||||
if [ "$IS_PHYSICAL_HOST" -gt 0 ]; then
|
||||
cpufreq-set -r -g performance
|
||||
cpupower frequency-set --governor performance
|
||||
|
||||
# Potentially merge the below if needed.
|
||||
# power-profiles-daemon
|
||||
# powerprofilesctl set performance
|
||||
#tsys1# systemctl enable power-profiles-daemon
|
||||
#tsys1# systemctl start power-profiles-daemon
|
||||
|
||||
fi
|
||||
|
||||
if [ "$IS_VIRT_GUEST" = 1 ]; then
|
||||
tuned-adm profile virtual-guest
|
||||
fi
|
||||
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
####################################################################################################
|
||||
# Run various modules
|
||||
####################################################################################################
|
||||
|
||||
####################################################################################################
|
||||
# Security Hardening
|
||||
####################################################################################################
|
||||
|
||||
# SSH
|
||||
|
||||
function secharden-ssh() {
|
||||
print_info "Now running $FUNCNAME"
|
||||
|
||||
cd ./Modules/Security || exit
|
||||
bash ./secharden-ssh.sh
|
||||
cd -
|
||||
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function secharden-wazuh() {
|
||||
print_info "Now running $FUNCNAME"
|
||||
cd ./Modules/Security || exit
|
||||
bash ./secharden-wazuh.sh
|
||||
cd -
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function secharden-2fa() {
|
||||
print_info "Now running $FUNCNAME"
|
||||
cd ./Modules/Security || exit
|
||||
bash ./secharden-2fa.sh
|
||||
cd -
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function secharden-scap-stig() {
|
||||
print_info "Now running $FUNCNAME"
|
||||
cd ./Modules/Security || exit
|
||||
bash ./secharden-scap-stig.sh
|
||||
cd -
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function secharden-agents() {
|
||||
print_info "Now running $FUNCNAME"
|
||||
cd ./Modules/Security || exit
|
||||
bash ./secharden-audit-agents.sh
|
||||
cd -
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
function secharden-auto-upgrades() {
|
||||
print_info "Now running $FUNCNAME"
|
||||
#curl --silent ${DL_ROOT}/Modules/Security/secharden-ssh.sh|$(which bash)
|
||||
print_info "Completed running $FUNCNAME"
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
####################################################################################################
|
||||
# Authentication
|
||||
####################################################################################################
|
||||
|
||||
function auth-cloudron-ldap() {
|
||||
print_info "Now running "$FUNCNAME""
|
||||
#curl --silent ${DL_ROOT}/Modules/Auth/auth-cloudron-ldap.sh|$(which bash)
|
||||
print_info "Completed running "$FUNCNAME""
|
||||
}
|
||||
|
||||
####################################################################################################
|
||||
# RUn the various functions in the correct order
|
||||
####################################################################################################
|
||||
|
||||
echo >$LOGFILENAME
|
||||
|
||||
print_info "Execution starting at $CURRENT_TIMESTAMP..."
|
||||
|
||||
PreflightCheck
|
||||
global-oam
|
||||
global-installPackages
|
||||
global-systemServiceConfigurationFiles
|
||||
global-postPackageConfiguration
|
||||
|
||||
secharden-ssh
|
||||
secharden-wazuh
|
||||
secharden-scap-stig
|
||||
secharden-2fa
|
||||
#secharden-agents
|
||||
#secharden-auto-upgrades
|
||||
|
||||
#auth-cloudron-ldap
|
||||
|
||||
print_info "Execution ended at $CURRENT_TIMESTAMP..."
|
1
ProjectCode/legacy/profiled-tsys-shell.sh
Normal file
1
ProjectCode/legacy/profiled-tsys-shell.sh
Normal file
@@ -0,0 +1 @@
|
||||
export HISTTIMEFORMAT="%m/%d/%Y %T "
|
9
ProjectCode/legacy/prox7.sh
Normal file
9
ProjectCode/legacy/prox7.sh
Normal file
@@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
|
||||
rm -f /etc/apt/sources.list.d/*
|
||||
echo "deb https://download.proxmox.com/debian/pve bookworm pve-no-subscription" > /etc/apt/sources.list.d/pve-install-repo.list
|
||||
wget https://download.proxmox.com/debian/proxmox-release-bookworm.gpg -O /etc/apt/trusted.gpg.d/proxmox-release-bookworm.gpg
|
||||
apt update && apt -y full-upgrade
|
||||
apt-get -y install ifupdown2 ipmitool ethtool net-tools lshw
|
||||
|
||||
#curl -s http://dl.turnsys.net/newSrv.sh|/bin/bash
|
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
|
19
README.md
19
README.md
@@ -1,10 +1,21 @@
|
||||
# KNEL FetchApply
|
||||
|
||||
## Repo discription
|
||||
Known Element Enterprises (the entity serving as the TSYS Group management company) (through it’s executive leader, the COO) provides core IT/back office systems/services/support on a hands off/fully delegated authortity basis to the CCO and the orgs/members.
|
||||
|
||||
## Repo Issue
|
||||
## Repo Issues
|
||||
https://projects.knownelement.com/project/reachableceo-vptechnicaloperations/timeline
|
||||
|
||||
## Repo Discussion
|
||||
https://community.turnsys.com/c/chieftechnologyandproductofficer/26
|
||||
|
||||
|
||||
## Repo discription
|
||||
Known Element Enterprises (the entity serving as the TSYS Group management company) (through it’s executive leader, the COO) provides core IT/back office systems/services/support on a hands off/fully delegated authortity basis to the CCO and the orgs/members.
|
||||
|
||||
One of those functions is the provisoning of Linux servers. This repository is the Infrastructure As Code (IAC) repository for TSYS.
|
||||
|
||||
In the future it will be used via FetchApply https://github.com/P5vc/fetch-apply
|
||||
|
||||
## Usage
|
||||
|
||||
git clone this repo
|
||||
cd FetchApply/ProjectCode
|
||||
bash SetupNewSystem.sh
|
@@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
sudo wget -O - https://packages.cisofy.com/keys/cisofy-software-public.key | sudo apt-key add -
|
||||
echo "deb https://packages.cisofy.com/community/lynis/deb/ stable main" | sudo tee /etc/apt/sources.list.d/cisofy-lynis.list
|
||||
apt update
|
||||
apt install lynis
|
||||
lynis show version
|
||||
|
@@ -1,47 +0,0 @@
|
||||
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
|
||||
|
||||
|
||||
# Debian specific: Specifying a file name will cause the first
|
||||
# line of that file to be used as the name. The Debian default
|
||||
# is /etc/mailname.
|
||||
#myorigin = /etc/mailname
|
||||
|
||||
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
|
||||
biff = no
|
||||
|
||||
# appending .domain is the MUA's job.
|
||||
append_dot_mydomain = no
|
||||
|
||||
# Uncomment the next line to generate "delayed mail" warnings
|
||||
#delay_warning_time = 4h
|
||||
|
||||
readme_directory = no
|
||||
|
||||
# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
|
||||
# fresh installs.
|
||||
compatibility_level = 2
|
||||
|
||||
|
||||
|
||||
# TLS parameters
|
||||
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
|
||||
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
|
||||
smtpd_tls_security_level=may
|
||||
|
||||
smtp_tls_CApath=/etc/ssl/certs
|
||||
smtp_tls_security_level=may
|
||||
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
|
||||
|
||||
|
||||
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
|
||||
myhostname = pfv-vpn.turnsys.net
|
||||
alias_maps = hash:/etc/aliases
|
||||
alias_database = hash:/etc/aliases
|
||||
myorigin = /etc/mailname
|
||||
mydestination = pfv-vpn.turnsys.net, $myhostname, pfv-vpn, localhost.localdomain, localhost
|
||||
relayhost = pfv-mail.turnsys.net
|
||||
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
|
||||
mailbox_size_limit = 0
|
||||
recipient_delimiter = +
|
||||
inet_interfaces = all
|
||||
inet_protocols = all
|
@@ -1,32 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#curl -s http://dl.turnsys.net/omsa.sh|/bin/bash
|
||||
|
||||
gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-key 1285491434D8786F
|
||||
gpg -a --export 1285491434D8786F | apt-key add -
|
||||
echo "deb http://linux.dell.com/repo/community/openmanage/930/bionic bionic main" > /etc/apt/sources.list.d/linux.dell.com.sources.list
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman-curl-client-transport1_2.6.5-0ubuntu3_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman-client4_2.6.5-0ubuntu3_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman1_2.6.5-0ubuntu3_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/libwsman-server1_2.6.5-0ubuntu3_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/s/sblim-sfcc/libcimcclient0_2.2.8-0ubuntu2_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/o/openwsman/openwsman_2.6.5-0ubuntu3_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/multiverse/c/cim-schema/cim-schema_2.48.0-0ubuntu1_all.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/s/sblim-sfc-common/libsfcutil0_1.0.1-0ubuntu4_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/multiverse/s/sblim-sfcb/sfcb_1.4.9-0ubuntu5_amd64.deb
|
||||
wget http://archive.ubuntu.com/ubuntu/pool/universe/s/sblim-cmpi-devel/libcmpicppimpl0_2.0.3-0ubuntu2_amd64.deb
|
||||
dpkg -i libwsman-curl-client-transport1_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libwsman-client4_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libwsman1_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libwsman-server1_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i libcimcclient0_2.2.8-0ubuntu2_amd64.deb
|
||||
dpkg -i openwsman_2.6.5-0ubuntu3_amd64.deb
|
||||
dpkg -i cim-schema_2.48.0-0ubuntu1_all.deb
|
||||
dpkg -i libsfcutil0_1.0.1-0ubuntu4_amd64.deb
|
||||
dpkg -i sfcb_1.4.9-0ubuntu5_amd64.deb
|
||||
dpkg -i libcmpicppimpl0_2.0.3-0ubuntu2_amd64.deb
|
||||
|
||||
apt update
|
||||
apt -y install srvadmin-all
|
||||
touch /opt/dell/srvadmin/lib64/openmanage/IGNORE_GENERATION
|
||||
/opt/dell/srvadmin/sbin/srvadmin-services.sh enable && /opt/dell/srvadmin/sbin/srvadmin-services.sh start &&
|
@@ -1,9 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
rm -f /etc/apt/sources.list.d/*
|
||||
echo "deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription" > /etc/apt/sources.list.d/pve-install-repo.list
|
||||
wget http://download.proxmox.com/debian/proxmox-release-bookworm.gpg -O /etc/apt/trusted.gpg.d/proxmox-release-bookworm.gpg
|
||||
apt update && apt -y full-upgrade
|
||||
apt-get -y install ifupdown2 ipmitool ethtool net-tools lshw
|
||||
|
||||
#curl -s http://dl.turnsys.net/newSrv.sh|/bin/bash
|
@@ -1,8 +0,0 @@
|
||||
#Charles N Wyble ssh key (putty windows 10 surface)
|
||||
|
||||
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCnhDjA004vIMMIwFSFv5K0mj0avk997fVdiVtqoSMAAe/OabK/yuFNF3/LRMtWeTG8r859cmdvs+9z+l9jcXIDRgMVW+hR8exysk5JtQgGwSijdwYz9yRmoT3apNSvwFN0g0HkhAWLTQWmafTYCR9CQWJTfPWZN/ypW7Vm/ZHcl9UxLUnT6LWpOL7usEN4OLT6NRwQDaYOtR3OFm62UqIaIFQXAnMg0qbDICllpXatPWtlkN7CU6xHhSwD0GycuJbX1/KBNcQ4msoIMGCUaA8yTWZfqAg6KDE3ojoZJh1w14ABHZPb6imz5jzQEG6eOUVOAlKwv/Ry5RxNfP3Vz9Ld rsa-key-20210828
|
||||
|
||||
|
||||
#Librenms/openvas/rundeck key
|
||||
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGIzki6Xxyyih5HWMXR/uWLGgJprDGEBWC3JX8G7562zcx3eKDl0GKmZv4cl0AZZUwLATvpks8w2Bk6BL7cDvgUkmgpawHgGeRCjLi19/gG8t6M7k+U/rw6uu5SeaFXy5q22zkkE2TDTotWsoa6NE59Gc5/dNgQkYC0r1adD/J2+A6XgxoHdAEVX7gkFhBhXJKTkCYgatDzyE1IUoWLYAQpnMPcBUwK/i7qrcrVYqz0IS6p3MuYYS1+hr1MbMd5bX+Gm6PB6zf/CKhJkUFvaYS+QkVCMzQKrxNRuCs7ULyYvvi9EfxcCow06LuYvslMpEMIfJp8zKX9rhlvu9tuOkF
|
||||
|
BIN
librenms.tar.gz
BIN
librenms.tar.gz
Binary file not shown.
114
librenms/distro
114
librenms/distro
@@ -1,114 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Detects which OS and if it is Linux then it will detect which Linux Distribution.
|
||||
|
||||
OS=`uname -s`
|
||||
REV=`uname -r`
|
||||
MACH=`uname -m`
|
||||
|
||||
if [ "${OS}" = "SunOS" ] ; then
|
||||
OS=Solaris
|
||||
ARCH=`uname -p`
|
||||
OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
|
||||
|
||||
elif [ "${OS}" = "AIX" ] ; then
|
||||
OSSTR="${OS} `oslevel` (`oslevel -r`)"
|
||||
|
||||
elif [ "${OS}" = "Linux" ] ; then
|
||||
KERNEL=`uname -r`
|
||||
|
||||
if [ -f /etc/fedora-release ]; then
|
||||
DIST=$(cat /etc/fedora-release | awk '{print $1}')
|
||||
REV=`cat /etc/fedora-release | sed s/.*release\ // | sed s/\ .*//`
|
||||
|
||||
elif [ -f /etc/redhat-release ] ; then
|
||||
DIST=$(cat /etc/redhat-release | awk '{print $1}')
|
||||
if [ "${DIST}" = "CentOS" ]; then
|
||||
DIST="CentOS"
|
||||
elif [ "${DIST}" = "Mandriva" ]; then
|
||||
DIST="Mandriva"
|
||||
PSEUDONAME=`cat /etc/mandriva-release | sed s/.*\(// | sed s/\)//`
|
||||
REV=`cat /etc/mandriva-release | sed s/.*release\ // | sed s/\ .*//`
|
||||
elif [ -f /etc/oracle-release ]; then
|
||||
DIST="Oracle"
|
||||
else
|
||||
DIST="RedHat"
|
||||
fi
|
||||
|
||||
PSEUDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
|
||||
REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
|
||||
|
||||
elif [ -f /etc/mandrake-release ] ; then
|
||||
DIST='Mandrake'
|
||||
PSEUDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
|
||||
REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
|
||||
|
||||
elif [ -f /etc/devuan_version ] ; then
|
||||
DIST="Devuan `cat /etc/devuan_version`"
|
||||
REV=""
|
||||
|
||||
elif [ -f /etc/debian_version ] ; then
|
||||
DIST="Debian `cat /etc/debian_version`"
|
||||
REV=""
|
||||
ID=`lsb_release -i | awk -F ':' '{print $2}' | sed 's/ //g'`
|
||||
if [ "${ID}" = "Raspbian" ] ; then
|
||||
DIST="Raspbian `cat /etc/debian_version`"
|
||||
fi
|
||||
|
||||
elif [ -f /etc/gentoo-release ] ; then
|
||||
DIST="Gentoo"
|
||||
REV=$(tr -d '[[:alpha:]]' </etc/gentoo-release | tr -d " ")
|
||||
|
||||
elif [ -f /etc/arch-release ] ; then
|
||||
DIST="Arch Linux"
|
||||
REV="" # Omit version since Arch Linux uses rolling releases
|
||||
IGNORE_LSB=1 # /etc/lsb-release would overwrite $REV with "rolling"
|
||||
|
||||
elif [ -f /etc/os-release ] ; then
|
||||
DIST=$(grep '^NAME=' /etc/os-release | cut -d= -f2- | tr -d '"')
|
||||
REV=$(grep '^VERSION_ID=' /etc/os-release | cut -d= -f2- | tr -d '"')
|
||||
|
||||
elif [ -f /etc/openwrt_version ] ; then
|
||||
DIST="OpenWrt"
|
||||
REV=$(cat /etc/openwrt_version)
|
||||
|
||||
elif [ -f /etc/pld-release ] ; then
|
||||
DIST=$(cat /etc/pld-release)
|
||||
REV=""
|
||||
|
||||
elif [ -f /etc/SuSE-release ] ; then
|
||||
DIST=$(echo SLES $(grep VERSION /etc/SuSE-release | cut -d = -f 2 | tr -d " "))
|
||||
REV=$(echo SP$(grep PATCHLEVEL /etc/SuSE-release | cut -d = -f 2 | tr -d " "))
|
||||
fi
|
||||
|
||||
if [ -f /etc/lsb-release -a "${IGNORE_LSB}" != 1 ] ; then
|
||||
LSB_DIST=$(lsb_release -si)
|
||||
LSB_REV=$(lsb_release -sr)
|
||||
if [ "$LSB_DIST" != "" ] ; then
|
||||
DIST=$LSB_DIST
|
||||
fi
|
||||
if [ "$LSB_REV" != "" ] ; then
|
||||
REV=$LSB_REV
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "`uname -a | awk '{print $(NF)}'`" = "DD-WRT" ] ; then
|
||||
DIST="dd-wrt"
|
||||
fi
|
||||
|
||||
if [ -n "${REV}" ]
|
||||
then
|
||||
OSSTR="${DIST} ${REV}"
|
||||
else
|
||||
OSSTR="${DIST}"
|
||||
fi
|
||||
|
||||
elif [ "${OS}" = "Darwin" ] ; then
|
||||
if [ -f /usr/bin/sw_vers ] ; then
|
||||
OSSTR=`/usr/bin/sw_vers|grep -v Build|sed 's/^.*:.//'| tr "\n" ' '`
|
||||
fi
|
||||
|
||||
elif [ "${OS}" = "FreeBSD" ] ; then
|
||||
OSSTR=`/usr/bin/uname -mior`
|
||||
fi
|
||||
|
||||
echo ${OSSTR}
|
@@ -1,25 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
################################################################
|
||||
# copy this script to somewhere like /opt and make chmod +x it #
|
||||
# edit your snmpd.conf and include #
|
||||
# extend ntp-client /opt/ntp-client.sh #
|
||||
# restart snmpd and activate the app for desired host #
|
||||
# please make sure you have the path/binaries below #
|
||||
################################################################
|
||||
# Binaries and paths required #
|
||||
################################################################
|
||||
BIN_NTPQ="$(command -v ntpq)"
|
||||
BIN_GREP="$(command -v grep)"
|
||||
BIN_TR="$(command -v tr)"
|
||||
BIN_CUT="$(command -v cut)"
|
||||
################################################################
|
||||
# Don't change anything unless you know what are you doing #
|
||||
################################################################
|
||||
CMD1=`$BIN_NTPQ -c rv | $BIN_GREP 'jitter' | $BIN_TR '\n' ' '`
|
||||
IFS=', ' read -r -a array <<< "$CMD1"
|
||||
|
||||
for value in 2 3 4 5 6
|
||||
do
|
||||
echo ${array["$value"]} | $BIN_CUT -d "=" -f 2
|
||||
done
|
||||
|
363
librenms/smart
363
librenms/smart
@@ -1,363 +0,0 @@
|
||||
#!/usr/bin/env perl
|
||||
#Copyright (c) 2017, Zane C. Bowers-Hadley
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source and binary forms, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
#IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
#OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
|
||||
#THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
=for comment
|
||||
|
||||
Add this to snmpd.conf like below.
|
||||
|
||||
extend smart /etc/snmp/smart
|
||||
|
||||
Then add to root's cron tab, if you have more than a few disks.
|
||||
|
||||
*/3 * * * * /etc/snmp/smart -u
|
||||
|
||||
You will also need to create the config file, which defaults to the same path as the script,
|
||||
but with .config appended. So if the script is located at /etc/snmp/smart, the config file
|
||||
will be /etc/snmp/smart.config. Alternatively you can also specific a config via -c.
|
||||
|
||||
Anything starting with a # is comment. The format for variables is $variable=$value. Empty
|
||||
lines are ignored. Spaces and tabes at either the start or end of a line are ignored. Any
|
||||
line with out a = or # are treated as a disk.
|
||||
|
||||
#This is a comment
|
||||
cache=/var/cache/smart
|
||||
smartctl=/usr/local/sbin/smartctl
|
||||
useSN=0
|
||||
ada0
|
||||
ada1
|
||||
|
||||
The variables are as below.
|
||||
|
||||
cache = The path to the cache file to use. Default: /var/cache/smart
|
||||
smartctl = The path to use for smartctl. Default: /usr/bin/env smartctl
|
||||
useSN = If set to 1, it will use the disks SN for reporting instead of the device name.
|
||||
1 is the default. 0 will use the device name.
|
||||
|
||||
If you want to guess at the configuration, call it with -g and it will print out what it thinks
|
||||
it should be.
|
||||
|
||||
=cut
|
||||
|
||||
##
|
||||
## You should not need to touch anything below here.
|
||||
##
|
||||
use warnings;
|
||||
use strict;
|
||||
use Getopt::Std;
|
||||
|
||||
my $cache='/var/cache/smart';
|
||||
my $smartctl='/usr/bin/env smartctl';
|
||||
my @disks;
|
||||
my $useSN=1;
|
||||
|
||||
$Getopt::Std::STANDARD_HELP_VERSION = 1;
|
||||
sub main::VERSION_MESSAGE {
|
||||
print "SMART SNMP extend 0.0.0\n";
|
||||
};
|
||||
|
||||
|
||||
sub main::HELP_MESSAGE {
|
||||
print "\n".
|
||||
"-u Update '".$cache."'\n".
|
||||
"-g Guess at the config and print it to STDOUT.\n".
|
||||
"-c <config> The config file to use.\n";
|
||||
}
|
||||
|
||||
#gets the options
|
||||
my %opts=();
|
||||
getopts('ugc:', \%opts);
|
||||
|
||||
# guess if asked
|
||||
if ( defined( $opts{g} ) ){
|
||||
|
||||
#get what path to use for smartctl
|
||||
$smartctl=`which smartctl`;
|
||||
chomp($smartctl);
|
||||
if ( $? != 0 ){
|
||||
warn("'which smartctl' failed with a exit code of $?");
|
||||
exit 1;
|
||||
}
|
||||
|
||||
#try to touch the default cache location and warn if it can't be done
|
||||
system('touch '.$cache.'>/dev/null');
|
||||
if ( $? != 0 ){
|
||||
$cache='#Could not touch '.$cache. "You will need to manually set it\n".
|
||||
"cache=?\n";
|
||||
}else{
|
||||
$cache='cache='.$cache."\n";
|
||||
}
|
||||
|
||||
my %found_disks;
|
||||
|
||||
#check for drives named /dev/sd*
|
||||
my @matches=glob('/dev/sd*');
|
||||
@matches=grep(!/[0-9]/, @matches);
|
||||
my $matches_int=0;
|
||||
while ( defined( $matches[$matches_int] ) ){
|
||||
my $device=$matches[$matches_int];
|
||||
system( $smartctl.' -A '.$device.' > /dev/null' );
|
||||
if ( $? == 0 ){
|
||||
$device =~ s/\/dev\///;
|
||||
$found_disks{$device}=1;
|
||||
}
|
||||
|
||||
$matches_int++;
|
||||
}
|
||||
|
||||
#check for drives named /dev/ada*
|
||||
@matches=glob('/dev/ada*');
|
||||
@matches=grep(!/[ps]/, @matches);
|
||||
$matches_int=0;
|
||||
while ( defined( $matches[$matches_int] ) ){
|
||||
my $device=$matches[$matches_int];
|
||||
system( $smartctl.' -A '.$device.' > /dev/null' );
|
||||
if ( $? == 0 ){
|
||||
$device =~ s/\/dev\///;
|
||||
$found_disks{$device}=1;
|
||||
}
|
||||
|
||||
$matches_int++;
|
||||
}
|
||||
|
||||
#check for drives named /dev/da*
|
||||
@matches=glob('/dev/da*');
|
||||
@matches=grep(!/[ps]/, @matches);
|
||||
$matches_int=0;
|
||||
while ( defined( $matches[$matches_int] ) ){
|
||||
my $device=$matches[$matches_int];
|
||||
system( $smartctl.' -A '.$device.' > /dev/null' );
|
||||
if ( $? == 0 ){
|
||||
$device =~ s/\/dev\///;
|
||||
$found_disks{$device}=1;
|
||||
}
|
||||
|
||||
$matches_int++;
|
||||
}
|
||||
|
||||
#have smartctl scan and see if it finds anythings not get found
|
||||
my $scan_output=`$smartctl --scan-open`;
|
||||
my @scan_outputA=split(/\n/, $scan_output);
|
||||
@scan_outputA=grep(!/ses[0-9]/, @scan_outputA); # not a disk, but may or may not have SMART attributes
|
||||
@scan_outputA=grep(!/pass[0-9]/, @scan_outputA); # very likely a duplicate and a disk under another name
|
||||
$matches_int=0;
|
||||
while ( defined( $scan_outputA[$matches_int] ) ){
|
||||
my $device=$scan_outputA[$matches_int];
|
||||
$device =~ s/ .*//;
|
||||
system( $smartctl.' -A '.$device.' > /dev/null' );
|
||||
if ( $? == 0 ){
|
||||
$device =~ s/\/dev\///;
|
||||
$found_disks{$device}=1;
|
||||
}
|
||||
|
||||
$matches_int++;
|
||||
}
|
||||
|
||||
print "useSN=0\n".'smartctl='.$smartctl."\n".
|
||||
$cache.
|
||||
join( "\n", keys(%found_disks) )."\n";
|
||||
|
||||
exit 0;
|
||||
}
|
||||
|
||||
#get which config file to use
|
||||
my $config=$0.'.config';
|
||||
if ( defined( $opts{c} ) ){
|
||||
$config=$opts{c};
|
||||
}
|
||||
|
||||
#reads the config file, optionally
|
||||
my $config_file='';
|
||||
open(my $readfh, "<", $config) or die "Can't open '".$config."'";
|
||||
read($readfh , $config_file , 1000000);
|
||||
close($readfh);
|
||||
|
||||
#parse the config file and remove comments and empty lines
|
||||
my @configA=split(/\n/, $config_file);
|
||||
@configA=grep(!/^$/, @configA);
|
||||
@configA=grep(!/^\#/, @configA);
|
||||
@configA=grep(!/^[\s\t]*$/, @configA);
|
||||
my $configA_int=0;
|
||||
while ( defined( $configA[$configA_int] ) ){
|
||||
my $line=$configA[$configA_int];
|
||||
$line=~s/^[\t\s]+//;
|
||||
$line=~s/[\t\s]+$//;
|
||||
|
||||
my ( $var, $val )=split(/=/, $line, 2);
|
||||
|
||||
if ( $var eq 'cache' ){
|
||||
$cache=$val;
|
||||
}
|
||||
|
||||
if ( $var eq 'smartctl' ){
|
||||
$smartctl=$val;
|
||||
}
|
||||
|
||||
if ( $var eq 'useSN' ){
|
||||
$useSN=$val;
|
||||
}
|
||||
|
||||
if ( !defined( $val ) ){
|
||||
push(@disks, $var);
|
||||
}
|
||||
|
||||
$configA_int++;
|
||||
}
|
||||
|
||||
#if set to 1, no cache will be written and it will be printed instead
|
||||
my $noWrite=0;
|
||||
|
||||
# if no -u, it means we are being called from snmped
|
||||
if ( ! defined( $opts{u} ) ){
|
||||
# if the cache file exists, print it, otherwise assume one is not being used
|
||||
if ( -f $cache ){
|
||||
my $old='';
|
||||
open(my $readfh, "<", $cache) or die "Can't open '".$cache."'";
|
||||
read($readfh , $old , 1000000);
|
||||
close($readfh);
|
||||
print $old;
|
||||
exit 0;
|
||||
}else{
|
||||
$opts{u}=1;
|
||||
$noWrite=1;
|
||||
}
|
||||
}
|
||||
|
||||
my $toReturn='';
|
||||
my $int=0;
|
||||
while ( defined($disks[$int]) ) {
|
||||
my $disk=$disks[$int];
|
||||
my $disk_sn=$disk;
|
||||
my $output=`$smartctl -A /dev/$disk`;
|
||||
|
||||
my %IDs=( '5'=>'null',
|
||||
'10'=>'null',
|
||||
'173'=>'null',
|
||||
'177'=>'null',
|
||||
'183'=>'null',
|
||||
'184'=>'null',
|
||||
'187'=>'null',
|
||||
'188'=>'null',
|
||||
'190'=>'null',
|
||||
'194'=>'null',
|
||||
'196'=>'null',
|
||||
'197'=>'null',
|
||||
'198'=>'null',
|
||||
'199'=>'null',
|
||||
'231'=>'null',
|
||||
'233'=>'null',
|
||||
);
|
||||
|
||||
my @outputA=split( /\n/, $output );
|
||||
my $outputAint=0;
|
||||
while ( defined($outputA[$outputAint]) ) {
|
||||
my $line=$outputA[$outputAint];
|
||||
$line=~s/^ +//;
|
||||
$line=~s/ +/ /g;
|
||||
|
||||
if ( $line =~ /^[0123456789]+ / ) {
|
||||
my @lineA=split(/\ /, $line, 10);
|
||||
my $raw=$lineA[9];
|
||||
my $id=$lineA[0];
|
||||
|
||||
# single int raw values
|
||||
if (
|
||||
( $id == 5 ) ||
|
||||
( $id == 10 ) ||
|
||||
( $id == 173 ) ||
|
||||
( $id == 177 ) ||
|
||||
( $id == 183 ) ||
|
||||
( $id == 184 ) ||
|
||||
( $id == 187 ) ||
|
||||
( $id == 196 ) ||
|
||||
( $id == 197 ) ||
|
||||
( $id == 198 ) ||
|
||||
( $id == 199 ) ||
|
||||
( $id == 231 ) ||
|
||||
( $id == 233 )
|
||||
) {
|
||||
$IDs{$id}=$raw;
|
||||
}
|
||||
|
||||
# 188, Command_Timeout
|
||||
if ( $id == 188 ) {
|
||||
my $total=0;
|
||||
my @rawA=split( /\ /, $raw );
|
||||
my $rawAint=0;
|
||||
while ( defined( $rawA[$rawAint] ) ) {
|
||||
$total=$total+$rawA[$rawAint];
|
||||
$rawAint++;
|
||||
}
|
||||
$IDs{$id}=$total;
|
||||
}
|
||||
|
||||
# 190, airflow temp
|
||||
# 194, temp
|
||||
if (
|
||||
( $id == 190 ) ||
|
||||
( $id == 194 )
|
||||
) {
|
||||
my ( $temp )=split(/\ /, $raw);
|
||||
$IDs{$id}=$temp;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$outputAint++;
|
||||
}
|
||||
|
||||
#get the selftest logs
|
||||
$output=`$smartctl -l selftest /dev/$disk`;
|
||||
@outputA=split( /\n/, $output );
|
||||
my $completed=scalar grep(/Completed without error/, @outputA);
|
||||
my $interrupted=scalar grep(/Interrupted/, @outputA);
|
||||
my $read_failure=scalar grep(/read failure/, @outputA);
|
||||
my $unknown_failure=scalar grep(/unknown failure/, @outputA);
|
||||
my $extended=scalar grep(/Extended/, @outputA);
|
||||
my $short=scalar grep(/Short/, @outputA);
|
||||
my $conveyance=scalar grep(/Conveyance/, @outputA);
|
||||
my $selective=scalar grep(/Selective/, @outputA);
|
||||
|
||||
# get the drive serial number, if needed
|
||||
my $disk_id=$disk;
|
||||
if ( $useSN ){
|
||||
while (`$smartctl -i /dev/$disk` =~ /Serial Number:(.*)/g) {
|
||||
$disk_id = $1;
|
||||
$disk_id =~ s/^\s+|\s+$//g;
|
||||
}
|
||||
}
|
||||
|
||||
$toReturn=$toReturn.$disk_id.','.$IDs{'5'}.','.$IDs{'10'}.','.$IDs{'173'}.','.$IDs{'177'}.','.$IDs{'183'}.','.$IDs{'184'}.','.$IDs{'187'}.','.$IDs{'188'}
|
||||
.','.$IDs{'190'} .','.$IDs{'194'}.','.$IDs{'196'}.','.$IDs{'197'}.','.$IDs{'198'}.','.$IDs{'199'}.','.$IDs{'231'}.','.$IDs{'233'}.','.
|
||||
$completed.','.$interrupted.','.$read_failure.','.$unknown_failure.','.$extended.','.$short.','.$conveyance.','.$selective."\n";
|
||||
|
||||
$int++;
|
||||
}
|
||||
|
||||
if ( ! $noWrite ){
|
||||
open(my $writefh, ">", $cache) or die "Can't open '".$cache."'";
|
||||
print $writefh $toReturn;
|
||||
close($writefh);
|
||||
}else{
|
||||
print $toReturn;
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user