diff --git a/.agents/skills/devops-engineer/SKILL.md b/.agents/skills/devops-engineer/SKILL.md new file mode 100644 index 0000000..8b7004b --- /dev/null +++ b/.agents/skills/devops-engineer/SKILL.md @@ -0,0 +1,146 @@ +--- +name: devops-engineer +description: Creates Dockerfiles, configures CI/CD pipelines, writes Kubernetes manifests, and generates Terraform/Pulumi infrastructure templates. Handles deployment automation, GitOps configuration, incident response runbooks, and internal developer platform tooling. Use when setting up CI/CD pipelines, containerizing applications, managing infrastructure as code, deploying to Kubernetes clusters, configuring cloud platforms, automating releases, or responding to production incidents. Invoke for pipelines, Docker, Kubernetes, GitOps, Terraform, GitHub Actions, on-call, or platform engineering. +license: MIT +metadata: + author: https://github.com/Jeffallan + version: "1.1.1" + domain: devops + triggers: DevOps, CI/CD, deployment, Docker, Kubernetes, Terraform, GitHub Actions, infrastructure, platform engineering, incident response, on-call, self-service + role: engineer + scope: implementation + output-format: code + related-skills: terraform-engineer, kubernetes-specialist, sre-engineer, monitoring-expert, security-reviewer +--- + +# DevOps Engineer + +Senior DevOps engineer specializing in CI/CD pipelines, infrastructure as code, and deployment automation. + +## Role Definition + +You are a senior DevOps engineer with 10+ years of experience. You operate with three perspectives: +- **Build Hat**: Automating build, test, and packaging +- **Deploy Hat**: Orchestrating deployments across environments +- **Ops Hat**: Ensuring reliability, monitoring, and incident response + +## When to Use This Skill + +- Setting up CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins) +- Containerizing applications (Docker, Docker Compose) +- Kubernetes deployments and configurations +- Infrastructure as code (Terraform, Pulumi) +- Cloud platform configuration (AWS, GCP, Azure) +- Deployment strategies (blue-green, canary, rolling) +- Building internal developer platforms and self-service tools +- Incident response, on-call, and production troubleshooting +- Release automation and artifact management + +## Core Workflow + +1. **Assess** - Understand application, environments, requirements +2. **Design** - Pipeline structure, deployment strategy +3. **Implement** - IaC, Dockerfiles, CI/CD configs +4. **Validate** - Run `terraform plan`, lint configs, execute unit/integration tests; confirm no destructive changes before proceeding +5. **Deploy** - Roll out with verification; run smoke tests post-deployment +6. **Monitor** - Set up observability, alerts; confirm rollback procedure is ready before going live + +## Reference Guide + +Load detailed guidance based on context: + +| Topic | Reference | Load When | +|-------|-----------|-----------| +| GitHub Actions | `references/github-actions.md` | Setting up CI/CD pipelines, GitHub workflows | +| Docker | `references/docker-patterns.md` | Containerizing applications, writing Dockerfiles | +| Kubernetes | `references/kubernetes.md` | K8s deployments, services, ingress, pods | +| Terraform | `references/terraform-iac.md` | Infrastructure as code, AWS/GCP provisioning | +| Deployment | `references/deployment-strategies.md` | Blue-green, canary, rolling updates, rollback | +| Platform | `references/platform-engineering.md` | Self-service infra, developer portals, golden paths, Backstage | +| Release | `references/release-automation.md` | Artifact management, feature flags, multi-platform CI/CD | +| Incidents | `references/incident-response.md` | Production outages, on-call, MTTR, postmortems, runbooks | + +## Constraints + +### MUST DO +- Use infrastructure as code (never manual changes) +- Implement health checks and readiness probes +- Store secrets in secret managers (not env files) +- Enable container scanning in CI/CD +- Document rollback procedures +- Use GitOps for Kubernetes (ArgoCD, Flux) + +### MUST NOT DO +- Deploy to production without explicit approval +- Store secrets in code or CI/CD variables +- Skip staging environment testing +- Ignore resource limits in containers +- Use `latest` tag in production +- Deploy on Fridays without monitoring + +## Output Templates + +Provide: CI/CD pipeline config, Dockerfile, K8s/Terraform files, deployment verification, rollback procedure + +### Minimal GitHub Actions Example + +```yaml +name: CI +on: + push: + branches: [main] +jobs: + build-test-push: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build image + run: docker build -t myapp:${{ github.sha }} . + - name: Run tests + run: docker run --rm myapp:${{ github.sha }} pytest + - name: Scan image + uses: aquasecurity/trivy-action@master + with: + image-ref: myapp:${{ github.sha }} + - name: Push to registry + run: | + docker tag myapp:${{ github.sha }} ghcr.io/org/myapp:${{ github.sha }} + docker push ghcr.io/org/myapp:${{ github.sha }} +``` + +### Minimal Dockerfile Example + +```dockerfile +FROM python:3.12-slim AS builder +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +FROM python:3.12-slim +WORKDIR /app +COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages +COPY . . +USER nonroot +HEALTHCHECK --interval=30s --timeout=5s CMD curl -f http://localhost:8080/health || exit 1 +CMD ["python", "main.py"] +``` + +### Rollback Procedure Example + +```bash +# Kubernetes: roll back to previous deployment revision +kubectl rollout undo deployment/myapp -n production +kubectl rollout status deployment/myapp -n production + +# Verify rollback succeeded +kubectl get pods -n production -l app=myapp +curl -f https://myapp.example.com/health +``` + +Always document the rollback command and verification step in the PR or change ticket before deploying. + +## Knowledge Reference + +GitHub Actions, GitLab CI, Jenkins, CircleCI, Docker, Kubernetes, Helm, ArgoCD, Flux, Terraform, Pulumi, Crossplane, AWS/GCP/Azure, Prometheus, Grafana, PagerDuty, Backstage, LaunchDarkly, Flagger + +[Documentation](https://jeffallan.github.io/claude-skills/skills/devops/devops-engineer/) diff --git a/.agents/skills/devops-engineer/references/deployment-strategies.md b/.agents/skills/devops-engineer/references/deployment-strategies.md new file mode 100644 index 0000000..795bdd9 --- /dev/null +++ b/.agents/skills/devops-engineer/references/deployment-strategies.md @@ -0,0 +1,241 @@ +# Deployment Strategies + +## Strategy Comparison + +| Strategy | Use When | Rollback | Risk | +|----------|----------|----------|------| +| **Rolling** | Standard updates, can tolerate mixed versions | Automatic via health checks | Low | +| **Blue-Green** | Zero downtime, instant rollback needed | Switch traffic to old env | Medium | +| **Canary** | Risk mitigation, gradual rollout | Scale down canary | Low | +| **Recreate** | Stateful apps, breaking changes | Redeploy previous version | High | + +## Rolling Deployment (Kubernetes) + +```yaml +apiVersion: apps/v1 +kind: Deployment +spec: + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 25% # Max pods above desired + maxUnavailable: 25% # Max pods unavailable +``` + +## Blue-Green with Ingress + +```yaml +# Blue deployment (current) +apiVersion: apps/v1 +kind: Deployment +metadata: + name: app-blue + labels: + version: blue +--- +# Green deployment (new) +apiVersion: apps/v1 +kind: Deployment +metadata: + name: app-green + labels: + version: green +--- +# Service pointing to active version +apiVersion: v1 +kind: Service +metadata: + name: app +spec: + selector: + version: blue # Switch to 'green' for cutover +``` + +## Canary with Istio + +```yaml +apiVersion: networking.istio.io/v1beta1 +kind: VirtualService +metadata: + name: app +spec: + hosts: + - app + http: + - match: + - headers: + canary: + exact: "true" + route: + - destination: + host: app-canary + - route: + - destination: + host: app-stable + weight: 90 + - destination: + host: app-canary + weight: 10 +``` + +## Rollback Procedures + +### Kubernetes Rollback +```bash +# View rollout history +kubectl rollout history deployment/app + +# Rollback to previous +kubectl rollout undo deployment/app + +# Rollback to specific revision +kubectl rollout undo deployment/app --to-revision=2 + +# Check status +kubectl rollout status deployment/app +``` + +### ArgoCD Rollback +```bash +argocd app rollback app-prod --revision=123 +``` + +### Terraform Rollback +```bash +# Identify previous state +terraform state list + +# Import previous configuration +git checkout HEAD~1 -- main.tf +terraform apply +``` + +## Pre-deployment Checklist + +- [ ] Database migrations are backward compatible +- [ ] Feature flags for new functionality +- [ ] Monitoring dashboards updated +- [ ] Alert thresholds reviewed +- [ ] Rollback procedure documented +- [ ] Staging tested and approved +- [ ] Team notified of deployment window + +## Post-deployment Verification + +```bash +# Check pod status +kubectl get pods -l app=app + +# Check logs for errors +kubectl logs -l app=app --tail=100 | grep -i error + +# Verify endpoints +curl -f https://app.example.com/health + +# Check metrics +# - Error rate < 1% +# - Latency p99 < 500ms +# - No memory/CPU spikes +``` + +## Deployment Metrics (DORA) + +Track four key metrics: +- **Deployment Frequency**: Target 10+/day +- **Lead Time for Changes**: Target <1 hour +- **Change Failure Rate**: Target <5% +- **MTTR**: Target <30 minutes + +```yaml +# Prometheus metrics for DORA tracking +- record: deployment:frequency:1d + expr: count_over_time(deployment_completed[1d]) + +- record: deployment:lead_time:p95 + expr: histogram_quantile(0.95, + rate(commit_to_deploy_seconds_bucket[1h])) + +- record: deployment:failure_rate + expr: | + sum(rate(deployment_failed[1h])) + / sum(rate(deployment_total[1h])) +``` + +## Advanced Canary with Automated Analysis + +```yaml +# Flagger: Automated canary with rollback +apiVersion: flagger.app/v1beta1 +kind: Canary +metadata: + name: api +spec: + provider: istio + targetRef: + apiVersion: apps/v1 + kind: Deployment + name: api + progressDeadlineSeconds: 60 + service: + port: 8080 + trafficPolicy: + tls: + mode: ISTIO_MUTUAL + analysis: + interval: 30s + threshold: 5 + maxWeight: 50 + stepWeight: 10 + metrics: + - name: error-rate + templateRef: + name: error-rate + thresholdRange: + max: 1 + - name: latency + templateRef: + name: latency + thresholdRange: + max: 500 + webhooks: + - name: acceptance-test + type: pre-rollout + url: http://test-runner/ + - name: load-test + url: http://loadtester/ + timeout: 5s + metadata: + type: bash + cmd: "hey -z 1m -q 10 http://api-canary:8080/" +``` + +## Shadow Deployment + +```yaml +# Mirror traffic to shadow deployment +apiVersion: networking.istio.io/v1beta1 +kind: VirtualService +metadata: + name: api +spec: + hosts: + - api + http: + - match: + - headers: + x-test-version: + exact: "v2" + route: + - destination: + host: api + subset: v2 + mirror: + host: api + subset: v2-shadow + mirrorPercentage: + value: 100 + - route: + - destination: + host: api + subset: v1 +``` diff --git a/.agents/skills/devops-engineer/references/docker-patterns.md b/.agents/skills/devops-engineer/references/docker-patterns.md new file mode 100644 index 0000000..f5523e7 --- /dev/null +++ b/.agents/skills/devops-engineer/references/docker-patterns.md @@ -0,0 +1,113 @@ +# Docker Patterns + +## Multi-stage Dockerfile (Node.js) + +```dockerfile +# Build stage +FROM node:20-alpine AS builder +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production && npm cache clean --force +COPY . . +RUN npm run build + +# Production stage +FROM node:20-alpine AS runner +WORKDIR /app +ENV NODE_ENV=production +RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001 +COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist +COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules +USER nodejs +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \ + CMD wget -qO- http://localhost:3000/health || exit 1 +CMD ["node", "dist/main.js"] +``` + +## Multi-stage Dockerfile (Python) + +```dockerfile +FROM python:3.12-slim AS builder +WORKDIR /app +RUN pip install --no-cache-dir poetry +COPY pyproject.toml poetry.lock ./ +RUN poetry export -f requirements.txt --output requirements.txt +RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt + +FROM python:3.12-slim AS runner +WORKDIR /app +RUN useradd -m -u 1001 appuser +COPY --from=builder /wheels /wheels +RUN pip install --no-cache-dir /wheels/* +COPY --chown=appuser:appuser . . +USER appuser +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=3s \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] +``` + +## Docker Compose (Development) + +```yaml +version: '3.8' +services: + app: + build: + context: . + target: builder # Use dev stage + volumes: + - .:/app + - /app/node_modules + ports: + - "3000:3000" + environment: + - DATABASE_URL=postgres://user:pass@db:5432/app + depends_on: + db: + condition: service_healthy + + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass + POSTGRES_DB: app + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U user -d app"] + interval: 5s + timeout: 5s + retries: 5 + +volumes: + postgres_data: +``` + +## Security Best Practices + +| Practice | Implementation | +|----------|----------------| +| Non-root user | `USER nodejs` or `USER 1001` | +| Minimal base image | Use `-alpine` or `-slim` variants | +| No secrets in image | Use runtime env vars or secrets | +| Pin versions | `FROM node:20.10.0-alpine` not `latest` | +| Scan images | `docker scout`, `trivy`, `snyk` | +| Health checks | `HEALTHCHECK` instruction | +| .dockerignore | Exclude `node_modules`, `.git`, `.env` | + +## .dockerignore Template + +``` +node_modules +.git +.env* +*.md +Dockerfile* +docker-compose* +.dockerignore +coverage +.nyc_output +``` diff --git a/.agents/skills/devops-engineer/references/github-actions.md b/.agents/skills/devops-engineer/references/github-actions.md new file mode 100644 index 0000000..367c273 --- /dev/null +++ b/.agents/skills/devops-engineer/references/github-actions.md @@ -0,0 +1,139 @@ +# GitHub Actions Pipelines + +## Complete CI/CD Pipeline + +```yaml +name: CI/CD Pipeline + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + - run: npm ci + - run: npm test + - run: npm run lint + + build: + needs: test + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + outputs: + image-tag: ${{ steps.meta.outputs.tags }} + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=sha,prefix= + type=ref,event=branch + - uses: docker/build-push-action@v5 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + cache-from: type=gha + cache-to: type=gha,mode=max + + deploy-staging: + needs: build + if: github.ref == 'refs/heads/develop' + runs-on: ubuntu-latest + environment: staging + steps: + - uses: actions/checkout@v4 + - run: | + kubectl set image deployment/app app=${{ needs.build.outputs.image-tag }} + + deploy-production: + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + environment: production + steps: + - uses: actions/checkout@v4 + - run: | + kubectl set image deployment/app app=${{ needs.build.outputs.image-tag }} +``` + +## Common Workflow Patterns + +### Matrix Builds (Multi-version testing) +```yaml +jobs: + test: + strategy: + matrix: + node-version: [18, 20, 22] + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} +``` + +### Reusable Workflows +```yaml +# .github/workflows/deploy.yml +on: + workflow_call: + inputs: + environment: + required: true + type: string + secrets: + DEPLOY_KEY: + required: true + +jobs: + deploy: + runs-on: ubuntu-latest + environment: ${{ inputs.environment }} + steps: + - run: echo "Deploying to ${{ inputs.environment }}" +``` + +### Caching Dependencies +```yaml +- uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- +``` + +## Quick Reference + +| Action | Purpose | +|--------|---------| +| `actions/checkout@v4` | Clone repository | +| `actions/setup-node@v4` | Install Node.js | +| `docker/build-push-action@v5` | Build and push Docker image | +| `docker/metadata-action@v5` | Generate Docker tags | +| `actions/cache@v4` | Cache dependencies | diff --git a/.agents/skills/devops-engineer/references/incident-response.md b/.agents/skills/devops-engineer/references/incident-response.md new file mode 100644 index 0000000..1ff7731 --- /dev/null +++ b/.agents/skills/devops-engineer/references/incident-response.md @@ -0,0 +1,331 @@ +# Incident Response + +## Response Metrics + +- **MTTD** (Mean Time to Detect): Target < 5 minutes +- **MTTA** (Mean Time to Acknowledge): Target < 5 minutes +- **MTTR** (Mean Time to Resolve): Target < 30 minutes +- **MTBF** (Mean Time Between Failures): Maximize + +### Severity Levels + +| Level | Impact | Response | Example | +|-------|--------|----------|---------| +| SEV1 | Complete outage | Immediate | Database down, payment failed | +| SEV2 | Major degradation | 15 min | API latency >5s, 50% errors | +| SEV3 | Minor degradation | 1 hour | Non-critical feature broken | +| SEV4 | Low impact | Business hours | UI glitch, logging issues | + +## Runbook Template + +```markdown +# Runbook: High API Error Rate + +## Symptoms +- Alert: `api_error_rate > 0.05` +- Dashboard: https://grafana.example.com/d/api-errors + +## Impact +Users cannot complete purchases (~$X per minute) + +## Triage +1. Check dashboard for affected endpoints +2. Check recent deployments: `kubectl rollout history deployment/api` +3. Check dependencies: database, redis, external APIs + +## Resolution + +### Option 1: Rollback +kubectl rollout undo deployment/api -n production + +### Option 2: Scale Up +kubectl scale deployment/api --replicas=10 -n production + +### Option 3: Fix Config +kubectl set env deployment/api DB_POOL_SIZE=50 -n production + +## Verification +- [ ] Error rate <1% +- [ ] P95 latency <500ms +- [ ] Health checks passing + +## Communication +- Update status page +- Notify #incidents +- Post if user-facing +``` + +## Auto-Remediation Script + +```python +#!/usr/bin/env python3 +import kubernetes, prometheus_api_client + +class IncidentRemediator: + def check_high_error_rate(self): + query = 'rate(http_requests_total{status=~"5.."}[5m]) > 0.05' + result = self.prometheus.custom_query(query) + return len(result) > 0 + + def rollback_deployment(self, namespace, deployment): + body = {'spec': {'rollbackTo': {'revision': 0}}} + self.k8s.patch_namespaced_deployment(deployment, namespace, body) + + def remediate(self): + if self.check_high_error_rate(): + if self.rollback_deployment('production', 'api'): + time.sleep(120) + if not self.check_high_error_rate(): + return # Success + # Escalate if remediation fails + self.create_incident("Auto-remediation failed") +``` + +## Postmortem Template + +```markdown +# Postmortem: API Outage - 2024-01-15 + +**Date**: January 15, 2024 +**Duration**: 45 minutes (14:23 - 15:08 UTC) +**Severity**: SEV1 +**Impact**: Complete API outage, ~$25K revenue loss + +## Summary +API became unresponsive due to database connection pool exhaustion +from slow query in v2.3.1. + +## Timeline (UTC) +- 14:23 - Alert fired +- 14:27 - Incident declared SEV1 +- 14:30 - Rollback initiated +- 14:45 - Identified slow query +- 14:50 - Killed queries +- 15:08 - Resolved + +## Root Cause +New query missing index on `user_id`, causing full table scans that +exhausted connection pool under load. + +## Impact +- 100% API failure for 45 minutes +- 15,000 users affected +- $25K revenue loss +- 200+ support tickets + +## Action Items +| Action | Owner | Deadline | +|--------|-------|----------| +| Add index on user_id | DB team | 2024-01-16 | +| Add query perf testing | Platform | 2024-01-22 | +| Increase staging DB size | Infra | 2024-01-30 | + +## Lessons Learned +- Performance testing must use production-scale data +- Connection pool exhaustion needs active intervention +- Consider circuit breakers for DB operations +``` + +## PagerDuty Configuration + +```yaml +schedules: + - name: Primary On-Call + time_zone: America/New_York + layers: + - rotation_turn_length_seconds: 604800 # 1 week + users: [PXXXXXX, PXXXXXX, PXXXXXX] + +escalation_policies: + - name: Production + rules: + - escalation_delay_in_minutes: 0 + targets: [{type: schedule, id: primary}] + - escalation_delay_in_minutes: 15 + targets: [{type: schedule, id: secondary}] + - escalation_delay_in_minutes: 30 + targets: [{type: user, id: manager}] +``` + +## Chaos Engineering + +```yaml +# chaos-mesh: Pod failure test +apiVersion: chaos-mesh.org/v1alpha1 +kind: PodChaos +metadata: + name: pod-failure-test +spec: + action: pod-failure + mode: one + duration: "30s" + selector: + namespaces: [production] + labelSelectors: + app: api + scheduler: + cron: "@every 2h" +``` + +```bash +#!/bin/bash +# Game Day: Database failover drill + +echo "๐ŸŽฎ Game Day: Database failover" +slack-cli -d incidents "Starting failover drill" + +# Simulate failure +kubectl delete pod postgres-0 -n production + +# Monitor recovery +start=$(date +%s) +while ! kubectl get pod postgres-1 | grep Running; do + sleep 5 +done +duration=$(($(date +%s) - start)) + +echo "Failover: ${duration}s" >> results.md +curl -f https://api.example.com/health || echo "FAIL" +``` + +## Evidence Collection & Forensics + +```bash +#!/bin/bash +# collect-evidence.sh - Preserve incident evidence + +INCIDENT_ID=$1 +EVIDENCE_DIR="incidents/${INCIDENT_ID}/evidence" +mkdir -p $EVIDENCE_DIR + +# Preserve logs +kubectl logs -l app=api --all-containers --timestamps \ + --since=2h > $EVIDENCE_DIR/pod-logs.txt + +# Capture current state +kubectl get all -n production -o yaml > $EVIDENCE_DIR/k8s-state.yaml +kubectl describe pods -n production > $EVIDENCE_DIR/pod-details.txt + +# Network traces +kubectl exec -n production deploy/api -- \ + tcpdump -i any -w /tmp/capture.pcap -G 60 -W 5 & + +# Memory/CPU snapshot +kubectl top pods -n production > $EVIDENCE_DIR/resource-usage.txt + +# Git commit at time of incident +git log --since="2 hours ago" --oneline > $EVIDENCE_DIR/recent-commits.txt + +# Database queries +psql -c "SELECT * FROM pg_stat_activity" > $EVIDENCE_DIR/db-activity.txt + +# Create timeline +echo "$(date): Evidence collection completed" >> $EVIDENCE_DIR/timeline.txt +``` + +## Communication Templates + +```markdown +## SEV1 Initial Notification + +**INCIDENT ALERT - SEV1** + +**Status**: Investigating +**Impact**: Payment API unavailable (100% error rate) +**Started**: 2024-01-15 14:23 UTC +**Affected**: All users (~15K active sessions) +**Lead**: @oncall-engineer +**War Room**: https://zoom.us/incident-123 + +Updates every 15 minutes or on major change. + +--- + +## SEV1 Resolution Notification + +**INCIDENT RESOLVED** + +**Summary**: Payment API restored after database connection pool exhaustion +**Duration**: 45 minutes (14:23 - 15:08 UTC) +**Resolution**: Rollback to v2.3.0 + query optimization +**Impact**: 15K users, ~$25K revenue loss +**Next Steps**: Postmortem scheduled for Jan 16 10am + +Thanks to @oncall-team for rapid response. +``` + +## Incident Classification + +| Type | Examples | Response Team | Escalation | +|------|----------|---------------|------------| +| **Security** | Breach, data leak, unauthorized access | Security + DevOps | CISO, Legal | +| **Service** | Outage, degradation, errors | DevOps + SRE | Engineering VP | +| **Data** | Corruption, loss, sync issues | DBA + DevOps | CTO | +| **Compliance** | GDPR, SOC2, audit violations | Compliance + Legal | CEO | +| **Third-party** | Provider outage, API failures | DevOps + Product | Account manager | + +## Security Incident Specifics + +```bash +# Compromise investigation checklist +โ–ก Isolate affected systems +โ–ก Preserve logs and memory dumps +โ–ก Identify attack vector +โ–ก Check for lateral movement +โ–ก Scan for malware/backdoors +โ–ก Review access logs for 30 days +โ–ก Identify data accessed +โ–ก Assess exfiltration risk +โ–ก Check for persistence mechanisms +โ–ก Coordinate with security team +โ–ก Notify legal if PII involved +โ–ก Document chain of custody +``` + +## Compliance Requirements + +```yaml +# Incident notification requirements +gdpr: + notification_deadline: 72h + authority: Data Protection Officer + required_info: + - Nature of breach + - Data categories affected + - Number of individuals + - Consequences + - Remediation measures + +sox: + notification_deadline: immediate + authority: Audit Committee + documentation: + - Financial impact + - Control failures + - Remediation plan + +pci_dss: + notification_deadline: 24h + authority: Card brands + acquirer + required_info: + - Cardholder data affected + - Incident timeline + - Forensic investigation +``` + +## Best Practices + +- Maintain runbooks for critical services +- Practice with game days monthly +- Automate common remediation +- Keep postmortems blameless +- Track incident metrics +- Test recovery procedures +- Document all incidents +- Improve detection continuously +- Preserve evidence chain properly +- Coordinate communication clearly +- Escalate security incidents immediately +- Understand compliance obligations +- Train team on response procedures +- Review and update playbooks quarterly diff --git a/.agents/skills/devops-engineer/references/kubernetes.md b/.agents/skills/devops-engineer/references/kubernetes.md new file mode 100644 index 0000000..1bb44f7 --- /dev/null +++ b/.agents/skills/devops-engineer/references/kubernetes.md @@ -0,0 +1,154 @@ +# Kubernetes Manifests + +## Complete Deployment Stack + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: app + labels: + app: app +spec: + replicas: 3 + selector: + matchLabels: + app: app + template: + metadata: + labels: + app: app + spec: + containers: + - name: app + image: ghcr.io/org/app:latest + ports: + - containerPort: 3000 + resources: + requests: + memory: "128Mi" + cpu: "100m" + limits: + memory: "256Mi" + cpu: "500m" + livenessProbe: + httpGet: + path: /health + port: 3000 + initialDelaySeconds: 10 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /ready + port: 3000 + initialDelaySeconds: 5 + periodSeconds: 5 + env: + - name: DATABASE_URL + valueFrom: + secretKeyRef: + name: app-secrets + key: database-url +--- +apiVersion: v1 +kind: Service +metadata: + name: app +spec: + selector: + app: app + ports: + - port: 80 + targetPort: 3000 + type: ClusterIP +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: app + annotations: + cert-manager.io/cluster-issuer: letsencrypt-prod +spec: + ingressClassName: nginx + tls: + - hosts: [app.example.com] + secretName: app-tls + rules: + - host: app.example.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: app + port: + number: 80 +``` + +## ConfigMap and Secrets + +```yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: app-config +data: + LOG_LEVEL: "info" + API_TIMEOUT: "30s" +--- +apiVersion: v1 +kind: Secret +metadata: + name: app-secrets +type: Opaque +stringData: + database-url: "postgres://user:pass@host:5432/db" +``` + +## Horizontal Pod Autoscaler + +```yaml +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: app-hpa +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: app + minReplicas: 2 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 70 +``` + +## Quick Reference + +| Resource | Purpose | +|----------|---------| +| Deployment | Manages ReplicaSets, rolling updates | +| Service | Internal load balancing, DNS | +| Ingress | External HTTP/HTTPS routing | +| ConfigMap | Non-sensitive configuration | +| Secret | Sensitive data (base64 encoded) | +| HPA | Auto-scaling based on metrics | +| PVC | Persistent storage claims | + +## Common kubectl Commands + +```bash +kubectl apply -f deployment.yaml +kubectl get pods -l app=app +kubectl describe pod +kubectl logs -f +kubectl exec -it -- /bin/sh +kubectl rollout status deployment/app +kubectl rollout undo deployment/app +``` diff --git a/.agents/skills/devops-engineer/references/platform-engineering.md b/.agents/skills/devops-engineer/references/platform-engineering.md new file mode 100644 index 0000000..cf9f081 --- /dev/null +++ b/.agents/skills/devops-engineer/references/platform-engineering.md @@ -0,0 +1,417 @@ +# Platform Engineering + +## Platform Principles + +- **Self-service first**: Reduce manual work to <10% +- **Golden paths**: Pre-approved, opinionated templates +- **Developer experience**: Measure and optimize productivity +- **Platform as product**: Treat with product mindset + +## Self-Service with Crossplane + +```yaml +# Composition for self-service database +apiVersion: apiextensions.crossplane.io/v1 +kind: Composition +metadata: + name: postgres-database +spec: + compositeTypeRef: + apiVersion: platform.example.com/v1alpha1 + kind: Database + resources: + - name: rds-instance + base: + apiVersion: rds.aws.crossplane.io/v1alpha1 + kind: DBInstance + spec: + forProvider: + dbInstanceClass: db.t3.micro + engine: postgres + engineVersion: "15" + masterUsername: admin + allocatedStorage: 20 +``` + +## Terraform Self-Service Module + +```hcl +# modules/service/main.tf +variable "service_name" {} +variable "environment" {} + +module "k8s_service" { + source = "./k8s-deployment" + name = var.service_name + env = var.environment +} + +module "database" { + source = "./postgres" + name = "${var.service_name}-db" +} + +module "monitoring" { + source = "./monitoring-stack" + service = var.service_name +} + +output "service_url" { + value = module.k8s_service.url +} +``` + +## Backstage Service Template + +```yaml +# templates/microservice/template.yaml +apiVersion: scaffolder.backstage.io/v1beta3 +kind: Template +metadata: + name: microservice-template + title: Microservice Golden Path +spec: + owner: platform-team + type: service + parameters: + - title: Service Info + properties: + name: + type: string + owner: + type: string + ui:field: OwnerPicker + language: + type: string + enum: [go, python, nodejs, java] + steps: + - id: fetch + action: fetch:template + input: + url: ./skeleton + values: + name: ${{ parameters.name }} + - id: publish + action: publish:github + input: + repoUrl: github.com?owner=org&repo=${{ parameters.name }} + - id: register + action: catalog:register +``` + +## Service Catalog Info + +```yaml +# catalog-info.yaml +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: payment-service + annotations: + github.com/project-slug: org/payment-service + pagerduty.com/integration-key: abc123 + grafana/dashboard-selector: service=payment +spec: + type: service + lifecycle: production + owner: payments-team + system: checkout + dependsOn: + - resource:default/payment-db + - component:default/auth-service + providesApis: + - payment-api +``` + +## Golden Path Scaffolding + +```bash +#!/bin/bash +# create-service.sh - Golden path for new services + +SERVICE=$1 +LANG=$2 + +# Create from template +gh repo create "org/$SERVICE" --template "org/template-$LANG" +git clone "git@github.com:org/$SERVICE.git" +cd "$SERVICE" + +# Setup CI/CD +cat > .github/workflows/ci.yml < terraform/main.tf < { + const metrics = { + selfServiceRate: 92, + avgProvisionTime: '3.5min', + uptime: '99.95%', + satisfaction: 4.6 + }; + + return ( + + +

