From 18eb8c5055ffea5dae68814a1acdee183ce5c99f Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Thu, 5 Nov 2026 12:45:55 +0500 Subject: [PATCH 1/2] Add course checks, PDF builder and restore .github folder --- .github/CODEOWNERS | 10 + .github/ISSUE_TEMPLATE/config.yml | 1 + .github/ISSUE_TEMPLATE/lesson-feedback.yml | 37 ++ .github/PULL_REQUEST_TEMPLATE.md | 18 + .github/workflows/pdf.yml | 114 ++++++ .github/workflows/protect-lessons.yml | 51 +++ .github/workflows/validate.yml | 33 ++ .gitignore | 4 + CONTRIBUTING.md | 17 + LESSON_TEMPLATE.md | 17 +- README.md | 11 + ROADMAP.md | 27 +- course.yml | 242 ++++++++++++ lessons/README.md | 26 +- projects/README.md | 6 +- scripts/build_pdf.py | 435 +++++++++++++++++++++ scripts/build_roadmap.py | 86 ++++ scripts/course.py | 255 ++++++++++++ scripts/requirements.txt | 4 + scripts/validate.py | 329 ++++++++++++++++ 20 files changed, 1702 insertions(+), 21 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/lesson-feedback.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/pdf.yml create mode 100644 .github/workflows/protect-lessons.yml create mode 100644 .github/workflows/validate.yml create mode 100644 .gitignore create mode 100644 course.yml create mode 100644 scripts/build_pdf.py create mode 100644 scripts/build_roadmap.py create mode 100644 scripts/course.py create mode 100644 scripts/requirements.txt create mode 100644 scripts/validate.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..f6777f6 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,10 @@ +# The maintainer must approve every pull request. +* @Muawiya-contact + +# Lessons and course files belong to the maintainer only. +/lessons/ @Muawiya-contact +/course.yml @Muawiya-contact +/ROADMAP.md @Muawiya-contact +/LESSON_TEMPLATE.md @Muawiya-contact +/scripts/ @Muawiya-contact +/.github/ @Muawiya-contact diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..0086358 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: true diff --git a/.github/ISSUE_TEMPLATE/lesson-feedback.yml b/.github/ISSUE_TEMPLATE/lesson-feedback.yml new file mode 100644 index 0000000..1036800 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/lesson-feedback.yml @@ -0,0 +1,37 @@ +name: Lesson feedback +description: Report a mistake, an outdated command, or something unclear in a lesson +title: "[Lesson feedback] " +labels: ["lesson-feedback"] +body: + - type: input + id: lesson + attributes: + label: Which lesson? + description: File path or link + placeholder: lessons/01-networking-fundamentals/01-tcp-ip/01-what-is-an-ip-address.md + validations: + required: true + - type: dropdown + id: kind + attributes: + label: Type of feedback + options: + - Wrong information + - Command doesn't work / outdated + - Unclear explanation + - Missing topic or example + - Typo / small fix + - Other + validations: + required: true + - type: textarea + id: problem + attributes: + label: What is the problem? + validations: + required: true + - type: textarea + id: fix + attributes: + label: Suggested fix + description: How should it be written? Add a source link if you have one. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..fc056e9 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,18 @@ +## What does this PR add? + + + +## Checklist + +- [ ] My changes are only inside `projects//` +- [ ] My project has a README (from `projects/PROJECT_TEMPLATE.md`) +- [ ] No passwords, API keys, personal data or real target addresses +- [ ] Any scanning/testing feature is for authorized targets only +- [ ] I tested it + +## How did you test it? + + + +--- + diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml new file mode 100644 index 0000000..19bc8c0 --- /dev/null +++ b/.github/workflows/pdf.yml @@ -0,0 +1,114 @@ +name: Course PDF + +# • Pull request → builds a preview PDF (download it from the run's "Artifacts") +# • Merge to main → updates the "latest" release with the new PDF +# • Every 1 January (or run by hand) → saves a yearly edition, e.g. "2027 Edition" +# +# Download link that never changes: +# https://github.com///releases/download/latest/network-security-lab.pdf + +on: + pull_request: + branches: [main] + push: + branches: [main] + schedule: + - cron: "10 0 1 1 *" # 1 January, 00:10 UTC + workflow_dispatch: + inputs: + edition: + description: "Edition name (leave empty for ' Edition')" + required: false + +concurrency: + group: pdf-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # full history → growth chart in the PDF + + - name: Skip PRs that don't touch the course + id: scope + run: | + if [ "${{ github.event_name }}" != "pull_request" ]; then + echo "build=true" >> "$GITHUB_OUTPUT"; exit 0 + fi + if git diff --name-only "${{ github.event.pull_request.base.sha }}...HEAD" \ + | grep -qE '^(lessons/|projects/|course.yml|scripts/)'; then + echo "build=true" >> "$GITHUB_OUTPUT" + else + echo "No course changes — no preview needed." + echo "build=false" >> "$GITHUB_OUTPUT" + fi + + - uses: actions/setup-python@v5 + if: steps.scope.outputs.build == 'true' + with: + python-version: "3.12" + + - name: Install + if: steps.scope.outputs.build == 'true' + run: | + sudo apt-get update -q + sudo apt-get install -y -q libpango-1.0-0 libpangoft2-1.0-0 fonts-noto-core fonts-dejavu-core + pip install -r scripts/requirements.txt + + - name: Pick edition name + if: steps.scope.outputs.build == 'true' + id: ed + run: | + case "${{ github.event_name }}" in + schedule) echo "name=$(date +%Y) Edition" >> "$GITHUB_OUTPUT" ;; + workflow_dispatch) n="${{ github.event.inputs.edition }}"; echo "name=${n:-$(date +%Y) Edition}" >> "$GITHUB_OUTPUT" ;; + pull_request) echo "name=Preview — PR #${{ github.event.number }}" >> "$GITHUB_OUTPUT" ;; + *) echo "name=Latest edition" >> "$GITHUB_OUTPUT" ;; + esac + + - name: Build PDF + if: steps.scope.outputs.build == 'true' + run: python scripts/build_pdf.py --edition "${{ steps.ed.outputs.name }}" + + # ── PR: preview only ── + - name: Upload preview + if: github.event_name == 'pull_request' && steps.scope.outputs.build == 'true' + uses: actions/upload-artifact@v4 + with: + name: course-pdf-preview + path: dist/network-security-lab.pdf + retention-days: 14 + + # ── main: refresh the "latest" release ── + - name: Update latest release + if: github.event_name == 'push' + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release delete latest --cleanup-tag --yes 2>/dev/null || true + gh release create latest dist/network-security-lab.pdf \ + --target "${{ github.sha }}" \ + --title "Course PDF — latest" \ + --notes "Auto-built from \`${{ github.sha }}\` on $(date -u +'%d %b %Y'). Lessons not written yet are marked *Coming soon*." \ + --latest + + # ── yearly edition ── + - name: Save yearly edition + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + env: + GH_TOKEN: ${{ github.token }} + EDITION: ${{ steps.ed.outputs.name }} + run: | + TAG="edition-$(echo "$EDITION" | tr '[:upper:] ' '[:lower:]-' | tr -cd 'a-z0-9-')" + cp dist/network-security-lab.pdf "dist/network-security-lab-${TAG#edition-}.pdf" + gh release delete "$TAG" --cleanup-tag --yes 2>/dev/null || true + gh release create "$TAG" "dist/network-security-lab-${TAG#edition-}.pdf" \ + --target "${{ github.sha }}" \ + --title "Course PDF — $EDITION" \ + --notes "Snapshot of the course on $(date -u +'%d %b %Y')." \ + --latest=false diff --git a/.github/workflows/protect-lessons.yml b/.github/workflows/protect-lessons.yml new file mode 100644 index 0000000..9fc92fa --- /dev/null +++ b/.github/workflows/protect-lessons.yml @@ -0,0 +1,51 @@ +name: Protect lessons + +# Contributors may only change files inside projects/. +# Pull requests from maintainers are allowed to change anything. + +on: + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + check-paths: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Only projects/ can be changed by contributors + env: + AUTHOR: ${{ github.event.pull_request.user.login }} + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + run: | + # Add more maintainers separated by spaces. + MAINTAINERS="Muawiya-contact" + + for m in $MAINTAINERS; do + if [ "${AUTHOR,,}" = "${m,,}" ]; then + echo "Maintainer PR ($AUTHOR) — skipping check." + exit 0 + fi + done + + CHANGED=$(git diff --name-only "$BASE...$HEAD") + echo "Changed files:" + echo "$CHANGED" + + BLOCKED=$(echo "$CHANGED" | grep -Ev '^projects/' || true) + + if [ -n "$BLOCKED" ]; then + echo "::error::Contributors can only change files inside projects/." + echo "These files are not allowed in your PR:" + echo "$BLOCKED" + echo "Want to suggest a lesson fix? Open a 'Lesson feedback' issue instead." + exit 1 + fi + + echo "All changes are inside projects/ — OK." diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..d1a3f4a --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,33 @@ +name: Check course + +# Runs on every PR, for everyone (maintainer too). +# If the PR doesn't touch lessons/, projects/, course.yml or ROADMAP.md +# the check passes straight away. +# +# Note: no "paths:" filter on purpose — if this check is "required", +# a filtered-out PR would wait forever for it. + +on: + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + check-course: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install + run: pip install pyyaml + + - name: Check lessons, projects and roadmap + run: python scripts/validate.py --base "${{ github.event.pull_request.base.sha }}" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f60ee09 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +dist/ +__pycache__/ +*.pyc +.venv/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 71138c4..5098838 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,6 +12,22 @@ Thanks for helping! Please read this before opening a pull request. **Contributors cannot change lesson files** (or anything outside `projects/`). A check runs on every pull request. If your PR changes files outside `projects/`, it will fail and can't be merged. +## Automatic checks on every PR + +| Check | What it looks at | +| ----- | ---------------- | +| **Protect lessons** | Contributors only changed files in `projects/` | +| **Check course** | Lesson names and folders match `course.yml` · required sections are there and in order · links and images work · `ROADMAP.md` is up to date · project folder name and README sections · no secrets or huge files | +| **Course PDF** | Builds a preview PDF — download it from the PR's check run (Artifacts) | + +PRs that don't touch lessons, projects or the roadmap pass straight away. +Run the same check on your computer before you push: + +```bash +pip install -r scripts/requirements.txt +python scripts/validate.py +``` + --- ## 1. Adding a project @@ -19,6 +35,7 @@ A check runs on every pull request. If your PR changes files outside `projects/` 1. Fork the repo. 2. Create a new folder: `projects/your-project-name/` (lowercase, use `-` between words). 3. Add a `README.md` inside it using the [project template](projects/PROJECT_TEMPLATE.md). + Required sections: What it does · How to run · How I tested it · Safety note, plus the `**Author:**` line. 4. Add your code in the same folder. 5. Open a pull request. diff --git a/LESSON_TEMPLATE.md b/LESSON_TEMPLATE.md index 7546406..0ab595b 100644 --- a/LESSON_TEMPLATE.md +++ b/LESSON_TEMPLATE.md @@ -1,10 +1,21 @@ # Lesson title > **Phase:** 01 — Networking Fundamentals -> **Module:** TCP/IP +> **Module:** TCP/IP and IP Addressing > **Lesson:** 01 > **Tested on:** (OS / tool version, if relevant) + + ## Objective What will you learn today? (1–2 lines) @@ -21,7 +32,6 @@ Real, easy-to-follow examples. Add a diagram if it helps. ```bash # command — what it does ``` -(Skip this section if the topic has no commands.) ## Practical work A safe exercise you can do on your own machine or lab. @@ -39,6 +49,3 @@ How this topic connects to attacks or defense. ## References - [Official source](https://example.com) - ---- -*Not every lesson needs every section. Fit the lesson to the topic.* diff --git a/README.md b/README.md index bdb8473..95d1822 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,24 @@ Every lesson is small, focused on one topic, and has a practical exercise. One lesson = one topic. A new lesson is added about once a day. ``` +course.yml → the course plan (source of the roadmap) +ROADMAP.md → generated from course.yml lessons/ → the course (written by the maintainer) 01-networking-fundamentals/ 01-tcp-ip/ 01-what-is-an-ip-address.md + code/01-what-is-an-ip-address/ → practice code for that lesson + assets/ → images projects/ → projects built by the community +scripts/ → checks, roadmap and PDF builders ``` +## Download the course as a PDF + +📘 **[Download the latest PDF](../../releases/download/latest/network-security-lab.pdf)** + +The PDF is rebuilt automatically every time something is merged. It has every published lesson, "Coming soon" for the rest, clickable links to each lesson, its practice code and the community projects on GitHub, and a progress page showing how the course grows. A yearly edition is saved every 1 January in [Releases](../../releases). + ## Where to start 1. Read the [Roadmap](ROADMAP.md) to see what's coming. diff --git a/ROADMAP.md b/ROADMAP.md index bfb58ca..973d119 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,25 +1,31 @@ # Learning Roadmap -✅ = published · ⬜ = not yet written + -Phases 00–02 are active now. Later phases are planned and may change as the course grows. +**Progress: 0 / 78 lessons published** + +✅ = published · ⬜ = coming soon --- ## 00 — Getting Started +### Introduction - ⬜ What is computer networking? - ⬜ What is cybersecurity? - ⬜ What is ethical hacking? - ⬜ Security vs hacking — what's the difference? - ⬜ Legal boundaries and responsible disclosure + +### Lab Setup - ⬜ Setting up a personal learning environment - ⬜ Understanding virtual machines - ⬜ Building an isolated practice network ## 01 — Networking Fundamentals -### TCP/IP and IP addressing +### TCP/IP and IP Addressing - ⬜ What is an IP address? - ⬜ IPv4 and IPv6 - ⬜ Public and private IP addresses @@ -52,7 +58,7 @@ Phases 00–02 are active now. Later phases are planned and may change as the co - ⬜ TLS certificates - ⬜ The TLS handshake -### Routing and switching +### Routing and Switching - ⬜ What is routing? - ⬜ What is switching? - ⬜ Routers vs switches @@ -77,7 +83,7 @@ Phases 00–02 are active now. Later phases are planned and may change as the co ## 02 — Linux Fundamentals -### Command line +### Command Line - ⬜ Terminal and shell - ⬜ Navigating directories - ⬜ Working with files and directories @@ -86,21 +92,21 @@ Phases 00–02 are active now. Later phases are planned and may change as the co - ⬜ Environment variables - ⬜ Basic system information -### Filesystem and permissions +### Filesystem and Permissions - ⬜ Linux filesystem hierarchy - ⬜ Users and groups - ⬜ File permissions - ⬜ chmod and chown - ⬜ sudo and root -### Processes and services +### Processes and Services - ⬜ Understanding processes - ⬜ Process management and signals - ⬜ systemd basics - ⬜ Managing services - ⬜ Viewing system logs -### Bash scripting +### Bash Scripting - ⬜ Variables - ⬜ Conditions - ⬜ Loops @@ -108,7 +114,7 @@ Phases 00–02 are active now. Later phases are planned and may change as the co - ⬜ Automating repetitive tasks - ⬜ Log processing scripts -### Package management +### Package Management - ⬜ Package managers - ⬜ Installing, updating and removing software - ⬜ Repositories and trusted sources @@ -128,6 +134,7 @@ OSINT · passive vs active recon · domain and DNS research · WHOIS · subdomai ### 06 — Scanning and Enumeration Host discovery · port scanning · TCP/UDP scans · service detection · Nmap · Netcat · directory enumeration · Gobuster · Nikto · false positives + > All scanning is done only on your own systems or authorized labs. ### 07 — Network and System Security @@ -135,10 +142,12 @@ Common attacks and defenses · packet sniffing · Wireshark · segmentation · L ### 08 — Web Security Cookies and sessions · same-origin policy · CORS · input validation · XSS · SQL injection · CSRF · broken access control · misconfiguration · file uploads · API security · Burp Suite · secure coding + > Follows the current OWASP Top 10. ### 09 — Vulnerability Assessment and Controlled Exploitation CVEs and CVSS · security advisories · exploit concepts · Metasploit basics · shells and payloads · safe proof-of-concept · privilege escalation basics · cleaning up labs + > Only on intentionally vulnerable machines or with explicit permission. ### 10 — Reporting diff --git a/course.yml b/course.yml new file mode 100644 index 0000000..c829f3f --- /dev/null +++ b/course.yml @@ -0,0 +1,242 @@ +# ───────────────────────────────────────────────────────────── +# Network Security Lab — course structure (single source of truth) +# +# Everything is built from this file: +# • ROADMAP.md → python scripts/build_roadmap.py +# • PR checks → python scripts/validate.py +# • the course PDF → python scripts/build_pdf.py +# +# Lesson file path = lessons/-/-/-.md +# Example: lessons/01-networking-fundamentals/01-tcp-ip/01-what-is-an-ip-address.md +# +# Rules: +# • id = two digits ("01", "02" ...). Order in this file = order in the course. +# • slug = lowercase letters, numbers and "-" only. +# • To add a lesson to the roadmap: add a line here, then run build_roadmap.py. +# • A lesson is "done" when its .md file exists. No manual ticking needed. +# ───────────────────────────────────────────────────────────── + +title: Network Security Lab +subtitle: Learn networking. Understand security. Think like a security engineer. + +phases: + - id: "00" + slug: getting-started + title: Getting Started + modules: + - id: "01" + slug: introduction + title: Introduction + lessons: + - { id: "01", slug: what-is-computer-networking, title: "What is computer networking?" } + - { id: "02", slug: what-is-cybersecurity, title: "What is cybersecurity?" } + - { id: "03", slug: what-is-ethical-hacking, title: "What is ethical hacking?" } + - { id: "04", slug: security-vs-hacking, title: "Security vs hacking — what's the difference?" } + - { id: "05", slug: legal-boundaries-and-disclosure, title: "Legal boundaries and responsible disclosure" } + - id: "02" + slug: lab-setup + title: Lab Setup + lessons: + - { id: "01", slug: personal-learning-environment, title: "Setting up a personal learning environment" } + - { id: "02", slug: virtual-machines, title: "Understanding virtual machines" } + - { id: "03", slug: isolated-practice-network, title: "Building an isolated practice network" } + + - id: "01" + slug: networking-fundamentals + title: Networking Fundamentals + modules: + - id: "01" + slug: tcp-ip + title: TCP/IP and IP Addressing + lessons: + - { id: "01", slug: what-is-an-ip-address, title: "What is an IP address?" } + - { id: "02", slug: ipv4-and-ipv6, title: "IPv4 and IPv6" } + - { id: "03", slug: public-and-private-ip, title: "Public and private IP addresses" } + - { id: "04", slug: mac-addresses, title: "MAC addresses" } + - { id: "05", slug: subnet-masks, title: "Subnet masks" } + - { id: "06", slug: cidr-notation, title: "CIDR notation" } + - { id: "07", slug: default-gateways, title: "Default gateways" } + - { id: "08", slug: tcp-vs-udp, title: "TCP vs UDP" } + - { id: "09", slug: ports-and-sockets, title: "Ports and sockets" } + - { id: "10", slug: osi-model, title: "The OSI model" } + - { id: "11", slug: tcp-ip-model, title: "The TCP/IP model" } + - { id: "12", slug: arp-and-icmp, title: "ARP and ICMP" } + - id: "02" + slug: dns + title: DNS + lessons: + - { id: "01", slug: what-is-dns, title: "What is DNS?" } + - { id: "02", slug: how-dns-resolution-works, title: "How DNS resolution works" } + - { id: "03", slug: dns-records, title: "DNS records: A, AAAA, CNAME, MX, TXT, NS" } + - { id: "04", slug: recursive-and-authoritative, title: "Recursive and authoritative servers" } + - { id: "05", slug: dns-caching-and-ttl, title: "DNS caching and TTL" } + - { id: "06", slug: doh-and-dot, title: "DNS over HTTPS and DNS over TLS" } + - { id: "07", slug: dns-troubleshooting, title: "Basic DNS troubleshooting" } + - id: "03" + slug: http-https + title: HTTP and HTTPS + lessons: + - { id: "01", slug: how-the-web-works, title: "How the web works" } + - { id: "02", slug: http-requests-and-responses, title: "HTTP requests and responses" } + - { id: "03", slug: http-methods, title: "HTTP methods" } + - { id: "04", slug: status-codes, title: "Status codes" } + - { id: "05", slug: headers, title: "Headers" } + - { id: "06", slug: https-and-tls, title: "HTTPS and TLS" } + - { id: "07", slug: tls-certificates, title: "TLS certificates" } + - { id: "08", slug: tls-handshake, title: "The TLS handshake" } + - id: "04" + slug: routing-switching + title: Routing and Switching + lessons: + - { id: "01", slug: what-is-routing, title: "What is routing?" } + - { id: "02", slug: what-is-switching, title: "What is switching?" } + - { id: "03", slug: routers-vs-switches, title: "Routers vs switches" } + - { id: "04", slug: routing-tables, title: "Routing tables and default routes" } + - { id: "05", slug: static-and-dynamic-routing, title: "Static and dynamic routing" } + - { id: "06", slug: nat-and-pat, title: "NAT and PAT" } + - { id: "07", slug: vlan-basics, title: "VLAN basics" } + - id: "05" + slug: firewalls + title: Firewalls + lessons: + - { id: "01", slug: what-is-a-firewall, title: "What is a firewall?" } + - { id: "02", slug: packet-filtering, title: "Packet filtering" } + - { id: "03", slug: stateful-vs-stateless, title: "Stateful vs stateless firewalls" } + - { id: "04", slug: firewall-rules, title: "Firewall rules — inbound and outbound" } + - { id: "05", slug: host-vs-network-firewalls, title: "Host-based vs network firewalls" } + - { id: "06", slug: firewall-configuration, title: "Basic firewall configuration" } + - id: "06" + slug: vpns + title: VPNs + lessons: + - { id: "01", slug: what-is-a-vpn, title: "What is a VPN and why use one?" } + - { id: "02", slug: vpn-types, title: "Remote-access vs site-to-site VPNs" } + - { id: "03", slug: tunneling-and-encryption, title: "Tunneling and encryption" } + - { id: "04", slug: vpn-limits-and-myths, title: "VPN limits and common myths" } + + - id: "02" + slug: linux-fundamentals + title: Linux Fundamentals + modules: + - id: "01" + slug: command-line + title: Command Line + lessons: + - { id: "01", slug: terminal-and-shell, title: "Terminal and shell" } + - { id: "02", slug: navigating-directories, title: "Navigating directories" } + - { id: "03", slug: files-and-directories, title: "Working with files and directories" } + - { id: "04", slug: searching-files, title: "Searching files" } + - { id: "05", slug: pipes-and-redirection, title: "Pipes and redirection" } + - { id: "06", slug: environment-variables, title: "Environment variables" } + - { id: "07", slug: system-information, title: "Basic system information" } + - id: "02" + slug: filesystem-permissions + title: Filesystem and Permissions + lessons: + - { id: "01", slug: filesystem-hierarchy, title: "Linux filesystem hierarchy" } + - { id: "02", slug: users-and-groups, title: "Users and groups" } + - { id: "03", slug: file-permissions, title: "File permissions" } + - { id: "04", slug: chmod-and-chown, title: "chmod and chown" } + - { id: "05", slug: sudo-and-root, title: "sudo and root" } + - id: "03" + slug: processes-services + title: Processes and Services + lessons: + - { id: "01", slug: understanding-processes, title: "Understanding processes" } + - { id: "02", slug: process-management, title: "Process management and signals" } + - { id: "03", slug: systemd-basics, title: "systemd basics" } + - { id: "04", slug: managing-services, title: "Managing services" } + - { id: "05", slug: system-logs, title: "Viewing system logs" } + - id: "04" + slug: bash-scripting + title: Bash Scripting + lessons: + - { id: "01", slug: variables, title: "Variables" } + - { id: "02", slug: conditions, title: "Conditions" } + - { id: "03", slug: loops, title: "Loops" } + - { id: "04", slug: functions-and-arguments, title: "Functions and arguments" } + - { id: "05", slug: automating-tasks, title: "Automating repetitive tasks" } + - { id: "06", slug: log-processing, title: "Log processing scripts" } + - id: "05" + slug: package-management + title: Package Management + lessons: + - { id: "01", slug: package-managers, title: "Package managers" } + - { id: "02", slug: installing-and-updating, title: "Installing, updating and removing software" } + - { id: "03", slug: repositories-and-trust, title: "Repositories and trusted sources" } + + # ── Planned phases: no lessons yet. Add modules + lessons when you start a phase. ── + + - id: "03" + slug: programming-for-security + title: Programming for Security + summary: "Python (basics, files, errors, sockets, HTTP requests, JSON/APIs, network automation) · JavaScript (browser basics, DOM, requests, browser security) · SQL (queries, joins, permissions, SQL injection concepts, parameterized queries)" + modules: [] + + - id: "04" + slug: security-fundamentals + title: Security Fundamentals + summary: "CIA triad · threats, vulnerabilities and risk · attack surface · authentication vs authorization · MFA · access control · hashing vs encryption · symmetric and asymmetric crypto · digital signatures · certificates and PKI · patching · vulnerability management · least privilege · defense in depth" + modules: [] + + - id: "05" + slug: reconnaissance + title: Reconnaissance + summary: "OSINT · passive vs active recon · domain and DNS research · WHOIS · subdomain enumeration concepts · network discovery · recording findings responsibly" + modules: [] + + - id: "06" + slug: scanning-enumeration + title: Scanning and Enumeration + summary: "Host discovery · port scanning · TCP/UDP scans · service detection · Nmap · Netcat · directory enumeration · Gobuster · Nikto · false positives" + note: "All scanning is done only on your own systems or authorized labs." + modules: [] + + - id: "07" + slug: network-system-security + title: Network and System Security + summary: "Common attacks and defenses · packet sniffing · Wireshark · segmentation · Linux and Windows security · Active Directory basics · Wi-Fi security · SSH security · hardening · logging and monitoring" + modules: [] + + - id: "08" + slug: web-security + title: Web Security + summary: "Cookies and sessions · same-origin policy · CORS · input validation · XSS · SQL injection · CSRF · broken access control · misconfiguration · file uploads · API security · Burp Suite · secure coding" + note: "Follows the current OWASP Top 10." + modules: [] + + - id: "09" + slug: vulnerability-assessment + title: Vulnerability Assessment and Controlled Exploitation + summary: "CVEs and CVSS · security advisories · exploit concepts · Metasploit basics · shells and payloads · safe proof-of-concept · privilege escalation basics · cleaning up labs" + note: "Only on intentionally vulnerable machines or with explicit permission." + modules: [] + + - id: "10" + slug: reporting + title: Reporting + summary: "Writing a vulnerability report · evidence · severity and impact · remediation · retesting · a full assessment report" + modules: [] + + - id: "11" + slug: practice-platforms + title: Practice Platforms + summary: "TryHackMe · Hack The Box · PortSwigger Web Security Academy · VulnHub · CTFs · your own home lab" + modules: [] + + - id: "12" + slug: specialization + title: Choose a Specialization + summary: "Web app security · network security · Active Directory · cloud · wireless · reverse engineering · red teaming · DevSecOps · security engineering · security operations" + modules: [] + +project_ideas: + - Network information collector + - DNS lookup and analysis tool + - Firewall rule analyzer + - Linux security checker + - Network traffic / monitoring dashboard + - Log monitoring tool + - HTTP security header checker + - Subdomain inventory tool (authorized domains only) + - Security report generator diff --git a/lessons/README.md b/lessons/README.md index 2ca1eb8..eb9581a 100644 --- a/lessons/README.md +++ b/lessons/README.md @@ -2,18 +2,38 @@ The course, one topic per file. Start from `00-getting-started` and go in order. -Folder naming: +## Structure ``` -lessons/-/-/-.md +lessons/ + -/ + -/ + -.md ← the lesson + code/-/ ← practice code (optional) + assets/ ← images (optional) ``` Example: ``` lessons/01-networking-fundamentals/01-tcp-ip/01-what-is-an-ip-address.md +lessons/01-networking-fundamentals/01-tcp-ip/code/01-what-is-an-ip-address/show_ip.py ``` -See the full plan in [ROADMAP.md](../ROADMAP.md). +All ids, slugs and titles come from [`course.yml`](../course.yml). The file name must match exactly — the PR check will tell you the right name if it's wrong. + +## Adding a lesson (maintainer) + +1. Find the lesson in `course.yml`. If it's new, add a line there first. +2. Copy [`LESSON_TEMPLATE.md`](../LESSON_TEMPLATE.md) to the right path. +3. Write it. Required sections: Objective, Explanation, Check your understanding, References. +4. Run: + ```bash + pip install -r scripts/requirements.txt + python scripts/build_roadmap.py # updates ROADMAP.md + python scripts/validate.py # same check as the PR + python scripts/build_pdf.py # optional: preview the PDF in dist/ + ``` +5. Commit everything (lesson + ROADMAP.md) and open a PR. > Lessons are written by the maintainer. Found a problem? Open a "Lesson feedback" issue. diff --git a/projects/README.md b/projects/README.md index 83bdfa8..af5da52 100644 --- a/projects/README.md +++ b/projects/README.md @@ -2,8 +2,6 @@ Projects built by learners using what they learned in the course. -Want to add yours? Read [CONTRIBUTING.md](../CONTRIBUTING.md) and use the [project template](PROJECT_TEMPLATE.md). +Every project here is listed automatically in the course PDF, with a link back to its folder. -| Project | Author | Description | -| ------- | ------ | ----------- | -| *(none yet — be the first!)* | | | +Want to add yours? Read [CONTRIBUTING.md](../CONTRIBUTING.md) and copy the [project template](PROJECT_TEMPLATE.md) into `projects//README.md`. diff --git a/scripts/build_pdf.py b/scripts/build_pdf.py new file mode 100644 index 0000000..1fb3691 --- /dev/null +++ b/scripts/build_pdf.py @@ -0,0 +1,435 @@ +"""Build the full course as one PDF. + + python scripts/build_pdf.py # → dist/network-security-lab.pdf + python scripts/build_pdf.py --edition "2026 Edition" + python scripts/build_pdf.py --html # also save the HTML (for debugging) + +Written lessons are included in full. Missing lessons show "Coming soon". +Every lesson, code file and project links back to GitHub. +""" + +from __future__ import annotations + +import argparse +import datetime as dt +import html +import re +import subprocess +from collections import OrderedDict +from pathlib import Path + +import markdown + +from course import ROOT, github_url, load_course, load_projects, repo_slug + +OUT_DIR = ROOT / "dist" +PDF_NAME = "network-security-lab.pdf" + +ACADEMY_URL = "https://codingmoves.com/academy/" +LAB_URL = "https://codingmoves.com/lab/" +SITE_URL = "https://codingmoves.com/" + + +def esc(s: str) -> str: + return html.escape(s, quote=True) + + +# ───────────────────────── markdown → html ───────────────────────── + +MD_EXT = ["fenced_code", "tables", "codehilite", "sane_lists", "attr_list"] +MD_CFG = {"codehilite": {"guess_lang": False, "css_class": "hl"}} + + +def lesson_html(lesson) -> str: + text = lesson.path.read_text(encoding="utf-8").lstrip("") + # drop the title line and the info block — the PDF prints its own header + text = re.sub(r"\A#\s+.*\n", "", text) + text = re.sub(r"\A\s*(>.*\n)+", "", text) + body = markdown.markdown(text, extensions=MD_EXT, extension_configs=MD_CFG) + # lesson "## Section" becomes h4 under the lesson's h3 + for n in (3, 2, 1): + body = re.sub(rf"<(/?)h{n}([ >])", rf"<\1h{n + 2}\2", body) + return fix_links(body, lesson.path.parent) + + +def fix_links(body: str, base: Path) -> str: + """Relative links → GitHub URLs. Relative images → embedded local files.""" + + def href(m: re.Match) -> str: + url = m.group(2) + if re.match(r"^(https?:|mailto:|#)", url): + return m.group(0) + target = (base / url.split("#")[0]).resolve() + try: + rel = target.relative_to(ROOT).as_posix() + except ValueError: + return m.group(0) + return f'{m.group(1)}"{github_url(rel, folder=target.is_dir())}"' + + def src(m: re.Match) -> str: + url = m.group(2) + if re.match(r"^(https?:|data:)", url): + return m.group(0) + return f'{m.group(1)}"{(base / url).resolve().as_uri()}"' + + body = re.sub(r'(href=)"([^"]+)"', href, body) + body = re.sub(r'(src=)"([^"]+)"', src, body) + return body + + +# ───────────────────────── growth history (from git) ───────────────────────── + +def lesson_history(course) -> list[tuple[str, int, int]]: + """[(month, added that month, running total)] from git history.""" + known = {l.rel_path for l in course.lessons} + try: + out = subprocess.run( + ["git", "log", "--diff-filter=A", "--name-only", "--format=@%cs", "--reverse", "--", "lessons/"], + cwd=ROOT, capture_output=True, text=True, check=True, + ).stdout + except (subprocess.CalledProcessError, FileNotFoundError): + return [] + first_seen: dict[str, str] = {} + month = None + for line in out.splitlines(): + if line.startswith("@"): + month = line[1:8] + elif line.strip() in known and line.strip() not in first_seen and month: + first_seen[line.strip()] = month + # lessons that exist but aren't committed yet (local build) + this_month = dt.date.today().strftime("%Y-%m") + for l in course.lessons: + if l.done and l.rel_path not in first_seen: + first_seen[l.rel_path] = this_month + + per_month: OrderedDict[str, int] = OrderedDict() + for m in sorted(first_seen.values()): + per_month[m] = per_month.get(m, 0) + 1 + rows, total = [], 0 + for m, n in per_month.items(): + total += n + rows.append((m, n, total)) + return rows + + +# ───────────────────────── page sections ───────────────────────── + +def bar(pct: float) -> str: + return f'
' + + +def cover(course, projects, edition: str) -> str: + total = len(course.lessons) + done = sum(l.done for l in course.lessons) + pct = (done / total * 100) if total else 0 + today = dt.date.today().strftime("%d %B %Y") + return f""" +
+
CODING MOVES · LAB · ACADEMY
+

