spinny:~/writing $ vim devsecops-shift-left-security-guide.md
1~2कोड लिखते समय पाई गई vulnerability को ठीक करने में developer को कुछ मिनट लगते हैं। वही vulnerability production में पकड़ी जाए तो एक पूरा sprint खर्च हो जाता है। और अगर कोई attacker इसे पहले खोज ले, तो इसकी कीमत लाखों-करोड़ों हो सकती है। यही **shift-left security** का मूल तर्क है - security checks को development lifecycle में जितना जल्दी हो सके उतना आगे लाना।3~4DevSecOps इस विचार को एक practice में बदलता है: security अंत में कोई अलग चरण नहीं है, बल्कि यह development के हर चरण में बुनी गई एक निरंतर प्रक्रिया है, कोड की पहली पंक्ति से लेकर production deployment तक।5~6## देर से Security का खर्च7~8IBM की Cost of a Data Breach Report ने लगातार दिखाया है कि security issues को ठीक करने की लागत जितनी देर से पकड़ी जाएं उतनी तेजी से बढ़ती है:9~10| चरण | ठीक करने की लागत | ठीक करने का समय |11|-------|------------|-------------|12| **IDE / Local Dev** | मिनट | सेकंड से मिनट |13| **Code Review / PR** | घंटे | मिनट से घंटे |14| **CI/CD Pipeline** | दिन | घंटे से दिन |15| **Staging / QA** | सप्ताह | दिन |16| **Production** | महीने | सप्ताह से महीने |17| **Post-breach** | लाखों ($) | महीने से साल |18~19निष्कर्ष स्पष्ट है: security को जितना पहले लाएं, लागत और समय में उतनी ही बचत होती है।20~21## DevSecOps Pipeline22~23एक परिपक्व DevSecOps pipeline हर चरण में security checks को एकीकृत करती है:24~25```mermaid26graph LR27 IDE[IDE / Editor] --> PC[Pre-commit Hooks]28 PC --> PR[Pull Request]29 PR --> CI[CI Pipeline]30 CI --> Build[Build / Package]31 Build --> Deploy[Deploy]32 Deploy --> Runtime[Runtime / Production]33~34 IDE -.- S1[SAST\nSecret Detection\nLinting]35 PC -.- S2[Secrets Scan\nFormat Check]36 PR -.- S3[Code Review\nDependency Audit]37 CI -.- S4[SAST\nSCA\nContainer Scan\nSBOM]38 Build -.- S5[Image Signing\nArtifact Verification]39 Deploy -.- S6[Policy Enforcement\nAdmission Control]40 Runtime -.- S7[DAST\nWAF\nMonitoring]41```42~43आइए हर चरण को ठोस tools और configuration के साथ समझते हैं।44~45## चरण 1: IDE में Security46~47सबसे तेज feedback loop। File save करने से पहले ही vulnerabilities को पकड़ें।48~49### अनुशंसित Tools50~51- **Semgrep**: OWASP vulnerabilities के लिए community rules के साथ हल्का static analysis52- **Snyk IDE Extension**: real-time dependency vulnerability scanning53- **GitLens + GitLeaks**: आपके editor में secrets detect करें54- **ESLint Security Plugins**: Node.js के लिए `eslint-plugin-security`, DOM XSS के लिए `eslint-plugin-no-unsanitized`55~56### उदाहरण: ESLint Security Configuration57~58```json59{60 "extends": ["eslint:recommended"],61 "plugins": ["security", "no-unsanitized"],62 "rules": {63 "security/detect-object-injection": "warn",64 "security/detect-non-literal-regexp": "warn",65 "security/detect-unsafe-regex": "error",66 "security/detect-buffer-noassert": "error",67 "security/detect-eval-with-expression": "error",68 "security/detect-no-csrf-before-method-override": "error",69 "security/detect-possible-timing-attacks": "warn",70 "no-unsanitized/method": "error",71 "no-unsanitized/property": "error"72 }73}74```75~76## चरण 2: Pre-commit Hooks77~78रक्षा की दूसरी पंक्ति। हर commit से पहले स्वचालित रूप से चलती है, खतरनाक कोड को repository में प्रवेश करने से रोकती है।79~80### Gitleaks: Git में पहुंचने से पहले Secrets पकड़ें81~82Codebases में सबसे आम security गलती secrets commit करना है - API keys, database passwords, tokens। एक बार secret git history में आ जाए, तो इसे पूरी तरह हटाना बेहद मुश्किल है (force pushes के बाद भी, forks और caches इसे बनाए रख सकते हैं)।83~84```yaml85# .pre-commit-config.yaml86repos:87 - repo: https://github.com/gitleaks/gitleaks88 rev: v8.21.089 hooks:90 - id: gitleaks91~92 - repo: https://github.com/semgrep/semgrep93 rev: v1.90.094 hooks:95 - id: semgrep96 args: ['--config', 'auto']97```98~99Install और activate करें:100~101```bash102pip install pre-commit103pre-commit install104```105~106अब हर `git commit` स्वचालित रूप से leaked secrets और सामान्य vulnerabilities के लिए scan करता है। अगर कुछ मिलता है, तो commit block हो जाता है।107~108### Custom Gitleaks Rules109~110आप अपने organization के secrets के लिए custom patterns जोड़ सकते हैं:111~112```toml113# .gitleaks.toml114title = "Custom Gitleaks Config"115~116[[rules]]117id = "internal-api-key"118description = "Internal API key detected"119regex = '''INTERNAL_KEY_[A-Za-z0-9]{32}'''120tags = ["key", "internal"]121```122~123## चरण 3: CI/CD Pipeline Security124~125यहां भारी काम होता है। आपकी CI pipeline को हर pull request पर कई security scans चलाने चाहिए।126~127### SAST (Static Application Security Testing)128~129SAST tools source code को बिना execute किए analyze करते हैं, ऐसे patterns खोजते हैं जो vulnerabilities indicate करते हैं।130~131```yaml132# .github/workflows/security.yml133name: Security Scan134on:135 pull_request:136 branches: [main]137~138jobs:139 sast:140 name: Static Analysis141 runs-on: ubuntu-latest142 steps:143 - uses: actions/checkout@v4144~145 - name: Run Semgrep146 uses: semgrep/semgrep-action@v1147 with:148 config: >-149 p/owasp-top-ten150 p/typescript151 p/nodejs152 p/react153 generateSarif: true154~155 - name: Upload SARIF156 uses: github/codeql-action/upload-sarif@v3157 with:158 sarif_file: semgrep.sarif159```160~161Semgrep का `p/owasp-top-ten` ruleset सबसे आम vulnerabilities पकड़ता है: SQL injection, XSS, SSRF, path traversal, insecure deserialization, और बहुत कुछ।162~163### SCA (Software Composition Analysis)164~165SCA आपकी dependencies को ज्ञात vulnerabilities के लिए scan करता है। यह महत्वपूर्ण है - आधुनिक application code का 80% से अधिक open-source dependencies से आता है।166~167```yaml168 dependency-scan:169 name: Dependency Audit170 runs-on: ubuntu-latest171 steps:172 - uses: actions/checkout@v4173~174 - name: Run Snyk175 uses: snyk/actions/node@master176 env:177 SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}178 with:179 args: --severity-threshold=high180~181 - name: npm audit182 run: npm audit --audit-level=high183```184~185### Trivy के साथ Container Security186~187अगर आप Docker images build करते हैं, तो उन्हें vulnerabilities के लिए scan करना आवश्यक है। **Trivy** सबसे लोकप्रिय open-source container scanner है।188~189```yaml190 container-scan:191 name: Container Security192 runs-on: ubuntu-latest193 steps:194 - uses: actions/checkout@v4195~196 - name: Build image197 run: docker build -t my-app:${{ github.sha }} .198~199 - name: Run Trivy200 uses: aquasecurity/trivy-action@master201 with:202 image-ref: my-app:${{ github.sha }}203 format: 'sarif'204 output: 'trivy-results.sarif'205 severity: 'CRITICAL,HIGH'206 exit-code: '1'207~208 - name: Upload Trivy SARIF209 uses: github/codeql-action/upload-sarif@v3210 with:211 sarif_file: trivy-results.sarif212```213~214### SBOM Generation215~216**Software Bill of Materials (SBOM)** आपके application में हर component की पूरी सूची है। Compliance frameworks और सरकारी नियमों द्वारा इसकी मांग बढ़ रही है (US Executive Order on Cybersecurity federal software के लिए SBOM अनिवार्य करता है)।217~218```yaml219 sbom:220 name: Generate SBOM221 runs-on: ubuntu-latest222 steps:223 - uses: actions/checkout@v4224~225 - name: Generate SBOM with Syft226 uses: anchore/sbom-action@v0227 with:228 format: spdx-json229 output-file: sbom.spdx.json230~231 - name: Upload SBOM232 uses: actions/upload-artifact@v4233 with:234 name: sbom235 path: sbom.spdx.json236```237~238## चरण 4: Secure Docker Images239~240एक production Docker image को least privilege के सिद्धांत का पालन करना चाहिए। एक hardened Dockerfile ऐसा दिखता है:241~242```dockerfile243# Build stage244FROM node:22-alpine AS builder245WORKDIR /app246COPY package.json package-lock.json ./247RUN npm ci248COPY . .249RUN npm run build250~251# Production stage252FROM node:22-alpine AS runner253WORKDIR /app254~255# Install dumb-init before dropping root256RUN apk add --no-cache dumb-init257~258# Don't run as root259RUN addgroup -S app && adduser -S app -G app260~261# Copy only what's needed262COPY --from=builder --chown=app:app /app/dist ./dist263COPY --from=builder --chown=app:app /app/node_modules ./node_modules264COPY --from=builder --chown=app:app /app/package.json ./265~266# Drop to non-root user267USER app268ENTRYPOINT ["dumb-init", "--"]269~270# Health check271HEALTHCHECK --interval=30s --timeout=3s --retries=3 \272 CMD wget -qO- http://localhost:3000/health || exit 1273~274EXPOSE 3000275CMD ["node", "dist/server.js"]276```277~278मुख्य practices:279~2801. **Multi-stage builds का उपयोग करें**: builder stage में dev dependencies होती हैं; runner stage में केवल production code होता है2812. **Root के रूप में न चलाएं**: एक non-root user बनाएं और उसमें switch करें2823. **Alpine images का उपयोग करें**: छोटा attack surface (default रूप से कम packages installed)2834. **Image versions pin करें**: supply chain attacks से बचने के लिए `node:latest` के बजाय `node:22-alpine`2845. **`npm ci` का उपयोग करें**: lock file से deterministic installs, `npm install` नहीं285~286## चरण 5: Secret Management287~288Hard-coded secrets developer-caused incidents में breaches का नंबर एक कारण हैं।289~290### क्या नहीं करना चाहिए291~292```typescript293// NEVER do this294const API_KEY = "sk-1234567890abcdef";295const DB_PASSWORD = "supersecret123";296~297const client = new Client({298 connectionString: `postgres://admin:${DB_PASSWORD}@db.example.com/prod`299});300```301~302### इसके बजाय क्या करें303~304```typescript305// Use environment variables306const client = new Client({307 connectionString: process.env.DATABASE_URL308});309~310// Or use a secret manager311import { SecretManagerServiceClient } from '@google-cloud/secret-manager';312~313const client = new SecretManagerServiceClient();314const [version] = await client.accessSecretVersion({315 name: 'projects/my-project/secrets/db-password/versions/latest',316});317const dbPassword = version.payload?.data?.toString();318```319~320### Secret Management Hierarchy321~322```mermaid323graph TD324 A[Secret Manager\nAWS Secrets Manager\nGCP Secret Manager\nHashiCorp Vault] --> B[Best: Rotated, audited, centralized]325 C[Environment Variables\nInjected at deploy time] --> D[Good: Not in code, but static]326 E[.env files\nWith .gitignore] --> F[Acceptable: Local development only]327 G[Hard-coded in source] --> H[NEVER: Instant breach risk]328~329 style A fill:#d4edda330 style C fill:#fff3cd331 style E fill:#ffeeba332 style G fill:#f8d7da333```334~335## OWASP Top 10: एक त्वरित संदर्भ336~337हर developer को OWASP Top 10 जानना चाहिए। संक्षिप्त संस्करण:338~339| # | Vulnerability | यह क्या है | रोकथाम |340|---|--------------|-----------|------------|341| 1 | **Broken Access Control** | Users उन resources तक पहुंचते हैं जिनतक उन्हें नहीं पहुंचना चाहिए | Default रूप से deny करें, server side पर validate करें |342| 2 | **Cryptographic Failures** | कमजोर encryption, plaintext data | मजबूत algorithms का उपयोग करें (AES-256, bcrypt), हर जगह TLS |343| 3 | **Injection** | SQL, NoSQL, OS command injection | Parameterized queries, input validation |344| 4 | **Insecure Design** | दोषपूर्ण architecture | Threat modeling, secure design patterns |345| 5 | **Security Misconfiguration** | Default credentials, खुले cloud buckets | Hardened defaults, automated config audits |346| 6 | **Vulnerable Components** | Dependencies में ज्ञात CVEs | SCA scanning, नियमित updates |347| 7 | **Auth Failures** | कमजोर passwords, टूटे sessions | MFA, rate limiting, secure session management |348| 8 | **Data Integrity Failures** | Unsigned updates, अविश्वसनीय CI/CD | Code signing, SBOM, pipeline integrity |349| 9 | **Logging Failures** | कोई audit trail नहीं | Structured logging, anomalies पर alerting |350| 10 | **SSRF** | Server-side request forgery | Outbound URLs allowlist करें, inputs validate करें |351~352## पूर्ण GitHub Actions Security Workflow353~354एक पूर्ण, production-ready workflow जो ऊपर की सब चीजों को जोड़ता है:355~356```yaml357# .github/workflows/security.yml358name: Security Pipeline359on:360 pull_request:361 branches: [main]362 push:363 branches: [main]364~365permissions:366 contents: read367 security-events: write368~369jobs:370 secrets-scan:371 name: Secret Detection372 runs-on: ubuntu-latest373 steps:374 - uses: actions/checkout@v4375 with:376 fetch-depth: 0377 - uses: gitleaks/gitleaks-action@v2378 env:379 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}380~381 sast:382 name: Static Analysis (SAST)383 runs-on: ubuntu-latest384 steps:385 - uses: actions/checkout@v4386 - uses: semgrep/semgrep-action@v1387 with:388 config: p/owasp-top-ten p/typescript p/nodejs389~390 dependency-audit:391 name: Dependency Scan (SCA)392 runs-on: ubuntu-latest393 steps:394 - uses: actions/checkout@v4395 - uses: actions/setup-node@v4396 with:397 node-version: 22398 - run: npm ci399 - run: npm audit --audit-level=high400 - uses: snyk/actions/node@master401 env:402 SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}403 with:404 args: --severity-threshold=high405 continue-on-error: true406~407 container-scan:408 name: Container Scan409 runs-on: ubuntu-latest410 needs: [sast, dependency-audit]411 steps:412 - uses: actions/checkout@v4413 - run: docker build -t app:${{ github.sha }} .414 - uses: aquasecurity/trivy-action@master415 with:416 image-ref: app:${{ github.sha }}417 severity: CRITICAL,HIGH418 exit-code: '1'419~420 sbom:421 name: SBOM Generation422 runs-on: ubuntu-latest423 needs: [container-scan]424 steps:425 - uses: actions/checkout@v4426 - uses: anchore/sbom-action@v0427 with:428 format: spdx-json429 output-file: sbom.spdx.json430```431~432```mermaid433graph TD434 PR[Pull Request] --> S1[Secret Detection]435 PR --> S2[SAST - Semgrep]436 PR --> S3[SCA - Snyk + npm audit]437 S2 --> S4[Container Scan - Trivy]438 S3 --> S4439 S4 --> S5[SBOM Generation]440 S5 --> Deploy[Deploy]441~442 S1 -.- F1[Block if secrets found]443 S2 -.- F2[Block on critical vulns]444 S3 -.- F3[Block on high severity]445 S4 -.- F4[Block on critical CVEs]446```447~448## Track करने योग्य Metrics449~450आपको कैसे पता चलेगा कि आपका DevSecOps program काम कर रहा है? इन metrics को track करें:451~452- **Mean time to remediate (MTTR)**: detection के बाद आप कितनी तेजी से vulnerabilities ठीक करते हैं453- **Vulnerability escape rate**: production तक पहुंचने वाली vulnerabilities का प्रतिशत454- **False positive rate**: बहुत अधिक false positives alert fatigue और ignored warnings की ओर ले जाते हैं455- **Dependency freshness**: आपकी dependencies की औसत आयु (पुरानी = ज्ञात CVEs होने की अधिक संभावना)456- **SBOM coverage**: up-to-date SBOMs वाले projects का प्रतिशत457~458## शुरुआत करना: एक व्यावहारिक Roadmap459~460सब कुछ एक साथ implement करने की कोशिश न करें। चरणबद्ध दृष्टिकोण बेहतर काम करता है:461~462```mermaid463flowchart TD464 A[Week 1-2: Foundations] --> B[Week 3-4: CI/CD Integration]465 B --> C[Month 2: Container Security]466 C --> D[Month 3+: Advanced]467~468 A --> A1[Add Gitleaks pre-commit hooks]469 A --> A2[Enable npm audit in CI]470 A --> A3[Add .gitignore for .env files]471~472 B --> B1[Add Semgrep to GitHub Actions]473 B --> B2[Add Snyk dependency scanning]474 B --> B3[Set up SARIF upload to GitHub]475~476 C --> C1[Add Trivy container scanning]477 C --> C2[Harden Dockerfiles]478 C --> C3[Generate SBOMs]479~480 D --> D1[Secret manager integration]481 D --> D2[Runtime protection - DAST]482 D --> D3[Policy as code - OPA]483```484~485## निष्कर्ष486~487DevSecOps आपकी pipeline में और tools जोड़ने के बारे में नहीं है - यह security को software बनाने के तरीके का एक स्वाभाविक हिस्सा बनाने के बारे में है। लक्ष्य हर PR को security warnings से block करना नहीं है, बल्कि developers को तेज feedback देना है ताकि वे issues को तब ठीक कर सकें जब code अभी उनके दिमाग में ताजा हो।488~489बुनियादी चीजों से शुरू करें: secrets के लिए pre-commit hooks, CI में dependency scanning, और Docker images के लिए container scanning। फिर अपनी team की जरूरतों के अनुसार iterate करें।490~491Security एक ऐसी feature नहीं है जो आप एक बार ship करते हैं। यह एक practice है जो आप हर commit में बनाते हैं।492~493> **DevSecOps Starter Checklist:**494>495> - [x] Gitleaks pre-commit hooks installed496> - [x] .env और secret files .gitignore में497> - [x] CI pipeline में Semgrep SAST498> - [x] Dependency scanning के लिए Snyk या npm audit499> - [x] Container image scanning के लिए Trivy500> - [x] Dockerfiles में non-root user501> - [x] Environment variables या secret manager में secrets502> - [x] हर release पर SBOM generation503> - [x] पूरी team में OWASP Top 10 जागरूकता504~
NORMAL · devsecops-shift-left-security-guide.md [readonly]504 lines · :q to close