Provision Time: {metrics.avgProvisionTime}

+

Uptime: {metrics.uptime}

+

Satisfaction: {metrics.satisfaction}/5

+
+ ); +}; +``` + +## Cost Allocation + +```yaml +# kubecost/allocation.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: cost-allocation +data: + allocation.json: | + { + "defaultLabels": { + "team": "team", + "service": "app", + "environment": "env" + }, + "shareNamespaces": ["kube-system"], + "shareCost": "weighted" + } +``` + +## Platform APIs + +```python +# Platform API for self-service provisioning +from fastapi import FastAPI, Depends +from pydantic import BaseModel + +app = FastAPI() + +class ServiceRequest(BaseModel): + name: str + environment: str + language: str + database: bool = False + +@app.post("/api/v1/services") +async def create_service(request: ServiceRequest): + # Validate and enqueue + task = platform.provision_service( + name=request.name, + env=request.environment, + template=f"golden-path-{request.language}" + ) + return {"task_id": task.id, "status": "provisioning"} + +@app.get("/api/v1/services/{name}/status") +async def service_status(name: str): + return { + "status": "running", + "url": f"https://{name}.example.com", + "health": "healthy", + "cost_mtd": "$142.50" + } +``` + +## Multi-Tenant Architecture + +```yaml +# Policy: Resource quotas per tenant +apiVersion: v1 +kind: ResourceQuota +metadata: + name: team-quota + namespace: team-payments +spec: + hard: + requests.cpu: "20" + requests.memory: 40Gi + persistentvolumeclaims: "10" + services.loadbalancers: "2" +--- +# RBAC: Namespace admin +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: team-admin + namespace: team-payments +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: namespace-admin +subjects: + - kind: Group + name: team-payments +``` + +## Adoption Strategy + +```yaml +# Platform metrics tracking +apiVersion: v1 +kind: ConfigMap +metadata: + name: platform-goals +data: + goals.yaml: | + q1_2024: + self_service_rate: 90% + avg_provision_time: 5min + developer_satisfaction: 4.5/5 + golden_path_adoption: 80% + + tracking: + weekly_provisioning: true + team_feedback: true + support_tickets: true + training_completion: true +``` + +## CLI Tool Example + +```bash +#!/bin/bash +# platform-cli - Self-service CLI + +platform() { + case $1 in + create) + curl -X POST $PLATFORM_API/services \ + -d "{\"name\":\"$2\",\"env\":\"$3\",\"language\":\"$4\"}" + ;; + status) + curl $PLATFORM_API/services/$2/status | jq + ;; + logs) + kubectl logs -l app=$2 -n ${3:-staging} --tail=100 + ;; + cost) + curl $PLATFORM_API/services/$2/cost?period=mtd + ;; + esac +} +``` + +## Best Practices + +- Design for self-service from day one +- Make golden paths the easiest option +- Measure developer satisfaction continuously +- Automate platform operations +- Provide excellent documentation +- Build APIs, not just tools +- Enable safe experimentation +- Maintain backward compatibility +- Treat platform as a product +- Gather and act on feedback +- Track adoption metrics weekly +- Run platform as a product team +- Invest in developer evangelism +- Maintain SLOs for platform uptime +- Provide fast, helpful support diff --git a/.agents/skills/devops-engineer/references/release-automation.md b/.agents/skills/devops-engineer/references/release-automation.md new file mode 100644 index 0000000..ca42519 --- /dev/null +++ b/.agents/skills/devops-engineer/references/release-automation.md @@ -0,0 +1,527 @@ +# Release Automation + +## Artifact Management + +### Container Registry Lifecycle + +```json +{ + "rules": [ + { + "rulePriority": 1, + "description": "Keep last 10 prod images", + "selection": { + "tagStatus": "tagged", + "tagPrefixList": ["prod-"], + "countType": "imageCountMoreThan", + "countNumber": 10 + }, + "action": {"type": "expire"} + }, + { + "rulePriority": 2, + "description": "Remove untagged after 7 days", + "selection": { + "tagStatus": "untagged", + "countType": "sinceImagePushed", + "countUnit": "days", + "countNumber": 7 + }, + "action": {"type": "expire"} + } + ] +} +``` + +### Artifact Promotion + +```yaml +# .github/workflows/promote.yml +name: Artifact Promotion + +on: + workflow_dispatch: + inputs: + image_tag: + required: true + target_env: + type: choice + options: [staging, production] + +jobs: + promote: + runs-on: ubuntu-latest + steps: + - name: Re-tag for environment + run: | + docker pull $REGISTRY/$IMAGE:${{ inputs.image_tag }} + docker tag $REGISTRY/$IMAGE:${{ inputs.image_tag }} \ + $REGISTRY/$IMAGE:${{ inputs.target_env }}-latest + docker push $REGISTRY/$IMAGE:${{ inputs.target_env }}-latest + + - name: Sign artifact + uses: sigstore/cosign-installer@v3 + - run: cosign sign $REGISTRY/$IMAGE:${{ inputs.target_env }}-latest + + - name: Update GitOps + run: | + cd gitops/apps/${{ inputs.target_env }} + yq e '.image.tag = "${{ inputs.image_tag }}"' -i values.yaml + git commit -am "Promote to ${{ inputs.target_env }}" + git push +``` + +## Feature Flags + +### LaunchDarkly Integration + +```python +import launchdarkly + +ld = launchdarkly.get() + +def should_enable(user_id, feature_key): + user = {"key": user_id, "custom": {"groups": get_groups(user_id)}} + return ld.variation(feature_key, user, False) + +# Usage +if should_enable(user.id, "new-payment-flow"): + return new_payment_service.process(payment) +else: + return legacy_payment_service.process(payment) +``` + +### Flagger Progressive Delivery + +```yaml +apiVersion: flagger.app/v1beta1 +kind: Canary +metadata: + name: payment-service +spec: + targetRef: + kind: Deployment + name: payment-service + service: + port: 8080 + analysis: + interval: 1m + threshold: 5 + maxWeight: 50 + stepWeight: 10 + metrics: + - name: request-success-rate + thresholdRange: + min: 99 + - name: request-duration + thresholdRange: + max: 500 + webhooks: + - name: load-test + url: http://flagger-loadtester/ + metadata: + cmd: "hey -z 1m -q 10 http://payment-canary/" +``` + +## Multi-Platform CI/CD + +### GitLab CI + +```yaml +stages: [test, build, deploy] + +test: + stage: test + image: node:20 + script: + - npm ci && npm test + +build: + stage: build + image: docker:latest + services: [docker:dind] + script: + - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA . + - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + +deploy:production: + stage: deploy + script: + - kubectl set image deployment/app app=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + environment: production + when: manual + only: [main] +``` + +### Jenkins Pipeline + +```groovy +pipeline { + agent any + + environment { + IMAGE = "registry.example.com/app" + } + + stages { + stage('Test') { + steps { + sh 'npm ci && npm test' + junit 'reports/junit.xml' + } + } + + stage('Build') { + steps { + script { + docker.build("${IMAGE}:${BUILD_NUMBER}") + } + } + } + + stage('Security Scan') { + steps { + sh "trivy image ${IMAGE}:${BUILD_NUMBER}" + } + } + + stage('Deploy Staging') { + when { branch 'main' } + steps { + sh "kubectl set image deployment/app app=${IMAGE}:${BUILD_NUMBER} -n staging" + } + } + + stage('Deploy Production') { + when { branch 'main' } + steps { + input 'Deploy to production?' + sh "kubectl set image deployment/app app=${IMAGE}:${BUILD_NUMBER} -n production" + } + } + } + + post { + failure { + slackSend color: 'danger', message: "Build failed: ${JOB_NAME}" + } + } +} +``` + +## Build Optimization + +### Multi-stage Docker Build + +```dockerfile +FROM node:20 AS deps +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production + +FROM node:20 AS builder +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +RUN npm run build + +FROM node:20-slim AS runner +WORKDIR /app +ENV NODE_ENV production +COPY --from=deps /app/node_modules ./node_modules +COPY --from=builder /app/dist ./dist +USER node +CMD ["node", "dist/main.js"] +``` + +### Parallel Testing + +```yaml +# CircleCI +version: 2.1 +jobs: + test: + parallelism: 4 + docker: + - image: cimg/node:20 + steps: + - checkout + - run: npm ci + - run: | + TESTS=$(circleci tests glob "test/**/*.js" | circleci tests split) + npm test $TESTS +``` + +## Release Orchestration + +```bash +#!/bin/bash +# release.sh - Multi-service coordinated release + +VERSION=$1 +SERVICES=(auth api worker frontend) + +echo "Release: $VERSION" + +# Create release branches +for svc in "${SERVICES[@]}"; do + gh api repos/org/$svc/git/refs -f ref=refs/heads/release/$VERSION -f sha=$(git rev-parse main) +done + +# Trigger builds +for svc in "${SERVICES[@]}"; do + gh workflow run ci.yml --repo org/$svc --ref release/$VERSION +done + +# Wait for completion +for svc in "${SERVICES[@]}"; do + gh run watch --repo org/$svc $(gh run list --repo org/$svc -L1 -q '.[0].databaseId') +done + +# Deploy to staging +kubectl apply -f staging/release-$VERSION.yaml + +# Smoke tests +./scripts/smoke-test.sh staging + +echo "โœ“ Release $VERSION ready for production" +``` + +## Dependency Management + +### Renovate Auto-Update + +```json +{ + "extends": ["config:base"], + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch"], + "automerge": true + }, + { + "matchDepTypes": ["devDependencies"], + "automerge": true + } + ], + "schedule": ["before 6am on Monday"], + "prConcurrentLimit": 5 +} +``` + +## Build Optimization + +### Build Caching Strategy + +```yaml +# GitHub Actions: Multi-layer caching +- name: Cache dependencies + uses: actions/cache@v3 + with: + path: | + ~/.npm + ~/.cache + node_modules + key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-deps- + +- name: Cache Docker layers + uses: docker/build-push-action@v4 + with: + context: . + cache-from: type=gha + cache-to: type=gha,mode=max +``` + +### Parallel CI Pipeline + +```yaml +# Multi-platform builds in parallel +name: Build + +on: [push] + +jobs: + test: + strategy: + matrix: + node: [18, 20, 22] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node }} + - run: npm ci && npm test + + build-images: + needs: test + strategy: + matrix: + platform: [linux/amd64, linux/arm64] + runs-on: ubuntu-latest + steps: + - uses: docker/build-push-action@v4 + with: + platforms: ${{ matrix.platform }} + tags: app:${{ github.sha }} +``` + +## Multi-Service Release Orchestration + +```yaml +# release-coordinator.yaml +apiVersion: batch/v1 +kind: Job +metadata: + name: release-v2.5.0 +spec: + template: + spec: + containers: + - name: coordinator + image: release-bot:latest + env: + - name: RELEASE_VERSION + value: "v2.5.0" + - name: SERVICES + value: "auth,api,worker,frontend" + command: + - /bin/bash + - -c + - | + # Deploy in dependency order + for svc in auth api worker frontend; do + echo "Deploying $svc..." + kubectl set image deploy/$svc \ + $svc=registry.io/$svc:$RELEASE_VERSION + + kubectl rollout status deploy/$svc --timeout=5m + + # Health check + kubectl run test-$svc --rm -i --restart=Never \ + --image=curlimages/curl -- \ + curl -f http://$svc/health + + echo "$svc deployed successfully" + done +``` + +## Advanced Artifact Management + +```bash +#!/bin/bash +# artifact-scanner.sh - Scan before promotion + +IMAGE=$1 +SEVERITY=${2:-HIGH} + +# Vulnerability scan +trivy image --severity $SEVERITY --exit-code 1 $IMAGE + +# License compliance +syft $IMAGE -o json | \ + jq '.artifacts[].licenses[] | select(.value | + contains("GPL") or contains("AGPL"))' && \ + echo "License violation detected" && exit 1 + +# SBOM generation +syft $IMAGE -o spdx-json > sbom-$(basename $IMAGE).spdx.json + +# Sign artifact +cosign sign --key cosign.key $IMAGE + +# Promote +docker tag $IMAGE $IMAGE-approved +docker push $IMAGE-approved + +echo "Artifact $IMAGE approved and promoted" +``` + +## Zero-Downtime Database Migrations + +```python +# migrations/release_v2.5.py +from alembic import op +import sqlalchemy as sa + +def upgrade(): + # Step 1: Add new column (nullable) + op.add_column('users', + sa.Column('email_verified', sa.Boolean(), nullable=True)) + + # Step 2: Backfill data (in batches) + connection = op.get_bind() + connection.execute(""" + UPDATE users SET email_verified = true + WHERE email IS NOT NULL + LIMIT 1000 + """) + # Repeat until complete (or use background job) + + # Step 3: Make non-nullable (in next release) + # op.alter_column('users', 'email_verified', nullable=False) + +def downgrade(): + op.drop_column('users', 'email_verified') +``` + +## Release Metrics Dashboard + +```yaml +# Grafana dashboard for release metrics +apiVersion: v1 +kind: ConfigMap +metadata: + name: release-dashboard +data: + dashboard.json: | + { + "panels": [ + { + "title": "Deployment Frequency", + "targets": [{ + "expr": "count_over_time(deployment_completed[1d])" + }] + }, + { + "title": "Lead Time", + "targets": [{ + "expr": "histogram_quantile(0.95, commit_to_deploy_seconds_bucket)" + }] + }, + { + "title": "Change Failure Rate", + "targets": [{ + "expr": "sum(rate(deployment_failed[1h])) / sum(rate(deployment_total[1h]))" + }] + }, + { + "title": "Active Releases", + "targets": [{ + "expr": "count(release_in_progress == 1)" + }] + } + ] + } +``` + +## Best Practices + +- Version artifacts with immutable tags +- Implement retention policies +- Use progressive delivery for high-risk changes +- Automate security scanning +- Maintain deployment audit trails +- Enable easy rollbacks +- Monitor deployment metrics +- Use feature flags for flexibility +- Cache aggressively for fast builds +- Parallelize test and build jobs +- Coordinate multi-service releases +- Generate and track SBOMs +- Sign artifacts for supply chain security +- Automate dependency updates +- Track DORA metrics continuously diff --git a/.agents/skills/devops-engineer/references/terraform-iac.md b/.agents/skills/devops-engineer/references/terraform-iac.md new file mode 100644 index 0000000..62f5289 --- /dev/null +++ b/.agents/skills/devops-engineer/references/terraform-iac.md @@ -0,0 +1,141 @@ +# Terraform Infrastructure as Code + +## AWS ECS Fargate Setup + +```hcl +terraform { + required_providers { + aws = { source = "hashicorp/aws", version = "~> 5.0" } + } + backend "s3" { + bucket = "terraform-state" + key = "app/terraform.tfstate" + region = "us-east-1" + } +} + +resource "aws_ecs_cluster" "main" { + name = "app-cluster" + setting { + name = "containerInsights" + value = "enabled" + } +} + +resource "aws_ecs_task_definition" "app" { + family = "app" + network_mode = "awsvpc" + requires_compatibilities = ["FARGATE"] + cpu = "256" + memory = "512" + execution_role_arn = aws_iam_role.ecs_execution.arn + + container_definitions = jsonencode([{ + name = "app" + image = "${var.ecr_repository}:${var.image_tag}" + portMappings = [{ containerPort = 3000 }] + logConfiguration = { + logDriver = "awslogs" + options = { + awslogs-group = aws_cloudwatch_log_group.app.name + awslogs-region = var.region + awslogs-stream-prefix = "app" + } + } + secrets = [ + { name = "DATABASE_URL", valueFrom = aws_ssm_parameter.db_url.arn } + ] + }]) +} + +resource "aws_ecs_service" "app" { + name = "app" + cluster = aws_ecs_cluster.main.id + task_definition = aws_ecs_task_definition.app.arn + desired_count = 2 + launch_type = "FARGATE" + + network_configuration { + subnets = var.private_subnets + security_groups = [aws_security_group.app.id] + } + + load_balancer { + target_group_arn = aws_lb_target_group.app.arn + container_name = "app" + container_port = 3000 + } +} +``` + +## AWS RDS PostgreSQL + +```hcl +resource "aws_db_instance" "postgres" { + identifier = "app-db" + engine = "postgres" + engine_version = "16.1" + instance_class = "db.t3.micro" + allocated_storage = 20 + storage_encrypted = true + + db_name = "app" + username = "admin" + password = var.db_password + + vpc_security_group_ids = [aws_security_group.db.id] + db_subnet_group_name = aws_db_subnet_group.main.name + + backup_retention_period = 7 + skip_final_snapshot = false + final_snapshot_identifier = "app-db-final" + + tags = { Environment = var.environment } +} +``` + +## Variables and Outputs + +```hcl +# variables.tf +variable "environment" { + type = string + description = "Environment name" +} + +variable "region" { + type = string + default = "us-east-1" +} + +# outputs.tf +output "ecs_cluster_arn" { + value = aws_ecs_cluster.main.arn +} + +output "alb_dns_name" { + value = aws_lb.main.dns_name +} +``` + +## Best Practices + +| Practice | Implementation | +|----------|----------------| +| State locking | S3 backend with DynamoDB | +| Secrets | Use AWS Secrets Manager / SSM | +| Modules | Reusable components | +| Workspaces | Environment separation | +| Tagging | Consistent resource tags | +| Validation | `terraform validate`, `tflint` | + +## Common Commands + +```bash +terraform init +terraform plan -out=tfplan +terraform apply tfplan +terraform destroy +terraform state list +terraform import aws_instance.app i-1234567890 +``` diff --git a/.agents/skills/reverse-proxy/SKILL.md b/.agents/skills/reverse-proxy/SKILL.md new file mode 100644 index 0000000..7e5100b --- /dev/null +++ b/.agents/skills/reverse-proxy/SKILL.md @@ -0,0 +1,404 @@ +--- +name: reverse-proxy +description: Configure nginx and Traefik as reverse proxies. Implement SSL termination and routing. Use when setting up application gateways. +license: MIT +metadata: + author: devops-skills + version: "1.0" +--- + +# Reverse Proxy + +Configure reverse proxies to route traffic, terminate TLS, enforce rate limits, and serve as the gateway between clients and backend services. + +## When to Use + +- Routing traffic from a public domain to one or more backend services. +- Terminating TLS at the edge and forwarding plain HTTP to backends. +- Adding rate limiting, CORS, security headers, and access control. +- Consolidating multiple services under a single domain with path-based routing. +- Handling WebSocket upgrades, gRPC proxying, or HTTP/2 passthrough. + +## Prerequisites + +- Backend service(s) running on known host:port. +- TLS certificate (Let's Encrypt, ACM, or self-signed for development). +- nginx 1.25+ or Traefik 3.x installed. +- DNS record pointing the domain to the proxy server. + +## nginx Reverse Proxy + +### Basic HTTPS Proxy with Redirect + +```nginx +# /etc/nginx/sites-available/app.example.com +server { + listen 80; + server_name app.example.com; + return 301 https://$host$request_uri; +} + +server { + listen 443 ssl http2; + server_name app.example.com; + + # TLS configuration + ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384; + ssl_prefer_server_ciphers on; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 10m; + + # Security headers + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + add_header X-Frame-Options DENY always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy strict-origin-when-cross-origin always; + + # Proxy to backend + location / { + proxy_pass http://127.0.0.1:3000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Timeouts + proxy_connect_timeout 5s; + proxy_read_timeout 60s; + proxy_send_timeout 60s; + + # Buffering + proxy_buffering on; + proxy_buffer_size 4k; + proxy_buffers 8 4k; + } +} +``` + +### Path-Based Routing to Multiple Services + +```nginx +server { + listen 443 ssl http2; + server_name app.example.com; + + ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem; + + # Frontend SPA + location / { + proxy_pass http://127.0.0.1:3000; + proxy_set_header Host $host; + } + + # API backend + location /api/ { + proxy_pass http://127.0.0.1:8080/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_read_timeout 120s; + } + + # WebSocket endpoint + location /ws/ { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_read_timeout 86400s; # 24h for long-lived connections + } + + # Static assets with caching + location /static/ { + alias /var/www/static/; + expires 30d; + add_header Cache-Control "public, immutable"; + } +} +``` + +### Rate Limiting + +```nginx +# Define rate limit zones in http block +http { + # 10 requests/second per IP + limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; + + # 1 request/second for login + limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s; + + # Connection limit per IP + limit_conn_zone $binary_remote_addr zone=conn_limit:10m; +} + +server { + listen 443 ssl http2; + server_name app.example.com; + + # Apply rate limit to API + location /api/ { + limit_req zone=api_limit burst=20 nodelay; + limit_req_status 429; + proxy_pass http://127.0.0.1:8080; + } + + # Strict rate limit on auth endpoints + location /api/auth/ { + limit_req zone=login_limit burst=5; + limit_req_status 429; + proxy_pass http://127.0.0.1:8080; + } + + # Connection limit + location / { + limit_conn conn_limit 100; + proxy_pass http://127.0.0.1:3000; + } +} +``` + +### Gzip and Brotli Compression + +```nginx +http { + gzip on; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml; + gzip_min_length 256; + gzip_vary on; + gzip_proxied any; + gzip_comp_level 5; + + # Brotli (requires ngx_brotli module) + # brotli on; + # brotli_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml; + # brotli_comp_level 6; +} +``` + +### Let's Encrypt with Certbot + +```bash +# Install certbot with nginx plugin +sudo apt install certbot python3-certbot-nginx + +# Obtain and install certificate +sudo certbot --nginx -d app.example.com -d www.example.com + +# Auto-renewal is configured via systemd timer +sudo systemctl status certbot.timer + +# Manual renewal test +sudo certbot renew --dry-run +``` + +## Traefik Reverse Proxy + +### Static Configuration + +```yaml +# traefik.yml +entryPoints: + web: + address: ":80" + http: + redirections: + entryPoint: + to: websecure + scheme: https + websecure: + address: ":443" + +certificatesResolvers: + letsencrypt: + acme: + email: admin@example.com + storage: /letsencrypt/acme.json + httpChallenge: + entryPoint: web + +providers: + docker: + exposedByDefault: false + file: + directory: /etc/traefik/dynamic/ + +api: + dashboard: true + insecure: false + +log: + level: INFO + +accessLog: + filePath: /var/log/traefik/access.log +``` + +### Dynamic Configuration (File Provider) + +```yaml +# /etc/traefik/dynamic/services.yml +http: + routers: + app: + rule: "Host(`app.example.com`)" + entryPoints: + - websecure + service: app + tls: + certResolver: letsencrypt + middlewares: + - security-headers + - rate-limit + + api: + rule: "Host(`app.example.com`) && PathPrefix(`/api`)" + entryPoints: + - websecure + service: api + tls: + certResolver: letsencrypt + + services: + app: + loadBalancer: + servers: + - url: "http://127.0.0.1:3000" + healthCheck: + path: /health + interval: 10s + timeout: 3s + + api: + loadBalancer: + servers: + - url: "http://127.0.0.1:8080" + healthCheck: + path: /api/health + interval: 10s + timeout: 3s + + middlewares: + security-headers: + headers: + stsSeconds: 63072000 + stsIncludeSubdomains: true + frameDeny: true + contentTypeNosniff: true + browserXssFilter: true + referrerPolicy: strict-origin-when-cross-origin + + rate-limit: + rateLimit: + average: 100 + burst: 50 + period: 1m +``` + +### Traefik with Docker Labels + +```yaml +# docker-compose.yml +version: "3.8" + +services: + traefik: + image: traefik:v3.0 + ports: + - "80:80" + - "443:443" + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + - ./traefik.yml:/etc/traefik/traefik.yml:ro + - letsencrypt:/letsencrypt + + frontend: + image: my-frontend:latest + labels: + - "traefik.enable=true" + - "traefik.http.routers.frontend.rule=Host(`app.example.com`)" + - "traefik.http.routers.frontend.tls.certresolver=letsencrypt" + - "traefik.http.services.frontend.loadbalancer.server.port=3000" + + api: + image: my-api:latest + labels: + - "traefik.enable=true" + - "traefik.http.routers.api.rule=Host(`app.example.com`) && PathPrefix(`/api`)" + - "traefik.http.routers.api.tls.certresolver=letsencrypt" + - "traefik.http.services.api.loadbalancer.server.port=8080" + - "traefik.http.routers.api.middlewares=api-ratelimit" + - "traefik.http.middlewares.api-ratelimit.ratelimit.average=50" + - "traefik.http.middlewares.api-ratelimit.ratelimit.burst=25" + +volumes: + letsencrypt: +``` + +## nginx Testing and Management + +```bash +# Test configuration syntax +sudo nginx -t + +# Reload without downtime +sudo nginx -s reload + +# View active connections +sudo nginx -s status + +# Check which config file is active +nginx -V 2>&1 | grep -o '\-\-conf-path=[^ ]*' + +# Monitor access logs +tail -f /var/log/nginx/access.log + +# Monitor error logs +tail -f /var/log/nginx/error.log +``` + +## IP Allowlisting and Geoblocking + +```nginx +# Allow only specific IPs (admin panel) +location /admin/ { + allow 203.0.113.0/24; + allow 198.51.100.5; + deny all; + proxy_pass http://127.0.0.1:3000; +} + +# Block by country (requires GeoIP2 module) +# geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb { +# auto_reload 60m; +# $geoip2_data_country_iso_code country iso_code; +# } +# if ($geoip2_data_country_iso_code = "XX") { +# return 403; +# } +``` + +## Troubleshooting + +| Symptom | Cause | Fix | +|---------|-------|-----| +| 502 Bad Gateway | Backend not running or unreachable | Verify backend is listening; check `proxy_pass` URL | +| 504 Gateway Timeout | Backend too slow | Increase `proxy_read_timeout`; check backend performance | +| Mixed content warnings | `X-Forwarded-Proto` not set | Add `proxy_set_header X-Forwarded-Proto $scheme` | +| WebSocket disconnects after 60s | Default proxy timeout expires | Set `proxy_read_timeout 86400s` for WebSocket locations | +| Rate limit hits legitimate users | Zone rate too aggressive | Increase `rate` or `burst` values; use different zones per endpoint | +| Let's Encrypt renewal fails | Port 80 blocked or wrong server block | Ensure `.well-known/acme-challenge/` is accessible | +| Traefik shows 404 for all routes | Docker labels not detected | Verify Docker socket is mounted; check `exposedByDefault` setting | +| TLS handshake failure | Certificate chain incomplete | Include intermediate certificates in `ssl_certificate` | + +## Related Skills + +- [load-balancing](../load-balancing/) - Multi-backend traffic distribution +- [cdn-setup](../cdn-setup/) - CDN in front of reverse proxy +- [dns-management](../dns-management/) - DNS records for proxy domains +- [service-mesh](../service-mesh/) - Service-level routing in Kubernetes diff --git a/.agents/skills/sysadmin-toolbox/.clawhub/origin.json b/.agents/skills/sysadmin-toolbox/.clawhub/origin.json new file mode 100644 index 0000000..7f94cdb --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/.clawhub/origin.json @@ -0,0 +1,7 @@ +{ + "version": 1, + "registry": "https://clawhub.ai", + "slug": "sysadmin-toolbox", + "installedVersion": "1.1.0", + "installedAt": 1772232079431 +} diff --git a/.agents/skills/sysadmin-toolbox/SKILL.md b/.agents/skills/sysadmin-toolbox/SKILL.md new file mode 100644 index 0000000..8d38cfc --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/SKILL.md @@ -0,0 +1,102 @@ +--- +name: sysadmin-toolbox +description: "Tool discovery and shell one-liner reference for sysadmin, DevOps, and security tasks. AUTO-CONSULT this skill when the user is: troubleshooting network issues, debugging processes, analyzing logs, working with SSL/TLS, managing DNS, testing HTTP endpoints, auditing security, working with containers, writing shell scripts, or asks 'what tool should I use for X'. Source: github.com/trimstray/the-book-of-secret-knowledge" +permissions: + - exec: "May recommend or run narrowly scoped shell commands when the user asks for operational diagnosis." + - network: "Covers network-debugging tools and HTTP diagnostics when those are part of the requested workflow." +--- + +# Sysadmin Toolbox + +Curated tool recommendations and practical shell one-liners for operational work. + +## When to Auto-Consult + +Load relevant references when user is: +- Debugging network connectivity, ports, traffic +- Troubleshooting DNS or SSL/TLS +- Analyzing processes, memory, disk usage +- Working with logs or system diagnostics +- Writing shell scripts or one-liners +- Asking "what's a good tool for..." +- Doing security audits or pentesting +- Working with containers/Docker/K8s + +## Bundled Guides + +| File | Use When | +|------|----------| +| `shell-oneliners.md` in this skill's `references` folder | Need practical commands for: terminal, networking, SSL, curl, ssh, tcpdump, git, awk, sed, grep, find | +| `cli-tools.md` in this skill's `references` folder | Recommending CLI tools: shells, file managers, network utils, databases, security tools | +| `web-tools.md` in this skill's `references` folder | Web-based tools: SSL checkers, DNS lookup, performance testing, OSINT, scanners | +| `security-tools.md` in this skill's `references` folder | Pentesting, vulnerability scanning, exploit databases, CTF resources | +| `shell-tricks.md` in this skill's `references` folder | Shell scripting patterns and tricks | + +## Safety Boundaries + +- Do not run destructive system commands, privilege-escalation steps, or offensive tooling unless the user explicitly asked for that scope. +- Do not scan hosts, domains, or networks the user does not control or have permission to assess. +- Do not assume a command is safe to paste into production without explaining what it does. +- Do not persist logs, captures, or credentials outside the user's requested troubleshooting workflow. + +## Quick Tool Index + +### Network Debugging +- `mtr` - traceroute + ping combined +- `tcpdump` / `tshark` - packet capture +- `netstat` / `ss` - connection monitoring +- `nmap` - port scanning +- `curl` / `httpie` - HTTP testing + +### DNS +- `dig` / `host` - DNS queries +- `dnsdiag` - DNS diagnostics +- `subfinder` / `amass` - subdomain enumeration + +### SSL/TLS +- `openssl` - certificate inspection +- `testssl.sh` - TLS testing +- `sslyze` - SSL scanning +- `certbot` - Let's Encrypt + +### Process/System +- `htop` / `btop` - process monitoring +- `strace` / `ltrace` - syscall/library tracing +- `lsof` - open files/connections +- `ncdu` - disk usage + +### Log Analysis +- `lnav` - log navigator +- `GoAccess` - web log analyzer +- `angle-grinder` - log slicing + +### Containers +- `dive` - Docker image analysis +- `ctop` - container top +- `lazydocker` - Docker TUI + +## Keeping Current + +References auto-refresh weekly (Sundays 5am ET) from the upstream repo: +```bash +~/clawd-duke-leto/skills/sysadmin-toolbox/scripts/refresh.sh +``` + +Manual refresh anytime: +```bash +./scripts/refresh.sh [skill-dir] +``` + +## Example Queries โ†’ Actions + +**"Why is this port not responding?"** +โ†’ Load shell-oneliners.md, search for netstat/ss/lsof commands + +**"What's a good tool for testing SSL?"** +โ†’ Load cli-tools.md SSL section, recommend testssl.sh or sslyze + +**"Show me how to find large files"** +โ†’ Load shell-oneliners.md, search for find/ncdu/du commands + +**"I need to debug DNS resolution"** +โ†’ Load shell-oneliners.md dig section + recommend dnsdiag from cli-tools.md diff --git a/.agents/skills/sysadmin-toolbox/_meta.json b/.agents/skills/sysadmin-toolbox/_meta.json new file mode 100644 index 0000000..3f157d6 --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/_meta.json @@ -0,0 +1,6 @@ +{ + "ownerId": "kn73ft5fmjrf1h9n78fc61tgfs7yp8ez", + "slug": "sysadmin-toolbox", + "version": "1.1.0", + "publishedAt": 1768843243799 +} \ No newline at end of file diff --git a/.agents/skills/sysadmin-toolbox/references/cli-tools.md b/.agents/skills/sysadmin-toolbox/references/cli-tools.md new file mode 100644 index 0000000..6c1e5c5 --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/references/cli-tools.md @@ -0,0 +1,272 @@ +#### CLI Tools  [[TOC]](#anger-table-of-contents) + +##### :black_small_square: Shells + +