{esc(course.title)}

+

{esc(course.subtitle)}

+
+
{done}of {total} lessons
+
{pct:.0f}%complete
+
{len(projects)}community projects
+
+ {bar(pct)} +
+

{esc(edition)} · generated {today}

+

Source: github.com/{repo_slug()}

+

Course: codingmoves.com/academy · Lab: codingmoves.com/lab

+
+

This book grows with the project. Lessons not written yet are marked + Coming soon. Download the newest version any time from the + latest release.

+
""" + + +def progress_page(course, projects) -> str: + rows = [] + for p in course.phases: + t = len(p.lessons) + d = sum(l.done for l in p.lessons) + pct = (d / t * 100) if t else 0 + status = "Planned" if p.planned else f"{d} / {t}" + rows.append( + f"{p.id}{esc(p.title)}" + f"{status}{bar(pct) if t else ''}" + ) + + hist = lesson_history(course) + if hist: + peak = max(n for _, n, _ in hist) + hrows = "".join( + f"{dt.datetime.strptime(m, '%Y-%m').strftime('%b %Y')}" + f"+{n}{tot}" + f"{bar(n / peak * 100)}" + for m, n, tot in hist + ) + growth = f""" +

Growth

+

New lessons published each month.

+ +{hrows}
MonthAddedTotal
""" + else: + growth = "" + + return f""" +
+