+   GNU Bash - is an sh-compatible shell that incorporates useful features from the Korn shell and C shell.
+   Zsh - is a shell designed for interactive use, although it is also a powerful scripting language.
+   tclsh - is a very powerful cross-platform shell, suitable for a huge range of uses.
+   bash-it - is a framework for using, developing and maintaining shell scripts and custom commands.
+   Oh My ZSH! - is the best framework for managing your Zsh configuration.
+   Oh My Fish - the Fishshell framework.
+   Starship - the cross-shell prompt written in Rust.
+   powerlevel10k - is a fast reimplementation of Powerlevel9k ZSH theme.
+

+ +##### :black_small_square: Shell plugins + +

+   z - tracks the folder you use the most and allow you to jump, without having to type the whole path.
+   fzf - is a general-purpose command-line fuzzy finder.
+   zsh-autosuggestions - Fish-like autosuggestions for Zsh.
+   zsh-syntax-highlighting - Fish shell like syntax highlighting for Zsh.
+   Awesome ZSH Plugins - A list of frameworks, plugins, themes and tutorials for ZSH.
+

+ +##### :black_small_square: Managers + +

+   Midnight Commander - is a visual file manager, licensed under GNU General Public License.
+   ranger - is a VIM-inspired filemanager for the console.
+   nnn - is a tiny, lightning fast, feature-packed file manager.
+   screen - is a full-screen window manager that multiplexes a physical terminal.
+   tmux - is a terminal multiplexer, lets you switch easily between several programs in one terminal.
+   tmux-cssh - is a tool to set comfortable and easy to use functionality tmux-sessions.
+

+ +##### :black_small_square: Text editors + +

+   vi - is one of the most common text editors on Unix.
+   vim - is a highly configurable text editor.
+   emacs - is an extensible, customizable, free/libre text editor, and more.
+   micro - is a modern and intuitive terminal-based text editor.
+   neovim - is a free open source, powerful, extensible and usable code editor.
+   spacemacs - a community-driven Emacs distribution.
+   spacevim - a community-driven vim distribution.
+

+ +##### :black_small_square: Files and directories + +

+   fd - is a simple, fast and user-friendly alternative to find.
+   ncdu - is an easy to use, fast disk usage analyzer.
+

+ +##### :black_small_square: Network + +

+   PuTTY - is an SSH and telnet client, developed originally by Simon Tatham.
+   Mosh - is a SSH wrapper designed to keep a SSH session alive over a volatile connection.
+   Eternal Terminal - enables mouse-scrolling and tmux commands inside the SSH session.
+   nmap - is a free and open source (license) utility for network discovery and security auditing.
+   zmap - is a fast single packet network scanner designed for Internet-wide network surveys.
+   Rust Scan - to find all open ports faster than Nmap.
+   masscan - is the fastest Internet port scanner, spews SYN packets asynchronously.
+   pbscan - is a faster and more efficient stateless SYN scanner and banner grabber.
+   hping - is a command-line oriented TCP/IP packet assembler/analyzer.
+   mtr - is a tool that combines the functionality of the 'traceroute' and 'ping' programs in a single tool.
+   mylg - utility which combines the functions of the different network probes in one diagnostic tool.
+   netcat - utility which reads and writes data across network connections, using the TCP/IP protocol.
+   socat - utility which transfers data between two objects.
+   tcpdump - is a powerful command-line packet analyzer.
+   tshark - is a tool that allows us to dump and analyze network traffic (wireshark cli).
+   Termshark - is a simple terminal user-interface for tshark.
+   ngrep - is like GNU grep applied to the network layer.
+   netsniff-ng - is a Swiss army knife for your daily Linux network plumbing if you will.
+   sockdump - dump unix domain socket traffic.
+   stenographer - is a packet capture solution which aims to quickly spool all packets to disk.
+   tcpterm - visualize packets in TUI.
+   bmon - is a monitoring and debugging tool to capture networking related statistics and prepare them visually.
+   iptraf-ng - is a console-based network monitoring program for Linux that displays information about IP traffic.
+   vnstat - is a network traffic monitor for Linux and BSD.
+   iPerf3 - is a tool for active measurements of the maximum achievable bandwidth on IP networks.
+   ethr - is a Network Performance Measurement Tool for TCP, UDP & HTTP.
+   Etherate - is a Linux CLI based Ethernet and MPLS traffic testing tool.
+   echoip - is a IP address lookup service.
+   Nemesis - packet manipulation CLI tool; craft and inject packets of several protocols.
+   packetfu - a mid-level packet manipulation library for Ruby.
+   Scapy - packet manipulation library; forge, send, decode, capture packets of a wide number of protocols.
+   impacket - is a collection of Python classes for working with network protocols.
+   ssh-audit - is a tool for SSH server auditing.
+   aria2 - is a lightweight multi-protocol & multi-source command-line download utility.
+   iptables-tracer - observe the path of packets through the iptables chains.
+   inception - a highly configurable tool to check for whatever you like against any number of hosts.
+   mRemoteNG - a fork of mRemote, multi-tabbed PuTTy on steroids!
+

+ +##### :black_small_square: Network (DNS) + +

+   dnsdiag - is a DNS diagnostics and performance measurement tools.
+   fierce - is a DNS reconnaissance tool for locating non-contiguous IP space.
+   subfinder - is a subdomain discovery tool that discovers valid subdomains for websites.
+   sublist3r - is a fast subdomains enumeration tool for penetration testers.
+   amass - is tool that obtains subdomain names by scraping data sources, crawling web archives, and more.
+   namebench - provides personalized DNS server recommendations based on your browsing history.
+   massdns - is a high-performance DNS stub resolver for bulk lookups and reconnaissance.
+   knock - is a tool to enumerate subdomains on a target domain through a wordlist.
+   dnsperf - DNS performance testing tools.
+   dnscrypt-proxy 2 - a flexible DNS proxy, with support for encrypted DNS protocols.
+   dnsdbq - API client providing access to passive DNS database systems.
+   grimd - fast dns proxy, built to black-hole internet advertisements and malware servers.
+    dnstwist - detect typosquatters, phishing attacks, fraud, and brand impersonation.
+

+ +##### :black_small_square: Network (HTTP) + +

+   curl - is a command line tool and library for transferring data with URLs.
+   kurly - is an alternative to the widely popular curl program, written in Golang.
+   HTTPie - is an user-friendly HTTP client.
+   wuzz - is an interactive cli tool for HTTP inspection.
+   h2spec - is a conformance testing tool for HTTP/2 implementation.
+   h2t - is a simple tool to help sysadmins to hardening their websites.
+   htrace.sh - is a simple Swiss Army knife for http/https troubleshooting and profiling.
+   httpstat - is a tool that visualizes curl statistics in a way of beauty and clarity.
+   httplab - is an interactive web server.
+   Lynx - is a text browser for the World Wide Web.
+   Browsh - is a fully interactive, real-time, and modern text-based browser.
+   HeadlessBrowsers - a list of (almost) all headless web browsers in existence.
+   ab - is a single-threaded command line tool for measuring the performance of HTTP web servers.
+   siege - is an http load testing and benchmarking utility.
+   wrk - is a modern HTTP benchmarking tool capable of generating significant load.
+   wrk2 - is a constant throughput, correct latency recording variant of wrk.
+   vegeta - is a constant throughput, correct latency recording variant of wrk.
+   bombardier - is a fast cross-platform HTTP benchmarking tool written in Go.
+   gobench - http/https load testing and benchmarking tool.
+   hey - HTTP load generator, ApacheBench (ab) replacement, formerly known as rakyll/boom.
+   boom - is a script you can use to quickly smoke-test your web app deployment.
+   SlowHTTPTest - is a tool that simulates some Application Layer Denial of Service attacks by prolonging HTTP.
+   gobuster - is a free and open source directory/file & DNS busting tool written in Go.
+   ssllabs-scan - command-line reference-implementation client for SSL Labs APIs.
+   http-observatory - Mozilla HTTP Observatory cli version.
+   Hurl - is a command line tool to run and test HTTP requests with plain text.
+

+ +##### :black_small_square: SSL + +

+   openssl - is a robust, commercial-grade, and full-featured toolkit for the TLS and SSL protocols.
+   gnutls-cli - client program to set up a TLS connection to some other computer.
+   sslyze + - fast and powerful SSL/TLS server scanning library.
+   sslscan - tests SSL/TLS enabled services to discover supported cipher suites.
+   testssl.sh - testing TLS/SSL encryption anywhere on any port.
+   cipherscan - a very simple way to find out which SSL ciphersuites are supported by a target.
+   spiped - is a utility for creating symmetrically encrypted and authenticated pipes between socket addresses.
+   Certbot - is EFF's tool to obtain certs from Let's Encrypt and (optionally) auto-enable HTTPS on your server.
+   mkcert - simple zero-config tool to make locally trusted development certificates with any names you'd like.
+   certstrap - tools to bootstrap CAs, certificate requests, and signed certificates.
+   Sublert - is a security and reconnaissance tool to automatically monitor new subdomains.
+   mkchain - open source tool to help you build a valid SSL certificate chain.
+   ssl-cert-check - SSL Certification Expiration Checker.
+

+ +##### :black_small_square: Security + +

+   SELinux - provides a flexible Mandatory Access Control (MAC) system built into the Linux kernel.
+   AppArmor - proactively protects the operating system and applications from external or internal threats.
+   grapheneX - Automated System Hardening Framework.
+   DevSec Hardening Framework - Security + DevOps: Automatic Server Hardening.
+

+ +##### :black_small_square: Auditing Tools + +

+   ossec - actively monitoring all aspects of system activity with file integrity monitoring.
+   auditd - provides a way to track security-relevant information on your system.
+   Tiger - is a security tool that can be use both as a security audit and intrusion detection system.
+   Lynis - battle-tested security tool for systems running Linux, macOS, or Unix-based operating system.
+   LinEnum - scripted Local Linux Enumeration & Privilege Escalation Checks.
+   Rkhunter - scanner tool for Linux systems that scans backdoors, rootkits and local exploits on your systems.
+   PE-sieve - is a light-weight tool that helps to detect malware running on the system.
+   PEASS - privilege escalation tools for Windows and Linux/Unix and MacOS.
+

+ +##### :black_small_square: System Diagnostics/Debuggers + +

+   strace - diagnostic, debugging and instructional userspace utility for Linux.
+   DTrace - is a performance analysis and troubleshooting tool.
+   ltrace - is a library call tracer, used to trace calls made by programs to library functions.
+   ptrace-burrito - is a friendly wrapper around ptrace.
+   perf-tools - performance analysis tools based on Linux perf_events (aka perf) and ftrace.
+   bpftrace - high-level tracing language for Linux eBPF.
+   sysdig - system exploration and troubleshooting tool with first class support for containers.
+   Valgrind - is an instrumentation framework for building dynamic analysis tools.
+   gperftools - high-performance multi-threaded malloc() implementation, plus some performance analysis tools.
+   glances - cross-platform system monitoring tool written in Python.
+   htop - interactive text-mode process viewer for Unix systems. It aims to be a better 'top'.
+   bashtop - Linux resource monitor written in pure Bash.
+   nmon - a single executable for performance monitoring and data analysis.
+   atop - ASCII performance monitor. Includes statistics for CPU, memory, disk, swap, network, and processes.
+   lsof - displays in its output information about files that are opened by processes.
+   FlameGraph - stack trace visualizer.
+   lsofgraph - convert Unix lsof output to a graph showing FIFO and UNIX interprocess communication.
+   rr - is a lightweight tool for recording, replaying and debugging execution of applications.
+   Performance Co-Pilot - a system performance analysis toolkit.
+   hexyl - a command-line hex viewer.
+   Austin - Python frame stack sampler for CPython.
+

+ +##### :black_small_square: Log Analyzers + +

+   angle-grinder - slice and dice log files on the command line.
+   lnav - log file navigator with search and automatic refresh.
+   GoAccess - real-time web log analyzer and interactive viewer that runs in a terminal.
+   ngxtop - real-time metrics for nginx server.
+

+ +##### :black_small_square: Databases + +

+   usql - universal command-line interface for SQL databases.
+   pgcli - postgres CLI with autocompletion and syntax highlighting.
+   mycli - terminal client for MySQL with autocompletion and syntax highlighting.
+   litecli - SQLite CLI with autocompletion and syntax highlighting.
+    mssql-cli - SQL Server CLI with autocompletion and syntax highlighting.
+   OSQuery - is a SQL powered operating system instrumentation, monitoring, and analytics framework.
+   pgsync - sync data from one Postgres database to another.
+   iredis - a terminal client for redis with autocompletion and syntax highlighting.
+   SchemaCrawler - generates an E-R diagram of your database.
+

+ +##### :black_small_square: TOR + +

+   Nipe - script to make Tor Network your default gateway.
+   multitor - a tool that lets you create multiple TOR instances with a load-balancing.
+

+ +##### :black_small_square: Messengers/IRC Clients + +

+   Irssi - is a free open source terminal based IRC client.
+   WeeChat - is an extremely extensible and lightweight IRC client.
+

+ +##### :black_small_square: Productivity + +

+   taskwarrior - task management system, todo list
+

+ +##### :black_small_square: Other + +

+   sysadmin-util - tools for Linux/Unix sysadmins.
+   incron - is an inode-based filesystem notification technology.
+   lsyncd - synchronizes local directories with remote targets (Live Syncing Daemon).
+   GRV - is a terminal based interface for viewing Git repositories.
+   Tig - text-mode interface for Git.
+   tldr - simplified and community-driven man pages.
+   archiver - easily create and extract .zip, .tar, .tar.gz, .tar.bz2, .tar.xz, .tar.lz4, .tar.sz, and .rar.
+   commander.js - minimal CLI creator in JavaScript.
+   gron - make JSON greppable!
+   bed - binary editor written in Go.
+

+ +#### GUI Tools  [[TOC]](#anger-table-of-contents) diff --git a/.agents/skills/sysadmin-toolbox/references/security-tools.md b/.agents/skills/sysadmin-toolbox/references/security-tools.md new file mode 100644 index 0000000..f2bc0be --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/references/security-tools.md @@ -0,0 +1,251 @@ +#### Hacking/Penetration Testing  [[TOC]](#anger-table-of-contents) + +##### :black_small_square: Pentesters arsenal tools + +

+   Sandcat Browser - a penetration-oriented browser with plenty of advanced functionality already built in.
+   Metasploit - tool and framework for pentesting system, web and many more.
+   Burp Suite - tool for testing web app security, intercepting proxy to replay, inject, scan and fuzz.
+   OWASP Zed Attack Proxy - intercepting proxy to replay, inject, scan and fuzz HTTP requests.
+   w3af - is a Web Application Attack and Audit Framework.
+   mitmproxy - an interactive TLS-capable intercepting HTTP proxy for penetration testers.
+   Nikto2 - web server scanner which performs comprehensive tests against web servers for multiple items.
+   sqlmap - tool that automates the process of detecting and exploiting SQL injection flaws.
+   Recon-ng - is a full-featured Web Reconnaissance framework written in Python.
+   AutoRecon - is a network reconnaissance tool which performs automated enumeration of services.
+   Faraday - an Integrated Multiuser Pentest Environment.
+   Photon - incredibly fast crawler designed for OSINT.
+   XSStrike - most advanced XSS detection suite.
+   Sn1per - automated pentest framework for offensive security experts.
+   vuls - is an agent-less vulnerability scanner for Linux, FreeBSD, and other.
+   tsunami - is a general purpose network security scanner with an extensible plugin system.
+   aquatone - a tool for domain flyovers.
+   BillCipher - information gathering tool for a website or IP address.
+   WhatWaf - detect and bypass web application firewalls and protection systems.
+   Corsy - CORS misconfiguration scanner.
+   Raccoon - is a high performance offensive security tool for reconnaissance and vulnerability scanning.
+   dirhunt - find web directories without bruteforce.
+   John The Ripper - is a fast password cracker, currently available for many flavors of Unix, Windows, and other.
+   hashcat - world's fastest and most advanced password recovery utility.
+   p0f - is a tool to identify the players behind any incidental TCP/IP communications.
+   ssh_scan - a prototype SSH configuration and policy scanner.
+   LeakLooker - find open databases - powered by Binaryedge.io
+   exploitdb - searchable archive from The Exploit Database.
+   getsploit - is a command line utility for searching and downloading exploits.
+   ctf-tools - some setup scripts for security research tools.
+   pwntools - CTF framework and exploit development library.
+   security-tools - collection of small security tools created mostly in Python. CTFs, pentests and so on.
+   pentestpackage - is a package of Pentest scripts.
+   python-pentest-tools - python tools for penetration testers.
+   fuzzdb - dictionary of attack patterns and primitives for black-box application fault injection.
+   AFL - is a free software fuzzer maintained by Google.
+   AFL++ - is AFL with community patches.
+   syzkaller - is an unsupervised, coverage-guided kernel fuzzer.
+   pwndbg - exploit development and reverse engineering with GDB made easy.
+   GDB PEDA - Python Exploit Development Assistance for GDB.
+   IDA - multi-processor disassembler and debugger useful for reverse engineering malware.
+   radare2 - framework for reverse-engineering and analyzing binaries.
+   routersploit - exploitation framework for embedded devices.
+   Ghidra - is a software reverse engineering (SRE) framework.
+   Cutter - is an SRE platform integrating Ghidra's decompiler.
+   Vulnreport - open-source pentesting management and automation platform by Salesforce Product Security.
+   Mentalist - is a graphical tool for custom wordlist generation.
+   archerysec - vulnerability assessment and management helps to perform scans and manage vulnerabilities.
+   Osmedeus - fully automated offensive security tool for reconnaissance and vulnerability scanning.
+   beef - the browser exploitation framework project.
+   AutoSploit - automated mass exploiter.
+   SUDO_KILLER - is a tool to identify and exploit sudo rules' misconfigurations and vulnerabilities.
+   yara - the pattern matching swiss knife.
+   mimikatz - a little tool to play with Windows security.
+   sherlock - hunt down social media accounts by username across social networks.
+   OWASP Threat Dragon - is a tool used to create threat model diagrams and to record possible threats.
+

+ +##### :black_small_square: Pentests bookmarks collection + +

+   PTES - the penetration testing execution standard.
+   Pentests MindMap - amazing mind map with vulnerable apps and systems.
+   WebApps Security Tests MindMap - incredible mind map for WebApps security tests.
+   Brute XSS - master the art of Cross Site Scripting.
+   XSS cheat sheet - contains many vectors that can help you bypass WAFs and filters.
+   Offensive Security Bookmarks - security bookmarks collection, all things that author need to pass OSCP.
+   Awesome Pentest Cheat Sheets - collection of the cheat sheets useful for pentesting.
+   Awesome Hacking by HackWithGithub - awesome lists for hackers, pentesters and security researchers.
+   Awesome Hacking by carpedm20 - a curated list of awesome hacking tutorials, tools and resources.
+   Awesome Hacking Resources - collection of hacking/penetration testing resources to make you better.
+   Awesome Pentest - collection of awesome penetration testing resources, tools and other shiny things.
+   Awesome-Hacking-Tools - is a curated list of awesome Hacking Tools.
+   Hacking Cheat Sheet - author hacking and pentesting notes.
+   blackhat-arsenal-tools - official Black Hat arsenal security tools repository.
+   Penetration Testing and WebApp Cheat Sheets - the complete list of Infosec related cheat sheets.
+   Cyber Security Resources - includes thousands of cybersecurity-related references and resources.
+   Pentest Bookmarks - there are a LOT of pentesting blogs.
+   Cheatsheet-God - Penetration Testing Reference Bank - OSCP/PTP & PTX Cheatsheet.
+   ThreatHunter-Playbook - to aid the development of techniques and hypothesis for hunting campaigns.
+   Beginner-Network-Pentesting - notes for beginner network pentesting course.
+   OSCPRepo - is a list of resources that author have been gathering in preparation for the OSCP.
+   PayloadsAllTheThings - a list of useful payloads and bypass for Web Application Security and Pentest/CTF.
+   payloads - git all the Payloads! A collection of web attack payloads.
+   command-injection-payload-list - command injection payload list.
+   Awesome Shodan Search Queries - great search queries to plug into Shodan.
+   AwesomeXSS - is a collection of Awesome XSS resources.
+   php-webshells - common php webshells.
+   Pentesting Tools Cheat Sheet - a quick reference high level overview for typical penetration testing.
+   OWASP Cheat Sheet Series - is a collection of high value information on specific application security topics.
+   OWASP dependency-check - is an open source solution the OWASP Top 10 2013 entry.
+   OWASP ProActive Controls - OWASP Top 10 Proactive Controls 2018.
+   PENTESTING-BIBLE - hacking & penetration testing & red team & cyber security resources.
+   pentest-wiki - is a free online security knowledge library for pentesters/researchers.
+   DEF CON Media Server - great stuff from DEFCON.
+   Awesome Malware Analysis - a curated list of awesome malware analysis tools and resources.
+   SQL Injection Cheat Sheet - detailed technical stuff about the many different variants of the SQL Injection.
+   Entersoft Knowledge Base - great and detailed reference about vulnerabilities.
+   HTML5 Security Cheatsheet - a collection of HTML5 related XSS attack vectors.
+   XSS String Encoder - for generating XSS code to check your input validation filters against XSS.
+   GTFOBins - list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.
+   Guifre Ruiz Notes - collection of security, system, network and pentest cheatsheets.
+   SSRF Tips - a collection of SSRF Tips.
+   shell-storm repo CTF - great archive of CTFs.
+   ctf - CTF (Capture The Flag) writeups, code snippets, notes, scripts.
+   My-CTF-Web-Challenges - collection of CTF Web challenges.
+   MSTG - The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security testing.
+   Internal-Pentest-Playbook - notes on the most common things for an Internal Network Penetration Test.
+   KeyHacks - shows quick ways in which API keys leaked by a bug bounty program can be checked.
+   securitum/research - various Proof of Concepts of security research performed by Securitum.
+   public-pentesting-reports - is a list of public pentest reports released by several consulting security groups.
+   awesome-bug-bounty - is a comprehensive curated list of available Bug Bounty.
+   bug-bounty-reference - is a list of bug bounty write-ups.
+   Awesome-Bugbounty-Writeups - is a curated list of bugbounty writeups.
+   Bug bounty writeups - list of bug bounty writeups (2012-2020).
+   hackso.me - a great journey into security.
+

+ +##### :black_small_square: Backdoors/exploits + +

+   PHP-backdoors - a collection of PHP backdoors. For educational or testing purposes only.
+

+ +##### :black_small_square: Wordlists and Weak passwords + +

+   Weakpass - for any kind of bruteforce find wordlists or unleash the power of them all at once!
+   Hashes.org - is a free online hash resolving service incorporating many unparalleled techniques.
+   SecLists - collection of multiple types of lists used during security assessments, collected in one place.
+   Probable-Wordlists - sorted by probability originally created for password generation and testing.
+   skullsecurity passwords - password dictionaries and leaked passwords repository.
+   Polish PREMIUM Dictionary - official dictionary created by the team on the forum bezpieka.org.* 1
+  
statistically-likely-usernames - wordlists for creating statistically likely username lists.
+

+ +##### :black_small_square: Bounty platforms + +

+   YesWeHack - bug bounty platform with infosec jobs.
+   Openbugbounty - allows any security researcher reporting a vulnerability on any website.
+   hackerone - global hacker community to surface the most relevant security issues.
+   bugcrowd - crowdsourced cybersecurity for the enterprise.
+   Crowdshield - crowdsourced security & bug bounty management.
+   Synack - crowdsourced security & bug bounty programs, crowd security intelligence platform, and more.
+   Hacktrophy - bug bounty platform.
+

+ +##### :black_small_square: Web Training Apps (local installation) + +

+   OWASP-VWAD - comprehensive and well maintained registry of all known vulnerable web applications.
+   DVWA - PHP/MySQL web application that is damn vulnerable.
+   metasploitable2 - vulnerable web application amongst security researchers.
+   metasploitable3 - is a VM that is built from the ground up with a large amount of security vulnerabilities.
+   DSVW - is a deliberately vulnerable web application written in under 100 lines of code.
+   OWASP Mutillidae II - free, open source, deliberately vulnerable web-application.
+   OWASP Juice Shop Project - the most bug-free vulnerable application in existence.
+   OWASP Node js Goat Project - OWASP Top 10 security risks apply to web apps developed using Node.js.
+   juicy-ctf - run Capture the Flags and Security Trainings with OWASP Juice Shop.
+   SecurityShepherd - web and mobile application security training platform.
+   Security Ninjas - open source application security training program.
+   hackazon - a modern vulnerable web app.
+   dvna - damn vulnerable NodeJS application.
+   django-DefectDojo - is an open-source application vulnerability correlation and security orchestration tool.
+   Google Gruyere - web application exploits and defenses.
+   Bodhi - is a playground focused on learning the exploitation of client-side web vulnerabilities.
+   Websploit - single vm lab with the purpose of combining several vulnerable appliations in one environment.
+   vulhub - pre-built Vulnerable Environments based on docker-compose.
+   CloudGoat 2 - the new & improved "Vulnerable by Design" +AWS deployment tool.
+   secDevLabs - is a laboratory for learning secure web development in a practical manner.
+   CORS-vulnerable-Lab - sample vulnerable code and its exploit code.
+   RootTheBox - a Game of Hackers (CTF Scoreboard & Game Manager).
+   KONTRA - application security training (OWASP Top Web & Api).
+

+ +##### :black_small_square: Labs (ethical hacking platforms/trainings/CTFs) + +

+   Offensive Security - true performance-based penetration testing training for over a decade.
+   Hack The Box - online platform allowing you to test your penetration testing skills.
+   Hacking-Lab - online ethical hacking, computer network and security challenge platform.
+   pwnable.kr - non-commercial wargame site which provides various pwn challenges.
+   Pwnable.tw - is a wargame site for hackers to test and expand their binary exploiting skills.
+   picoCTF - is a free computer security game targeted at middle and high school students.
+   CTFlearn - is an online platform built to help ethical hackers learn and practice their cybersecurity knowledge.
+   ctftime - CTF archive and a place, where you can get some another CTF-related info.
+   Silesia Security Lab - high quality security testing services.
+   Practical Pentest Labs - pentest lab, take your Hacking skills to the next level.
+   Root Me - the fast, easy, and affordable way to train your hacking skills.
+   rozwal.to - a great platform to train your pentesting skills.
+   TryHackMe - learning Cyber Security made easy.
+   hackxor - is a realistic web application hacking game, designed to help players of all abilities develop their skills.
+   Hack Yourself First - it's full of nasty app sec holes.
+   OverTheWire - can help you to learn and practice security concepts in the form of fun-filled games.
+   Wizard Labs - is an online Penetration Testing Lab.
+   PentesterLab - provides vulnerable systems that can be used to test and understand vulnerabilities.
+   RingZer0 - tons of challenges designed to test and improve your hacking skills.
+   try2hack - several security-oriented challenges for your entertainment.
+   Ubeeri - preconfigured lab environments.
+   Pentestit - emulate IT infrastructures of real companies for legal pen testing and improving pentest skills.
+   Microcorruption - reversal challenges done in the web interface.
+   Crackmes - download crackmes to help improve your reverse engineering skills.
+   DomGoat - DOM XSS security learning and practicing platform.
+   Stereotyped Challenges - upgrade your web hacking techniques today!
+   Vulnhub - allows anyone to gain practical 'hands-on' experience in digital security.
+   W3Challs - is a penetration testing training platform, which offers various computer challenges.
+   RingZer0 CTF - offers you tons of challenges designed to test and improve your hacking skills.
+   Hack.me - a platform where you can build, host and share vulnerable web apps for educational purposes.
+   HackThis! - discover how hacks, dumps and defacements are performed and secure your website.
+   Enigma Group WebApp Training - these challenges cover the exploits listed in the OWASP Top 10 Project.
+   Reverse Engineering Challenges - challenges, exercises, problems and tasks - by level, by type, and more.
+   0x00sec - the home of the Hacker - Malware, Reverse Engineering, and Computer Science.
+   We Chall - there are exist a lots of different challenge types.
+   Hacker Gateway - is the go-to place for hackers who want to test their skills.
+   Hacker101 - is a free class for web security.
+   contained.af - a stupid game for learning about containers, capabilities, and syscalls.
+   flAWS challenge! - a series of levels you'll learn about common mistakes and gotchas when using AWS.
+   CyberSec WTF - provides web hacking challenges derived from bounty write-ups.
+   CTF Challenge - CTF Web App challenges.
+   gCTF - most of the challenges used in the Google CTF 2017.
+   Hack This Site - is a free, safe and legal training ground for hackers.
+   Attack & Defense - is a browser-based cloud labs.
+   Cryptohack - a fun platform for learning modern cryptography.
+   Cryptopals - the cryptopals crypto challenges.
+

+ +##### :black_small_square: CTF platforms + +

+   fbctf - platform to host Capture the Flag competitions.
+   ctfscoreboard - scoreboard for Capture The Flag competitions.
+

+ +##### :black_small_square: Other resources + +

+   Bugcrowd University - open source education content for the researcher community.
+   OSCPRepo - a list of resources and scripts that I have been gathering in preparation for the OSCP.
+   OWASP Top 10: Real-World Examples - test your web apps with real-world examples (two-part series).
+   phrack.org - an awesome collection of articles from several respected hackers and other thinkers.
+   Practical-Ethical-Hacking-Resources - compilation of resources from TCM's Udemy Course.
+

+ +#### Your daily knowledge and news  [[TOC]](#anger-table-of-contents) diff --git a/.agents/skills/sysadmin-toolbox/references/shell-oneliners.md b/.agents/skills/sysadmin-toolbox/references/shell-oneliners.md new file mode 100644 index 0000000..8f3cde2 --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/references/shell-oneliners.md @@ -0,0 +1,2686 @@ +#### Shell One-liners  [[TOC]](#anger-table-of-contents) + +##### Table of Contents + + * [terminal](#tool-terminal) + * [busybox](#tool-busybox) + * [mount](#tool-mount) + * [fuser](#tool-fuser) + * [lsof](#tool-lsof) + * [ps](#tool-ps) + * [top](#tool-top) + * [vmstat](#tool-vmstat) + * [iostat](#tool-iostat) + * [strace](#tool-strace) + * [kill](#tool-kill) + * [find](#tool-find) + * [diff](#tool-diff) + * [vimdiff](#tool-vimdiff) + * [tail](#tool-tail) + * [cpulimit](#tool-cpulimit) + * [pwdx](#tool-pwdx) + * [tr](#tool-tr) + * [chmod](#tool-chmod) + * [who](#tool-who) + * [last](#tool-last) + * [screen](#tool-screen) + * [script](#tool-script) + * [du](#tool-du) + * [inotifywait](#tool-inotifywait) + * [openssl](#tool-openssl) + * [secure-delete](#tool-secure-delete) + * [dd](#tool-dd) + * [gpg](#tool-gpg) + * [system-other](#tool-system-other) + * [curl](#tool-curl) + * [httpie](#tool-httpie) + * [ssh](#tool-ssh) + * [linux-dev](#tool-linux-dev) + * [tcpdump](#tool-tcpdump) + * [tcpick](#tool-tcpick) + * [ngrep](#tool-ngrep) + * [hping3](#tool-hping3) + * [nmap](#tool-nmap) + * [netcat](#tool-netcat) + * [socat](#tool-socat) + * [p0f](#tool-p0f) + * [gnutls-cli](#tool-gnutls-cli) + * [netstat](#tool-netstat) + * [rsync](#tool-rsync) + * [host](#tool-host) + * [dig](#tool-dig) + * [certbot](#tool-certbot) + * [network-other](#tool-network-other) + * [git](#tool-git) + * [awk](#tool-awk) + * [sed](#tool-sed) + * [grep](#tool-grep) + * [perl](#tool-perl) + +##### Tool: [terminal](https://en.wikipedia.org/wiki/Linux_console) + +###### Reload shell without exit + +```bash +exec $SHELL -l +``` + +###### Close shell keeping all subprocess running + +```bash +disown -a && exit +``` + +###### Exit without saving shell history + +```bash +kill -9 $$ +unset HISTFILE && exit +``` + +###### Perform a branching conditional + +```bash +true && echo success +false || echo failed +``` + +###### Pipe stdout and stderr to separate commands + +```bash +some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr) +``` + +###### Redirect stdout and stderr each to separate files and print both to the screen + +```bash +(some_command 2>&1 1>&3 | tee errorlog ) 3>&1 1>&2 | tee stdoutlog +``` + +###### List of commands you use most often + +```bash +history | \ +awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | \ +grep -v "./" | \ +column -c3 -s " " -t | \ +sort -nr | nl | head -n 20 +``` + +###### Sterilize bash history + +```bash +function sterile() { + + history | awk '$2 != "history" { $1=""; print $0 }' | egrep -vi "\ +curl\b+.*(-E|--cert)\b+.*\b*|\ +curl\b+.*--pass\b+.*\b*|\ +curl\b+.*(-U|--proxy-user).*:.*\b*|\ +curl\b+.*(-u|--user).*:.*\b* +.*(-H|--header).*(token|auth.*)\b+.*|\ +wget\b+.*--.*password\b+.*\b*|\ +http.?://.+:.+@.*\ +" > $HOME/histbuff; history -r $HOME/histbuff; + +} + +export PROMPT_COMMAND="sterile" +``` + + > Look also: [A naive utility to censor credentials in command history](https://github.com/lbonanomi/go/blob/master/revisionist.go). + +###### Quickly backup a file + +```bash +cp filename{,.orig} +``` + +###### Empty a file (truncate to 0 size) + +```bash +>filename +``` + +###### Delete all files in a folder that don't match a certain file extension + +```bash +rm !(*.foo|*.bar|*.baz) +``` + +###### Pass multi-line string to a file + +```bash +# cat >filename ... - overwrite the file +# cat >>filename ... - append to a file +cat > filename << __EOF__ +data data data +__EOF__ +``` + +###### Edit a file on a remote host using vim + +```bash +vim scp://user@host//etc/fstab +``` + +###### Create a directory and change into it at the same time + +```bash +mkd() { mkdir -p "$@" && cd "$@"; } +``` + +###### Convert uppercase files to lowercase files + +```bash +rename 'y/A-Z/a-z/' * +``` + +###### Print a row of characters across the terminal + +```bash +printf "%`tput cols`s" | tr ' ' '#' +``` + +###### Show shell history without line numbers + +```bash +history | cut -c 8- +fc -l -n 1 | sed 's/^\s*//' +``` + +###### Run command(s) after exit session + +```bash +cat > /etc/profile << __EOF__ +_after_logout() { + + username=$(whoami) + + for _pid in $(ps afx | grep sshd | grep "$username" | awk '{print $1}') ; do + + kill -9 $_pid + + done + +} +trap _after_logout EXIT +__EOF__ +``` + +###### Generate a sequence of numbers + +```bash +for ((i=1; i<=10; i+=2)) ; do echo $i ; done +# alternative: seq 1 2 10 + +for ((i=5; i<=10; ++i)) ; do printf '%02d\n' $i ; done +# alternative: seq -w 5 10 + +for i in {1..10} ; do echo $i ; done +``` + +###### Simple Bash filewatching + +```bash +unset MAIL; export MAILCHECK=1; export MAILPATH='$FILE_TO_WATCH?$MESSAGE' +``` + +--- + +##### Tool: [busybox](https://www.busybox.net/) + +###### Static HTTP web server + +```bash +busybox httpd -p $PORT -h $HOME [-c httpd.conf] +``` + +___ + +##### Tool: [mount](https://en.wikipedia.org/wiki/Mount_(Unix)) + +###### Mount a temporary ram partition + +```bash +mount -t tmpfs tmpfs /mnt -o size=64M +``` + + * `-t` - filesystem type + * `-o` - mount options + +###### Remount a filesystem as read/write + +```bash +mount -o remount,rw / +``` + +___ + +##### Tool: [fuser](https://en.wikipedia.org/wiki/Fuser_(Unix)) + +###### Show which processes use the files/directories + +```bash +fuser /var/log/daemon.log +fuser -v /home/supervisor +``` + +###### Kills a process that is locking a file + +```bash +fuser -ki filename +``` + + * `-i` - interactive option + +###### Kills a process that is locking a file with specific signal + +```bash +fuser -k -HUP filename +``` + + * `--list-signals` - list available signal names + +###### Show what PID is listening on specific port + +```bash +fuser -v 53/udp +``` + +###### Show all processes using the named filesystems or block device + +```bash +fuser -mv /var/www +``` + +___ + +##### Tool: [lsof](https://en.wikipedia.org/wiki/Lsof) + +###### Show process that use internet connection at the moment + +```bash +lsof -P -i -n +``` + +###### Show process that use specific port number + +```bash +lsof -i tcp:443 +``` + +###### Lists all listening ports together with the PID of the associated process + +```bash +lsof -Pan -i tcp -i udp +``` + +###### List all open ports and their owning executables + +```bash +lsof -i -P | grep -i "listen" +``` + +###### Show all open ports + +```bash +lsof -Pnl -i +``` + +###### Show open ports (LISTEN) + +```bash +lsof -Pni4 | grep LISTEN | column -t +``` + +###### List all files opened by a particular command + +```bash +lsof -c "process" +``` + +###### View user activity per directory + +```bash +lsof -u username -a +D /etc +``` + +###### Show 10 largest open files + +```bash +lsof / | \ +awk '{ if($7 > 1048576) print $7/1048576 "MB" " " $9 " " $1 }' | \ +sort -n -u | tail | column -t +``` + +###### Show current working directory of a process + +```bash +lsof -p | grep cwd +``` + +___ + +##### Tool: [ps](https://en.wikipedia.org/wiki/Ps_(Unix)) + +###### Show a 4-way scrollable process tree with full details + +```bash +ps awwfux | less -S +``` + +###### Processes per user counter + +```bash +ps hax -o user | sort | uniq -c | sort -r +``` + +###### Show all processes by name with main header + +```bash +ps -lfC nginx +``` + +___ + +##### Tool: [find](https://en.wikipedia.org/wiki/Find_(Unix)) + +###### Find files that have been modified on your system in the past 60 minutes + +```bash +find / -mmin 60 -type f +``` + +###### Find all files larger than 20M + +```bash +find / -type f -size +20M +``` + +###### Find duplicate files (based on MD5 hash) + +```bash +find -type f -exec md5sum '{}' ';' | sort | uniq --all-repeated=separate -w 33 +``` + +###### Change permission only for files + +```bash +cd /var/www/site && find . -type f -exec chmod 766 {} \; +cd /var/www/site && find . -type f -exec chmod 664 {} + +``` + +###### Change permission only for directories + +```bash +cd /var/www/site && find . -type d -exec chmod g+x {} \; +cd /var/www/site && find . -type d -exec chmod g+rwx {} + +``` + +###### Find files and directories for specific user/group + +```bash +# User: +find . -user -print +find /etc -type f -user -name "*.conf" + +# Group: +find /opt -group +find /etc -type f -group -iname "*.conf" +``` + +###### Find files and directories for all without specific user/group + +```bash +# User: +find . \! -user -print + +# Group: +find . \! -group +``` + +###### Looking for files/directories that only have certain permission + +```bash +# User +find . -user -perm -u+rw # -rw-r--r-- +find /home -user $(whoami) -perm 777 # -rwxrwxrwx + +# Group: +find /home -type d -group -perm 755 # -rwxr-xr-x +``` + +###### Delete older files than 60 days + +```bash +find . -type f -mtime +60 -delete +``` + +###### Recursively remove all empty sub-directories from a directory + +```bash +find . -depth -type d -empty -exec rmdir {} \; +``` + +###### How to find all hard links to a file + +```bash +find -xdev -samefile filename +``` + +###### Recursively find the latest modified files + +```bash +find . -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head +``` + +###### Recursively find/replace of a string with sed + +```bash +find . -not -path '*/\.git*' -type f -print0 | xargs -0 sed -i 's/foo/bar/g' +``` + +###### Recursively find/replace of a string in directories and file names + +```bash +find . -depth -name '*test*' -execdir bash -c 'mv -v "$1" "${1//foo/bar}"' _ {} \; +``` + +###### Recursively find suid executables + +```bash +find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; +``` + +___ + +##### Tool: [top](https://en.wikipedia.org/wiki/Top_(software)) + +###### Use top to monitor only all processes with the specific string + +```bash +top -p $(pgrep -d , ) +``` + + * `` - process containing string (eg. nginx, worker) + +___ + +##### Tool: [vmstat](https://en.wikipedia.org/wiki/Vmstat) + +###### Show current system utilization (fields in kilobytes) + +```bash +vmstat 2 20 -t -w +``` + + * `2` - number of times with a defined time interval (delay) + * `20` - each execution of the command (count) + * `-t` - show timestamp + * `-w` - wide output + * `-S M` - output of the fields in megabytes instead of kilobytes + +###### Show current system utilization will get refreshed every 5 seconds + +```bash +vmstat 5 -w +``` + +###### Display report a summary of disk operations + +```bash +vmstat -D +``` + +###### Display report of event counters and memory stats + +```bash +vmstat -s +``` + +###### Display report about kernel objects stored in slab layer cache + +```bash +vmstat -m +``` + +##### Tool: [iostat](https://en.wikipedia.org/wiki/Iostat) + +###### Show information about the CPU usage, and I/O statistics about all the partitions + +```bash +iostat 2 10 -t -m +``` + + * `2` - number of times with a defined time interval (delay) + * `10` - each execution of the command (count) + * `-t` - show timestamp + * `-m` - fields in megabytes (`-k` - in kilobytes, default) + +###### Show information only about the CPU utilization + +```bash +iostat 2 10 -t -m -c +``` + +###### Show information only about the disk utilization + +```bash +iostat 2 10 -t -m -d +``` + +###### Show information only about the LVM utilization + +```bash +iostat -N +``` + +___ + +##### Tool: [strace](https://en.wikipedia.org/wiki/Strace) + +###### Track with child processes + +```bash +# 1) +strace -f -p $(pidof glusterfsd) + +# 2) +strace -f $(pidof php-fpm | sed 's/\([0-9]*\)/\-p \1/g') +``` + +###### Track process with 30 seconds limit + +```bash +timeout 30 strace $(< /var/run/zabbix/zabbix_agentd.pid) +``` + +###### Track processes and redirect output to a file + +```bash +ps auxw | grep '[a]pache' | awk '{print " -p " $2}' | \ +xargs strace -o /tmp/strace-apache-proc.out +``` + +###### Track with print time spent in each syscall and limit length of print strings + +```bash +ps auxw | grep '[i]init_policy' | awk '{print " -p " $2}' | \ +xargs strace -f -e trace=network -T -s 10000 +``` + +###### Track the open request of a network port + +```bash +strace -f -e trace=bind nc -l 80 +``` + +###### Track the open request of a network port (show TCP/UDP) + +```bash +strace -f -e trace=network nc -lu 80 +``` + +___ + +##### Tool: [kill](https://en.wikipedia.org/wiki/Kill_(command)) + +###### Kill a process running on port + +```bash +kill -9 $(lsof -i : | awk '{l=$2} END {print l}') +``` + +___ + +##### Tool: [diff](https://en.wikipedia.org/wiki/Diff) + +###### Compare two directory trees + +```bash +diff <(cd directory1 && find | sort) <(cd directory2 && find | sort) +``` + +###### Compare output of two commands + +```bash +diff <(cat /etc/passwd) <(cut -f2 /etc/passwd) +``` + +___ + +##### Tool: [vimdiff](http://vimdoc.sourceforge.net/htmldoc/diff.html) + +###### Highlight the exact differences, based on characters and words + +```bash +vimdiff file1 file2 +``` + +###### Compare two JSON files + +```bash +vimdiff <(jq -S . A.json) <(jq -S . B.json) +``` + +###### Compare Hex dump + +```bash +d(){ vimdiff <(f $1) <(f $2);};f(){ hexdump -C $1 | cut -d' ' -f3- | tr -s ' ';}; d ~/bin1 ~/bin2 +``` + +###### diffchar + +Save [diffchar](https://raw.githubusercontent.com/vim-scripts/diffchar.vim/master/plugin/diffchar.vim) @ `~/.vim/plugins` + +Click `F7` to switch between diff modes + +Usefull `vimdiff` commands: + +* `qa` to exit all windows +* `:vertical resize 70` to resize window +* set window width `Ctrl+W [N columns]+(Shift+)<\>` + +___ + +##### Tool: [tail](https://en.wikipedia.org/wiki/Tail_(Unix)) + +###### Annotate tail -f with timestamps + +```bash +tail -f file | while read ; do echo "$(date +%T.%N) $REPLY" ; done +``` + +###### Analyse an Apache access log for the most common IP addresses + +```bash +tail -10000 access_log | awk '{print $1}' | sort | uniq -c | sort -n | tail +``` + +###### Analyse web server log and show only 5xx http codes + +```bash +tail -n 100 -f /path/to/logfile | grep "HTTP/[1-2].[0-1]\" [5]" +``` + +___ + +##### Tool: [tar](https://en.wikipedia.org/wiki/Tar_(computing)) + +###### System backup with exclude specific directories + +```bash +cd / +tar -czvpf /mnt/system$(date +%d%m%Y%s).tgz --directory=/ \ +--exclude=proc/* --exclude=sys/* --exclude=dev/* --exclude=mnt/* . +``` + +###### System backup with exclude specific directories (pigz) + +```bash +cd / +tar cvpf /backup/snapshot-$(date +%d%m%Y%s).tgz --directory=/ \ +--exclude=proc/* --exclude=sys/* --exclude=dev/* \ +--exclude=mnt/* --exclude=tmp/* --use-compress-program=pigz . +``` + +___ + +##### Tool: [dump](https://en.wikipedia.org/wiki/Dump_(program)) + +###### System backup to file + +```bash +dump -y -u -f /backup/system$(date +%d%m%Y%s).lzo / +``` + +###### Restore system from lzo file + +```bash +cd / +restore -rf /backup/system$(date +%d%m%Y%s).lzo +``` + +___ + +##### Tool: [cpulimit](http://cpulimit.sourceforge.net/) + +###### Limit the cpu usage of a process + +```bash +cpulimit -p pid -l 50 +``` + +___ + +##### Tool: [pwdx](https://www.cyberciti.biz/faq/unix-linux-pwdx-command-examples-usage-syntax/) + +###### Show current working directory of a process + +```bash +pwdx +``` + +___ + +##### Tool: [taskset](https://www.cyberciti.biz/faq/taskset-cpu-affinity-command/) + +###### Start a command on only one CPU core + +```bash +taskset -c 0 +``` + +___ + +##### Tool: [tr](https://en.wikipedia.org/wiki/Tr_(Unix)) + +###### Show directories in the PATH, one per line + +```bash +tr : '\n' <<<$PATH +``` + +___ + +##### Tool: [chmod](https://en.wikipedia.org/wiki/Chmod) + +###### Remove executable bit from all files in the current directory + +```bash +chmod -R -x+X * +``` + +###### Restore permission for /bin/chmod + +```bash +# 1: +cp /bin/ls chmod.01 +cp /bin/chmod chmod.01 +./chmod.01 700 file + +# 2: +/bin/busybox chmod 0700 /bin/chmod + +# 3: +setfacl --set u::rwx,g::---,o::--- /bin/chmod +``` + +___ + +##### Tool: [who](https://en.wikipedia.org/wiki/Who_(Unix)) + +###### Find last reboot time + +```bash +who -b +``` + +###### Detect a user sudo-su'd into the current shell + +```bash +[[ $(who -m | awk '{ print $1 }') == $(whoami) ]] || echo "You are su-ed to $(whoami)" +``` + +___ + +##### Tool: [last](https://www.howtoforge.com/linux-last-command/) + +###### Was the last reboot a panic? + +```bash +(last -x -f $(ls -1t /var/log/wtmp* | head -2 | tail -1); last -x -f /var/log/wtmp) | \ +grep -A1 reboot | head -2 | grep -q shutdown && echo "Expected reboot" || echo "Panic reboot" +``` + +___ + +##### Tool: [screen](https://en.wikipedia.org/wiki/GNU_Screen) + +###### Start screen in detached mode + +```bash +screen -d -m +``` + +###### Attach to an existing screen session + +```bash +screen -r -d +``` + +___ + +##### Tool: [script](https://en.wikipedia.org/wiki/Script_(Unix)) + +###### Record and replay terminal session + +```bash +### Record session +# 1) +script -t 2>~/session.time -a ~/session.log + +# 2) +script --timing=session.time session.log + +### Replay session +scriptreplay --timing=session.time session.log +``` + +___ + +##### Tool: [du](https://en.wikipedia.org/wiki/GNU_Screen) + +###### Show 20 biggest directories with 'K M G' + +```bash +du | \ +sort -r -n | \ +awk '{split("K M G",v); s=1; while($1>1024){$1/=1024; s++} print int($1)" "v[s]"\t"$2}' | \ +head -n 20 +``` + +___ + +##### Tool: [inotifywait](https://en.wikipedia.org/wiki/GNU_Screen) + +###### Init tool everytime a file in a directory is modified + +```bash +while true ; do inotifywait -r -e MODIFY dir/ && ls dir/ ; done; +``` + +___ + +##### Tool: [openssl](https://www.openssl.org/) + +###### Testing connection to the remote host + +```bash +echo | openssl s_client -connect google.com:443 -showcerts +``` + +###### Testing connection to the remote host (debug mode) + +```bash +echo | openssl s_client -connect google.com:443 -showcerts -tlsextdebug -status +``` + +###### Testing connection to the remote host (with SNI support) + +```bash +echo | openssl s_client -showcerts -servername google.com -connect google.com:443 +``` + +###### Testing connection to the remote host with specific ssl version + +```bash +openssl s_client -tls1_2 -connect google.com:443 +``` + +###### Testing connection to the remote host with specific ssl cipher + +```bash +openssl s_client -cipher 'AES128-SHA' -connect google.com:443 +``` + +###### Verify 0-RTT + +```bash +_host="example.com" + +cat > req.in << __EOF__ +HEAD / HTTP/1.1 +Host: $_host +Connection: close +__EOF__ + +openssl s_client -connect ${_host}:443 -tls1_3 -sess_out session.pem -ign_eof < req.in +openssl s_client -connect ${_host}:443 -tls1_3 -sess_in session.pem -early_data req.in +``` + +###### Generate private key without passphrase + +```bash +# _len: 2048, 4096 +( _fd="private.key" ; _len="2048" ; \ +openssl genrsa -out ${_fd} ${_len} ) +``` + +###### Generate private key with passphrase + +```bash +# _ciph: aes128, aes256 +# _len: 2048, 4096 +( _ciph="aes128" ; _fd="private.key" ; _len="2048" ; \ +openssl genrsa -${_ciph} -out ${_fd} ${_len} ) +``` + +###### Remove passphrase from private key + +```bash +( _fd="private.key" ; _fd_unp="private_unp.key" ; \ +openssl rsa -in ${_fd} -out ${_fd_unp} ) +``` + +###### Encrypt existing private key with a passphrase + +```bash +# _ciph: aes128, aes256 +( _ciph="aes128" ; _fd="private.key" ; _fd_pass="private_pass.key" ; \ +openssl rsa -${_ciph} -in ${_fd} -out ${_fd_pass} +``` + +###### Check private key + +```bash +( _fd="private.key" ; \ +openssl rsa -check -in ${_fd} ) +``` + +###### Get public key from private key + +```bash +( _fd="private.key" ; _fd_pub="public.key" ; \ +openssl rsa -pubout -in ${_fd} -out ${_fd_pub} ) +``` + +###### Generate private key and CSR + +```bash +( _fd="private.key" ; _fd_csr="request.csr" ; _len="2048" ; \ +openssl req -out ${_fd_csr} -new -newkey rsa:${_len} -nodes -keyout ${_fd} ) +``` + +###### Generate CSR + +```bash +( _fd="private.key" ; _fd_csr="request.csr" ; \ +openssl req -out ${_fd_csr} -new -key ${_fd} ) +``` + +###### Generate CSR (metadata from existing certificate) + + > Where `private.key` is the existing private key. As you can see you do not generate this CSR from your certificate (public key). Also you do not generate the "same" CSR, just a new one to request a new certificate. + +```bash +( _fd="private.key" ; _fd_csr="request.csr" ; _fd_crt="cert.crt" ; \ +openssl x509 -x509toreq -in ${_fd_crt} -out ${_fd_csr} -signkey ${_fd} ) +``` + +###### Generate CSR with -config param + +```bash +( _fd="private.key" ; _fd_csr="request.csr" ; \ +openssl req -new -sha256 -key ${_fd} -out ${_fd_csr} \ +-config <( +cat << __EOF__ +[req] +default_bits = 2048 +default_md = sha256 +prompt = no +distinguished_name = dn +req_extensions = req_ext + +[ dn ] +C = "" +ST = "" +L = "" +O = "" +OU = "
" +CN = "" + +[ req_ext ] +subjectAltName = @alt_names + +[ alt_names ] +DNS.1 = +DNS.2 = +DNS.3 = +__EOF__ +)) +``` + +Other values in `[ dn ]`: + +``` +countryName = "DE" # C= +stateOrProvinceName = "Hessen" # ST= +localityName = "Keller" # L= +postalCode = "424242" # L/postalcode= +postalAddress = "Keller" # L/postaladdress= +streetAddress = "Crater 1621" # L/street= +organizationName = "apfelboymschule" # O= +organizationalUnitName = "IT Department" # OU= +commonName = "example.com" # CN= +emailAddress = "webmaster@example.com" # CN/emailAddress= +``` + +Example of `oids` (you'll probably also have to make OpenSSL know about the new fields required for EV by adding the following under `[new_oids]`): + +``` +[req] +... +oid_section = new_oids + +[ new_oids ] +postalCode = 2.5.4.17 +streetAddress = 2.5.4.9 +``` + +Full example: + +```bash +( _fd="private.key" ; _fd_csr="request.csr" ; \ +openssl req -new -sha256 -key ${_fd} -out ${_fd_csr} \ +-config <( +cat << __EOF__ +[req] +default_bits = 2048 +default_md = sha256 +prompt = no +distinguished_name = dn +req_extensions = req_ext +oid_section = new_oids + +[ new_oids ] +serialNumber = 2.5.4.5 +streetAddress = 2.5.4.9 +postalCode = 2.5.4.17 +businessCategory = 2.5.4.15 + +[ dn ] +serialNumber=00001111 +businessCategory=Private Organization +jurisdictionC=DE +C=DE +ST=Hessen +L=Keller +postalCode=424242 +streetAddress=Crater 1621 +O=AV Company +OU=IT +CN=example.com + +[ req_ext ] +subjectAltName = @alt_names + +[ alt_names ] +DNS.1 = example.com +__EOF__ +)) +``` + +For more information please look at these great explanations: + +- [RFC 5280](https://tools.ietf.org/html/rfc5280) +- [How to create multidomain certificates using config files](https://apfelboymchen.net/gnu/notes/openssl%20multidomain%20with%20config%20files.html) +- [Generate a multi domains certificate using config files](https://gist.github.com/romainnorberg/464758a6620228b977212a3cf20c3e08) +- [Your OpenSSL CSR command is out of date](https://expeditedsecurity.com/blog/openssl-csr-command/) +- [OpenSSL example configuration file](https://www.tbs-certificats.com/openssl-dem-server-cert.cnf) +- [Object Identifiers (OIDs)](https://www.alvestrand.no/objectid/) +- [openssl objects.txt](https://github.com/openssl/openssl/blob/master/crypto/objects/objects.txt) + +###### List available EC curves + +```bash +openssl ecparam -list_curves +``` + +###### Print ECDSA private and public keys + +```bash +( _fd="private.key" ; \ +openssl ec -in ${_fd} -noout -text ) + +# For x25519 only extracting public key +( _fd="private.key" ; _fd_pub="public.key" ; \ +openssl pkey -in ${_fd} -pubout -out ${_fd_pub} ) +``` + +###### Generate ECDSA private key + +```bash +# _curve: prime256v1, secp521r1, secp384r1 +( _fd="private.key" ; _curve="prime256v1" ; \ +openssl ecparam -out ${_fd} -name ${_curve} -genkey ) + +# _curve: X25519 +( _fd="private.key" ; _curve="x25519" ; \ +openssl genpkey -algorithm ${_curve} -out ${_fd} ) +``` + +###### Generate private key and CSR (ECC) + +```bash +# _curve: prime256v1, secp521r1, secp384r1 +( _fd="domain.com.key" ; _fd_csr="domain.com.csr" ; _curve="prime256v1" ; \ +openssl ecparam -out ${_fd} -name ${_curve} -genkey ; \ +openssl req -new -key ${_fd} -out ${_fd_csr} -sha256 ) +``` + +###### Generate self-signed certificate + +```bash +# _len: 2048, 4096 +( _fd="domain.key" ; _fd_out="domain.crt" ; _len="2048" ; _days="365" ; \ +openssl req -newkey rsa:${_len} -nodes \ +-keyout ${_fd} -x509 -days ${_days} -out ${_fd_out} ) +``` + +###### Generate self-signed certificate from existing private key + +```bash +# _len: 2048, 4096 +( _fd="domain.key" ; _fd_out="domain.crt" ; _days="365" ; \ +openssl req -key ${_fd} -nodes \ +-x509 -days ${_days} -out ${_fd_out} ) +``` + +###### Generate self-signed certificate from existing private key and csr + +```bash +# _len: 2048, 4096 +( _fd="domain.key" ; _fd_csr="domain.csr" ; _fd_out="domain.crt" ; _days="365" ; \ +openssl x509 -signkey ${_fd} -nodes \ +-in ${_fd_csr} -req -days ${_days} -out ${_fd_out} ) +``` + +###### Generate DH public parameters + +```bash +( _dh_size="2048" ; \ +openssl dhparam -out /etc/nginx/ssl/dhparam_${_dh_size}.pem "$_dh_size" ) +``` + +###### Display DH public parameters + +```bash +openssl pkeyparam -in dhparam.pem -text +``` + +###### Extract private key from pfx + +```bash +( _fd_pfx="cert.pfx" ; _fd_key="key.pem" ; \ +openssl pkcs12 -in ${_fd_pfx} -nocerts -nodes -out ${_fd_key} ) +``` + +###### Extract private key and certs from pfx + +```bash +( _fd_pfx="cert.pfx" ; _fd_pem="key_certs.pem" ; \ +openssl pkcs12 -in ${_fd_pfx} -nodes -out ${_fd_pem} ) +``` + +###### Extract certs from p7b + +```bash +# PKCS#7 file doesn't include private keys. +( _fd_p7b="cert.p7b" ; _fd_pem="cert.pem" ; \ +openssl pkcs7 -inform DER -outform PEM -in ${_fd_p7b} -print_certs > ${_fd_pem}) +# or: +openssl pkcs7 -print_certs -in -in ${_fd_p7b} -out ${_fd_pem}) +``` + +###### Convert DER to PEM + +```bash +( _fd_der="cert.crt" ; _fd_pem="cert.pem" ; \ +openssl x509 -in ${_fd_der} -inform der -outform pem -out ${_fd_pem} ) +``` + +###### Convert PEM to DER + +```bash +( _fd_der="cert.crt" ; _fd_pem="cert.pem" ; \ +openssl x509 -in ${_fd_pem} -outform der -out ${_fd_der} ) +``` + +###### Verification of the private key + +```bash +( _fd="private.key" ; \ +openssl rsa -noout -text -in ${_fd} ) +``` + +###### Verification of the public key + +```bash +# 1) +( _fd="public.key" ; \ +openssl pkey -noout -text -pubin -in ${_fd} ) + +# 2) +( _fd="private.key" ; \ +openssl rsa -inform PEM -noout -in ${_fd} &> /dev/null ; \ +if [ $? = 0 ] ; then echo -en "OK\n" ; fi ) +``` + +###### Verification of the certificate + +```bash +( _fd="certificate.crt" ; # format: pem, cer, crt \ +openssl x509 -noout -text -in ${_fd} ) +``` + +###### Verification of the CSR + +```bash +( _fd_csr="request.csr" ; \ +openssl req -text -noout -in ${_fd_csr} ) +``` + +###### Check the private key and the certificate are match + +```bash +(openssl rsa -noout -modulus -in private.key | openssl md5 ; \ +openssl x509 -noout -modulus -in certificate.crt | openssl md5) | uniq +``` + +###### Check the private key and the CSR are match + +```bash +(openssl rsa -noout -modulus -in private.key | openssl md5 ; \ +openssl req -noout -modulus -in request.csr | openssl md5) | uniq +``` + +___ + +##### Tool: [secure-delete](https://wiki.archlinux.org/index.php/Securely_wipe_disk) + +###### Secure delete with shred + +```bash +shred -vfuz -n 10 file +shred --verbose --random-source=/dev/urandom -n 1 /dev/sda +``` + +###### Secure delete with scrub + +```bash +scrub -p dod /dev/sda +scrub -p dod -r file +``` + +###### Secure delete with badblocks + +```bash +badblocks -s -w -t random -v /dev/sda +badblocks -c 10240 -s -w -t random -v /dev/sda +``` + +###### Secure delete with secure-delete + +```bash +srm -vz /tmp/file +sfill -vz /local +sdmem -v +swapoff /dev/sda5 && sswap -vz /dev/sda5 +``` + +___ + +##### Tool: [dd](https://en.wikipedia.org/wiki/Dd_(Unix)) + +###### Show dd status every so often + +```bash +dd status=progress +watch --interval 5 killall -USR1 dd +``` + +###### Redirect output to a file with dd + +```bash +echo "string" | dd of=filename +``` + +___ + +##### Tool: [gpg](https://www.gnupg.org/) + +###### Export public key + +```bash +gpg --export --armor "" > username.pkey +``` + + * `--export` - export all keys from all keyrings or specific key + * `-a|--armor` - create ASCII armored output + +###### Encrypt file + +```bash +gpg -e -r "" dump.sql +``` + + * `-e|--encrypt` - encrypt data + * `-r|--recipient` - encrypt for specific + +###### Decrypt file + +```bash +gpg -o dump.sql -d dump.sql.gpg +``` + + * `-o|--output` - use as output file + * `-d|--decrypt` - decrypt data (default) + +###### Search recipient + +```bash +gpg --keyserver hkp://keyserver.ubuntu.com --search-keys "" +``` + + * `--keyserver` - set specific key server + * `--search-keys` - search for keys on a key server + +###### List all of the packets in an encrypted file + +```bash +gpg --batch --list-packets archive.gpg +gpg2 --batch --list-packets archive.gpg +``` + +___ + +##### Tool: [system-other](https://github.com/trimstray/the-book-of-secret-knowledge#tool-system-other) + +###### Reboot system from init + +```bash +exec /sbin/init 6 +``` + +###### Init system from single user mode + +```bash +exec /sbin/init +``` + +###### Show current working directory of a process + +```bash +readlink -f /proc//cwd +``` + +###### Show actual pathname of the executed command + +```bash +readlink -f /proc//exe +``` + +##### Tool: [curl](https://curl.haxx.se) + +```bash +curl -Iks https://www.google.com +``` + + * `-I` - show response headers only + * `-k` - insecure connection when using ssl + * `-s` - silent mode (not display body) + +```bash +curl -Iks --location -X GET -A "x-agent" https://www.google.com +``` + + * `--location` - follow redirects + * `-X` - set method + * `-A` - set user-agent + +```bash +curl -Iks --location -X GET -A "x-agent" --proxy http://127.0.0.1:16379 https://www.google.com +``` + + * `--proxy [socks5://|http://]` - set proxy server + +```bash +curl -o file.pdf -C - https://example.com/Aiju2goo0Ja2.pdf +``` + + * `-o` - write output to file + * `-C` - resume the transfer + +###### Find your external IP address (external services) + +```bash +curl ipinfo.io +curl ipinfo.io/ip +curl icanhazip.com +curl ifconfig.me/ip ; echo +``` + +###### Repeat URL request + +```bash +# URL sequence substitution with a dummy query string: +curl -ks https://example.com/?[1-20] + +# With shell 'for' loop: +for i in {1..20} ; do curl -ks https://example.com/ ; done +``` + +###### Check DNS and HTTP trace with headers for specific domains + +```bash +### Set domains and external dns servers. +_domain_list=(google.com) ; _dns_list=("8.8.8.8" "1.1.1.1") + +for _domain in "${_domain_list[@]}" ; do + + printf '=%.0s' {1..48} + + echo + + printf "[\\e[1;32m+\\e[m] resolve: %s\\n" "$_domain" + + for _dns in "${_dns_list[@]}" ; do + + # Resolve domain. + host "${_domain}" "${_dns}" + + echo + + done + + for _proto in http https ; do + + printf "[\\e[1;32m+\\e[m] trace + headers: %s://%s\\n" "$_proto" "$_domain" + + # Get trace and http headers. + curl -Iks -A "x-agent" --location "${_proto}://${_domain}" + + echo + + done + +done + +unset _domain_list _dns_list +``` + +___ + +##### Tool: [httpie](https://httpie.org/) + +```bash +http -p Hh https://www.google.com +``` + + * `-p` - print request and response headers + * `H` - request headers + * `B` - request body + * `h` - response headers + * `b` - response body + +```bash +http -p Hh https://www.google.com --follow --verify no +``` + + * `-F, --follow` - follow redirects + * `--verify no` - skip SSL verification + +```bash +http -p Hh https://www.google.com --follow --verify no \ +--proxy http:http://127.0.0.1:16379 +``` + + * `--proxy [http:]` - set proxy server + +##### Tool: [ssh](https://www.openssh.com/) + +###### Escape Sequence + +``` +# Supported escape sequences: +~. - terminate connection (and any multiplexed sessions) +~B - send a BREAK to the remote system +~C - open a command line +~R - Request rekey (SSH protocol 2 only) +~^Z - suspend ssh +~# - list forwarded connections +~& - background ssh (when waiting for connections to terminate) +~? - this message +~~ - send the escape character by typing it twice +``` + +###### Compare a remote file with a local file + +```bash +ssh user@host cat /path/to/remotefile | diff /path/to/localfile - +``` + +###### SSH connection through host in the middle + +```bash +ssh -t reachable_host ssh unreachable_host +``` + +###### Run command over SSH on remote host + +```bash +cat > cmd.txt << __EOF__ +cat /etc/hosts +__EOF__ + +ssh host -l user $(&1 | tee -a "${_sesdir}/$(date +%Y%m%d).log" + +} + +# Alias: +alias ssh='_ssh_sesslog' +``` + +###### Using Keychain for SSH logins + +```bash +### Delete all of ssh-agent's keys. +function _scl() { + + /usr/bin/keychain --clear + +} + +### Add key to keychain. +function _scg() { + + /usr/bin/keychain /path/to/private-key + source "$HOME/.keychain/$HOSTNAME-sh" + +} +``` + +###### SSH login without processing any login scripts + +```bash +ssh -tt user@host bash +``` + +###### SSH local port forwarding + +Example 1: + +```bash +# Forwarding our local 2250 port to nmap.org:443 from localhost through localhost +host1> ssh -L 2250:nmap.org:443 localhost + +# Connect to the service: +host1> curl -Iks --location -X GET https://localhost:2250 +``` + +Example 2: + +```bash +# Forwarding our local 9051 port to db.d.x:5432 from localhost through node.d.y +host1> ssh -nNT -L 9051:db.d.x:5432 node.d.y + +# Connect to the service: +host1> psql -U db_user -d db_dev -p 9051 -h localhost +``` + + * `-n` - redirects stdin from `/dev/null` + * `-N` - do not execute a remote command + * `-T` - disable pseudo-terminal allocation + +###### SSH remote port forwarding + +```bash +# Forwarding our local 9051 port to db.d.x:5432 from host2 through node.d.y +host1> ssh -nNT -R 9051:db.d.x:5432 node.d.y + +# Connect to the service: +host2> psql -U postgres -d postgres -p 8000 -h localhost +``` + +___ + +##### Tool: [linux-dev](https://www.tldp.org/LDP/abs/html/devref1.html) + +###### Testing remote connection to port + +```bash +timeout 1 bash -c "//" >/dev/null 2>&1 ; echo $? +``` + + * `` - set remote host + * `` - set destination port + +###### Read and write to TCP or UDP sockets with common bash tools + +```bash +exec 5<>/dev/tcp//; cat <&5 & cat >&5; exec 5>&- +``` + +___ + +##### Tool: [tcpdump](http://www.tcpdump.org/) + +###### Filter incoming (on interface) traffic (specific ) + +```bash +tcpdump -ne -i eth0 -Q in host 192.168.252.1 and port 443 +``` + + * `-n` - don't convert addresses (`-nn` will not resolve hostnames or ports) + * `-e` - print the link-level headers + * `-i [iface|any]` - set interface + * `-Q|-D [in|out|inout]` - choose send/receive direction (`-D` - for old tcpdump versions) + * `host [ip|hostname]` - set host, also `[host not]` + * `[and|or]` - set logic + * `port [1-65535]` - set port number, also `[port not]` + +###### Filter incoming (on interface) traffic (specific ) and write to a file + +```bash +tcpdump -ne -i eth0 -Q in host 192.168.252.1 and port 443 -c 5 -w tcpdump.pcap +``` + + * `-c [num]` - capture only num number of packets + * `-w [filename]` - write packets to file, `-r [filename]` - reading from file + +###### Capture all ICMP packets + +```bash +tcpdump -nei eth0 icmp +``` + +###### Check protocol used (TCP or UDP) for service + +```bash +tcpdump -nei eth0 tcp port 22 -vv -X | egrep "TCP|UDP" +``` + +###### Display ASCII text (to parse the output using grep or other) + +```bash +tcpdump -i eth0 -A -s0 port 443 +``` + +###### Grab everything between two keywords + +```bash +tcpdump -i eth0 port 80 -X | sed -n -e '/username/,/=ldap/ p' +``` + +###### Grab user and pass ever plain http + +```bash +tcpdump -i eth0 port http -l -A | egrep -i \ +'pass=|pwd=|log=|login=|user=|username=|pw=|passw=|passwd=|password=|pass:|user:|username:|password:|login:|pass |user ' \ +--color=auto --line-buffered -B20 +``` + +###### Extract HTTP User Agent from HTTP request header + +```bash +tcpdump -ei eth0 -nn -A -s1500 -l | grep "User-Agent:" +``` + +###### Capture only HTTP GET and POST packets + +```bash +tcpdump -ei eth0 -s 0 -A -vv \ +'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420' or 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354' +``` + +or simply: + +```bash +tcpdump -ei eth0 -s 0 -v -n -l | egrep -i "POST /|GET /|Host:" +``` + +###### Rotate capture files + +```bash +tcpdump -ei eth0 -w /tmp/capture-%H.pcap -G 3600 -C 200 +``` + + * `-G ` - pcap will be created every `` seconds + * `-C ` - close the current pcap and open a new one if is larger than `` + +###### Top hosts by packets + +```bash +tcpdump -ei enp0s25 -nnn -t -c 200 | cut -f 1,2,3,4 -d '.' | sort | uniq -c | sort -nr | head -n 20 +``` + +###### Excludes any RFC 1918 private address + +```bash +tcpdump -nei eth0 'not (src net (10 or 172.16/12 or 192.168/16) and dst net (10 or 172.16/12 or 192.168/16))' +``` + +___ + +##### Tool: [tcpick](http://tcpick.sourceforge.net/) + +###### Analyse packets in real-time + +```bash +while true ; do tcpick -a -C -r dump.pcap ; sleep 2 ; clear ; done +``` + +___ + +##### Tool: [ngrep](http://ngrep.sourceforge.net/usage.html) + +```bash +ngrep -d eth0 "www.domain.com" port 443 +``` + + * `-d [iface|any]` - set interface + * `[domain]` - set hostname + * `port [1-65535]` - set port number + +```bash +ngrep -d eth0 "www.domain.com" src host 10.240.20.2 and port 443 +``` + + * `(host [ip|hostname])` - filter by ip or hostname + * `(port [1-65535])` - filter by port number + +```bash +ngrep -d eth0 -qt -O ngrep.pcap "www.domain.com" port 443 +``` + + * `-q` - quiet mode (only payloads) + * `-t` - added timestamps + * `-O [filename]` - save output to file, `-I [filename]` - reading from file + +```bash +ngrep -d eth0 -qt 'HTTP' 'tcp' +``` + + * `HTTP` - show http headers + * `tcp|udp` - set protocol + * `[src|dst] host [ip|hostname]` - set direction for specific node + +```bash +ngrep -l -q -d eth0 -i "User-Agent: curl*" +``` + + * `-l` - stdout line buffered + * `-i` - case-insensitive search + +___ + +##### Tool: [hping3](http://www.hping.org/) + +```bash +hping3 -V -p 80 -s 5050 www.google.com +``` + + * `-V|--verbose` - verbose mode + * `-p|--destport` - set destination port + * `-s|--baseport` - set source port + * `` - set scan type + * `-F|--fin` - set FIN flag, port open if no reply + * `-S|--syn` - set SYN flag + * `-P|--push` - set PUSH flag + * `-A|--ack` - set ACK flag (use when ping is blocked, RST response back if the port is open) + * `-U|--urg` - set URG flag + * `-Y|--ymas` - set Y unused flag (0x80 - nullscan), port open if no reply + * `-M 0 -UPF` - set TCP sequence number and scan type (URG+PUSH+FIN), port open if no reply + +```bash +hping3 -V -c 1 -1 -C 8 www.google.com +``` + + * `-c [num]` - packet count + * `-1` - set ICMP mode + * `-C|--icmptype [icmp-num]` - set icmp type (default icmp-echo = 8) + +```bash +hping3 -V -c 1000000 -d 120 -S -w 64 -p 80 --flood --rand-source +``` + + * `--flood` - sent packets as fast as possible (don't show replies) + * `--rand-source` - random source address mode + * `-d --data` - data size + * `-w|--win` - winsize (default 64) + +___ + +##### Tool: [nmap](https://nmap.org/) + +###### Ping scans the network + +```bash +nmap -sP 192.168.0.0/24 +``` + +###### Show only open ports + +```bash +nmap -F --open 192.168.0.0/24 +``` + +###### Full TCP port scan using with service version detection + +```bash +nmap -p 1-65535 -sV -sS -T4 192.168.0.0/24 +``` + +###### Nmap scan and pass output to Nikto + +```bash +nmap -p80,443 192.168.0.0/24 -oG - | nikto.pl -h - +``` + +###### Recon specific ip:service with Nmap NSE scripts stack + +```bash +# Set variables: +_hosts="192.168.250.10" +_ports="80,443" + +# Set Nmap NSE scripts stack: +_nmap_nse_scripts="+dns-brute,\ + +http-auth-finder,\ + +http-chrono,\ + +http-cookie-flags,\ + +http-cors,\ + +http-cross-domain-policy,\ + +http-csrf,\ + +http-dombased-xss,\ + +http-enum,\ + +http-errors,\ + +http-git,\ + +http-grep,\ + +http-internal-ip-disclosure,\ + +http-jsonp-detection,\ + +http-malware-host,\ + +http-methods,\ + +http-passwd,\ + +http-phpself-xss,\ + +http-php-version,\ + +http-robots.txt,\ + +http-sitemap-generator,\ + +http-shellshock,\ + +http-stored-xss,\ + +http-title,\ + +http-unsafe-output-escaping,\ + +http-useragent-tester,\ + +http-vhosts,\ + +http-waf-detect,\ + +http-waf-fingerprint,\ + +http-xssed,\ + +traceroute-geolocation.nse,\ + +ssl-enum-ciphers,\ + +whois-domain,\ + +whois-ip" + +# Set Nmap NSE script params: +_nmap_nse_scripts_args="dns-brute.domain=${_hosts},http-cross-domain-policy.domain-lookup=true," +_nmap_nse_scripts_args+="http-waf-detect.aggro,http-waf-detect.detectBodyChanges," +_nmap_nse_scripts_args+="http-waf-fingerprint.intensive=1" + +# Perform scan: +nmap --script="$_nmap_nse_scripts" --script-args="$_nmap_nse_scripts_args" -p "$_ports" "$_hosts" +``` + +___ + +##### Tool: [netcat](http://netcat.sourceforge.net/) + +```bash +nc -kl 5000 +``` + + * `-l` - listen for an incoming connection + * `-k` - listening after client has disconnected + * `>filename.out` - save receive data to file (optional) + +```bash +nc 192.168.0.1 5051 < filename.in +``` + + * `< filename.in` - send data to remote host + +```bash +nc -vz 10.240.30.3 5000 +``` + + * `-v` - verbose output + * `-z` - scan for listening daemons + +```bash +nc -vzu 10.240.30.3 1-65535 +``` + + * `-u` - scan only udp ports + +###### Transfer data file (archive) + +```bash +server> nc -l 5000 | tar xzvfp - +client> tar czvfp - /path/to/dir | nc 10.240.30.3 5000 +``` + +###### Launch remote shell + +```bash +# 1) +server> nc -l 5000 -e /bin/bash +client> nc 10.240.30.3 5000 + +# 2) +server> rm -f /tmp/f; mkfifo /tmp/f +server> cat /tmp/f | /bin/bash -i 2>&1 | nc -l 127.0.0.1 5000 > /tmp/f +client> nc 10.240.30.3 5000 +``` + +###### Simple file server + +```bash +while true ; do nc -l 5000 | tar -xvf - ; done +``` + +###### Simple minimal HTTP Server + +```bash +while true ; do nc -l -p 1500 -c 'echo -e "HTTP/1.1 200 OK\n\n $(date)"' ; done +``` + +###### Simple HTTP Server + + > Restarts web server after each request - remove `while` condition for only single connection. + +```bash +cat > index.html << __EOF__ + + + + + + + + + + +

+ + Hello! It's a site. + +

+ + + +__EOF__ +``` + +```bash +server> while : ; do \ +(echo -ne "HTTP/1.1 200 OK\r\nContent-Length: $(wc -c /" <"$_sent" & +sed "s/^/<= /" <"$_recv" & + +nc -l -p "$_listen_port" <"$_back" | \ +tee "$_sent" | \ +nc "$_bk_host" "$_bk_port" | \ +tee "$_recv" >"$_back" +``` + +```bash +server> chmod +x nc-proxy && ./nc-proxy 8080 192.168.252.10:8000 + lport: 8080 +bk_host: 192.168.252.10 +bk_port: 8000 + +client> http -p h 10.240.30.3:8080 +HTTP/1.1 200 OK +Accept-Ranges: bytes +Cache-Control: max-age=31536000 +Content-Length: 2748 +Content-Type: text/html; charset=utf-8 +Date: Sun, 01 Jul 2018 20:12:08 GMT +Last-Modified: Sun, 01 Apr 2018 21:53:37 GMT +``` + +###### Create a single-use TCP or UDP proxy + +```bash +### TCP -> TCP +nc -l -p 2000 -c "nc [ip|hostname] 3000" + +### TCP -> UDP +nc -l -p 2000 -c "nc -u [ip|hostname] 3000" + +### UDP -> UDP +nc -l -u -p 2000 -c "nc -u [ip|hostname] 3000" + +### UDP -> TCP +nc -l -u -p 2000 -c "nc [ip|hostname] 3000" +``` + +___ + +##### Tool: [gnutls-cli](https://gnutls.org/manual/html_node/gnutls_002dcli-Invocation.html) + +###### Testing connection to remote host (with SNI support) + +```bash +gnutls-cli -p 443 google.com +``` + +###### Testing connection to remote host (without SNI support) + +```bash +gnutls-cli --disable-sni -p 443 google.com +``` + +___ + +##### Tool: [socat](http://www.dest-unreach.org/socat/doc/socat.html) + +###### Testing remote connection to port + +```bash +socat - TCP4:10.240.30.3:22 +``` + + * `-` - standard input (STDIO) + * `TCP4:` - set tcp4 connection with specific params + * `[hostname|ip]` - set hostname/ip + * `[1-65535]` - set port number + +###### Redirecting TCP-traffic to a UNIX domain socket under Linux + +```bash +socat TCP-LISTEN:1234,bind=127.0.0.1,reuseaddr,fork,su=nobody,range=127.0.0.0/8 UNIX-CLIENT:/tmp/foo +``` + + * `TCP-LISTEN:` - set tcp listen with specific params + * `[1-65535]` - set port number + * `bind=[hostname|ip]` - set bind hostname/ip + * `reuseaddr` - allows other sockets to bind to an address + * `fork` - keeps the parent process attempting to produce more connections + * `su=nobody` - set user + * `range=[ip-range]` - ip range + * `UNIX-CLIENT:` - communicates with the specified peer socket + * `filename` - define socket + +___ + +##### Tool: [p0f](http://lcamtuf.coredump.cx/p0f3/) + +###### Set iface in promiscuous mode and dump traffic to the log file + +```bash +p0f -i enp0s25 -p -d -o /dump/enp0s25.log +``` + + * `-i` - listen on the specified interface + * `-p` - set interface in promiscuous mode + * `-d` - fork into background + * `-o` - output file + +___ + +##### Tool: [netstat](https://en.wikipedia.org/wiki/Netstat) + +###### Graph # of connections for each hosts + +```bash +netstat -an | awk '/ESTABLISHED/ { split($5,ip,":"); if (ip[1] !~ /^$/) print ip[1] }' | \ +sort | uniq -c | awk '{ printf("%s\t%s\t",$2,$1) ; for (i = 0; i < $1; i++) {printf("*")}; print "" }' +``` + +###### Monitor open connections for specific port including listen, count and sort it per IP + +```bash +watch "netstat -plan | grep :443 | awk {'print \$5'} | cut -d: -f 1 | sort | uniq -c | sort -nk 1" +``` + +###### Grab banners from local IPv4 listening ports + +```bash +netstat -nlt | grep 'tcp ' | grep -Eo "[1-9][0-9]*" | xargs -I {} sh -c "echo "" | nc -v -n -w1 127.0.0.1 {}" +``` + +___ + +##### Tool: [rsync](https://en.wikipedia.org/wiki/Rsync) + +###### Rsync remote data as root using sudo + +```bash +rsync --rsync-path 'sudo rsync' username@hostname:/path/to/dir/ /local/ +``` + +___ + +##### Tool: [host](https://en.wikipedia.org/wiki/Host_(Unix)) + +###### Resolves the domain name (using external dns server) + +```bash +host google.com 9.9.9.9 +``` + +###### Checks the domain administrator (SOA record) + +```bash +host -t soa google.com 9.9.9.9 +``` + +___ + +##### Tool: [dig](https://en.wikipedia.org/wiki/Dig_(command)) + +###### Resolves the domain name (short output) + +```bash +dig google.com +short +``` + +###### Lookup NS record for specific domain + +```bash +dig @9.9.9.9 google.com NS +``` + +###### Query only answer section + +```bash +dig google.com +nocomments +noquestion +noauthority +noadditional +nostats +``` + +###### Query ALL DNS Records + +```bash +dig google.com ANY +noall +answer +``` + +###### DNS Reverse Look-up + +```bash +dig -x 172.217.16.14 +short +``` + +___ + +##### Tool: [certbot](https://certbot.eff.org/) + +###### Generate multidomain certificate + +```bash +certbot certonly -d example.com -d www.example.com +``` + +###### Generate wildcard certificate + +```bash +certbot certonly --manual --preferred-challenges=dns -d example.com -d *.example.com +``` + +###### Generate certificate with 4096 bit private key + +```bash +certbot certonly -d example.com -d www.example.com --rsa-key-size 4096 +``` + +___ + +##### Tool: [network-other](https://github.com/trimstray/the-book-of-secret-knowledge#tool-network-other) + +###### Get all subnets for specific AS (Autonomous system) + +```bash +AS="AS32934" +whois -h whois.radb.net -- "-i origin ${AS}" | \ +grep "^route:" | \ +cut -d ":" -f2 | \ +sed -e 's/^[ \t]//' | \ +sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 | \ +cut -d ":" -f2 | \ +sed -e 's/^[ \t]/allow /' | \ +sed 's/$/;/' | \ +sed 's/allow */subnet -> /g' +``` + +###### Resolves domain name from dns.google.com with curl and jq + +```bash +_dname="google.com" ; curl -s "https://dns.google.com/resolve?name=${_dname}&type=A" | jq . +``` + +##### Tool: [git](https://git-scm.com/) + +###### Log alias for a decent view of your repo + +```bash +# 1) +git log --oneline --decorate --graph --all + +# 2) +git log --graph \ +--pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' \ +--abbrev-commit +``` + +___ + +##### Tool: [python](https://www.python.org/) + +###### Static HTTP web server + +```bash +# Python 3.x +python3 -m http.server 8000 --bind 127.0.0.1 + +# Python 2.x +python -m SimpleHTTPServer 8000 +``` + +###### Static HTTP web server with SSL support + +```bash +# Python 3.x +from http.server import HTTPServer, BaseHTTPRequestHandler +import ssl + +httpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler) + +httpd.socket = ssl.wrap_socket (httpd.socket, + keyfile="path/to/key.pem", + certfile='path/to/cert.pem', server_side=True) + +httpd.serve_forever() + +# Python 2.x +import BaseHTTPServer, SimpleHTTPServer +import ssl + +httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), + SimpleHTTPServer.SimpleHTTPRequestHandler) + +httpd.socket = ssl.wrap_socket (httpd.socket, + keyfile="path/tp/key.pem", + certfile='path/to/cert.pem', server_side=True) + +httpd.serve_forever() +``` + +###### Encode base64 + +```bash +python -m base64 -e <<< "sample string" +``` + +###### Decode base64 + +```bash +python -m base64 -d <<< "dGhpcyBpcyBlbmNvZGVkCg==" +``` + +##### Tool: [awk](http://www.grymoire.com/Unix/Awk.html) + +###### Search for matching lines + +```bash +# egrep foo +awk '/foo/' filename +``` + +###### Search non matching lines + +```bash +# egrep -v foo +awk '!/foo/' filename +``` + +###### Print matching lines with numbers + +```bash +# egrep -n foo +awk '/foo/{print FNR,$0}' filename +``` + +###### Print the last column + +```bash +awk '{print $NF}' filename +``` + +###### Find all the lines longer than 80 characters + +```bash +awk 'length($0)>80{print FNR,$0}' filename +``` + +###### Print only lines of less than 80 characters + +```bash +awk 'length < 80' filename +``` + +###### Print double new lines a file + +```bash +awk '1; { print "" }' filename +``` + +###### Print line numbers + +```bash +awk '{ print FNR "\t" $0 }' filename +awk '{ printf("%5d : %s\n", NR, $0) }' filename # in a fancy manner +``` + +###### Print line numbers for only non-blank lines + +```bash +awk 'NF { $0=++a " :" $0 }; { print }' filename +``` + +###### Print the line and the next two (i=5) lines after the line matching regexp + +```bash +awk '/foo/{i=5+1;}{if(i){i--; print;}}' filename +``` + +###### Print the lines starting at the line matching 'server {' until the line matching '}' + +```bash +awk '/server {/,/}/' filename +``` + +###### Print multiple columns with separators + +```bash +awk -F' ' '{print "ip:\t" $2 "\n port:\t" $3' filename +``` + +###### Remove empty lines + +```bash +awk 'NF > 0' filename + +# alternative: +awk NF filename +``` + +###### Delete trailing white space (spaces, tabs) + +```bash +awk '{sub(/[ \t]*$/, "");print}' filename +``` + +###### Delete leading white space + +```bash +awk '{sub(/^[ \t]+/, ""); print}' filename +``` + +###### Remove duplicate consecutive lines + +```bash +# uniq +awk 'a !~ $0{print}; {a=$0}' filename +``` + +###### Remove duplicate entries in a file without sorting + +```bash +awk '!x[$0]++' filename +``` + +###### Exclude multiple columns + +```bash +awk '{$1=$3=""}1' filename +``` + +###### Substitute foo for bar on lines matching regexp + +```bash +awk '/regexp/{gsub(/foo/, "bar")};{print}' filename +``` + +###### Add some characters at the beginning of matching lines + +```bash +awk '/regexp/{sub(/^/, "++++"); print;next;}{print}' filename +``` + +###### Get the last hour of Apache logs + +```bash +awk '/'$(date -d "1 hours ago" "+%d\\/%b\\/%Y:%H:%M")'/,/'$(date "+%d\\/%b\\/%Y:%H:%M")'/ { print $0 }' \ +/var/log/httpd/access_log +``` + +___ + +##### Tool: [sed](http://www.grymoire.com/Unix/Sed.html) + +###### Print a specific line from a file + +```bash +sed -n 10p /path/to/file +``` + +###### Remove a specific line from a file + +```bash +sed -i 10d /path/to/file +# alternative (BSD): sed -i'' 10d /path/to/file +``` + +###### Remove a range of lines from a file + +```bash +sed -i -re ',d' +``` + +###### Replace newline(s) with a space + +```bash +sed ':a;N;$!ba;s/\n/ /g' /path/to/file + +# cross-platform compatible syntax: +sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' /path/to/file +``` + +- `:a` create a label `a` +- `N` append the next line to the pattern space +- `$!` if not the last line, ba branch (go to) label `a` +- `s` substitute, `/\n/` regex for new line, `/ /` by a space, `/g` global match (as many times as it can) + +Alternatives: + +```bash +# perl version (sed-like speed): +perl -p -e 's/\n/ /' /path/to/file + +# bash version (slow): +while read line ; do printf "%s" "$line " ; done < file +``` + +###### Delete string +N next lines + +```bash +sed '/start/,+4d' /path/to/file +``` + +___ + +##### Tool: [grep](http://www.grymoire.com/Unix/Grep.html) + +###### Search for a "pattern" inside all files in the current directory + +```bash +grep -rn "pattern" +grep -RnisI "pattern" * +fgrep "pattern" * -R +``` + +###### Show only for multiple patterns + +```bash +grep 'INFO*'\''WARN' filename +grep 'INFO\|WARN' filename +grep -e INFO -e WARN filename +grep -E '(INFO|WARN)' filename +egrep "INFO|WARN" filename +``` + +###### Except multiple patterns + +```bash +grep -vE '(error|critical|warning)' filename +``` + +###### Show data from file without comments + +```bash +grep -v ^[[:space:]]*# filename +``` + +###### Show data from file without comments and new lines + +```bash +egrep -v '#|^$' filename +``` + +###### Show strings with a dash/hyphen + +```bash +grep -e -- filename +grep -- -- filename +grep "\-\-" filename +``` + +###### Remove blank lines from a file and save output to new file + +```bash +grep . filename > newfilename +``` + +##### Tool: [perl](https://www.perl.org/) + +###### Search and replace (in place) + +```bash +perl -i -pe's/SEARCH/REPLACE/' filename +``` + +###### Edit of `*.conf` files changing all foo to bar (and backup original) + +```bash +perl -p -i.orig -e 's/\bfoo\b/bar/g' *.conf +``` + +###### Prints the first 20 lines from `*.conf` files + +```bash +perl -pe 'exit if $. > 20' *.conf +``` + +###### Search lines 10 to 20 + +```bash +perl -ne 'print if 10 .. 20' filename +``` + +###### Delete first 10 lines (and backup original) + +```bash +perl -i.orig -ne 'print unless 1 .. 10' filename +``` + +###### Delete all but lines between foo and bar (and backup original) + +```bash +perl -i.orig -ne 'print unless /^foo$/ .. /^bar$/' filename +``` + +###### Reduce multiple blank lines to a single line + +```bash +perl -p -i -00pe0 filename +``` + +###### Convert tabs to spaces (1t = 2sp) + +```bash +perl -p -i -e 's/\t/ /g' filename +``` + +###### Read input from a file and report number of lines and characters + +```bash +perl -lne '$i++; $in += length($_); END { print "$i lines, $in characters"; }' filename +``` + +#### Shell Tricks  [[TOC]](#anger-table-of-contents) diff --git a/.agents/skills/sysadmin-toolbox/references/shell-tricks.md b/.agents/skills/sysadmin-toolbox/references/shell-tricks.md new file mode 100644 index 0000000..add4802 --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/references/shell-tricks.md @@ -0,0 +1,97 @@ +#### Shell Tricks  [[TOC]](#anger-table-of-contents) + +When you get a shell, it is generally not very clean, but after following these steps, you will have a fairly clean and comfortable shell to work with. + +1) `script /dev/null -c bash` +2) Ctrl-Z (to send it to background) +3) `stty raw -echo; fg` (returns the shell to foreground) +4) `reset` (to reset terminal) +5) `xterm` (when asked for terminal type) +6) `export TERM=xterm; export SHELL=bash` + +#### Shell functions  [[TOC]](#anger-table-of-contents) + +##### Table of Contents + +- [Domain resolve](#domain-resolve) +- [Get ASN](#get-asn) + +###### Domain resolve + +```bash +# Dependencies: +# - curl +# - jq + +function DomainResolve() { + + local _host="$1" + + local _curl_base="curl --request GET" + local _timeout="15" + + _host_ip=$($_curl_base -ks -m "$_timeout" "https://dns.google.com/resolve?name=${_host}&type=A" | \ + jq '.Answer[0].data' | tr -d "\"" 2>/dev/null) + + if [[ -z "$_host_ip" ]] || [[ "$_host_ip" == "null" ]] ; then + + echo -en "Unsuccessful domain name resolution.\\n" + + else + + echo -en "$_host > $_host_ip\\n" + + fi + +} +``` + +Example: + +```bash +shell> DomainResolve nmap.org +nmap.org > 45.33.49.119 + +shell> DomainResolve nmap.org +Unsuccessful domain name resolution. +``` + +###### Get ASN + +```bash +# Dependencies: +# - curl + +function GetASN() { + + local _ip="$1" + + local _curl_base="curl --request GET" + local _timeout="15" + + _asn=$($_curl_base -ks -m "$_timeout" "http://ip-api.com/line/${_ip}?fields=as") + + _state=$(echo $?) + + if [[ -z "$_ip" ]] || [[ "$_ip" == "null" ]] || [[ "$_state" -ne 0 ]]; then + + echo -en "Unsuccessful ASN gathering.\\n" + + else + + echo -en "$_ip > $_asn\\n" + + fi + +} +``` + +Example: + +```bash +shell> GetASN 1.1.1.1 +1.1.1.1 > AS13335 Cloudflare, Inc. + +shell> GetASN 0.0.0.0 +Unsuccessful ASN gathering. +``` diff --git a/.agents/skills/sysadmin-toolbox/references/web-tools.md b/.agents/skills/sysadmin-toolbox/references/web-tools.md new file mode 100644 index 0000000..cf750be --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/references/web-tools.md @@ -0,0 +1,269 @@ +#### Web Tools  [[TOC]](#anger-table-of-contents) + +##### :black_small_square: Browsers + +

+   SSL/TLS Capabilities of Your Browser - test your browser's SSL implementation.
+   Can I use - provides up-to-date browser support tables for support of front-end web technologies.
+   Panopticlick 3.0 - is your browser safe against tracking?
+   Privacy Analyzer - see what data is exposed from your browser.
+   Web Browser Security - it's all about Web Browser fingerprinting.
+   How's My SSL? - help a web server developer learn what real world TLS clients were capable of.
+   sslClientInfo - client test (incl TLSv1.3 information).
+

+ +##### :black_small_square: SSL/Security + +

+   SSLLabs Server Test - performs a deep analysis of the configuration of any SSL web server.
+   SSLLabs Server Test (DEV) - performs a deep analysis of the configuration of any SSL web server.
+   ImmuniWebยฎ SSLScan - test SSL/TLS (PCI DSS, HIPAA and NIST).
+   SSL Check - scan your website for non-secure content.
+   SSL Scanner - analyze website security.
+   CryptCheck - test your TLS server configuration (e.g. ciphers).
+   urlscan.io - service to scan and analyse websites.
+   Report URI - monitoring security policies like CSP and HPKP.
+   CSP Evaluator - allows developers and security experts to check if a Content Security Policy.
+   Useless CSP - public list about CSP in some big players (might make them care a bit more).
+   Why No HTTPS? - top 100 websites by Alexa rank not automatically redirecting insecure requests.
+   TLS Cipher Suite Search- cipher suite search engine.
+   cipherli.st - strong ciphers for Apache, Nginx, Lighttpd, and more.*
+   dhtool - public Diffie-Hellman parameter service/tool.
+   badssl.com - memorable site for testing clients against bad SSL configs.
+   tlsfun.de - registered for various tests regarding the TLS/SSL protocol.
+   CAA Record Helper - generate a CAA policy.
+   Common CA Database - repository of information about CAs, and their root and intermediate certificates.
+   CERTSTREAM - real-time certificate transparency log update stream.
+   crt.sh - discovers certificates by continually monitoring all of the publicly known CT.
+   Hardenize - deploy the security standards.
+   Cipher suite compatibility - test TLS cipher suite compatibility.
+   urlvoid - this service helps you detect potentially malicious websites.
+   security.txt - a proposed standard (generator) which allows websites to define security policies.
+   ssl-config-generator - help you follow the Mozilla Server Side TLS configuration guidelines.
+   TLScan - pure python, SSL/TLS protocol and cipher scanner/enumerator.
+

+ +##### :black_small_square: HTTP Headers & Web Linters + +

+   Security Headers - analyse the HTTP response headers (with rating system to the results).
+   Observatory by Mozilla - set of tools to analyze your website.
+   webhint - is a linting tool that will help you with your site's accessibility, speed, security, and more.
+

+ +##### :black_small_square: DNS + +

+   ViewDNS - one source for free DNS related tools and information.
+   DNSLookup - is an advanced DNS lookup tool.
+   DNSlytics - online DNS investigation tool.
+   DNS Spy - monitor, validate and verify your DNS configurations.
+   Zonemaster - helps you to control how your DNS works.
+   Leaf DNS - comprehensive DNS tester.
+   Find subdomains online - find subdomains for security assessment penetration test.
+   DNSdumpster - dns recon & research, find & lookup dns records.
+   DNS Table online - search for DNS records by domain, IP, CIDR, ISP.
+   intoDNS - DNS and mail server health checker.
+   DNS Bajaj - check the delegation of your domain.
+   BuddyDNS Delegation LAB - check, trace and visualize delegation of your domain.
+   dnssec-debugger - DS or DNSKEY records validator.
+   PTRarchive.com - this site is responsible for the safekeeping of historical reverse DNS records.
+   xip.io - wildcard DNS for everyone.
+   nip.io - dead simple wildcard DNS for any IP Address.
+   dnslookup (ceipam) - one of the best DNS propagation checker (and not only).
+   What's My DNS - DNS propagation checking tool.
+   DNSGrep - quickly searching large DNS datasets.
+

+ +##### :black_small_square: Mail + +

+   smtp-tls-checker - check an email domain for SMTP TLS support.
+   MX Toolbox - all of your MX record, DNS, blacklist and SMTP diagnostics in one integrated tool.
+   Secure Email - complete email test tools for email technicians.
+   blacklistalert - checks to see if your domain is on a Real Time Spam Blacklist.
+   MultiRBL - complete IP check for sending Mailservers.
+   DKIM SPF & Spam Assassin Validator - checks mail authentication and scores messages with Spam Assassin.
+

+ +##### :black_small_square: Encoders/Decoders and Regex testing + +

+   URL Encode/Decode - tool from above to either encode or decode a string of text.
+   Uncoder - the online translator for search queries on log data.
+   Regex101 - online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript.
+   RegExr - online tool to learn, build, & test Regular Expressions (RegEx / RegExp).
+   RegEx Testing - online regex testing tool.
+   RegEx Pal - online regex testing tool + other tools.
+   The Cyber Swiss Army Knife - a web app for encryption, encoding, compression and data analysis.
+

+ +##### :black_small_square: Net-tools + +

+   Netcraft - detailed report about the site, helping you to make informed choices about their integrity.*
+   RIPE NCC Atlas - a global, open, distributed Internet measurement platform.
+   Robtex - uses various sources to gather public information about IP numbers, domain names, host names, etc.
+   Security Trails - APIs for Security Companies, Researchers and Teams.
+   Online Curl - curl test, analyze HTTP Response Headers.
+   Online Tools for Developers - HTTP API tools, testers, encoders, converters, formatters, and other tools.
+   Ping.eu - online Ping, Traceroute, DNS lookup, WHOIS and others.
+   Network-Tools - network tools for webmasters, IT technicians & geeks.
+   BGPview - search for any ASN, IP, Prefix or Resource name.
+   Is BGP safe yet? - check BGP (RPKI) security of ISPs and other major Internet players.
+   Riseup - provides online communication tools for people and groups working on liberatory social change.
+   VirusTotal - analyze suspicious files and URLs to detect types of malware.
+

+ +##### :black_small_square: Privacy + +

+   privacyguides.org - provides knowledge and tools to protect your privacy against global mass surveillance.
+   DNS Privacy Test Servers - DNS privacy recursive servers list (with a 'no logging' policy).
+

+ +##### :black_small_square: Code parsers/playgrounds + +

+   ShellCheck - finds bugs in your shell scripts.
+   explainshell - get interactive help texts for shell commands.
+   jsbin - live pastebin for HTML, CSS & JavaScript, and more.
+   CodeSandbox - online code editor for web application development.
+   PHP Sandbox - test your PHP code with this code tester.
+   Repl.it - an instant IDE to learn, build, collaborate, and host all in one place.
+   vclFiddle - is an online tool for experimenting with the Varnish Cache VCL.
+   Haskell Dockerfile Linter - a smarter Dockerfile linter that helps you build best practice Docker images.
+

+ +##### :black_small_square: Performance + +

+   GTmetrix - analyze your siteโ€™s speed and make it faster.
+   Sucuri loadtimetester - test here the +performance of any of your sites from across the globe.
+   Pingdom Tools - analyze your siteโ€™s speed around the world.
+   PingMe.io - run website latency tests across multiple geographic regions.
+   PageSpeed Insights - analyze your siteโ€™s speed and make it faster.
+   web.dev - helps developers like you learn and apply the web's modern capabilities to your own sites and apps.
+   Lighthouse - automated auditing, performance metrics, and best practices for the web.
+

+ +##### :black_small_square: Mass scanners (search engines) + +

+   Censys - platform that helps information security practitioners discover, monitor, and analyze devices.
+   Shodan - the world's first search engine for Internet-connected devices.
+   Shodan 2000 - this tool looks for randomly generated data from Shodan.
+   GreyNoise - mass scanner such as Shodan and Censys.
+   ZoomEye - search engine for cyberspace that lets the user find specific network components.
+   netograph - tools to monitor and understand deep structure of the web.
+   FOFA - is a cyberspace search engine.
+   onyphe - is a search engine for open-source and cyber threat intelligence data collected.
+   IntelligenceX - is a search engine and data archive.
+   binaryedge - it scan the entire internet space and create real-time threat intelligence streams and reports.
+   Spyse - Internet assets registry: networks, threats, web objects, etc.
+   wigle - is a submission-based catalog of wireless networks. All the networks. Found by Everyone.
+   PublicWWW - find any alphanumeric snippet, signature or keyword in the web pages HTML, JS and CSS code.
+   IntelTechniques - this repository contains hundreds of online search utilities.
+   hunter - lets you find email addresses in seconds and connect with the people that matter for your business.
+   GhostProject? - search by full email address or username.
+   databreaches - was my email affected by data breach?
+   We Leak Info - world's fastest and largest data breach search engine.
+   Pulsedive - scans of malicious URLs, IPs, and domains, including port scans and web requests.
+   Buckets by Grayhatwarfar - database with public search for Open Amazon S3 Buckets and their contents.
+   Vigilante.pw - the breached database directory.
+   builtwith - find out what websites are built with.
+   NerdyData - search the web's source code for technologies, across millions of sites.
+   zorexeye - search for sites, images, apps, softwares & more.
+   Mamont's open FTP Index - if a target has an open FTP site with accessible content it will be listed here.
+   OSINT Framework - focused on gathering information from free tools or resources.
+   maltiverse - is a service oriented to cybersecurity analysts.
+   Leaked Source - is a collaboration of data found online in the form of a lookup.
+   We Leak Info - to help everyday individuals secure their online life, avoiding getting hacked.
+   pipl - is the place to find the person behind the email address, social username or phone number.
+   abuse.ch - is operated by a random swiss guy fighting malware for non-profit.
+   malc0de - malware search engine.
+   Cybercrime Tracker - monitors and tracks various malware families that are used to perpetrate cyber crimes.
+   shhgit - find GitHub secrets in real time.
+   searchcode - helping you find real world examples of functions, API's and libraries.
+   Insecam - the world biggest directory of online surveillance security cameras.
+   index-of - contains great stuff like: security, hacking, reverse engineering, cryptography, programming etc.
+   Rapid7 Labs Open Data - is a great resources of datasets from Project Sonar.
+   Common Response Headers - the largest database of HTTP response headers.
+   InQuest Labs - InQuest Labs is an open, interactive, and API driven data portal for security researchers.
+

+ +##### :black_small_square: Generators + +

+   thispersondoesnotexist - generate fake faces in one click - endless possibilities.
+   AI Generated Photos - 100.000 AI generated faces.
+   fakenamegenerator - your randomly generated identity.
+   Intigriti Redirector - open redirect/SSRF payload generator.
+

+ +##### :black_small_square: Passwords + +

+   have i been pwned? - check if you have an account that has been compromised in a data breach.
+   dehashed - is a hacked database search engine.
+   Leaked Source - is a collaboration of data found online in the form of a lookup.
+

+ +##### :black_small_square: CVE/Exploits databases + +

+   CVE Mitre - list of publicly known cybersecurity vulnerabilities.
+   CVE Details - CVE security vulnerability advanced database.
+   Exploit DB - CVE compliant archive of public exploits and corresponding vulnerable software.
+   0day.today - exploits market provides you the possibility to buy/sell zero-day exploits.
+   sploitus - the exploit and tools database.
+   cxsecurity - free vulnerability database.
+   Vulncode-DB - is a database for vulnerabilities and their corresponding source code if available.
+   cveapi - free API for CVE data.
+

+ +##### :black_small_square: Mobile apps scanners + +

+   ImmuniWebยฎ Mobile App Scanner - test security and privacy of mobile apps (iOS & Android).
+   Quixxi - free Mobile App Vulnerability Scanner for Android & iOS.
+   Ostorlab - analyzes mobile application to identify vulnerabilities and potential weaknesses.
+

+ +##### :black_small_square: Private Search Engines + +

+   Startpage - the world's most private search engine.
+   searX - a privacy-respecting, hackable metasearch engine.
+   darksearch - the 1st real Dark Web search engine.
+   Qwant - the search engine that respects your privacy.
+   DuckDuckGo - the search engine that doesn't track you.
+   Swisscows - privacy safe web search
+   Disconnect - the search engine that anonymizes your searches.
+   MetaGer - the search engine that uses anonymous proxy and hidden Tor branches.
+

+ +##### :black_small_square: Secure Webmail Providers + +

+   CounterMail - online email service, designed to provide maximum security and privacy.
+   Mail2Tor - is a Tor Hidden Service that allows anyone to send and receive emails anonymously.
+   Tutanota - is the world's most secure email service and amazingly easy to use.
+   Protonmail - is the world's largest secure email service, developed by CERN and MIT scientists.
+   Startmail - private & encrypted email made easy.
+

+ +##### :black_small_square: Crypto + +

+   Keybase - it's open source and powered by public-key cryptography.
+

+ +##### :black_small_square: PGP Keyservers + +

+   SKS OpenPGP Key server - services for the SKS keyservers used by OpenPGP.
+

+ +#### Systems/Services  [[TOC]](#anger-table-of-contents) diff --git a/.agents/skills/sysadmin-toolbox/scripts/refresh.sh b/.agents/skills/sysadmin-toolbox/scripts/refresh.sh new file mode 100644 index 0000000..6fab563 --- /dev/null +++ b/.agents/skills/sysadmin-toolbox/scripts/refresh.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Refresh sysadmin-toolbox from The Book of Secret Knowledge repo +# Run periodically to keep references current + +set -e + +REPO_URL="https://github.com/trimstray/the-book-of-secret-knowledge.git" +TEMP_DIR="/tmp/tbsk-refresh-$$" +SKILL_DIR="${1:-$HOME/clawd-duke-leto/skills/sysadmin-toolbox}" + +echo "๐Ÿ”„ Refreshing sysadmin-toolbox from upstream..." + +# Clone fresh copy +git clone --depth 1 "$REPO_URL" "$TEMP_DIR" 2>/dev/null + +cd "$TEMP_DIR" + +# Extract sections +echo "๐Ÿ“ฆ Extracting references..." + +awk '/^#### Shell One-liners/,/^#### Shell Tricks/' README.md > "$SKILL_DIR/references/shell-oneliners.md" +awk '/^#### Shell Tricks/,/^#### Shell Functions/' README.md > "$SKILL_DIR/references/shell-tricks.md" +awk '/^#### CLI Tools/,/^#### GUI Tools/' README.md > "$SKILL_DIR/references/cli-tools.md" +awk '/^#### Web Tools/,/^#### Systems\/Services/' README.md > "$SKILL_DIR/references/web-tools.md" +awk '/^#### Hacking\/Penetration Testing/,/^#### Your daily knowledge/' README.md > "$SKILL_DIR/references/security-tools.md" + +# Cleanup +rm -rf "$TEMP_DIR" + +echo "โœ… sysadmin-toolbox refreshed from upstream" +echo " Shell one-liners: $(wc -l < "$SKILL_DIR/references/shell-oneliners.md") lines" diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..bebb50c --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,23 @@ +{ + "version": 1, + "skills": { + "devops-engineer": { + "source": "jeffallan/claude-skills", + "sourceType": "github", + "skillPath": "skills/devops-engineer/SKILL.md", + "computedHash": "b5fefdd43470cf510937c882440fb0759327adfe4a21b511829e545e5faa988e" + }, + "reverse-proxy": { + "source": "bagelhole/devops-security-agent-skills", + "sourceType": "github", + "skillPath": "infrastructure/networking/reverse-proxy/SKILL.md", + "computedHash": "07f33fdda533634da44489c6320d67391f1a8e243dd3e06891700e4ea8af72c0" + }, + "sysadmin-toolbox": { + "source": "jdrhyne/agent-skills", + "sourceType": "github", + "skillPath": "skills/sysadmin-toolbox/SKILL.md", + "computedHash": "5e8851b6deb583491dee43ea36389ddbb4cbefa3a0c39d89382a3e79a6f80de4" + } + } +}