Progress

+ +{''.join(rows)}
#PhaseLessons
+

Community projects: {len(projects)}

+{growth} +
""" + + +def toc(course, has_projects: bool) -> str: + items = [] + for p in course.phases: + cls = "planned" if p.planned else "" + items.append(f'
  • {p.id} — {esc(p.title)}
  • ') + for m in p.modules: + items.append(f'
  • {esc(m.title)}
  • ') + items.append('
  • Community Projects
  • ') + return f""" +
    +

    Contents

    + +
    """ + + +RESPONSIBLE = """ +
    +

    Responsible use

    +

    This course is for learning, defense and authorized testing only.

    +

    Do every exercise on systems you own, on intentionally vulnerable practice labs, or on systems +where you have written permission. Never scan, attack or access systems you are not allowed to.

    +

    Learning security also means learning responsibility.

    +

    How to read this book

    +
      +
    • Each lesson is one topic. Go in order.
    • +
    • Every lesson has a View on GitHub link to its source file.
    • +
    • Practice code is listed under each lesson — click a file to open it on GitHub.
    • +
    • Found a mistake? Open a "Lesson feedback" issue on GitHub.
    • +
    +
    """ + + +def code_files(lesson) -> list[str]: + d = ROOT / lesson.code_rel_dir + if not d.is_dir(): + return [] + return sorted(p.relative_to(ROOT).as_posix() for p in d.rglob("*") if p.is_file() and p.name != ".gitkeep") + + +def lesson_block(lesson) -> str: + head = ( + f'
    Lesson {lesson.phase.id}.{lesson.module.id}.{lesson.id}' + f" · {esc(lesson.module.title)}
    " + f'

    {esc(lesson.title)}

    ' + ) + if not lesson.done: + return f""" +
    {head} +
    Coming soon +This lesson isn't written yet. Follow progress on +GitHub.
    +
    """ + + links = [f'View on GitHub'] + files = code_files(lesson) + code_list = "" + if files: + lis = "".join( + f'
  • {esc(f.split("/code/", 1)[1].split("/", 1)[1])}
  • ' for f in files + ) + code_list = f'
    Practice code — click to open on GitHub
      {lis}
    ' + return f""" +
    {head} + +{lesson_html(lesson)} +{code_list} +
    """ + + +def phase_block(p) -> str: + out = [f'
    Phase {p.id}
    ' + f'

    {esc(p.title)}

    '] + if p.planned: + out.append('
    Coming soon This phase is planned.
    ') + if p.summary: + out.append(f'

    What it will cover: {esc(p.summary)}

    ') + if p.note: + out.append(f'

    {esc(p.note)}

    ') + out.append("
    ") + return "".join(out) + + d, t = sum(l.done for l in p.lessons), len(p.lessons) + out.append(f'

    {d} of {t} lessons published

    ') + for m in p.modules: + out.append(f'

    {esc(m.title)}

    ') + out.append('
      ' + "".join( + f'
    1. {esc(l.title)}' + f'{"" if l.done else " soon"}
    2. ' + for l in m.lessons) + "
    ") + for l in m.lessons: + out.append(lesson_block(l)) + out.append("") + return "".join(out) + + +def projects_block(course, projects) -> str: + out = ['
    Community
    ' + '

    Community Projects

    '] + if projects: + for pr in projects: + author = f' · by {esc(pr.author)}' if pr.author else "" + out.append( + f'

    {esc(pr.title)}

    ' + f'

    projects/{esc(pr.slug)}{author}

    ' + f'

    {esc(pr.summary)}

    ' + f'Open project on GitHub
    ' + ) + else: + out.append('
    Coming soon ' + 'No community projects yet — be the first!
    ') + if course.project_ideas: + out.append("

    Project ideas

      " + "".join(f"
    1. {esc(i)}
    2. " for i in course.project_ideas) + "
    ") + out.append(f'

    Want to add a project? Read ' + f'CONTRIBUTING.md.

    ') + return "".join(out) + + +# ───────────────────────── css ───────────────────────── + +def css() -> str: + from pygments.formatters import HtmlFormatter + pyg = HtmlFormatter(style="friendly").get_style_defs(".hl") + return """ +@page { size: A4; margin: 22mm 18mm 20mm 18mm; + @bottom-left { content: "Network Security Lab · Coding Moves"; font-size: 8pt; color: #8a94a6; } + @bottom-right { content: counter(page); font-size: 8pt; color: #8a94a6; } } +@page :first { margin: 0; @bottom-left { content: none } @bottom-right { content: none } } +:root { --ink:#0f172a; --muted:#64748b; --line:#e2e8f0; --accent:#0e7490; --accent-soft:#ecfeff; --soon:#b45309; --soon-soft:#fffbeb; } +body { margin: 0; } +html { font-family: "Noto Sans", "DejaVu Sans", sans-serif; font-size: 10pt; color: var(--ink); line-height: 1.55; } +a { color: var(--accent); text-decoration: none; } +h1,h2,h3,h4 { line-height: 1.25; } +code, pre { font-family: "DejaVu Sans Mono", monospace; font-size: 8.6pt; } +p code, li code { background:#f1f5f9; padding: 0 3px; border-radius: 3px; } +pre { background:#f8fafc; border:1px solid var(--line); border-radius:6px; padding:8px 10px; white-space: pre-wrap; } +table { border-collapse: collapse; width: 100%; margin: 8px 0; } +th, td { border-bottom: 1px solid var(--line); padding: 4px 6px; text-align: left; vertical-align: middle; } +th { font-size: 8.5pt; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; } +.num { white-space: nowrap; width: 1%; } +.barcell { width: 35%; } +.muted { color: var(--muted); } + +/* cover */ +.cover { page: first; height: 297mm; padding: 38mm 22mm 0; box-sizing: border-box; + background: #0f172a; color: #e2e8f0; page-break-after: always; } +.cover a { color: #67e8f9; } +.brand { letter-spacing: .25em; font-size: 9pt; color: #67e8f9; font-weight: bold; } +.cover-title { font-size: 34pt; margin: 14mm 0 4mm; color: #fff; bookmark-level: none; } +.cover-sub { font-size: 13pt; color: #cbd5e1; margin: 0 0 16mm; } +.cover-stats { display: flex; gap: 10mm; margin-bottom: 5mm; } +.stat b { display:block; font-size: 22pt; color:#fff; } +.stat span { font-size: 9pt; color:#94a3b8; } +.cover .bar { background:#1e293b; } +.cover-meta { margin-top: 14mm; font-size: 9.5pt; color:#cbd5e1; } +.cover-meta p { margin: 2px 0; } +.cover-note { margin-top: 18mm; font-size: 9pt; color:#94a3b8; max-width: 140mm; } + +.bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; } +.fill { height: 100%; background: var(--accent); } + +.page { page-break-after: always; } +h2.plain, h3.plain { bookmark-level: none; } +.page h2.plain { font-size: 18pt; margin-top: 0; } +#progress, #responsible { bookmark-level: 1; } + +/* toc */ +.toc { list-style: none; padding: 0; } +.toc li { margin: 2px 0; } +.toc li a::after { content: leader('.') target-counter(attr(href), page); color: var(--muted); } +.toc li a { color: var(--ink); display: block; } +.toc li.mod { padding-left: 8mm; font-size: 9pt; } +.toc li.mod a { color: var(--muted); } +.toc li.planned a { color: var(--muted); } + +/* phases */ +.phase { page-break-before: always; } +.phase-num { color: var(--accent); font-weight: bold; letter-spacing: .15em; text-transform: uppercase; font-size: 9pt; } +.phase h1 { font-size: 24pt; margin: 2px 0 4px; bookmark-level: 1; } +.phase > h2 { font-size: 15pt; border-bottom: 2px solid var(--accent); padding-bottom: 3px; margin-top: 10mm; bookmark-level: 2; } +.mod-list li.todo { color: var(--muted); } +.summary { margin-top: 6mm; } +.note { border-left: 3px solid var(--soon); padding-left: 8px; color: var(--soon); } + +/* lessons */ +.lesson { margin-top: 8mm; padding-top: 4mm; border-top: 1px solid var(--line); } +.lesson:not(.soon) { page-break-before: always; border-top: none; } +.lesson-kicker { color: var(--muted); font-size: 8.5pt; text-transform: uppercase; letter-spacing: .06em; } +.lesson h3 { font-size: 15pt; margin: 2px 0 6px; bookmark-level: 3; } +.lesson.soon h3 { font-size: 11.5pt; color: var(--muted); } +.lesson h4 { font-size: 11.5pt; color: var(--accent); margin: 6mm 0 2mm; bookmark-level: none; } +.lesson h5, .lesson h6 { bookmark-level: none; } +.links { margin-bottom: 4mm; } +.btn { display: inline-block; border: 1px solid var(--accent); border-radius: 4px; padding: 2px 8px; font-size: 8.5pt; margin-right: 4px; } +.soon-tag { display: inline-block; background: var(--soon-soft); color: var(--soon); border: 1px solid #fcd34d; + border-radius: 3px; font-size: 7.5pt; padding: 0 5px; font-weight: bold; text-transform: uppercase; letter-spacing: .04em; } +.soon-box { background: var(--soon-soft); border: 1px dashed #fcd34d; border-radius: 6px; padding: 6px 10px; font-size: 9pt; } +.soon-box.big { padding: 12px 14px; font-size: 10pt; margin-top: 6mm; } +.code-box { background: var(--accent-soft); border: 1px solid #a5f3fc; border-radius: 6px; padding: 6px 10px; margin-top: 6mm; font-size: 9pt; } +.code-box ul { margin: 4px 0 0; } +img { max-width: 100%; } + +/* projects */ +.project { border: 1px solid var(--line); border-radius: 6px; padding: 8px 12px; margin: 5mm 0; } +.project h3 { margin: 0; bookmark-level: 2; } +""" + pyg + + +# ───────────────────────── main ───────────────────────── + +def build(edition: str, save_html: bool) -> Path: + course = load_course() + if course.errors: + raise SystemExit("course.yml has errors — run python scripts/validate.py") + projects = load_projects() + + body = ( + cover(course, projects, edition) + + toc(course, bool(projects)) + + progress_page(course, projects) + + RESPONSIBLE + + "".join(phase_block(p) for p in course.phases) + + projects_block(course, projects) + ) + doc = f""" +{esc(course.title)} +{body}""" + + OUT_DIR.mkdir(exist_ok=True) + if save_html: + (OUT_DIR / "course.html").write_text(doc, encoding="utf-8") + + from weasyprint import HTML + out = OUT_DIR / PDF_NAME + HTML(string=doc, base_url=str(ROOT)).write_pdf(out) + done = sum(l.done for l in course.lessons) + print(f"Wrote {out.relative_to(ROOT)} — {done}/{len(course.lessons)} lessons, {len(projects)} projects") + return out + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--edition", default="Latest edition") + ap.add_argument("--html", action="store_true") + a = ap.parse_args() + build(a.edition, a.html) diff --git a/scripts/build_roadmap.py b/scripts/build_roadmap.py new file mode 100644 index 0000000..7092340 --- /dev/null +++ b/scripts/build_roadmap.py @@ -0,0 +1,86 @@ +"""Generate ROADMAP.md from course.yml. + +Usage: + python scripts/build_roadmap.py # write ROADMAP.md + python scripts/build_roadmap.py --check # fail if ROADMAP.md is out of date +""" + +from __future__ import annotations + +import sys + +from course import ROOT, load_course + +OUT = ROOT / "ROADMAP.md" + + +def render() -> str: + c = load_course() + total = len(c.lessons) + done = sum(l.done for l in c.lessons) + + lines = [ + "# Learning Roadmap", + "", + "", + "", + f"**Progress: {done} / {total} lessons published**", + "", + "✅ = published · ⬜ = coming soon", + "", + "---", + "", + ] + + active = [p for p in c.phases if not p.planned] + planned = [p for p in c.phases if p.planned] + + for p in active: + lines.append(f"## {p.id} — {p.title}") + lines.append("") + for m in p.modules: + lines.append(f"### {m.title}") + for l in m.lessons: + if l.done: + lines.append(f"- ✅ [{l.title}]({l.rel_path})") + else: + lines.append(f"- ⬜ {l.title}") + lines.append("") + + if planned: + lines += ["---", "", "## Planned phases", ""] + for p in planned: + lines.append(f"### {p.id} — {p.title}") + if p.summary: + lines.append(p.summary) + if p.note: + lines += ["", f"> {p.note}"] + lines.append("") + + if c.project_ideas: + lines += ["---", "", "## Project ideas", "", + "Community projects live in [`projects/`](projects/). Some ideas to start:", ""] + for i, idea in enumerate(c.project_ideas, 1): + lines.append(f"{i}. {idea}") + lines += ["", "Have your own idea? Add it through a pull request — see [CONTRIBUTING.md](CONTRIBUTING.md).", ""] + + return "\n".join(lines) + + +def main() -> int: + text = render() + if "--check" in sys.argv: + current = OUT.read_text(encoding="utf-8") if OUT.exists() else "" + if current != text: + print("ROADMAP.md is out of date. Run: python scripts/build_roadmap.py") + return 1 + print("ROADMAP.md is up to date.") + return 0 + OUT.write_text(text, encoding="utf-8") + print(f"Wrote {OUT.relative_to(ROOT)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/course.py b/scripts/course.py new file mode 100644 index 0000000..99bc60b --- /dev/null +++ b/scripts/course.py @@ -0,0 +1,255 @@ +"""Shared helpers: load course.yml and work out lesson / project paths.""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass, field +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parent.parent +LESSONS_DIR = ROOT / "lessons" +PROJECTS_DIR = ROOT / "projects" +COURSE_FILE = ROOT / "course.yml" + +SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") +ID_RE = re.compile(r"^\d{2}$") + +# Sections a lesson MUST have (as "## Heading"). +LESSON_REQUIRED = [ + "Objective", + "Explanation", + "Check your understanding", + "References", +] +# All sections a lesson MAY have, in this order. +LESSON_ALLOWED = [ + "Objective", + "Explanation", + "How it works", + "Examples", + "Commands", + "Practical work", + "Common mistakes", + "Why it matters for security", + "Check your understanding", + "References", +] + +# Sections a project README MUST have. +PROJECT_REQUIRED = [ + "What it does", + "How to run", + "How I tested it", + "Safety note", +] + + +def repo_slug() -> str: + return os.environ.get("GITHUB_REPOSITORY", "Muawiya-contact/network-security-lab") + + +def branch() -> str: + return os.environ.get("COURSE_BRANCH", "main") + + +def github_url(rel_path: str, folder: bool = False) -> str: + kind = "tree" if folder else "blob" + return f"https://github.com/{repo_slug()}/{kind}/{branch()}/{rel_path}" + + +@dataclass +class Lesson: + id: str + slug: str + title: str + phase: "Phase" + module: "Module" + + @property + def rel_path(self) -> str: + return f"lessons/{self.phase.dirname}/{self.module.dirname}/{self.id}-{self.slug}.md" + + @property + def path(self) -> Path: + return ROOT / self.rel_path + + @property + def code_rel_dir(self) -> str: + """Practice code for a lesson lives next to it: /code/-/""" + return f"lessons/{self.phase.dirname}/{self.module.dirname}/code/{self.id}-{self.slug}" + + @property + def done(self) -> bool: + return self.path.is_file() + + +@dataclass +class Module: + id: str + slug: str + title: str + phase: "Phase" + lessons: list[Lesson] = field(default_factory=list) + + @property + def dirname(self) -> str: + return f"{self.id}-{self.slug}" + + +@dataclass +class Phase: + id: str + slug: str + title: str + summary: str = "" + note: str = "" + modules: list[Module] = field(default_factory=list) + + @property + def dirname(self) -> str: + return f"{self.id}-{self.slug}" + + @property + def planned(self) -> bool: + return not any(m.lessons for m in self.modules) + + @property + def lessons(self) -> list[Lesson]: + return [l for m in self.modules for l in m.lessons] + + +@dataclass +class Course: + title: str + subtitle: str + phases: list[Phase] + project_ideas: list[str] + errors: list[str] + + @property + def lessons(self) -> list[Lesson]: + return [l for p in self.phases for l in p.lessons] + + +def _check_item(kind: str, item: dict, where: str, errors: list[str]) -> bool: + ok = True + for key in ("id", "slug", "title"): + if not item.get(key): + errors.append(f"course.yml: {kind} at {where} is missing '{key}'") + ok = False + if not ok: + return False + if not ID_RE.match(str(item["id"])): + errors.append(f"course.yml: {kind} '{item['title']}' id must be two digits like \"01\" (got {item['id']!r}). Put it in quotes.") + ok = False + if not SLUG_RE.match(str(item["slug"])): + errors.append(f"course.yml: {kind} '{item['title']}' slug '{item['slug']}' must be lowercase-words-with-dashes") + ok = False + return ok + + +def load_course() -> Course: + data = yaml.safe_load(COURSE_FILE.read_text(encoding="utf-8")) or {} + errors: list[str] = [] + phases: list[Phase] = [] + + seen_phase_ids: set[str] = set() + for p in data.get("phases") or []: + if not _check_item("phase", p, "top level", errors): + continue + pid = str(p["id"]) + if pid in seen_phase_ids: + errors.append(f"course.yml: phase id {pid} is used twice") + seen_phase_ids.add(pid) + phase = Phase(pid, p["slug"], p["title"], p.get("summary", ""), p.get("note", "")) + + seen_mod: set[str] = set() + for m in p.get("modules") or []: + if not _check_item("module", m, f"phase {pid}", errors): + continue + mid = str(m["id"]) + if mid in seen_mod: + errors.append(f"course.yml: module id {mid} is used twice in phase {pid}") + seen_mod.add(mid) + module = Module(mid, m["slug"], m["title"], phase) + + seen_les: set[str] = set() + seen_slug: set[str] = set() + for l in m.get("lessons") or []: + if not _check_item("lesson", l, f"phase {pid} / module {mid}", errors): + continue + lid = str(l["id"]) + if lid in seen_les: + errors.append(f"course.yml: lesson id {lid} is used twice in {phase.dirname}/{module.dirname}") + if l["slug"] in seen_slug: + errors.append(f"course.yml: lesson slug '{l['slug']}' is used twice in {phase.dirname}/{module.dirname}") + seen_les.add(lid) + seen_slug.add(l["slug"]) + module.lessons.append(Lesson(lid, l["slug"], l["title"], phase, module)) + phase.modules.append(module) + phases.append(phase) + + return Course( + title=data.get("title", "Course"), + subtitle=data.get("subtitle", ""), + phases=phases, + project_ideas=data.get("project_ideas") or [], + errors=errors, + ) + + +@dataclass +class Project: + slug: str + title: str + author: str + summary: str + + @property + def rel_dir(self) -> str: + return f"projects/{self.slug}" + + +def _section(text: str, heading: str) -> str: + m = re.search(rf"^##\s+{re.escape(heading)}\s*$(.*?)(?=^##\s|\Z)", text, re.M | re.S | re.I) + return m.group(1).strip() if m else "" + + +def load_projects() -> list[Project]: + projects = [] + if not PROJECTS_DIR.is_dir(): + return projects + for d in sorted(PROJECTS_DIR.iterdir()): + readme = d / "README.md" + if not d.is_dir() or not readme.is_file(): + continue + text = readme.read_text(encoding="utf-8") + title_m = re.search(r"^#\s+(.+)$", text, re.M) + author_m = re.search(r"\*\*Author:\*\*\s*(.+)", text) + summary = _section(text, "What it does").split("\n\n")[0].strip() + projects.append( + Project( + slug=d.name, + title=title_m.group(1).strip() if title_m else d.name, + author=author_m.group(1).strip() if author_m else "", + summary=summary, + ) + ) + return projects + + +def headings(text: str) -> list[str]: + """All level-2 headings, outside code blocks.""" + out, in_code = [], False + for line in text.splitlines(): + if line.strip().startswith("```"): + in_code = not in_code + continue + if not in_code: + m = re.match(r"^##\s+(.+?)\s*#*\s*$", line) + if m: + out.append(m.group(1).strip()) + return out diff --git a/scripts/requirements.txt b/scripts/requirements.txt new file mode 100644 index 0000000..1ff3c92 --- /dev/null +++ b/scripts/requirements.txt @@ -0,0 +1,4 @@ +pyyaml>=6.0 +markdown>=3.5 +pygments>=2.17 +weasyprint>=62 diff --git a/scripts/validate.py b/scripts/validate.py new file mode 100644 index 0000000..9e9c36e --- /dev/null +++ b/scripts/validate.py @@ -0,0 +1,329 @@ +"""Check lessons, projects and the roadmap. + +Usage: + python scripts/validate.py # check everything + python scripts/validate.py --base # in CI: skip if the PR doesn't touch course files +""" + +from __future__ import annotations + +import argparse +import difflib +import os +import re +import subprocess +import sys +from pathlib import Path + +import build_roadmap +from course import ( + LESSON_ALLOWED, + LESSON_REQUIRED, + LESSONS_DIR, + PROJECT_REQUIRED, + PROJECTS_DIR, + ROOT, + SLUG_RE, + headings, + load_course, +) + +WATCHED = ("lessons/", "projects/", "course.yml", "ROADMAP.md") +IMAGE_EXT = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"} +MAX_FILE_MB = 5 + +SECRET_PATTERNS = [ + (re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----"), "a private key"), + (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "an AWS access key"), + (re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"), "a GitHub token"), + (re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b"), "a Slack token"), + (re.compile(r"\bsk-[A-Za-z0-9]{32,}\b"), "an API secret key"), +] + +TEMPLATE_LEFTOVERS = [ + "https://example.com", + "(1–2 lines)", + "@your-github-username", + "# command — what it does", +] + +errors: list[tuple[str, str]] = [] # (file, message) + + +def err(file: Path | str, msg: str) -> None: + rel = str(Path(file).relative_to(ROOT)) if isinstance(file, Path) and Path(file).is_absolute() else str(file) + errors.append((rel, msg)) + + +def rel(p: Path) -> str: + return str(p.relative_to(ROOT)) + + +# ───────────────────────── helpers ───────────────────────── + +def changed_files(base: str) -> list[str]: + out = subprocess.run( + ["git", "diff", "--name-only", f"{base}...HEAD"], + cwd=ROOT, capture_output=True, text=True, check=True, + ).stdout + return [l for l in out.splitlines() if l.strip()] + + +def section_body(text: str, heading: str) -> str: + m = re.search(rf"^##\s+{re.escape(heading)}\s*$(.*?)(?=^##\s|\Z)", text, re.M | re.S) + return m.group(1).strip() if m else "" + + +def check_links(path: Path, text: str) -> None: + """Relative links and images inside a markdown file must point to real files.""" + no_code = re.sub(r"```.*?```", "", text, flags=re.S) + for target in re.findall(r"!?\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)", no_code): + if re.match(r"^(https?:|mailto:|#)", target): + continue + clean = target.split("#")[0] + if not clean: + continue + if not (path.parent / clean).resolve().exists(): + err(path, f"broken link: '{target}' does not exist") + + +def check_secrets(path: Path) -> None: + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + return + for pattern, what in SECRET_PATTERNS: + if pattern.search(text): + err(path, f"looks like it contains {what}. Remove it — never commit secrets.") + + +def check_leftovers(path: Path, text: str) -> None: + for t in TEMPLATE_LEFTOVERS: + if t in text: + err(path, f"template placeholder left in file: '{t}'") + + +# ───────────────────────── lessons ───────────────────────── + +def check_lesson_file(lesson, text: str) -> None: + path = lesson.path + lines = text.lstrip("").splitlines() + + if not lines or not lines[0].startswith("# "): + err(path, "first line must be the lesson title, like '# What is an IP address?'") + + if "> **Phase:**" not in text or "> **Module:**" not in text: + err(path, "missing the info block at the top ('> **Phase:** ...' and '> **Module:** ...'). Copy it from LESSON_TEMPLATE.md") + + found = headings(text) + for h in LESSON_REQUIRED: + if h not in found: + err(path, f"missing required section '## {h}'") + elif not section_body(text, h): + err(path, f"section '## {h}' is empty") + + unknown = [h for h in found if h not in LESSON_ALLOWED] + for h in unknown: + close = difflib.get_close_matches(h, LESSON_ALLOWED, n=1) + hint = f" — did you mean '## {close[0]}'?" if close else f". Allowed: {', '.join(LESSON_ALLOWED)}" + err(path, f"unknown section '## {h}'{hint}") + + known = [h for h in found if h in LESSON_ALLOWED] + if known != sorted(known, key=LESSON_ALLOWED.index): + err(path, "sections are in the wrong order. Follow the order in LESSON_TEMPLATE.md") + if len(known) != len(set(known)): + err(path, "a section heading is used twice") + + refs = section_body(text, "References") + if refs and not re.search(r"https?://", refs): + err(path, "'## References' needs at least one link to a real source") + + check_leftovers(path, text) + check_links(path, text) + + +def check_lessons(course) -> None: + lessons_by_path = {l.rel_path: l for l in course.lessons} + phases = {p.dirname: p for p in course.phases} + + if not LESSONS_DIR.is_dir(): + return + + for f in sorted(LESSONS_DIR.rglob("*")): + if f.is_dir(): + continue + r = rel(f) + parts = Path(r).parts # ('lessons', phase, module, file...) + + if f.name == ".gitkeep": + continue + if f.stat().st_size > MAX_FILE_MB * 1024 * 1024: + err(f, f"file is bigger than {MAX_FILE_MB} MB") + check_secrets(f) + + if r == "lessons/README.md": + continue + + # phase folder + if len(parts) < 3: + err(f, "files must go inside a phase folder, e.g. lessons/01-networking-fundamentals/") + continue + phase = phases.get(parts[1]) + if not phase: + close = difflib.get_close_matches(parts[1], phases, n=1) + hint = f" Did you mean '{close[0]}'?" if close else "" + err(f, f"phase folder '{parts[1]}' is not in course.yml.{hint}") + continue + if len(parts) == 3: + if f.name == "README.md": + continue + err(f, "lessons must go inside a module folder, e.g. lessons/01-networking-fundamentals/01-tcp-ip/") + continue + + # module folder + modules = {m.dirname: m for m in phase.modules} + module = modules.get(parts[2]) + if not module: + close = difflib.get_close_matches(parts[2], modules, n=1) + hint = f" Did you mean '{close[0]}'?" if close else "" + err(f, f"module folder '{parts[2]}' is not in course.yml under phase {phase.dirname}.{hint}") + continue + + # assets/ — images for this module's lessons + if len(parts) >= 5 and parts[3] == "assets": + if f.suffix.lower() not in IMAGE_EXT: + err(f, f"assets/ is for images only ({', '.join(sorted(IMAGE_EXT))})") + continue + + # code// — practice code for one lesson + if len(parts) >= 5 and parts[3] == "code": + if len(parts) < 6: + err(f, "code must go inside a lesson folder: code/-/") + continue + names = {f"{l.id}-{l.slug}": l for l in module.lessons} + if parts[4] not in names: + close = difflib.get_close_matches(parts[4], names, n=1) + hint = f" Did you mean '{close[0]}'?" if close else "" + err(f, f"code folder '{parts[4]}' doesn't match any lesson in this module.{hint}") + elif not names[parts[4]].done: + err(f, f"code for '{parts[4]}' exists but the lesson file itself is missing") + continue + + if len(parts) != 4: + err(f, "unexpected folder. Inside a module only lesson .md files, assets/ and code/ are allowed") + continue + + # lesson .md file + if f.suffix != ".md": + err(f, "only .md lesson files go here. Put images in assets/ and code in code//") + continue + lesson = lessons_by_path.get(r) + if not lesson: + by_id = {l.id: l for l in module.lessons} + m = re.match(r"^(\d{2})-", f.name) + if not m: + err(f, "lesson file name must start with its two-digit id, like '01-what-is-an-ip-address.md'") + elif m.group(1) in by_id: + right = by_id[m.group(1)].rel_path.split("/")[-1] + err(f, f"file name doesn't match the roadmap. Lesson {m.group(1)} must be named '{right}'") + else: + err(f, f"lesson {m.group(1)} is not in course.yml for module '{module.title}'. " + "Add it to the roadmap first, then run: python scripts/build_roadmap.py") + continue + check_lesson_file(lesson, f.read_text(encoding="utf-8")) + + +# ───────────────────────── projects ───────────────────────── + +def check_projects() -> None: + if not PROJECTS_DIR.is_dir(): + return + root_ok = {"README.md", "PROJECT_TEMPLATE.md", ".gitkeep"} + + for f in sorted(PROJECTS_DIR.iterdir()): + if f.is_file(): + if f.name not in root_ok: + err(f, "don't put files directly in projects/. Make a folder: projects//") + continue + + if not SLUG_RE.match(f.name): + err(f, f"project folder '{f.name}' must be lowercase-words-with-dashes, e.g. 'dns-lookup-tool'") + + readme = f / "README.md" + if not readme.is_file(): + err(f, "project needs a README.md (copy projects/PROJECT_TEMPLATE.md)") + else: + text = readme.read_text(encoding="utf-8") + if not text.lstrip().startswith("# "): + err(readme, "first line must be the project name, like '# DNS Lookup Tool'") + if not re.search(r"\*\*Author:\*\*\s*@?\S+", text): + err(readme, "add the author line: '**Author:** @your-github-username'") + found = headings(text) + for h in PROJECT_REQUIRED: + if h not in found: + err(readme, f"missing required section '## {h}'") + elif not section_body(text, h): + err(readme, f"section '## {h}' is empty") + check_leftovers(readme, text) + check_links(readme, text) + + for sub in f.rglob("*"): + if sub.is_file(): + if sub.stat().st_size > MAX_FILE_MB * 1024 * 1024: + err(sub, f"file is bigger than {MAX_FILE_MB} MB") + check_secrets(sub) + + +# ───────────────────────── main ───────────────────────── + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--base", help="git base sha; skip if no course files changed") + args = ap.parse_args() + + if args.base: + changed = changed_files(args.base) + relevant = [c for c in changed if c.startswith(WATCHED)] + if not relevant: + print("This PR doesn't touch lessons, projects or the roadmap — nothing to check. ✅") + return 0 + print("Course files changed:\n " + "\n ".join(relevant)) + + course = load_course() + for e in course.errors: + errors.append(("course.yml", e.removeprefix("course.yml: "))) + + check_lessons(course) + check_projects() + + if build_roadmap.render() != (ROOT / "ROADMAP.md").read_text(encoding="utf-8"): + err("ROADMAP.md", "out of date. Run: python scripts/build_roadmap.py and commit the result") + + in_ci = os.environ.get("GITHUB_ACTIONS") == "true" + summary_path = os.environ.get("GITHUB_STEP_SUMMARY") + + if not errors: + done = sum(l.done for l in course.lessons) + msg = f"All checks passed ✅ ({done}/{len(course.lessons)} lessons published)" + print(msg) + if summary_path: + Path(summary_path).write_text(f"### {msg}\n", encoding="utf-8") + return 0 + + print(f"\n❌ Found {len(errors)} problem(s):\n") + for file, msg in errors: + print(f" {file}: {msg}") + if in_ci: + print(f"::error file={file}::{msg}") + + if summary_path: + rows = "\n".join(f"| `{f}` | {m} |" for f, m in errors) + Path(summary_path).write_text( + f"### ❌ {len(errors)} problem(s) found\n\n| File | Problem |\n|---|---|\n{rows}\n", + encoding="utf-8", + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) From 5ca9c3a308566e86a9a499c05c031da9373c49d0 Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Thu, 5 Nov 2026 12:47:22 +0500 Subject: [PATCH 2/2] Use org repo name in scripts --- scripts/course.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/course.py b/scripts/course.py index 99bc60b..1cc3957 100644 --- a/scripts/course.py +++ b/scripts/course.py @@ -48,7 +48,7 @@ def repo_slug() -> str: - return os.environ.get("GITHUB_REPOSITORY", "Muawiya-contact/network-security-lab") + return os.environ.get("GITHUB_REPOSITORY", "Coding-Moves/network-security-lab") def branch() -> str: