diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddf1ea8..2eda8cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,80 +11,22 @@ jobs: qa: runs-on: ubuntu-latest timeout-minutes: 15 - steps: - name: Check out repository uses: actions/checkout@v4 - - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' cache: 'pip' - - - name: Show tool versions - run: | - python --version - pip --version - bash --version | head -n 1 - - - name: Normalise executable permissions from manifest - run: bash 00_TOOLS/qa/apply_permissions.sh - - - name: Check executable permissions - run: bash 00_TOOLS/qa/check_executability.sh - - - name: Run Markdown link checker - run: python 00_TOOLS/qa/check_markdown_links.py - - - name: Run language & lexical integrity check (teaching corpus) - run: | - python - <<'PY' - from pathlib import Path - import shutil - import subprocess - import sys - import tempfile - - src = Path('.').resolve() - ignored_names = { - '.git', - '.github', - '__pycache__', - '.pytest_cache', - '.mypy_cache', - 'node_modules', - '.venv', - 'venv', - } - - with tempfile.TemporaryDirectory(prefix='compnet-integrity-') as td: - dst = Path(td) / 'repo' - - def ignore(path, names): - ignored = {name for name in names if name in ignored_names} - if Path(path).resolve() == src: - ignored.add('CHANGELOG.md') - return ignored - - shutil.copytree(src, dst, ignore=ignore) - subprocess.run([sys.executable, '00_TOOLS/qa/check_integrity.py'], cwd=dst, check=True) - - print('Integrity check passed on teaching corpus (root CHANGELOG.md intentionally excluded as an audit delta document).') - PY - - - name: Validate lecture figure targets - run: python 00_TOOLS/qa/check_fig_targets.py --puml-only - - - name: Run pytest (if present) - shell: bash - run: | - set -euo pipefail - - if find . -type f \( -name 'test_*.py' -o -name '*_test.py' \) -print -quit | grep -q .; then - python -m pip install --upgrade pip - python -m pip install 'pytest<9' pyyaml - PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -q - else - echo 'No pytest tests detected, skipping.' - fi + cache-dependency-path: | + 00_TOOLS/qa/requirements.txt + 03_LECTURES/tests/requirements.txt + - name: Set up Node for HTML control-logic tests + uses: actions/setup-node@v4 + with: + node-version: '24' + - name: Install QA dependencies + run: python -m pip install -r 00_TOOLS/qa/requirements.txt + - name: Check source and component regressions + run: python 00_TOOLS/qa/run_checks.py diff --git a/.gitignore b/.gitignore index c497e50..afe3b59 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,8 @@ build/ # Large binaries fetched later 00_TOOLS/plantuml.jar + +# Local formative assessment results (keep the documentation). +00_APPENDIX/a)PYTHON_self_study_guide/formative/results/quiz_results_*.json + +.venv-qa/ diff --git a/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md b/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md index 57f643a..b5230d7 100644 --- a/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md +++ b/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md @@ -16,7 +16,7 @@ Live coding is a teaching technique where the instructor **writes code in real t --- -## 2. Session Structure (15-20 minutess) +## 2. Session Structure (15-20 minutes) ``` ┌─────────────────────────────────────────────────────────────────────────────┐ @@ -134,13 +134,20 @@ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # STEP 1: "Let's see if Docker responds" import subprocess -# QUESTION: "What command checks if Docker is running?" -result = subprocess.run(['docker', '--version'], capture_output=True, text=True) -print(f"Docker version: {result.stdout.strip()}") - -# PLANNED MISTAKE: Run without sudo service docker start -# "Cannot connect to Docker daemon" -# "What do we need to do after restarting Windows?" +# QUESTION: "Which command contacts the Docker daemon rather than only the CLI?" +try: + result = subprocess.run(['docker', 'info'], capture_output=True, text=True, timeout=15) + print("Daemon accessible" if result.returncode == 0 else "Daemon inaccessible") + if result.returncode: + print(result.stderr.strip()) +except FileNotFoundError: + print("Docker CLI is not installed") +except subprocess.TimeoutExpired: + print("Docker daemon check timed out") + +# PLANNED MISTAKE: use an explicitly manual-start WSL setup with Docker stopped. +# A systemd-enabled distribution or Docker Desktop may start its daemon automatically. +# Inspect docker context, service state and access permissions before changing them. # STEP 2: "Let's run a simple container" # QUESTION: "What does 'docker run --rm' do?" @@ -164,8 +171,10 @@ def check_port(host, port): return False # QUESTION: "What port does Portainer listen on?" -portainer_ok = check_port('localhost', 9000) -print(f"Portainer accessible: {portainer_ok}") +portainer_ok = check_port('localhost', 9050) +print(f"TCP listener on the configured Portainer port: {portainer_ok}") +# A TCP connection does not establish HTTP readiness or successful authentication. +# Open the configured URL and verify the Portainer page separately. # RECAP # "We verified: Docker installed, daemon running, container functional, Portainer up" @@ -265,7 +274,7 @@ server.listen(1) - "What happens if the client disconnects?" ### Questions requiring postponement: -- "How does TLS work?" → "Excelslow question! We'll cover it in Week 10." +- "How does TLS work?" → "Excellent question! We'll cover it in Week 10." ### Off-topic questions: - "Can we do this in Rust?" → "Interesting, but let's focus on Python now. We'll chat at break." @@ -313,7 +322,7 @@ server.listen(1) ### Before next session - [ ] Have I published code for students? -- [ ] Have I updatad slides with clarifications? +- [ ] Have I updated slides with clarifications? - [ ] Have I prepared supplementary exercises for difficult concepts? - [ ] Have I reviewed timing (too fast / too slow)? @@ -339,7 +348,7 @@ server.listen(1) ### "A student asks questions continuously and derails the course" ``` -- "Excelslow question, but let's discuss at break to not lose the thread" +- "Excellent question, but let's discuss at break to not lose the thread" - Visibly note the question on the board - Return to it if relevant later ``` diff --git a/00_APPENDIX/Makefile b/00_APPENDIX/Makefile index 5081e9f..7e0a6e3 100644 --- a/00_APPENDIX/Makefile +++ b/00_APPENDIX/Makefile @@ -11,12 +11,12 @@ # make export - Export quiz to all formats # make clean - Clean generated files -.PHONY: help quiz test lint validate export clean verify all +.PHONY: help quiz quiz-review quiz-random quiz-validate test test-verbose test-exports test-all lint lint-fix validate validate-python validate-yaml validate-json export export-json export-moodle export-qti clean verify all # Configuration PYTHON := python3 QUIZ_DIR := formative -EXAMPLES_DIR := PYTHON_self_study_guide/examples +EXAMPLES_DIR := a)PYTHON_self_study_guide/examples TESTS_DIR := $(EXAMPLES_DIR)/tests # Colours for output @@ -90,20 +90,20 @@ quiz-validate: test: @echo "$(CYAN)Running smoke tests...$(NC)" - @$(PYTHON) $(TESTS_DIR)/test_smoke.py + @$(PYTHON) "$(TESTS_DIR)/test_smoke.py" @echo "$(GREEN)✓ Smoke tests passed$(NC)" test-verbose: @echo "$(CYAN)Running smoke tests (verbose)...$(NC)" - @$(PYTHON) -m pytest $(TESTS_DIR)/test_smoke.py -v 2>/dev/null || $(PYTHON) $(TESTS_DIR)/test_smoke.py + @$(PYTHON) -m pytest "$(TESTS_DIR)/test_smoke.py" -v test-exports: @echo "$(CYAN)Running export function tests...$(NC)" @if [ -f "$(QUIZ_DIR)/tests/test_quiz_exports.py" ]; then \ - $(PYTHON) $(QUIZ_DIR)/tests/test_quiz_exports.py; \ + $(PYTHON) $(QUIZ_DIR)/tests/test_quiz_exports.py || exit $$?; \ echo "$(GREEN)✓ Export tests passed$(NC)"; \ else \ - echo "$(YELLOW)⚠ Export tests not found$(NC)"; \ + echo "$(RED)Export tests not found$(NC)"; exit 1; \ fi test-all: test test-exports @@ -116,19 +116,19 @@ test-all: test test-exports lint: @echo "$(CYAN)Running linter...$(NC)" @if command -v ruff >/dev/null 2>&1; then \ - ruff check $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py --ignore E501; \ + ruff check "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py --ignore E501; \ elif command -v flake8 >/dev/null 2>&1; then \ - flake8 $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py --max-line-length=120; \ + flake8 "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py --max-line-length=120; \ else \ echo "$(YELLOW)⚠ No linter found. Install with: pip install ruff$(NC)"; \ - $(PYTHON) -m py_compile $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py; \ + $(PYTHON) -m py_compile "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py || exit $$?; \ echo "$(GREEN)✓ Syntax check passed$(NC)"; \ fi lint-fix: @echo "$(CYAN)Running linter with auto-fix...$(NC)" @if command -v ruff >/dev/null 2>&1; then \ - ruff check $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py --fix --ignore E501; \ + ruff check "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py --fix --ignore E501; \ else \ echo "$(YELLOW)⚠ ruff not found. Install with: pip install ruff$(NC)"; \ fi @@ -142,7 +142,7 @@ validate: validate-python validate-yaml validate-json validate-python: @echo "$(CYAN)Validating Python syntax...$(NC)" - @find . -name "*.py" -type f -exec $(PYTHON) -m py_compile {} \; + @$(PYTHON) -m compileall -q . @echo "$(GREEN)✓ Python syntax valid$(NC)" validate-yaml: @@ -153,7 +153,7 @@ validate-yaml: validate-json: @echo "$(CYAN)Validating JSON files...$(NC)" @if [ -f "$(QUIZ_DIR)/quiz.json" ]; then \ - $(PYTHON) -c "import json; json.load(open('$(QUIZ_DIR)/quiz.json'))"; \ + $(PYTHON) -c "import json; json.load(open('$(QUIZ_DIR)/quiz.json'))" || exit $$?; \ echo "$(GREEN)✓ JSON valid$(NC)"; \ else \ echo "$(YELLOW)⚠ quiz.json not found (optional)$(NC)"; \ @@ -163,7 +163,7 @@ validate-json: # EXPORT TARGETS #═══════════════════════════════════════════════════════════════════════════════ -export: export-json export-moodle +export: export-json export-moodle export-qti @echo "$(GREEN)✓ All exports completed$(NC)" export-json: @@ -204,7 +204,7 @@ clean: @find . -type f -name "*.pyc" -delete 2>/dev/null || true @find . -type f -name "*_export.json" -delete 2>/dev/null || true @find . -type f -name "*_moodle.gift" -delete 2>/dev/null || true - @find . -type f -name "*_qti.xml" -delete 2>/dev/null || true + @find . -type f \( -name "*_qti.xml" -o -name "*_qti.zip" \) -delete 2>/dev/null || true @echo "$(GREEN)✓ Clean completed$(NC)" #═══════════════════════════════════════════════════════════════════════════════ diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/CANONICAL_LAB_MAP.md b/00_APPENDIX/a)PYTHON_self_study_guide/CANONICAL_LAB_MAP.md new file mode 100644 index 0000000..d1afaac --- /dev/null +++ b/00_APPENDIX/a)PYTHON_self_study_guide/CANONICAL_LAB_MAP.md @@ -0,0 +1,62 @@ +# Python self-study: canonical COMPNET-EN paths + +Use this map with the [Python guide](PYTHON_NETWORKING_GUIDE.md) and its ten HTML +modules. Run terminal commands from the **repository root inside the Linux VM or +selected WSL environment**. A slide's Simulate/Show output control displays a +prepared teaching illustration; it does not execute Python or generate a capture. + +| Module | Real source or entry point | What to inspect or run | +|---|---|---| +| 1–2: setup and reading | [05_ping_latency.py](examples/05_ping_latency.py) | Dataclass, argparse, subprocess result and bounded failure handling | +| 3: bytes and text | [02_bytes_vs_str.py](examples/02_bytes_vs_str.py) | Encoding, decoding and temporary-file ownership | +| 4: sockets | [01_socket_tcp.py](examples/01_socket_tcp.py), [S02](../../04_SEMINARS/S02/) | Separate server/client processes and the actual protocol handout | +| 5: organisation | [03_struct_parsing.py](examples/03_struct_parsing.py) | Importable functions, IPHeader dataclass and main guard | +| 6: CLI | [05_ping_latency.py](examples/05_ping_latency.py), [lab runner](../../00_TOOLS/lab_runner/) | The actual --help and documented arguments | +| 7: packet analysis | [S07](../../04_SEMINARS/S07/), [PCAP tools](../../00_TOOLS/pcap/) | Capture privileges, interfaces and parsed fields | +| 8: concurrency | [S03 multi-client server](../../04_SEMINARS/S03/S03_Part01_Example_TCP_Multi_client_Server.py) | Client lifetime, framing and concurrency | +| 9: HTTP | [S08](../../04_SEMINARS/S08/), [C10 scenarios](../../03_LECTURES/C10/) | HTTP framing, request/response bytes and proxy behaviour | +| 10: debugging | [04_error_handling.py](examples/04_error_handling.py), [tests](examples/tests/) | Resource ownership, errors and component regression evidence | + +## First runnable checks + +```bash +cd "$HOME/COMPNET-EN" +python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --host 127.0.0.1 --count 3 +python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/02_bytes_vs_str.py" +python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py" +``` + +The ping helper needs Linux `ping` (iputils-ping). A missing command, unsuccessful +reply or unparsed RTT produces a non-zero exit. Report those observations rather +than substituting the slide's example timings. + +For the socket example, use two Linux terminals in the repository root: + +```bash +# Terminal A: stop with Ctrl+C after the experiment. +python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" server 9090 +``` + +```bash +# Terminal B +python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" client 127.0.0.1 9090 "Test" +``` + +For subnetting, the C05 calculator accepts a positional address/prefix: + +```bash +python3 03_LECTURES/C05/assets/scenario-cidr-basic/cidr-calc.py 192.168.23.233/24 +``` + +Do not assume every course script implements argparse or a common `--mode` option. +The S04 text framing, binary framing and pickle-based UDP exercise are defined by +[S04's source and handouts](../../04_SEMINARS/S04/). Generic JSON, checksum and package +sketches in this Python guide are separate learning examples. + +## Provenance + +Earlier versions of these optional materials referred to the external netROwsl kit. +The v1.5.0 revision maps learning activities to COMPNET-EN while retaining the Python +concepts. Repository v1.4.0 preserves the prior text. The VM remains +[MININET-SDN 1.0.0](https://doi.org/10.5281/zenodo.24289763); see +[environment routes](../docs/environment_routes.md) for installation and Portainer. diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/Makefile b/00_APPENDIX/a)PYTHON_self_study_guide/Makefile index 0318dfe..b689e4b 100644 --- a/00_APPENDIX/a)PYTHON_self_study_guide/Makefile +++ b/00_APPENDIX/a)PYTHON_self_study_guide/Makefile @@ -25,7 +25,7 @@ .DEFAULT_GOAL := help # Python interpreter -PYTHON := python3 +PYTHON := $(if $(wildcard .venv/bin/python),.venv/bin/python,python3) # Directories QUIZ_DIR := formative @@ -224,14 +224,7 @@ test: test-all test-all: @echo "$(COLOUR_BOLD)Running all tests...$(COLOUR_RESET)" - @if command -v pytest >/dev/null 2>&1; then \ - pytest $(TESTS_DIR)/ -v; \ - else \ - $(PYTHON) -m pytest $(TESTS_DIR)/ -v 2>/dev/null || \ - ($(PYTHON) $(TESTS_DIR)/test_smoke.py && \ - $(PYTHON) $(TESTS_DIR)/test_bytes_vs_str.py && \ - $(PYTHON) $(TESTS_DIR)/test_struct_parsing.py); \ - fi + @$(PYTHON) -m pytest $(TESTS_DIR)/ -v test-smoke: @echo "$(COLOUR_BOLD)Running smoke tests...$(COLOUR_RESET)" @@ -270,10 +263,11 @@ check: @echo "$(COLOUR_GREEN)Environment check complete.$(COLOUR_RESET)" install: - @echo "$(COLOUR_BOLD)Installing dependencies...$(COLOUR_RESET)" - @pip install --user pyyaml pytest 2>/dev/null || \ - pip install pyyaml pytest --break-system-packages || \ - echo "$(COLOUR_YELLOW)Please install: pip install pyyaml pytest$(COLOUR_RESET)" + @echo "Creating a local virtual environment for this guide..." + @python3 -m venv .venv + @.venv/bin/python -m pip install 'PyYAML==6.0.3' 'pytest==8.4.2' + @echo "Done. Make targets now use .venv/bin/python; activate it with: source .venv/bin/activate" + lint: @echo "$(COLOUR_BOLD)Checking code style...$(COLOUR_RESET)" diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html index c79a7a2..e3290d7 100644 --- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html +++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html @@ -809,7 +809,11 @@ margin-bottom: 1rem; animation: pulse 2s infinite; } - + button.quiz-option {width:100%;color:inherit;font:inherit;text-align:left;} +button.quiz-option:focus-visible,.page-dot:focus-visible {outline:3px solid var(--accent-primary);outline-offset:3px;} +button.page-dot {border:0;padding:0;} +code,.file-name {overflow-wrap:anywhere;} + @@ -833,6 +837,7 @@
+

Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map.

Python for Networks

Interactive Self-Study Guide

@@ -879,8 +884,8 @@

🎯 What will we learn in this module?

💻
- WSL2 Working Environment - How WSL2 + Ubuntu + Docker + Portainer work together and why we use them + Linux working environment + How the VM and separate WSL routes relate and why we use them
@@ -901,74 +906,20 @@

💡 Why it matters?

-
-
-

📂 Repository Structure netROwsl

- -

The repository at github.com/antonioclim/netROwsl contains all lab materials. Each week has its own folder following a consistent structure:

- -
-
-
- 📁 - netROwsl/ -
-
- 📁 - 01roWSL/ - ← Wk 1 -
-
- 📁 - src/exercises/ -
-
- 🐍 - ex_1_01_latency_ping.py -
-
- 📁 - docker/ -
-
- 📁 - docs/ -
-
- 📁 - 02roWSL/ - ← Wk 2 -
-
- ... -
-
- 📁 - 14roWSL/ - ← Wk 14 -
-
- -
-
-

📍 Key Folders

-

src/exercises/ - Main exercises with TODOs

-

src/apps/ - Complete demonstration applications

-

src/utils/ - Reusable helper functions

-

docker/ - Container configurations

-

tests/ - Automated tests

-
- -
-

⚠️ Warning

-

Files in exercises/ contain TODO sections for you to complete. Do not modify files in apps/ — those are reference examples!

-
-
-
-
-
+
+

Repository structure: COMPNET-EN

+

The course has separate entry points for lectures, seminars, projects and optional Python practice. Start with the README of the selected unit.

+ + + + + + +
Path from repository rootPurpose
03_LECTURES/C01/ … C14/Lecture notes, diagrams and executable scenarios
04_SEMINARS/S01/ … S14/Student explanations, tasks, examples and templates
02_PROJECTS/Project requirements and evidence criteria
00_TOOLS/Shared setup, capture and validation tools
00_APPENDIX/a)PYTHON_self_study_guide/This optional guide, examples and formative practice
+

Files labelled Example are references; Template files identify student completion work. Read each task's contract before changing a template.

+

Canonical examples and commands

+
-

🗓️ Weeks ↔ Python Modules Correlation

@@ -990,7 +941,7 @@

🗓️ Weeks ↔ Python Modules Correlation

1 ← S0 Preparation - Setup Setup & Structur Structure + Setup and repository structure 2 @@ -1032,13 +983,13 @@

🗓️ Weeks ↔ Python Modules Correlation

9 S8-12 Application Layer - HTTP HTTP & Protocoof Protocols + HTTP and protocols 10 S11-14 Integration, IoT - Debugging Debugging & Best practices Best practices + Debugging and best practices @@ -1052,60 +1003,17 @@

💡 Tip

-
-
-

🖥️ Working Environment: WSL2 + Docker

- -

The lab sessions employ a modern technology stack for network simulation:

- -
-
-

🪟 WSL2 (Windows Subsystem for Linux)

-

What it is: A real Linux kernel running in Windows

-

Why: Networking tools (Wireshark, tcpdump) work natively

-

Access: Open "Ubuntu" from Start Menu or type wsl in PowerShell

-
- -
-

🐳 Docker

-

What it is: Isolated containers for simulating network servers and services

-

Why: You can run DNS, HTTP, FTP servers without installing them on the system

-

Start: sudo service docker start

-
- -
-

🎛️ Portainer

-

What it is: Web interface for managing Docker containers

-

Why: Easily visualise running containers and inspect their logs

-

Access: http://localhost:9000

-
+
+

Choose the installed environment

+

The primary course route uses the working MININET-SDN VirtualBox appliance. Run Linux commands in the guest, normally through SSH on Windows loopback port 2222. The WSL2 route is a separately documented alternative.

+

VM or native WSL Engine

Docker and Python run inside the selected Linux environment. docker info checks daemon access; docker --version checks only the client.

Optional Portainer

The course setup maps host loopback 9050 to container HTTP 9000. Access from Windows into the VM requires a tunnel or forwarding rule. Existing personal credentials are preserved.

+
python3 --version
+docker context show
+docker info
+

Environment routes and canonical setup guides

+

MININET-SDN 1.0.0 on Zenodo

+
-
-

🐍 Python 3

-

What it is: The programming language in which all exercises are written

-

Why: Clear syntax, powerful networking libraries

-

Check: python3 --version

-
-
- -
-
- verify_environment.sh -
- -
-
-
-
# Verify that all components are working
-python3 --version          # Python 3.10+
-docker --version           # Docker 20+
-docker ps                  # Portainer should be listed
-
-
-
-
- -

🧪 Experiment: First Python Script

@@ -1121,8 +1029,8 @@

🧪 Experiment: First Python Script

1
-

Open Ubuntu Terminal

-

Click on "Ubuntu" in the Start Menu or type wsl in PowerShell

+

Open the Linux lab terminal

+

Use SSH to the VM, or the selected Ubuntu distribution if you follow the WSL route

🎯 Purpose: All tools are installed within this Linux environment

@@ -1131,8 +1039,8 @@

Open Ubuntu Terminal

2

Navigate to the lab folder

-

cd /mnt/d/NETWORKING/netROwsl/01roWSL

-

🎯 Purpose: Windows files are accessible through the /mnt/ mount point

+

cd $HOME/COMPNET-EN

+

🎯 Purpose: The command assumes the repository was cloned into your Linux home directory

@@ -1140,7 +1048,7 @@

Navigate to the lab folder

3

Run the ping exercise

-

python3 src/exercises/ex_1_01_latency_ping.py --host 127.0.0.1 --count 3

+

python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --host 127.0.0.1 --count 3

🎯 Purpose: Verify that Python and the networking modules work correctly

@@ -1150,7 +1058,7 @@

Run the ping exercise

Observe the result

You should see latency statistics (RTT)

-

🎯 Takeaway: The script sends ICMP packets and measures the response time

+

🎯 Takeaway: Python invokes Linux ping and parses its observations; times depend on the machine

@@ -1158,26 +1066,23 @@

Observe the result

- ex_1_01_latency_ping.py (expected output) + 00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py (expected output)
# Command:
-python3 src/exercises/ex_1_01_latency_ping.py --host 127.0.0.1 --count 3
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --host 127.0.0.1 --count 3
Output
-
🏓 Measuring latency to 127.0.0.1
-────────────────────────────────────
-Sequence 1: RTT = 0.042 ms ✓
-Sequence 2: RTT = 0.038 ms ✓
-Sequence 3: RTT = 0.041 ms ✓
-────────────────────────────────────
-📊 Statistics:
-   Packets: 3 sent, 3 received (0% loss)
-   RTT: min=0.038ms, avg=0.040ms, max=0.042ms
+
Illustrative output (your timings differ):
+PingResult(sequence=1, rtt_ms=0.042, succeeded=True, message='')
+PingResult(sequence=2, rtt_ms=0.038, succeeded=True, message='')
+PingResult(sequence=3, rtt_ms=0.041, succeeded=True, message='')
+Replies: 3/3
+RTT ms: min=0.038, mean=0.040, max=0.042
@@ -1202,22 +1107,22 @@

Quiz 1: Repository Structure

-
+
-
+ 03_LECTURES/C05/ + +
-
+ 04_SEMINARS/S05/ + +
-
+ 02_PROJECTS/ + +
+ 00_TOOLS/ +
@@ -1227,7 +1132,7 @@

Quiz 1: Repository Structure

Hint 1/3
-

Think about the folder names. Which folder suggests it contains tasks to complete (exercises)?

+

Seminar folders use S followed by the two-digit week number.

Hint 2/3
@@ -1238,7 +1143,7 @@

Quiz 1: Repository Structure

The correct answer is exercises/ - here you find files with TODOs that you complete during the lab.

-
+
@@ -1255,22 +1160,22 @@

Quiz 2: Working Environment

-
+
-
+ +
-
+ +
-
+ +
+
@@ -1291,7 +1196,7 @@

Quiz 2: Working Environment

Docker enables service isolation through containers. This allows us to simulate an entire network with different servers, each running in its own container.

-
+
@@ -1306,13 +1211,13 @@

✅ Summary and Next Steps

📌 What We Covered

@@ -894,19 +894,19 @@

⚖️ Broadcast vs Multicast — Side by Side

🤝 IGMP: How Multicast Membership Works

-IGMP (Internet Group Management Protocol, RFC 2236) is the mechanism that hosts use to inform routers about their multicast group subscriptions. Think of it as raising your hand and saying: "I want to receive messages for group 239.1.1.1." +IGMP (Internet Group Management Protocol, RFC 2236) is the mechanism that hosts use to inform routers about their multicast group subscriptions. Think of it as raising your hand and saying: "I want to receive messages for group 239.255.0.1."
-Host wants to join group 239.1.1.1: +Host wants to join group 239.255.0.1: ┌────────┐ ┌──────────┐ │ HOST │── IGMP Member Report ►│ ROUTER │ - │ │ (Join 239.1.1.1) │ │ + │ │ (Join 239.255.0.1) │ │ └────────┘ └────┬─────┘ │ Router updates its multicast │ forwarding table: "forward ▼ - 239.1.1.1 to this segment" Table updated + 239.255.0.1 to this segment" Table updated Later, the router periodically asks "who is still interested?": @@ -923,7 +923,7 @@

💻 Multicast Sender — Implementation

import socket # Configuration -MCAST_GROUP = "239.1.1.1" +MCAST_GROUP = "239.255.0.1" PORT = 5001 # TTL = 1 means link-local only @@ -960,7 +960,7 @@

💻 Multicast Receiver — The JOIN Process

import socket import struct -MCAST_GROUP = "239.1.1.1" +MCAST_GROUP = "239.255.0.1" PORT = 5001 # Step 1: Create a UDP socket @@ -1004,7 +1004,7 @@

🔍 Inside IP_ADD_MEMBERSHIP

Multicast Group IP
-
239.1.1.1
+
239.255.0.1
4 bytes — inet_aton()
@@ -1015,14 +1015,14 @@

🔍 Inside IP_ADD_MEMBERSHIP

# Building the mreq structure -mreq = socket.inet_aton("239.1.1.1") +mreq = socket.inet_aton("239.255.0.1") mreq += struct.pack( "=I", socket.INADDR_ANY ) # Or for a specific interface: -mreq = socket.inet_aton("239.1.1.1") +mreq = socket.inet_aton("239.255.0.1") mreq += socket.inet_aton("10.0.3.2")
@@ -1036,7 +1036,7 @@

🔍 Inside IP_ADD_MEMBERSHIP

-Common pitfall: Forgetting to call IP_ADD_MEMBERSHIP means you will never receive multicast packets, even if you are bound to the correct port. The bind alone is not sufficient. +Common pitfall: Join the intended group explicitly on the intended interface. Host membership and per-socket delivery are distinct: Linux normally has IP_MULTICAST_ALL=1, so a socket may also receive traffic for groups joined elsewhere on that host. The all-hosts group 224.0.0.1 is joined implicitly. Use a dedicated group such as 239.255.0.1 in an isolated namespace when comparing joined and unjoined cases; on Linux set IP_MULTICAST_ALL=0 for per-socket filtering.
@@ -1186,86 +1186,65 @@

🏗️ Tunnel Architecture — Bidirectional Forwarding

💻 Core Pattern: Unidirectional Forwarding

-def forward_stream( - src, dst, direction, stop_event -): - """Copy data from src to dst until closed.""" - total = 0 - try: - while not stop_event.is_set(): - # Read from source - data = src.recv(4096) - - if not data: - # Empty bytes = peer closed - print( - f"{direction}: closed" - ) - break - - # Write to destination +def forward_stream(src, dst, direction, stop_event): + """Forward this direction; EOF half-closes only the peer write side.""" + try: + while not stop_event.is_set(): + data = src.recv(4096) + if not data: + dst.shutdown(socket.SHUT_WR) + return dst.sendall(data) - total += len(data) - - except (ConnectionResetError, BrokenPipeError): - print( - f"{direction}: connection reset" - ) - finally: - # Signal the other thread to stop - stop_event.set()
+ except OSError as exc: + print(f"{direction}: {exc}") + stop_event.set() + for channel in (src, dst): + try: + channel.shutdown(socket.SHUT_RDWR) + except OSError: + pass +

💻 Client Handler and Accept Loop

-import threading - -def handle_client(client, host, port): - """Connect to target, forward both ways.""" - - # Connect to the actual target server - target = socket.socket( - socket.AF_INET, - socket.SOCK_STREAM - ) - target.settimeout(10.0) - target.connect((host, port)) - target.settimeout(None) - - # Shared shutdown signal - stop = threading.Event() - - # Two threads: one per direction - t1 = threading.Thread( - target=forward_stream, - args=(client, target, "c→t", stop) - ) - t2 = threading.Thread( - target=forward_stream, - args=(target, client, "t→c", stop) - ) - t1.start() - t2.start() - t1.join() - t2.join() - - # Clean up both sockets - client.close() - target.close()
+import threading + +def handle_client(client, host, port): + """Forward both ways; the lab uses a 30-second idle timeout.""" + target = None + try: + target = socket.create_connection((host, port), timeout=10) + target.settimeout(30) + client.settimeout(30) + stop = threading.Event() + workers = [threading.Thread(target=forward_stream, args=args) + for args in ((client, target, "c-to-t", stop), + (target, client, "t-to-c", stop))] + for worker in workers: + worker.start() + for worker in workers: + worker.join() + finally: + client.close() + if target is not None: + target.close() +
+

🚀 Running the Tunnel in Mininet

# Terminal 1: Echo server on b1 (target) -mininet> b1 python3 ex04_echo_server.py \ +mininet> b1 python3 ../../03_LECTURES/C03/assets/scenario-tcp-tunnel/echo.py \ --listen 0.0.0.0:8080 # Terminal 2: Tunnel on r1 (router) -mininet> r1 python3 ex03_tcp_tunnel.py \ +mininet> r1 python3 ../../03_LECTURES/C03/assets/scenario-tcp-tunnel/tunnel.py \ --listen 0.0.0.0:9090 \ --target 10.0.2.1:8080 @@ -1285,7 +1264,7 @@

🚀 Running the Tunnel in Mininet

🔄 Coordinating Thread Shutdown

-When one direction closes (e.g. the client sends FIN), the other forwarding thread must stop too. threading.Event provides a lightweight, thread-safe signalling mechanism — no locks required. +When one direction receives EOF (e.g. the client sends FIN), propagate a half-close and let the reverse direction drain. On an error or idle timeout, signal cancellation and shut down both sockets to wake blocked receives. threading.Event provides a lightweight, thread-safe signalling mechanism — no locks required.
@@ -1315,7 +1294,7 @@

🔄 Coordinating Thread Shutdown

-Note: recv() is a blocking call. When one thread calls stop.set(), the other thread may still be blocked in recv(). The connection close from the peer will cause recv() to return empty bytes, breaking the loop. +Note: recv() is a blocking call. When one thread calls stop.set(), the other thread may still be blocked in recv(). A cancellation flag alone does not wake a blocked receive. The implementation above uses socket shutdown on errors and a 30-second idle timeout; normal EOF only half-closes the corresponding write direction.
@@ -1356,9 +1335,9 @@

✅ The Fix (Multicast)

) sock.sendto( status, - ("239.1.1.1", 5007) + ("239.255.0.1", 5007) )
-

Only the 50 inventory devices that joined group 239.1.1.1 receive the packets. The other 290 devices are undisturbed.

+

Only the 50 inventory devices that joined group 239.255.0.1 receive the packets. The other 290 devices are undisturbed.

@@ -1429,7 +1408,7 @@

💭 Analogy: Postal System

🧠 Synthesis: The QUIC Protocol

-Context: Google developed QUIC (now standardised as HTTP/3 in RFC 9000) which runs over UDP but provides reliable, ordered delivery with built-in encryption. Given what you have learned about TCP and UDP trade-offs, why would engineers choose to rebuild TCP's features on top of UDP? +Context: Google developed the original QUIC; IETF QUIC transport is specified by RFC 9000, and HTTP/3 by RFC 9114 which runs over UDP but provides reliable, ordered delivery with built-in encryption. Given what you have learned about TCP and UDP trade-offs, why would engineers choose to rebuild TCP's features on top of UDP?
What is the primary advantage of QUIC over traditional TCP?
@@ -1489,7 +1468,8 @@

🎯 Ready for the Laboratory

Apply these concepts with the Seminar 3 starterkit
- cd ~/WEEK3 && make verify + cd ~/COMPNET-EN/04_SEMINARS/S03 + # Follow README.md for the chosen scenario and its expected evidence.
@@ -1632,6 +1612,7 @@

Table of Contents

// ═══════════════════════════════════════════════════════════════════ document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return; switch(e.key) { diff --git a/00_APPENDIX/b)optional_LECTURES/S4Theory_Physical_and_data_link_layer_EN.html b/00_APPENDIX/b)optional_LECTURES/S4Theory_Physical_and_data_link_layer_EN.html index eca5c2a..b0cf34c 100644 --- a/00_APPENDIX/b)optional_LECTURES/S4Theory_Physical_and_data_link_layer_EN.html +++ b/00_APPENDIX/b)optional_LECTURES/S4Theory_Physical_and_data_link_layer_EN.html @@ -2390,6 +2390,7 @@

Wrap‑up

document.getElementById('progressFill').style.width = ((currentSlide / totalSlides) * 100) + '%'; document.getElementById('prevBtn').disabled = currentSlide === 1; document.getElementById('nextBtn').disabled = currentSlide === totalSlides; + requestAnimationFrame(drawLineCoding); } function changeSlide(delta) { @@ -2498,6 +2499,7 @@

Wrap‑up

const canvas = document.getElementById(canvasId); if (!canvas) return; const ctx = canvas.getContext('2d'); + if (canvas.offsetWidth === 0) return; canvas.width = canvas.offsetWidth; canvas.height = 50; const w = canvas.width; @@ -2533,6 +2535,7 @@

Wrap‑up

const y = levels[i] === 1 ? high : low; if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); + ctx.lineTo(((i + 1) / levels.length) * w, y); } ctx.stroke(); } @@ -2641,6 +2644,7 @@

Wrap‑up

// Keyboard navigation document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (document.getElementById('tocModal').classList.contains('show')) { if (e.key === 'Escape') closeTOC(); return; diff --git a/00_APPENDIX/b)optional_LECTURES/S5Theory_Network_layer__IP_addressing_and_subnetting_EN.html b/00_APPENDIX/b)optional_LECTURES/S5Theory_Network_layer__IP_addressing_and_subnetting_EN.html index 64e2fd0..cbba8d3 100644 --- a/00_APPENDIX/b)optional_LECTURES/S5Theory_Network_layer__IP_addressing_and_subnetting_EN.html +++ b/00_APPENDIX/b)optional_LECTURES/S5Theory_Network_layer__IP_addressing_and_subnetting_EN.html @@ -183,7 +183,7 @@

The Network Layer:
IP Addressing & Subnetting<

The Day the Addresses Ran Out

3 February 2011 — IANA Exhaustion Day
-

On this date, the Internet Assigned Numbers Authority (IANA) handed the last five /8 blocks of IPv4 space to the Regional Internet Registries. After three decades of exponential growth, the pool of 4.3 billion publicly routable addresses was empty.

+

On this date, the Internet Assigned Numbers Authority (IANA) handed the last five /8 blocks of IPv4 space to the Regional Internet Registries. After three decades of exponential growth, the IANA free pool of ordinary /8 allocations was exhausted. The full 232 IPv4 space also includes private, reserved and other special-purpose ranges.

Yet the Internet kept growing. Billions of smartphones, IoT sensors and cloud instances came online. How?

By the end of this lecture you will understand the addressing system that both caused and survived this crisis — and you will be able to design efficient address plans yourself.

@@ -712,7 +712,7 @@

Special and Private IPv4 Addresses

Reserved Ranges

    -
  • 0.0.0.0/8 — “this host” / default route
  • +
  • 0.0.0.0/8 — this network; 0.0.0.0/0 is the default route
  • 127.0.0.0/8 — loopback (commonly 127.0.0.1)
  • 169.254.0.0/16 — link-local (APIPA)
  • 255.255.255.255 — limited broadcast
  • @@ -1378,6 +1378,7 @@

    Table of Contents

    } document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (e.key === 'ArrowRight' || e.key === ' ' || e.key === 'PageDown') { e.preventDefault(); changeSlide(1); diff --git a/00_APPENDIX/b)optional_LECTURES/S6Theory_NAT_PAT_ARP_DHCP_NDP_and_ICMP_EN.html b/00_APPENDIX/b)optional_LECTURES/S6Theory_NAT_PAT_ARP_DHCP_NDP_and_ICMP_EN.html index 1192982..aba9575 100644 --- a/00_APPENDIX/b)optional_LECTURES/S6Theory_NAT_PAT_ARP_DHCP_NDP_and_ICMP_EN.html +++ b/00_APPENDIX/b)optional_LECTURES/S6Theory_NAT_PAT_ARP_DHCP_NDP_and_ICMP_EN.html @@ -223,7 +223,7 @@

    3 February 2011 — IANA Headquarters, Los Angeles

    -

    Representatives of the five Regional Internet Registries (RIRs) gathered for what they described as a “solemn ceremony.” The Internet Assigned Numbers Authority (IANA) had just allocated the last five /8 blocks of IPv4 addresses — roughly 83 million addresses each — to the five regions. The global free pool was officially empty.

    +

    Representatives of the five Regional Internet Registries (RIRs) gathered for what they described as a “solemn ceremony.” The Internet Assigned Numbers Authority (IANA) had just allocated the last five /8 blocks of IPv4 addresses — 16,777,216 addresses each (83,886,080 in total) — to the five regions. The global free pool was officially empty.

    Yet the internet did not collapse. Thirty billion devices are online today, sharing barely 4.3 billion addresses. How?

    @@ -460,13 +460,13 @@

    PAT Port Utilisation Explorer

    Public IP: 85.120.33.7

    Port range used: 49152 – 49201

    -

    Utilisation: 50 / 16,383 ephemeral ports = 0.31%

    -

    Remaining capacity: 16,333 connections

    +

    Utilisation: 50 / 16,384 ephemeral ports = 0.31%

    +

    Remaining capacity: 16,334 connections

    Practical Limit

    -

    The IANA ephemeral range (49152–65535) provides 16,383 ports. In theory, a single public IP can support that many simultaneous connections. In practice, conntrack table memory, CPU overhead and timeout policies reduce this significantly — a typical consumer router handles 4,000–8,000 concurrent mappings before performance degrades.

    +

    The IANA ephemeral range (49152–65535) provides 16,384 ports. In theory, this simplified example permits that many distinct public ports per transport protocol; real NAT mappings can also depend on the remote endpoint. In practice, conntrack table memory, CPU overhead and timeout policies reduce this significantly — the measured capacity depends on the router and traffic pattern.

@@ -784,12 +784,12 @@

Neighbour Discovery Protocol

-

NDP: One Protocol to Replace Several

+

IPv6 Neighbour Discovery and Address Configuration

-

In IPv4, address resolution (ARP), router discovery (ICMP Router Solicitation) and address autoconfiguration (DHCP) are separate protocols. IPv6’s Neighbour Discovery Protocol (NDP, RFC 4861) consolidates all of these into a single, coherent framework built on top of ICMPv6.

+

In IPv4, address resolution (ARP), router discovery (ICMP Router Solicitation) and address autoconfiguration (DHCP) are separate protocols. IPv6 Neighbour Discovery (NDP, RFC 4861) uses ICMPv6 for neighbours, routers and prefix discovery. SLAAC uses these advertisements; DHCPv6 is a separate UDP-based configuration protocol.

- + @@ -1322,7 +1322,7 @@

Section III — DHCP

Section IV — NDP and Section V — ICMP

22 Section Title: NDP
-
23 NDP: One Protocol to Replace Several
+
23 IPv6 Neighbour Discovery and Address Configuration
24 SLAAC: Addresses Without a Server
25 Section Title: ICMP
26 Error Reporting and Diagnostics
@@ -1357,9 +1357,9 @@

Synthesis — Wrap-Up

let currentSlide = 1; document.addEventListener('DOMContentLoaded', () => { + const hash = window.location.hash; showSlide(1); updateProgress(); - const hash = window.location.hash; if (hash && hash.startsWith('#slide-')) { const n = parseInt(hash.replace('#slide-', '')); if (n >= 1 && n <= TOTAL_SLIDES) goToSlide(n); @@ -1394,6 +1394,7 @@

Synthesis — Wrap-Up

// Keyboard navigation document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return; switch (e.key) { case 'ArrowRight': case ' ': e.preventDefault(); nextSlide(); break; @@ -1466,13 +1467,13 @@

Synthesis — Wrap-Up

const n = parseInt(slider.value); const portStart = 49152; const portEnd = portStart + n - 1; - const util = ((n / 16383) * 100).toFixed(2); - const remaining = 16383 - n; + const util = ((n / 16384) * 100).toFixed(2); + const remaining = 16384 - n; document.getElementById('patCount').textContent = n; document.getElementById('patResult').innerHTML = '

Public IP: 85.120.33.7

' + '

Port range used: ' + portStart + ' \u2013 ' + portEnd + '

' + - '

Utilisation: ' + n + ' / 16,383 ephemeral ports = ' + util + '%

' + + '

Utilisation: ' + n + ' / 16,384 ephemeral ports = ' + util + '%

' + '

Remaining capacity: ' + remaining.toLocaleString() + ' connections

'; } diff --git a/00_APPENDIX/b)optional_LECTURES/S7Theory_Routing_protocols_EN.html b/00_APPENDIX/b)optional_LECTURES/S7Theory_Routing_protocols_EN.html index 55941cb..a6f0983 100644 --- a/00_APPENDIX/b)optional_LECTURES/S7Theory_Routing_protocols_EN.html +++ b/00_APPENDIX/b)optional_LECTURES/S7Theory_Routing_protocols_EN.html @@ -1546,9 +1546,9 @@

Route Poisoning

rather than simply removing it. This explicitly tells neighbours to discard it.

-

Holddown Timer

-

After a route is poisoned, ignore new information about it for a set period. -This prevents stale updates from resurrecting a dead route.

+

Implementation-specific Holddown

+

Some implementations temporarily restrict which updates can restore a failed route. +The exact acceptance rules and timer are vendor-specific; a holddown timer is not required by RFC 2453.

Triggered Updates

@@ -1568,7 +1568,7 @@

RIP Timers

Update Timer (30 s)

-

Every 30 seconds, the router broadcasts its entire routing table +

Approximately every 30 seconds, the router sends a periodic routing update to all neighbours. This is the heartbeat of the protocol.

@@ -1577,14 +1577,12 @@

Invalid Timer (180 s)

potentially invalid (metric set to 16). The route is not yet removed.

-

Flush Timer (240 s)

-

If the route remains invalid for an additional 60 seconds (total 240 s from -last valid update), it is permanently removed from the table.

+

Garbage Collection (120 s)

+

In RFC 2453, a route expires after 180 seconds without a valid refresh and then remains advertised with metric 16 during a 120-second garbage-collection interval before deletion.

-

Holddown Timer (180 s)

-

After a route is poisoned, the router ignores new information about that -destination for 180 seconds. This prevents routing loops from stale data.

+

Implementation-specific timers

+

Some router implementations add holddown and use different flush conventions. These are vendor policies, not the RFC 2453 180 + 120 second expiry sequence; consult the implementation before calculating a timeline.

@@ -1660,15 +1658,14 @@

Bellman–Ford — Worked Example

dist[B] = 1 (A→B) dist[C] = 4 (A→C) dist[D] = 3 (A→B→D) - 3 iterations needed + Pass 1 obtains final distances

Init: dist = [A:0, B:∞, C:∞, D:∞]

-

Iteration 1: Relax A→B (1), A→C (4), A→D (5) ⇒ [A:0, B:1, C:4, D:5]

-

Iteration 2: Relax B→D (1+2=3 < 5) ⇒ [A:0, B:1, C:4, D:3]

-

Iteration 3: No changes — converged.

+

Pass 1 (in-place code below): A→B gives 1, A→C gives 4, then B→D gives 3. C→D and A→D do not improve D. Result: [A:0, B:1, C:4, D:3].

+

Passes 2 and 3: No changes. The provided implementation executes all |V|−1 passes; an early-stop variant could finish after pass 2.

@@ -1972,7 +1969,7 @@

Dijkstra — Worked Example

Step 2: Visit B (dist=1)Update D=1+2=3 < 5 ⇒ D=3Step 3: Visit D (dist=3) - C: 3+3=6 > 4 ⇒ no change + D has no outgoing edge in this directed graphStep 4: Visit C (dist=4)Done. All visited. @@ -2236,7 +2233,7 @@

What we now understand

Synthesis Question

-

A company has 50 routers in a single site, all connected via Ethernet. +

A company connects 50 routers in a linear chain, with no shorter alternative paths. An engineer proposes using RIP for routing. Which is the strongest argument against this choice?

@@ -2246,7 +2243,7 @@

A company has 50 routers in a single site, all connected via Ethernet. B) RIP does not support Ethernet networks

-C) With 50 routers, some paths will exceed 15 hops, making portions of the network unreachable +C) In this chain, the end-to-end shortest paths exceed 15 hops, making distant networks unreachable via RIP
D) RIP cannot operate without a designated router @@ -2254,13 +2251,13 @@

A company has 50 routers in a single site, all connected via Ethernet.
✔ Correct. The 15-hop ceiling is the fundamental scalability limit of RIP. In a -network of 50 routers, the diameter (longest shortest path) can easily exceed 15 hops, +linear 50-router chain, the diameter (longest shortest path) exceeds 15 hops, rendering portions of the network unreachable. OSPF, with its area hierarchy and no hop limit, is the appropriate choice here.
✘ While RIP’s periodic broadcasts do consume some bandwidth, the primary -issue with 50 routers is the 15-hop limit. Paths longer than 15 hops +issue with the stated linear topology is the 15-hop limit. Paths longer than 15 hops are treated as unreachable (metric 16 = infinity). RIP works fine on Ethernet, and the DR/BDR concept belongs to OSPF, not RIP. The hop limit is the decisive factor.
@@ -2366,7 +2363,7 @@

Practical exercises

Self-assessment

Can you trace Dijkstra by hand on a 5-node graph?
-Can you explain why RIP fails in a 20-router network?
+Can you explain why RIP cannot reach end-to-end networks in a 20-router chain, while 20 routers in a shallow topology need not exceed its hop limit?
Can you calculate the OSPF cost of a path with mixed-speed links?

@@ -2519,6 +2516,7 @@

Reflection — Summary and Next Steps

// ==================== KEYBOARD NAVIGATION ==================== document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); nextSlide(); diff --git a/00_APPENDIX/b)optional_LECTURES/S8Theory_Transport_layer_EN.html b/00_APPENDIX/b)optional_LECTURES/S8Theory_Transport_layer_EN.html index 29e1360..0327036 100644 --- a/00_APPENDIX/b)optional_LECTURES/S8Theory_Transport_layer_EN.html +++ b/00_APPENDIX/b)optional_LECTURES/S8Theory_Transport_layer_EN.html @@ -530,10 +530,10 @@

Well-Known Ports

Quick check: DNS primarily uses port 53 over UDP. Why might DNS sometimes switch to TCP on the same port?

TCP is faster for short queries
UDP cannot carry DNS packets
-
When the response exceeds 512 bytes (e.g. zone transfers or DNSSEC), TCP handles the larger payload reliably
+
When UDP replies are truncated, the client can retry over TCP; AXFR also uses TCP
The DNS standard requires TCP for all queries since 2020
- Correct. Standard DNS responses fit within a single UDP datagram (historically capped at 512 bytes). Zone transfers (AXFR) and large DNSSEC-signed responses exceed this limit, so TCP is used for segmentation and reliable reassembly. The server listens on port 53 for both protocols. + Correct. The original DNS UDP payload limit was 512 bytes; EDNS supports a larger advertised size. Truncation signals TCP fallback, and AXFR uses TCP. DNS-over-TCP uses a two-byte length prefix per DNS message; it is not an unlimited message format.
@@ -668,7 +668,7 @@

The TCP Header (Minimum 20 Bytes)

TCP Flags: Controlling the Connection

-

The TCP header contains nine single-bit flags, each signalling a specific control action:

+

The RFC 9293 base TCP header defines eight control flags, each signalling a specific control action:

Connection lifecycle

@@ -679,14 +679,14 @@

Connection lifecycle

Data control

ACK — acknowledgement field is valid.

-

PSH — push to application immediately.

+

PSH — request prompt delivery without defining message boundaries.

URG — urgent data present (rare).

Congestion signals

ECE — congestion echo.

CWR — congestion window reduced.

-

NS — nonce concealment (experimental).

+

Historical NS belonged to the ECN nonce experiment, not the eight-flag RFC 9293 baseline.

@@ -916,7 +916,7 @@

Why it matters

SACK — Selective Acknowledgement

-

Without SACK, TCP acknowledgements are cumulative: an ACK for byte 5000 means “I have received all bytes up to 5000.” If bytes 5001–6000 are lost but 6001–8000 arrive, the sender must retransmit everything from 5001 onwards—even the data that arrived safely.

+

TCP acknowledgements are cumulative: ACK 5000 means the next expected byte is 5000, so all earlier bytes have arrived. If bytes 5000–5999 are missing but 6000–7999 arrive, SACK can report the later received range. Without SACK the sender has less information; it does not follow that it must retransmit every later byte.

Data stream with a gap (bytes 5001–6000 lost) @@ -1139,7 +1139,7 @@

TLS in the Protocol Stack

TLS is strictly speaking not a transport-layer protocol—it operates above TCP (or UDP, in the case of DTLS). However, it is tightly coupled to transport semantics. HTTPS is simply HTTP running through a TLS tunnel over TCP port 443.

-

TLS consists of several sub-protocols: the Handshake Protocol (key exchange, authentication), the Record Protocol (encryption of application data), the Alert Protocol (error signalling) and the Change Cipher Spec protocol (TLS 1.2 only; removed in TLS 1.3).

+

TLS consists of several sub-protocols: the Handshake Protocol (key exchange, authentication), the Record Protocol (encryption of application data), the Alert Protocol (error signalling) and the Change Cipher Spec mechanism (functional in TLS 1.2; TLS 1.3 may send compatibility CCS records that do not change keys).

@@ -1624,13 +1624,16 @@

Contents

const feedback = container.querySelector('.quiz-feedback'); options.forEach(opt => { - opt.style.pointerEvents = 'none'; + opt.classList.remove('correct', 'incorrect'); + // Keep options active so learners can retry after feedback. if (opt === element) { opt.classList.add(isCorrect ? 'correct' : 'incorrect'); + } else if (!isCorrect && (opt.getAttribute('onclick') || '').includes('true')) { + opt.classList.add('correct'); } }); - if (isCorrect && feedback) { + if (feedback) { feedback.classList.add('show'); } } @@ -1658,6 +1661,7 @@

Contents

// Keyboard navigation document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); changeSlide(1); diff --git a/00_APPENDIX/b)optional_LECTURES/S9Theory_Session_and_presentation_concepts_EN.html b/00_APPENDIX/b)optional_LECTURES/S9Theory_Session_and_presentation_concepts_EN.html index b079f49..9ba131b 100644 --- a/00_APPENDIX/b)optional_LECTURES/S9Theory_Session_and_presentation_concepts_EN.html +++ b/00_APPENDIX/b)optional_LECTURES/S9Theory_Session_and_presentation_concepts_EN.html @@ -472,9 +472,9 @@

By the end of this lecture, you will:

Practical connections:

-

🔧 Starterkit Exercises

-

ex_9_01_endianness.py — Binary framing

-

ex_9_02_pseudo_ftp.py — Session management

+

🔧 Canonical COMPNET-EN activities

+

S04 binary protocol — inspect the actual framing contract.

+

S09 pseudo-FTP — separate control/data channels.

🌐 Real-World Skills

@@ -664,7 +664,7 @@

Session State Includes:

Python Session Class

-

See ex_9_02_pseudo_ftp.py — the Session class maintains authenticated, username, and cwd state across commands.

+

The illustrative Session class on slide 29 maintains authentication, username and directory state. The repository’s S09 pseudo-FTP implements a different, explicitly documented teaching protocol; do not assume this class or authentication exchange is present there.

@@ -896,7 +896,7 @@

🔢 Byte Order: Big-Endian vs Little-Endian

-The Rule: Network protocols use Big-Endian (Network Byte Order). Always convert before sending! +The Rule: Use the byte order specified by the protocol. TCP/IP integer header fields use big-endian; application formats may differ (for example Protobuf fixed32/fixed64 use little-endian).
import struct @@ -987,7 +987,9 @@

Field Purposes:

-# From ex_9_01_endianness.py +# Standalone illustrative format, not the canonical S04 or S09 wire protocol +import struct +import zlib HEADER_FORMAT = "!2sBBII" MAGIC = b"S9" @@ -1067,8 +1069,8 @@

The Encoding Problem

- - + +
FunctionIPv4 ProtocolNDP Equivalent (IPv6)
FunctionIPv4 ProtocolIPv6 mechanism
IP → MAC resolutionARP (broadcast)Neighbour Solicitation / Advertisement (multicast)
Router discoveryICMP Router Discovery (optional)Router Solicitation / Advertisement (mandatory)
Address autoconfigurationDHCPSLAAC (stateless) or DHCPv6 (stateful)
Encoding"Ș" (Romanian)Notes
UTF-8C8 98Variable width, ASCII-compat
UTF-1601 982-4 bytes per char
ISO-8859-2AALatin-2, limited
UTF-16BE02 18U+0218 Ș; UTF-16LE is 18 02
ISO-8859-2Not representableAA encodes Ş (U+015E), not Ș (U+0218)
@@ -1310,8 +1312,8 @@

Passive Mode (PASV)

-

🛠️ Starterkit: Pseudo-FTP Implementation

-

The ex_9_02_pseudo_ftp.py implements simplified FTP demonstratification L5/L6 concepts:

+

🛠️ Illustrative Session and Framing Design

+

These self-contained design fragments illustrate session state and a custom 12-byte header. They are not an implementation of standard FTP or the repository’s S09 one-byte data-length protocol. For the runnable activity, follow the canonical S09 README.

Session Layer (L5) Features

@@ -1365,7 +1367,7 @@

Presentation Layer (L6) Features

-Try it: make server in one terminal, make client-list in another. Use make capture to see traffic in Wireshark. +Try the canonical activity: open S09 pseudo-FTP instructions. Start its supplied server and client in separate terminals and capture the actual control/data exchanges. Its framing differs from the illustrative header above.
@@ -1425,17 +1427,19 @@

What to Look For

-

Starterkit Helper

+

Local capture

# Automated capture -make capture-save -# Output: artifacts/demo.pcap +mkdir -p captures +sudo tcpdump -i lo -w "captures/s09-$(date +%Y%m%dT%H%M%S).pcap" \ + 'tcp and host 127.0.0.1' +# Run the local S09 client in another terminal, then Ctrl+C.
-Lab Deliverable: A .pcap file demonstratification control/data separation with correctly interpreted binary headers. +Lab Deliverable: A .pcap file demonstrating control/data separation with correctly interpreted binary headers.
@@ -1456,7 +1460,7 @@

Session Layer Functions

@@ -1490,7 +1494,7 @@

🧠 Knowledge Check: Presentation Layer

Answer: B
-

The ! prefix specifies network byte order (big-endian), and I means unsigned int (4 bytes). This is the standard format for transmitting integers in network protocols.

+

The ! prefix specifies network byte order (big-endian), and I means unsigned int (4 bytes). Use this format when the application protocol specifies an unsigned 32-bit big-endian field.

@@ -1762,12 +1766,12 @@

Online Documentation

  • Python socket HOWTO: docs.python.org/3/howto/sockets
  • MDN Web Docs: developer.mozilla.org
  • -

    Starterkit Files

    +

    Canonical repository activities

    @@ -1799,10 +1803,11 @@

    Thank You!

    Questions?

    See you at the seminar for hands-on implementation!

    -cd ~/WEEK9 -make setup -make server # Terminal 1 -make client-list # Terminal 2 +cd ~/COMPNET-EN +cd 04_SEMINARS/S09/2_custom-pseudo-ftp +python3 S09_Part02B_Script_Pseudo_FTP_Server.py +# Terminal 2, in the same directory: +python3 S09_Part02C_Script_Pseudo_FTP_Client.py

    ASE-CSIE 2025 | Computer Networks | Collective teaching staff

    @@ -1939,8 +1944,8 @@

    Wrap-up

    incorrect: '✗ Not quite. Compression is a Presentation Layer (L6) function — it transforms data representation. The Session Layer (L5) handles dialogue management: establishing/terminating sessions, synchronisation checkpoints, and dialogue control modes. Think of L5 as the "conversation manager" and L6 as the "translator".' }, 2: { - correct: '✓ Correct! The ! prefix means network byte order (big-endian), and I means unsigned 32-bit integer (4 bytes). This is the standard for sending multi-byte integers across networks — recall from Week 8 that TCP/IP uses big-endian for all protocol fields.', - incorrect: '✗ Not quite. In Python\'s struct module, ! specifies network byte order (big-endian), and I means unsigned 32-bit integer (4 bytes). The ! prefix is shorthand for > and is the correct choice for any value transmitted over a network. Signed integers use lowercase i; floating-point uses f or d.' + correct: '✓ Correct! The ! prefix means network byte order (big-endian), and I means unsigned 32-bit integer (4 bytes). This is appropriate for the specified big-endian field; application protocols may specify different encodings.', + incorrect: '✗ Not quite. In Python\'s struct module, ! specifies network byte order (big-endian), and I means unsigned 32-bit integer (4 bytes). The ! prefix is shorthand for > and is appropriate when the protocol specifies big-endian standard-width fields. Signed integers use lowercase i; floating-point uses f or d.' }, 3: { correct: '✓ Correct! In passive mode (PASV), the server opens a dynamic port and tells the client its number. The client then initiates the data connection — this works through NAT and firewalls because outbound connections from the client are typically permitted. Control commands (USER, PASS, LIST) are text-based, not binary.', @@ -2003,6 +2008,7 @@

    Wrap-up

    } document.addEventListener('keydown', (e) => { + if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return; if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); nextSlide(); } else if (e.key === 'ArrowLeft') { e.preventDefault(); prevSlide(); } else if (e.key === 'Home') { e.preventDefault(); showSlide(1); } diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W02_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W02_Questions.md index 391131a..d6f5d42 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W02_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W02_Questions.md @@ -58,18 +58,20 @@ A student instructor recommends using ss instead of netstat for socket inspectio ### Q4. `N01.T00.Q14` — Evaluating Socket Timeout Design / Evaluarea designului de timeout al socket-ului -*[Multiple Choice — Alegere multiplă]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -The ex_1_02_tcp_server_client.py exercise in the Week 1 lab uses a blocking recv(1024) without a timeout. A colleague proposes adding socket.settimeout(5) to both server and client. Which statement best evaluates this proposal? [Exercițiul ex_1_02_tcp_server_client.py din laboratorul Săptămânii 1 folosește un recv(1024) blocant fără timeout. Un coleg propune adăugarea socket.settimeout(5) atât la server, cât și la client. Care afirmație evaluează cel mai bine această propunere?] +A TCP client sends no data and leaves its connection open. How should a server choose an idle receive timeout? [Un client TCP nu trimite date și lasă conexiunea deschisă. Cum trebuie ales timeout-ul de inactivitate pentru recepție?] -- **a)** Server timeout is beneficial (prevents hang on client disconnect), but client timeout should be calibrated independently — a fixed 5 s may be too short under server load [Timeout-ul serverului este benefic (previne blocarea la deconectarea clientului), dar timeout-ul clientului ar trebui calibrat independent — 5 s fixe pot fi prea puțin sub sarcină] -- **b)** The proposal is entirely correct — both server and client should always share the same timeout value to ensure symmetrical behaviour across the connection [Propunerea este complet corectă — atât serverul, cât și clientul ar trebui să partajeze întotdeauna aceeași valoare de timeout pentru comportament simetric] -- **c)** Timeouts should never be added to socket code because they cause socket.timeout exceptions that crash the programme if not caught in a try-except block [Timeout-urile nu ar trebui niciodată adăugate la codul de socket deoarece cauzează excepții socket.timeout care opresc programul dacă nu sunt prinse] -- **d)** The proposal is unnecessary because TCP's built-in keepalive mechanism automatically detects dead connections and closes them within seconds on loopback [Propunerea este inutilă deoarece mecanismul keepalive TCP detectează automat conexiunile moarte și le închide în câteva secunde pe loopback] +- **a)** Choose and handle it according to the application contract; calibrate the client response timeout separately. [Alegeți și tratați timeout-ul conform contractului aplicației; calibrați separat timeout-ul de răspuns al clientului.] +- **b)** Always use the same five-second timeout for accept, receive and every client operation. [Folosiți întotdeauna același timeout de cinci secunde pentru accept, recepție și toate operațiile clientului.] +- **c)** A timeout is unnecessary because an idle TCP connection always closes within seconds. [Timeout-ul este inutil deoarece o conexiune TCP inactivă se închide mereu în câteva secunde.] +- **d)** Treat every timeout as proof that the peer has crashed. [Tratați orice timeout ca dovadă că procesul corespondent s-a oprit.] -> 💡 **Feedback:** -> *A 5-second timeout on the server's accept/recv is beneficial — it prevents indefinite hangs when clients disconnect unexpectedly. However, applying the same timeout to the client is risky if the server takes longer than 5 seconds to respond under load. The correct approach differentiates: server timeout prevents resource leaks; client timeout should be calibrated to expected response time. [Un timeout de 5 secunde pe accept/recv la server este benefic — previne blocările indefinite. Dar aplicarea aceluiași timeout la client este riscantă dacă serverul necesită mai mult timp sub sarcină.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** An idle or unreachable peer can leave a blocking receive waiting. A graceful peer shutdown instead yields EOF after buffered data. A timeout is a policy decision and must be handled; it is not a unique diagnosis of peer failure. [Un corespondent inactiv sau inaccesibil poate lăsa recepția blocată. O închidere grațioasă produce EOF după datele deja recepționate. Timeout-ul este o decizie a aplicației și trebuie tratat; nu demonstrează în mod unic defectarea corespondentului.] + +
    --- @@ -245,7 +247,7 @@ When a TCP server calls sock.accept(), what does it return? [Când un server TCP *[Multiple Choice — Alegere multiplă]* -Ten clients connect simultaneously to a server. Each request takes 100 ms to process. What is the approximate total time until all clients receive responses for an iterative server vs. a threaded server? [Zece clienți se conectează simultan la un server. Fiecare cerere necesită 100 ms pentru procesare. Care este timpul total aproximativ până când toți clienții primesc răspunsuri pentru un server iterativ versus un server cu fire de execuție?] +Ten clients connect simultaneously to a server. Each request spends 100 ms waiting for independent I/O, all ten workers can overlap this wait, and scheduling and network overhead are negligible. What is the approximate total time until all clients receive responses for an iterative server vs. a threaded server? [Zece clienți se conectează simultan la un server. Fiecare cerere petrece 100 ms așteptând I/O independent, cei zece workeri pot suprapune așteptarea, iar overhead-ul de planificare și rețea este neglijabil. Care este timpul total aproximativ până când toți clienții primesc răspunsuri pentru un server iterativ versus un server cu fire de execuție?] - **a)** Iterative: \~1000 ms; Threaded: \~100 ms [Iterativ: \~1000 ms; Cu fire: \~100 ms] - **b)** Iterative: \~100 ms; Threaded: \~100 ms [Iterativ: \~100 ms; Cu fire: \~100 ms] @@ -255,7 +257,6 @@ Ten clients connect simultaneously to a server. Each request takes 100 ms to pro > 💡 **Feedback:** > *An iterative server processes clients one at a time (10 x 100 ms = 1000 ms total). A threaded server handles all 10 in parallel, completing in approximately 100 ms plus minor thread overhead. A common misconception (Misconception #4) is that threading always improves performance; for a single short-lived client, threading adds unnecessary overhead. [Un server iterativ procesează clienții pe rând (10 x 100 ms = 1000 ms total). Un server cu fire de execuție gestionează toți cei 10 în paralel, finalizând în aproximativ 100 ms plus overhead minor de fire. O concepție greșită frecventă (Concepția greșită nr. 4) este că firele de execuție îmbunătățesc întotdeauna performanța; pentru un singur client cu cerere scurtă, firele adaugă overhead inutil.]* - --- ### Q16. `N02.T00.Q08` — Understanding what accept() returns on a TCP server / Înțelegerea valorii returnate de accept() pe un server TCP @@ -440,18 +441,20 @@ In Python, what is the correct sequence of method calls to set up a TCP server s ### Q26. `N02.S01.Q01` — Socket option to allow immediate rebind after restart / Opțiunea de socket pentru reconectare imediată după repornire -*[Multiple Choice — Alegere multiplă]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -Which socket option should be set on a server socket to allow immediate rebinding to a port that is still in TIME_WAIT state after a previous server instance was stopped? [Care opțiune de socket trebuie setată pe un socket de server pentru a permite reconectarea imediată la un port aflat încă în starea TIME_WAIT după oprirea unei instanțe anterioare a serverului?] +Which socket option is commonly set before bind() to support server-address reuse under the operating system’s reuse rules? [Ce opțiune este setată frecvent înainte de bind() pentru reutilizarea adresei serverului conform regulilor sistemului de operare?] - **a)** SO_REUSEADDR - **b)** SO_KEEPALIVE - **c)** SO_BROADCAST - **d)** SO_LINGER -> 💡 **Feedback:** -> *SO_REUSEADDR allows binding to a port in TIME_WAIT state, preventing the common "Address already in use" error during development and server restarts. Without this option, you must wait approximately 60 seconds (the TIME_WAIT duration) before the port becomes available again. A common misconception (Misconception #10) is that close() immediately frees the port; in reality, TIME_WAIT persists to handle delayed packets from the old connection. [SO_REUSEADDR permite asocierea la un port aflat în starea TIME_WAIT, prevenind eroarea frecventă „Address already in use" în timpul dezvoltării și repornirilor de server. Fără această opțiune, trebuie să așteptați aproximativ 60 de secunde (durata TIME_WAIT) înainte ca portul să devină disponibil. O concepție greșită frecventă (Concepția greșită nr. 10) este că close() eliberează imediat portul; în realitate, TIME_WAIT persistă pentru a gestiona pachetele întârziate de la vechea conexiune.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** SO_REUSEADDR can help a restarting server rebind when old TCP connections retain state. TIME_WAIT belongs to a connection, not a listening port. This option does not guarantee every bind succeeds or override an active listener; details and timeout durations vary by OS and configuration. [SO_REUSEADDR poate ajuta un server repornit când conexiunile TCP vechi păstrează stare. TIME_WAIT aparține unei conexiuni, nu portului listenerului. Opțiunea nu garantează orice bind și nu înlocuiește un listener activ; regulile și duratele depind de sistem și configurație.] + +
    --- @@ -459,7 +462,7 @@ Which socket option should be set on a server socket to allow immediate rebindin *[Multiple Choice — Alegere multiplă]* -What is the correct order of socket API calls to set up a TCP server that accepts connections? [Care este ordinea corectă a apelurilor API socket pentru a configura un server TCP care acceptă conexiuni?] +What is the explicit socket-call sequence used to bind the lab TCP server to a chosen local address and port before accepting connections? [Care este secvența explicită folosită pentru a lega serverul TCP de laborator la adresa și portul local alese înainte de acceptarea conexiunilor?] - **a)** socket() → bind() → listen() → accept() - **b)** socket() → listen() → bind() → accept() @@ -467,8 +470,7 @@ What is the correct order of socket API calls to set up a TCP server that accept - **d)** socket() → connect() → listen() → accept() > 💡 **Feedback:** -> *A TCP server must create a socket, bind it to a local address, call listen() to mark it as passive, then accept() to extract pending connections from the queue. Calling listen() before bind() would fail because the socket has no local address yet. A common error is inserting connect() instead of listen(), confusing the server-side and client-side API flows. [Un server TCP trebuie să creeze un socket, să-l asocieze la o adresă locală prin bind(), să apeleze listen() pentru a-l marca ca pasiv, apoi accept() pentru a extrage conexiunile în așteptare din coadă. Apelarea listen() înainte de bind() ar eșua deoarece socket-ul nu are încă o adresă locală. O eroare frecventă este inserarea connect() în locul listen(), confundând fluxurile API pe partea de server și pe partea de client.]* - +> *A TCP server must create a socket, bind it to a local address, call listen() to mark it as passive, then accept() to extract pending connections from the queue. On Linux, listen() on an unbound Internet socket may implicitly bind an ephemeral port; explicit bind() selects the required laboratory endpoint. A common error is inserting connect() instead of listen(), confusing the server-side and client-side API flows. [Un server TCP trebuie să creeze un socket, să-l asocieze la o adresă locală prin bind(), să apeleze listen() pentru a-l marca ca pasiv, apoi accept() pentru a extrage conexiunile în așteptare din coadă. Pe Linux, listen() pe un socket Internet nelegat poate face implicit bind la un port efemer; bind() explicit selectează endpointul cerut de laborator. O eroare frecventă este inserarea connect() în locul listen(), confundând fluxurile API pe partea de server și pe partea de client.]* --- @@ -559,33 +561,37 @@ Calling sock.bind(("0.0.0.0", 12345)) on a TCP server socket causes packets to b ### Q33. `N02.S04.Q08` — Closing a socket immediately frees the port / Închiderea unui socket eliberează imediat portul -*[True/False — Adevărat/Fals]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -After calling sock.close() on a TCP server socket, the port is immediately available for another process to bind to. [După apelarea sock.close() pe un socket de server TCP, portul este imediat disponibil pentru ca alt proces să facă bind la el.] +Does closing the listening TCP socket always guarantee that a new process can immediately bind the same endpoint? [Închiderea socketului TCP de ascultare garantează întotdeauna că alt proces poate face imediat bind la același endpoint?] -- **a)** True / Adevărat -- **b)** False / Fals +- **a)** No: accepted sockets, other bindings and address-reuse rules can still matter. [Nu: socketurile acceptate, alte legări și regulile de reutilizare a adresei pot conta.] +- **b)** Yes: close removes every connection owned by the process. [Da: close elimină toate conexiunile procesului.] +- **c)** No: every listening socket itself enters TIME_WAIT for exactly 60 seconds. [Nu: fiecare socket de ascultare intră el însuși în TIME_WAIT exact 60 de secunde.] -> 💡 **Feedback:** -> *False. TCP sockets enter TIME_WAIT state (typically 60 seconds) after closing to handle any delayed packets still in transit. Use SO_REUSEADDR to allow rebinding during development, or wait for the timeout to expire. This is a critical practical issue (Misconception #10): students frequently encounter "Address already in use" when restarting servers during development, and the solution is to set SO_REUSEADDR before calling bind(). [Fals. Socket-urile TCP intră în starea TIME_WAIT (de obicei 60 de secunde) după închidere pentru a gestiona pachetele întârziate aflate încă în tranzit. Utilizați SO_REUSEADDR pentru a permite reconectarea în timpul dezvoltării, sau așteptați expirarea timeout-ului. Aceasta este o problemă practică critică (Concepția greșită nr. 10): studenții întâlnesc frecvent eroarea „Address already in use" la repornirea serverelor în timpul dezvoltării, iar soluția este setarea SO_REUSEADDR înainte de apelul bind().]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** A listener is not an established TCP connection and does not itself enter TIME_WAIT. TIME_WAIT belongs to particular connections, usually at the active closer. SO_REUSEADDR can help server restarts when platform rules permit; it does not override an active listener. [Un listener nu este o conexiune TCP stabilită și nu intră el însuși în TIME_WAIT. TIME_WAIT aparține unor conexiuni, de regulă la capătul care închide activ. SO_REUSEADDR poate ajuta repornirea conform regulilor platformei, dar nu înlocuiește un listener activ.] + +
    --- ### Q34. `N02.S03.Q02` — TCP vs UDP minimum packet count for single exchange / Numărul minim de pachete TCP versus UDP pentru un singur schimb -*[Multiple Choice — Alegere multiplă]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -A client sends one message and receives one response, then disconnects. Approximately how many minimum packets would be visible in Wireshark for TCP vs. UDP? [Un client trimite un mesaj și primește un răspuns, apoi se deconectează. Aproximativ câte pachete minime ar fi vizibile în Wireshark pentru TCP versus UDP?] +For one request and one response, what can be concluded about captured TCP and UDP packet counts without further assumptions? [Pentru o cerere și un răspuns, ce se poate concluziona despre numărul pachetelor TCP și UDP capturate fără alte ipoteze?] -- **a)** TCP: \~10 packets; UDP: 2 packets [TCP: \~10 pachete; UDP: 2 pachete] -- **b)** TCP: 2 packets; UDP: 2 packets [TCP: 2 pachete; UDP: 2 pachete] -- **c)** TCP: \~10 packets; UDP: \~10 packets [TCP: \~10 pachete; UDP: \~10 pachete] -- **d)** TCP: 3 packets; UDP: 2 packets [TCP: 3 pachete; UDP: 2 pachete] +- **a)** TCP has no universal fixed count; unfragmented UDP contributes two application datagrams if both are delivered. [TCP nu are un număr universal fix; UDP nefragmentat contribuie două datagrame ale aplicației dacă ambele sunt livrate.] +- **b)** TCP always produces exactly ten packets. [TCP produce întotdeauna exact zece pachete.] +- **c)** TCP always produces exactly three packets including the response. [TCP produce întotdeauna exact trei pachete incluzând răspunsul.] -> 💡 **Feedback:** -> *TCP requires approximately 10 packets (3 handshake + 2 data + 2 ACKs + 3 teardown), while UDP requires only 2 packets (one request datagram, one response datagram) with no setup or teardown overhead. This stark difference illustrates why UDP is preferred for simple query-response protocols like DNS. A common error is underestimating TCP's overhead by forgetting the handshake and teardown phases. [TCP necesită aproximativ 10 pachete (3 handshake + 2 date + 2 confirmări ACK + 3 terminare), în timp ce UDP necesită doar 2 pachete (o datagramă de cerere, o datagramă de răspuns) fără overhead de stabilire sau terminare. Această diferență marcantă ilustrează de ce UDP este preferat pentru protocoale simple de tip cerere-răspuns precum DNS. O eroare frecventă este subestimarea overhead-ului TCP prin uitarea fazelor de handshake și terminare.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** TCP counts depend on handshake and close choices, segmentation, ACK combination, retransmissions and capture point. UDP has no transport handshake; fragmentation and unrelated ARP/DNS traffic can increase a capture total. [Numărul TCP depinde de stabilire și închidere, segmentare, combinarea ACK-urilor, retransmisii și punctul capturii. UDP nu are handshake de transport; fragmentarea și traficul ARP/DNS pot crește totalul capturii.] +
    --- diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W03_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W03_Questions.md index 05a87f3..eaaf016 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W03_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W03_Questions.md @@ -119,8 +119,7 @@ TCP connections can use broadcast addressing to reach all hosts on a local segme - **b)** false > 💡 **Feedback:** -> *Broadcast operates exclusively with UDP (connectionless datagrams). TCP requires a dedicated connection between two endpoints and cannot establish sessions with "all hosts" — there is no TCP broadcast. [Broadcast-ul funcționează exclusiv cu UDP (datagrame fără conexiune). TCP necesită o conexiune dedicată între două puncte terminale și nu poate stabili sesiuni cu "toate gazdele" — nu există TCP broadcast.]* - +> *In these socket examples UDP supports broadcast, whereas TCP does not. Broadcast also exists below the transport layer, for example Ethernet ARP frames. TCP requires a dedicated connection between two endpoints and cannot establish sessions with "all hosts" — there is no TCP broadcast. [În aceste exemple de socket, UDP suportă broadcast, iar TCP nu. Broadcast există și sub stratul de transport, de exemplu în cadrele Ethernet ARP. TCP necesită o conexiune dedicată între două puncte terminale și nu poate stabili sesiuni cu "toate gazdele" — nu există TCP broadcast.]* --- @@ -206,18 +205,21 @@ In the Week 3 Python exercises, what socket-level operation triggers the host's --- -### Q13. +### Q13. — Explicit multicast membership / Apartenență multicast explicită -*[True / False]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -For a UDP socket to receive multicast traffic, it is sufficient to call bind(('', port)) on the correct port; no additional socket options are required. [Pentru ca un socket UDP să primească trafic multicast, este suficient să se apeleze bind(('', port)) pe portul corect; nu sunt necesare opțiuni suplimentare de socket.] +The S03 receiver uses group 239.255.0.1. On Linux it sets IP_MULTICAST_ALL=0. Which additional step explicitly subscribes this socket on the selected interface? [Receptorul S03 folosește grupul 239.255.0.1. Pe Linux setează IP_MULTICAST_ALL=0. Ce pas suplimentar abonează explicit acest socket pe interfața aleasă?] -- **a)** true -- **b)** false +- **a)** `setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)` +- **b)** `setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)` +- **c)** `setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)` -> 💡 **Feedback:** -> *Binding alone is insufficient for multicast reception. The socket must also call setsockopt() with IP_ADD_MEMBERSHIP to join the group. Without this call, the kernel simply ignores incoming multicast packets even if the port matches. This is the most common student error in the Week 3 exercises. [Legarea singură nu este suficientă pentru recepția multicast. Socket-ul trebuie să apeleze și setsockopt() cu IP_ADD_MEMBERSHIP pentru a se alătura grupului. Fără acest apel, nucleul pur și simplu ignoră pachetele multicast primite chiar dacă portul se potrivește. Aceasta este cea mai frecventă eroare a studenților în exercițiile din Săptămâna 3.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Join the application group using IP_ADD_MEMBERSHIP and the intended local interface. Binding selects a local endpoint. Linux IP_MULTICAST_ALL=1 can also deliver traffic for groups joined elsewhere on the host, and 224.0.0.1 is the special all-hosts group. Therefore “no explicit join always means no reception” is not a portable rule. Receipt still depends on reachability and filtering. [Aderați la grupul aplicației prin IP_ADD_MEMBERSHIP pe interfața locală dorită. Bind selectează endpointul local. Linux IP_MULTICAST_ALL=1 poate livra și trafic pentru grupuri la care s-a aderat în altă parte pe gazdă, iar 224.0.0.1 este grupul special al tuturor gazdelor. Prin urmare, lipsa aderării explicite nu implică universal lipsa recepției. Recepția depinde și de conectivitate și filtrare.] +
    --- @@ -301,19 +303,21 @@ From a security perspective, what inherent risk does broadcast communication pos --- -### Q19. +### Q19. — Explicit multicast membership / Apartenență multicast explicită -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -A student writes a multicast receiver that binds to port 5001, sets SO_REUSEADDR, but forgets to call IP_ADD_MEMBERSHIP. The sender transmits to 224.0.0.1:5001. What is the observable result on the receiver? [Un student scrie un receptor multicast care se leagă la portul 5001, setează SO_REUSEADDR, dar uită să apeleze IP_ADD_MEMBERSHIP. Expeditorul transmite la 224.0.0.1:5001. Care este rezultatul observabil pe receptor?] +The S03 receiver uses group 239.255.0.1. On Linux it sets IP_MULTICAST_ALL=0. Which additional step explicitly subscribes this socket on the selected interface? [Receptorul S03 folosește grupul 239.255.0.1. Pe Linux setează IP_MULTICAST_ALL=0. Ce pas suplimentar abonează explicit acest socket pe interfața aleasă?] -- **a)** The bind succeeds but recvfrom() blocks indefinitely — multicast packets are silently ignored without group membership [Legarea reușește dar recvfrom() blochează indefinit — pachetele multicast sunt ignorate silențios fără apartenență la grup] -- **b)** The kernel raises an OSError at bind time because the socket cannot listen on a multicast port without group join in practice [Nucleul ridică o eroare OSError la momentul legării deoarece socket-ul nu poate asculta pe un port multicast fără aderare în practică] -- **c)** The receiver gets all multicast traffic on the subnet automatically because binding to the port is sufficient (default) [Receptorul primește automat tot traficul multicast din subrețea deoarece legarea la port este suficientă (implicit)] +- **a)** `setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)` +- **b)** `setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)` +- **c)** `setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)` -> 💡 **Feedback:** -> *Without IP_ADD_MEMBERSHIP, the kernel does not subscribe to the multicast group via IGMP. The NIC and kernel silently discard incoming multicast packets for groups not joined. Binding to the port is necessary but not sufficient — it only determines which local port to listen on, not which multicast groups to receive. [Fără IP_ADD_MEMBERSHIP, nucleul nu se abonează la grupul multicast prin IGMP. Placa de rețea și nucleul descarcă silențios pachetele multicast primite pentru grupuri la care nu s-a aderat. Legarea la port este necesară dar nu suficientă — determină doar pe ce port local să asculte, nu ce grupuri multicast să primească.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Join the application group using IP_ADD_MEMBERSHIP and the intended local interface. Binding selects a local endpoint. Linux IP_MULTICAST_ALL=1 can also deliver traffic for groups joined elsewhere on the host, and 224.0.0.1 is the special all-hosts group. Therefore “no explicit join always means no reception” is not a portable rule. Receipt still depends on reachability and filtering. [Aderați la grupul aplicației prin IP_ADD_MEMBERSHIP pe interfața locală dorită. Bind selectează endpointul local. Linux IP_MULTICAST_ALL=1 poate livra și trafic pentru grupuri la care s-a aderat în altă parte pe gazdă, iar 224.0.0.1 este grupul special al tuturor gazdelor. Prin urmare, lipsa aderării explicite nu implică universal lipsa recepției. Recepția depinde și de conectivitate și filtrare.] + +
    --- @@ -329,8 +333,7 @@ A Python script creates a UDP socket and immediately calls sock.sendto(b"test", - **d)** No exception — the send succeeds silently but the datagram is dropped before reaching the network interface [Nicio excepție — trimiterea reușește silențios dar datagrama este descărcată înainte de a ajunge la interfața de rețea] > 💡 **Feedback:** -> *The kernel treats SO_BROADCAST as a mandatory permission flag, not a hint. Without it, sendto() to a broadcast address raises OSError (errno 101: Network is unreachable) or PermissionError. This is a deliberate safety mechanism — not a timeout, not a warning, not a DNS failure. [Nucleul tratează SO_BROADCAST ca un flag obligatoriu de permisiune, nu un indiciu. Fără acesta, sendto() la o adresă broadcast ridică OSError (errno 101: Rețeaua nu este accesibilă) sau PermissionError. Acesta este un mecanism de siguranță deliberat — nu timeout, nu avertisment, nu eșec DNS.]* - +> *The kernel treats SO_BROADCAST as a mandatory permission flag, not a hint. Without it, sendto() to a broadcast address normally fails with a permission error (for example EACCES on Linux); other routing errors can occur independently. This is a deliberate safety mechanism — not a timeout, not a warning, not a DNS failure. [Nucleul tratează SO_BROADCAST ca un flag obligatoriu de permisiune, nu un indiciu. Fără acesta, sendto() la o adresă broadcast eșuează de regulă cu o eroare de permisiune (de exemplu EACCES pe Linux); alte erori de rutare pot apărea independent. Acesta este un mecanism de siguranță deliberat — nu timeout, nu avertisment, nu eșec DNS.]* --- @@ -369,18 +372,20 @@ In the Week 3 lab, the TCP tunnel on the router listens on port 12345 and forwar ### Q23. -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -The TCP tunnel in the Week 3 lab uses two threads per connection. Why is a single-threaded relay insufficient for full-duplex forwarding? [Tunelul TCP din laboratorul Săptămâna 3 folosește două fire de execuție per conexiune. De ce un releu cu un singur fir de execuție este insuficient pentru redirecționarea full-duplex?] +Why can a single sequential relay loop that performs blocking recv() in one direction stall forwarding in the other direction? [De ce o singură buclă secvențială de releu cu recv() blocant pe o direcție poate bloca redirecționarea în cealaltă direcție?] -- **a)** A blocking recv() on one direction would prevent the thread from forwarding data in the opposite direction [Un recv() blocant pe o direcție ar împiedica firul de execuție să redirecționeze date în direcția opusă] -- **b)** TCP requires separate threads for sending and receiving on the same socket object [TCP necesită fire de execuție separate pentru trimitere și recepție pe același obiect socket] -- **c)** Operating systems enforce a one-thread-per-socket limit for all network connections (default) [Sistemele de operare impun o limită de un fir de execuție per socket pentru toate conexiunile de rețea (implicit)] -- **d)** Multiple threads are required to handle the three-way handshake on both tunnel sockets in practice [Fire de execuție multiple sunt necesare pentru a gestiona handshake-ul triplu pe ambele socket-uri ale tunelului în practică] +- **a)** It cannot process the other direction while it waits in that blocking call. [Nu poate procesa cealaltă direcție cât timp așteaptă în acel apel blocant.] +- **b)** TCP requires one operating-system thread per direction. [TCP impune un fir al sistemului de operare per direcție.] +- **c)** Full-duplex forwarding cannot be implemented with one thread. [Redirecționarea full-duplex nu poate fi implementată cu un singur fir.] +- **d)** The TCP handshake requires multiple application threads. [Handshake-ul TCP impune mai multe fire de aplicație.] -> 💡 **Feedback:** -> *A recv() call blocks until data arrives. A single thread handling client→server direction would be stuck waiting on recv() and unable to simultaneously forward server→client data. Two threads (one per direction) ensure that data flows concurrently in both directions without blocking. [Un apel recv() blochează până când ajung date. Un singur fir de execuție care gestionează direcția client→server ar fi blocat așteptând recv() și incapabil să redirecționeze simultan datele server→client. Două fire de execuție (unul per direcție) asigură că datele curg concomitent în ambele direcții fără blocare.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Two relay threads are the supplied design. A single thread can also provide full-duplex forwarding with select(), selectors or an asynchronous event loop. The limitation is this sequential blocking loop, not TCP or single-threaded programming in general. [Două fire de releu reprezintă proiectarea furnizată. Un singur fir poate asigura full-duplex cu select(), selectors sau o buclă asincronă. Limita aparține acestei bucle blocante secvențiale, nu TCP sau programării cu un singur fir în general.] + +
    --- @@ -390,13 +395,12 @@ The TCP tunnel in the Week 3 lab uses two threads per connection. Why is a singl The tunnel relay function uses sendall(data) rather than send(data) . What problem does sendall() solve that send() does not? [Funcția releu a tunelului folosește sendall(data) în loc de send(data) . Ce problemă rezolvă sendall() pe care send() nu o rezolvă?] -- **a)** send() may perform a partial write, transmitting fewer bytes than provided; sendall() guarantees the complete buffer is sent [send() poate efectua o scriere parțială, transmițând mai puțini octeți decât s-a furnizat; sendall() garantează trimiterea completă a bufferului] +- **a)** send() may perform a partial write, transmitting fewer bytes than provided; sendall() continues until the complete buffer is accepted by the local socket API or an error occurs [send() poate efectua o scriere parțială, transmițând mai puțini octeți decât s-a furnizat; sendall() continuă până când bufferul complet este acceptat de API-ul local de socket sau apare o eroare] - **b)** send() can only transmit strings, while sendall() also accepts bytes objects and memoryview buffers across all supported platforms [send() poate transmite doar șiruri de caractere, în timp ce sendall() acceptă și obiecte bytes și buffere memoryview pe toate platformele suportate] - **c)** send() uses UDP internally for performance, whereas sendall() maintains proper TCP semantics [send() folosește intern UDP pentru performanță, în timp ce sendall() menține semantica TCP corespunzătoare] > 💡 **Feedback:** -> *The send() method may transmit fewer bytes than requested (partial send), returning the count actually sent. If the relay ignores this, data is silently lost. sendall() loops internally until all bytes are transmitted, guaranteeing complete delivery. [Metoda send() poate transmite mai puțini octeți decât s-a solicitat (trimitere parțială), returnând numărul efectiv trimis. Dacă releul ignoră acest lucru, datele se pierd silențios. sendall() iterează intern până când toți octeții sunt transmiși, garantând livrarea completă.]* - +> *The send() method may transmit fewer bytes than requested (partial send), returning the count actually sent. If the relay ignores this, data is silently lost. sendall() loops until the supplied bytes are accepted locally or an error occurs. A successful return is not proof that the peer application has read or processed them; that requires application-level acknowledgement. [Metoda send() poate transmite mai puțini octeți decât s-a solicitat (trimitere parțială), returnând numărul efectiv trimis. Dacă releul ignoră acest lucru, datele se pierd silențios. sendall() iterează până la acceptarea locală a octeților sau apariția unei erori. Succesul nu dovedește că aplicația corespondentă i-a citit sau procesat; pentru aceasta este necesară o confirmare la nivelul aplicației.]* --- @@ -552,20 +556,22 @@ In the Week 3 exercises, broadcast receivers set SO_REUSEADDR before calling bin --- -### Q34. +### Q34. — Multicast membership structure size / Dimensiunea structurii de apartenență multicast -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -To join multicast group 224.0.0.1, the code constructs mreq = struct.pack("4sl", socket.inet_aton("224.0.0.1"), socket.INADDR_ANY) . What is the total size of this packed structure in bytes? [Pentru a se alătura grupului multicast 224.0.0.1, codul construiește mreq = struct.pack("4sl", socket.inet_aton("224.0.0.1"), socket.INADDR_ANY) . Care este dimensiunea totală a acestei structuri împachetate în octeți?] +The receiver constructs `struct.pack("4s4s", socket.inet_aton("239.255.0.1"), socket.inet_aton("127.0.0.1"))`. How many bytes does this produce? [Receptorul construiește `struct.pack("4s4s", socket.inet_aton("239.255.0.1"), socket.inet_aton("127.0.0.1"))`. Câți octeți rezultă?] -- **a)** 8 bytes — 4 bytes for group IP address plus 4 bytes for the local interface identifier [8 octeți — 4 octeți pentru adresa IP a grupului plus 4 octeți pentru identificatorul interfeței locale] -- **b)** 16 bytes — 4 bytes group IP, 4 bytes interface IP, plus 8 bytes for a 64-bit alignment pad in practice [16 octeți — 4 octeți IP grup, 4 octeți IP interfață, plus 8 octeți pentru alinierea pe 64 de biți în practică] -- **c)** 4 bytes — only the multicast group address is needed; the interface is implicit [4 octeți — este necesară doar adresa grupului multicast; interfața este implicită] -- **d)** 12 bytes — 4 bytes group IP, 4 bytes interface IP, plus 4 bytes for a TTL field (default) [12 octeți — 4 octeți IP grup, 4 octeți IP interfață, plus 4 octeți pentru un câmp TTL (implicit)] +- **a)** 8 +- **b)** 16 +- **c)** 4 +- **d)** 12 -> 💡 **Feedback:** -> *The structure consists of 4 bytes for the multicast group IP address (inet_aton returns 4 bytes) plus 4 bytes for the interface address (INADDR_ANY as a 32-bit integer), totalling 8 bytes. This matches the ip_mreq C structure used by the kernel for multicast group management. [Structura constă din 4 octeți pentru adresa IP a grupului multicast (inet_aton returnează 4 octeți) plus 4 octeți pentru adresa interfeței (INADDR_ANY ca întreg pe 32 de biți), totalizând 8 octeți. Aceasta corespunde structurii C ip_mreq folosită de nucleu pentru gestionarea grupurilor multicast.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Each 4s field contains exactly four bytes, so the total is eight. The old native 4sl format is ABI-dependent: on LP64 it can occupy sixteen bytes because of alignment and an eight-byte long. Use two IPv4 address fields for this membership request. [Fiecare câmp 4s conține exact patru octeți, deci totalul este opt. Formatul nativ 4sl depinde de ABI: pe LP64 poate ocupa șaisprezece octeți din cauza alinierii și a unui long pe opt octeți. Cererea de apartenență folosește două câmpuri de adresă IPv4.] + +
    --- @@ -573,7 +579,7 @@ To join multicast group 224.0.0.1, the code constructs mreq = struct.pack("4sl", *[Multiple Choice]* -In Exercise 2, the multicast sender uses \--ttl 4 . Which Python setsockopt() call configures this TTL value? [În Exercițiul 2, expeditorul multicast folosește \--ttl 4 . Care apel Python setsockopt() configurează această valoare TTL?] +For an independent multicast example, set the IPv4 multicast TTL to 4. Which Python setsockopt() call does this? [Într-un exemplu multicast independent, setați TTL-ul IPv4 multicast la 4. Ce apel Python setsockopt() realizează aceasta?] - **a)** sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 4) - **b)** sock.setsockopt(socket.SOL_SOCKET, socket.IP_MULTICAST_TTL, 4) @@ -583,7 +589,6 @@ In Exercise 2, the multicast sender uses \--ttl 4 . Which Python setsockopt() ca > 💡 **Feedback:** > *IP_MULTICAST_TTL is set at the IPPROTO_IP level, not SOL_SOCKET. The TTL value of 4 allows the packet to cross 3 routers before being discarded. This is separate from the unicast IP TTL which is set differently. [IP_MULTICAST_TTL este setat la nivelul IPPROTO_IP, nu SOL_SOCKET. Valoarea TTL de 4 permite pachetului să traverseze 3 rutere înainte de a fi eliminat. Aceasta este separată de TTL-ul IP unicast care este setat diferit.]* - --- ### Q36. @@ -604,17 +609,20 @@ The socket option IP_MULTICAST_LOOP controls whether a multicast sender receives ### Q37. -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -In code tracing exercise T2, the final line calls setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP, mreq) . What network protocol message does this trigger? [În exercițiul de urmărire a codului T2, ultima linie apelează setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP, mreq) . Ce mesaj de protocol de rețea declanșează aceasta?] +A socket drops its membership of an IPv4 multicast group. Which statement about network signalling is valid? [Un socket renunță la apartenența la un grup multicast IPv4. Ce afirmație despre semnalizarea în rețea este corectă?] -- **a)** An IGMPv2 Leave Group message informing the router to stop forwarding this group's traffic [Un mesaj IGMPv2 Leave Group care informează ruterul să oprească redirecționarea traficului acestui grup] -- **b)** A TCP FIN segment that gracefully terminates the multicast session with the router [Un segment TCP FIN care termină grațios sesiunea multicast cu ruterul] -- **c)** An ICMP Destination Unreachable message blocking further packets to the group address in practice [Un mesaj ICMP Destination Unreachable care blochează pachete ulterioare la adresa grupului în practică] +- **a)** The OS updates membership state; any IGMP report depends on IGMP version, interface and remaining host memberships. [Sistemul actualizează apartenența; mesajul IGMP depinde de versiune, interfață și abonamentele rămase pe host.] +- **b)** Every call always emits exactly one IGMPv2 Leave Group packet. [Orice apel emite întotdeauna exact un pachet IGMPv2 Leave Group.] +- **c)** It sends a TCP FIN to the multicast router. [Trimite un TCP FIN către ruterul multicast.] +- **d)** It guarantees that the switch stops forwarding all frames for the group. [Garantează că switch-ul oprește toate cadrele grupului.] -> 💡 **Feedback:** -> *IP_DROP_MEMBERSHIP causes the kernel to send an IGMPv2 Leave Group message (type 0x17), informing the local router that this host no longer wants traffic for the specified group. The router can then stop forwarding if no other members remain. [IP_DROP_MEMBERSHIP determină nucleul să trimită un mesaj IGMPv2 Leave Group (tip 0x17), informând ruterul local că această gazdă nu mai dorește trafic pentru grupul specificat. Ruterul poate apoi să oprească redirecționarea dacă nu mai rămân alți membri.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Dropping one socket membership is not identical to the host leaving a group. Other sockets can retain membership; IGMP versions and loopback have different signalling behaviour. [Renunțarea unui socket nu este identică cu părăsirea grupului de către host. Alte socketuri pot rămâne membre; versiunile IGMP și loopback au comportamente de semnalizare diferite.] + +
    --- @@ -689,16 +697,22 @@ Complete the Python statement that enables broadcast on a UDP socket. [Completa ### Q42. -*[Drag and Drop]* +*Drag and Drop / Trageți și plasați* -Complete the Python code that constructs the mreq structure and joins a multicast group. [Completați codul Python care construiește structura mreq și aderă la un grup multicast.] mreq = socket.inet_aton("[[1]]") + struct.pack('=I', socket.INADDR_ANY)sock.setsockopt(socket.[[2]], socket.[[3]], mreq) +Complete the two separate Python statements for the same-VM multicast baseline. [Completați cele două instrucțiuni Python distincte pentru multicast în aceeași VM.] -> *Available items / Elemente disponibile:* -[ 224.0.0.1 ] [ IPPROTO_IP ] [ IP_ADD_MEMBERSHIP ] [ 224.0.0.1 ] [ SOL_SOCKET ] [ IP_MULTICAST_TTL ] +```python +mreq = struct.pack("4s4s", socket.inet_aton("[[1]]"), socket.inet_aton("127.0.0.1")) +sock.setsockopt(socket.[[2]], socket.[[3]], mreq) +``` -> 💡 **Feedback:** -> *The group address 224.0.0.1 is packed with INADDR_ANY into mreq. The setsockopt call uses IPPROTO_IP level and IP_ADD_MEMBERSHIP option. [Adresa de grup 224.0.0.1 este împachetată cu INADDR_ANY în mreq. Apelul setsockopt folosește nivelul IPPROTO_IP și opțiunea IP_ADD_MEMBERSHIP.]* +Available items / Elemente disponibile: `239.255.0.1`, `IPPROTO_IP`, `IP_ADD_MEMBERSHIP`, `SOL_SOCKET`, `IP_MULTICAST_TTL`. + +
    💡 Feedback + +1 = `239.255.0.1`; 2 = `IPPROTO_IP`; 3 = `IP_ADD_MEMBERSHIP`. The two statements must be separated by a newline. Use the selected local interface address instead of loopback for a different topology. [Cele două instrucțiuni trebuie separate printr-o linie nouă. Pentru altă topologie folosiți adresa interfeței locale alese în locul loopback.] +
    --- @@ -774,20 +788,21 @@ Broadcast is supported only over [[1]] because [[2]] requires a dedicated connec --- -### Q47. +### Q47. — Explicit multicast membership / Apartenență multicast explicită -*[Gap Select]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -To receive multicast traffic, a socket must call [[1]] at the [[2]] protocol level. Without this call, the kernel [[3]] incoming multicast packets. [Pentru a primi trafic multicast, un socket trebuie să apeleze ___ la nivelul de protocol ___. Fără acest apel, nucleul ___ pachetele multicast primite.] +The S03 receiver uses group 239.255.0.1. On Linux it sets IP_MULTICAST_ALL=0. Which additional step explicitly subscribes this socket on the selected interface? [Receptorul S03 folosește grupul 239.255.0.1. Pe Linux setează IP_MULTICAST_ALL=0. Ce pas suplimentar abonează explicit acest socket pe interfața aleasă?] -> *Options per gap / Opțiuni pentru fiecare spațiu:* -> **Gap [[1]]:** [ IP_ADD_MEMBERSHIP ] [ SO_BROADCAST ] [ IP_MULTICAST_TTL ] -> **Gap [[2]]:** [ IPPROTO_IP ] [ SOL_SOCKET ] [ IPPROTO_TCP ] -> **Gap [[3]]:** [ silently ignores ] [ queues indefinitely ] [ forwards to broadcast ] +- **a)** `setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)` +- **b)** `setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)` +- **c)** `setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)` -> 💡 **Feedback:** -> *IP_ADD_MEMBERSHIP at IPPROTO_IP level is mandatory. The kernel silently ignores multicast packets for groups the host has not joined. Binding to a port alone is necessary but not sufficient. [IP_ADD_MEMBERSHIP la nivelul IPPROTO_IP este obligatoriu. Nucleul ignoră silențios pachetele multicast pentru grupuri la care gazda nu a aderat. Legarea la un port singură este necesară dar nu suficientă.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Join the application group using IP_ADD_MEMBERSHIP and the intended local interface. Binding selects a local endpoint. Linux IP_MULTICAST_ALL=1 can also deliver traffic for groups joined elsewhere on the host, and 224.0.0.1 is the special all-hosts group. Therefore “no explicit join always means no reception” is not a portable rule. Receipt still depends on reachability and filtering. [Aderați la grupul aplicației prin IP_ADD_MEMBERSHIP pe interfața locală dorită. Bind selectează endpointul local. Linux IP_MULTICAST_ALL=1 poate livra și trafic pentru grupuri la care s-a aderat în altă parte pe gazdă, iar 224.0.0.1 este grupul special al tuturor gazdelor. Prin urmare, lipsa aderării explicite nu implică universal lipsa recepției. Recepția depinde și de conectivitate și filtrare.] +
    --- diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W04_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W04_Questions.md index 092ad89..1ffa19b 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W04_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W04_Questions.md @@ -195,31 +195,32 @@ The Maximum Transmission Unit (MTU) for standard Ethernet frames is 1500 bytes. CSMA/CD and CSMA/CA are both random-access media access control protocols. Which pairing of technology and protocol variant is correct? [CSMA/CD și CSMA/CA sunt ambele protocoale de acces la mediu de tip acces aleatoriu. Care asociere dintre tehnologie și varianta de protocol este corectă?] -- **a)** CSMA/CD for wired Ethernet; CSMA/CA for Wi-Fi (IEEE 802.11) [CSMA/CD pentru Ethernet cu fir; CSMA/CA pentru Wi-Fi (IEEE 802.11)] +- **a)** CSMA/CD for shared half-duplex Ethernet; CSMA/CA for Wi-Fi (IEEE 802.11) [CSMA/CD pentru Ethernet partajat half-duplex; CSMA/CA pentru Wi-Fi (IEEE 802.11)] - **b)** CSMA/CA for wired Ethernet; CSMA/CD for Wi-Fi (IEEE 802.11) [CSMA/CA pentru Ethernet cu fir; CSMA/CD pentru Wi-Fi (IEEE 802.11)] - **c)** CSMA/CD for both wired Ethernet and Wi-Fi simultaneously [CSMA/CD atât pentru Ethernet cu fir cât și pentru Wi-Fi simultan] - **d)** Token passing for Ethernet; CSMA/CA for fibre optic links [Transmitere cu jeton pentru Ethernet; CSMA/CA pentru legături de fibră] > 💡 **Feedback:** -> *CSMA/CD (Collision Detection) is used in wired Ethernet — the sender detects collisions and terminates early. CSMA/CA (Collision Avoidance) is used in Wi-Fi (IEEE 802.11) — collisions cannot be detected in wireless, so stations use acknowledgements to avoid them. [CSMA/CD (detecția coliziunilor) se folosește în Ethernet cu fir — emițătorul detectează coliziunile și oprește transmisia. CSMA/CA (evitarea coliziunilor) se folosește în Wi-Fi (IEEE 802.11) — coliziunile nu pot fi detectate în wireless, astfel că stațiile folosesc confirmări pentru a le evita.]* - +> *CSMA/CD (Collision Detection) is used in shared half-duplex Ethernet; full-duplex switched links do not use it. CSMA/CA (Collision Avoidance) is used in Wi-Fi (IEEE 802.11) — stations use contention and random backoff to reduce collisions; a missing acknowledgement indicates that delivery was not confirmed. Optional RTS/CTS can reduce hidden-terminal collisions. [CSMA/CD se folosește în Ethernet partajat half-duplex; legăturile comutate full-duplex nu îl folosesc. CSMA/CA (evitarea coliziunilor) se folosește în Wi-Fi (IEEE 802.11) — stațiile folosesc contendență și backoff aleatoriu pentru reducerea coliziunilor; lipsa confirmării arată că livrarea nu a fost confirmată. RTS/CTS opțional poate reduce coliziunile cauzate de terminale ascunse.]* --- ### Q13. `N04.C03.Q01` — TCP byte stream property / Proprietatea TCP de flux de octeți -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -A client calls sock.send(b'HELLO') immediately followed by sock.send(b'WORLD'). On the server side, sock.recv(1024) is invoked once. What is the most likely output? [Un client apelează sock.send(b'HELLO') urmat imediat de sock.send(b'WORLD'). Pe partea de server, sock.recv(1024) este apelat o singură dată. Care este rezultatul cel mai probabil?] +A client successfully calls sendall(b'HELLO') and sendall(b'WORLD'). The server then uses blocking recv(1024), with no earlier reads. Assuming data arrives and no error occurs, what is guaranteed about the returned non-empty bytes? [Un client execută cu succes sendall(b'HELLO') și sendall(b'WORLD'). Serverul apelează recv(1024) blocant, fără citiri anterioare. Presupunând că sosesc date fără eroare, ce se garantează pentru octeții nenuli returnați?] -- **a)** b'HELLOWORLD' — TCP may coalesce both sends into a single segment [b'HELLOWORLD' — TCP poate uni ambele trimiteri într-un singur segment] -- **b)** b'HELLO' alone, with b'WORLD' arriving in the subsequent recv() call [b'HELLO' singur, cu b'WORLD' sosind la următorul apel recv()] -- **c)** b'HELLO WORLD' with an automatic space separator inserted by TCP [b'HELLO WORLD' cu un separator de spațiu inserat automat de TCP] -- **d)** A ConnectionError because two rapid send() calls overload the buffer [O ConnectionError deoarece două apeluri send() rapide supraîncarcă buffer-ul] +- **a)** They form a prefix of b'HELLOWORLD'; recv() need not return all ten bytes at once. [Formează un prefix al b'HELLOWORLD'; recv() nu trebuie să returneze toți cei zece octeți odată.] +- **b)** They must be exactly b'HELLO'. [Trebuie să fie exact b'HELLO'.] +- **c)** They must be exactly b'HELLOWORLD'. [Trebuie să fie exact b'HELLOWORLD'.] +- **d)** TCP inserts a space between the writes. [TCP inserează un spațiu între scrieri.] -> 💡 **Feedback:** -> *TCP is a byte stream protocol with no inherent message boundaries. Consecutive send() calls may be coalesced into a single segment. The receiver sees b'HELLOWORLD' without any delimiter indicating where one message ends. Applications must implement framing (length-prefix or delimiter) to recover boundaries. [TCP este un protocol de flux de octeți fără delimitări inerente ale mesajelor. Apelurile consecutive send() pot fi unite într-un singur segment. Receptorul vede b'HELLOWORLD' fără niciun delimitator. Aplicațiile trebuie să implementeze cadraj (prefix de lungime sau delimitator) pentru a recupera limitele.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** TCP preserves byte order and has no application message boundaries. A receive can return a partial write, one write or several writes together. sendall() handles short sends locally, but framing and repeated receives are still required. [TCP păstrează ordinea octeților și nu are delimitări de mesaje de aplicație. O recepție poate întoarce o parte dintr-o scriere, o scriere sau mai multe împreună. sendall() gestionează trimiterile locale parțiale, dar încadrarea și recepțiile repetate rămân necesare.] + +
    --- @@ -259,18 +260,20 @@ A sender packs the integer 1000 as a 2-byte big-endian unsigned short. The recei ### Q16. `N04.C04.Q01` — CRC-32 burst error detection guarantee / Garanția detecției erorilor de rafală a CRC-32 -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -CRC-32 is mathematically guaranteed to detect which categories of transmission errors? [CRC-32 are garanția matematică de a detecta care categorii de erori de transmisie?] +For a degree-32 CRC generator with non-zero constant term, which burst-error guarantee is valid? [Pentru un polinom generator CRC de grad 32 cu termen liber nenul, ce garanție privind erorile de rafală este validă?] -- **a)** All single-bit, double-bit, odd-count, and burst errors up to 32 bits [Toate erorile de un bit, doi biți, număr impar și erorile de rafală de până la 32 biți] -- **b)** Only single-bit errors; multi-bit corruption requires Reed-Solomon codes [Doar erorile de un bit; coruperea multi-bit necesită coduri Reed-Solomon] -- **c)** All possible errors without exception, providing absolute data integrity [Toate erorile posibile fără excepție, oferind integritate absolută a datelor] -- **d)** All errors and also corrects them, functioning as forward error correction [Toate erorile și le corectează, funcționând ca și corecție de erori proactivă] +- **a)** Every non-zero burst error of length at most 32 bits is detected. [Orice eroare de rafală nenulă cu lungimea de cel mult 32 de biți este detectată.] +- **b)** Every possible error of any length is detected. [Orice eroare posibilă de orice lungime este detectată.] +- **c)** Every odd-weight error is detected for every CRC-32 polynomial. [Orice eroare cu număr impar de biți este detectată pentru orice polinom CRC-32.] +- **d)** The CRC automatically corrects all detected errors. [CRC corectează automat toate erorile detectate.] -> 💡 **Feedback:** -> *CRC-32 detects all single-bit errors, all double-bit errors, all odd numbers of bit errors, and all burst errors of 32 bits or fewer. For longer bursts, detection probability is approximately 99.99999998%. CRC detects but does not correct errors. [CRC-32 detectează toate erorile de un bit, toate erorile de doi biți, toate erorile cu un număr impar de biți și toate erorile de rafală de 32 de biți sau mai puțin. Pentru rafale mai lungi, probabilitatea de detecție este aproximativ 99,99999998%. CRC detectează dar nu corectează erorile.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The burst bound follows from the generator degree. Other guarantees depend on the polynomial and protected message length; the Ethernet CRC-32 polynomial does not provide a universal odd-weight guarantee. CRC is error detection, not authentication or automatic correction. [Limita de rafală rezultă din gradul generatorului. Alte garanții depind de polinom și de lungimea mesajului protejat; polinomul CRC-32 Ethernet nu oferă o garanție universală pentru greutate impară. CRC detectează erori, nu autentifică și nu corectează automat.] +
    --- @@ -286,8 +289,7 @@ A system transmits financial transaction data that must be protected against bot - **d)** A simple additive checksum, because it is very fast to compute at sender and receiver [O sumă de control aditivă simplă, deoarece este foarte rapidă de calculat la emițător și receptor] > 💡 **Feedback:** -> *Financial data requires protection against adversaries, not just noise. HMAC-SHA256 provides both error detection and cryptographic tamper resistance. CRC-32 detects accidental errors but is trivially forgeable; parity detects only single-bit errors. [Datele financiare necesită protecție împotriva adversarilor, nu doar a zgomotului. HMAC-SHA256 oferă atât detecție de erori cât și rezistență criptografică la falsificare. CRC-32 detectează erori accidentale dar poate fi falsificat trivial; paritatea detectează doar erori de un bit.]* - +> *Financial data requires protection against adversaries, not just noise. HMAC-SHA256 provides both error detection and cryptographic tamper resistance. CRC-32 detects accidental errors but is trivially forgeable; a single parity bit detects any odd number of flipped bits but misses an even number. [Datele financiare necesită protecție împotriva adversarilor, nu doar a zgomotului. HMAC-SHA256 oferă atât detecție de erori cât și rezistență criptografică la falsificare. CRC-32 detectează erori accidentale dar poate fi falsificat trivial; un bit de paritate detectează orice număr impar de biți inversați, dar nu un număr par.]* --- @@ -354,8 +356,7 @@ Stop-and-wait flow control transmits one frame and waits for acknowledgement bef - **d)** Frame corruption increases proportionally with the distance between nodes [Coruperea cadrelor crește proporțional cu distanța dintre noduri] > 💡 **Feedback:** -> *On high bandwidth-delay product links, the sender spends most of its time idle waiting for acknowledgements. The sliding window protocol allows multiple frames to be in flight simultaneously, utilising the link far more efficiently: efficiency = W / (1 + 2a). [Pe legături cu produs lățime de bandă-întârziere ridicat, emițătorul petrece cea mai mare parte a timpului inactiv așteptând confirmări. Protocolul cu fereastră glisantă permite trimiterea simultană a mai multor cadre, utilizând legătura mult mai eficient: eficiență = W / (1 + 2a).]* - +> *On high bandwidth-delay product links, the sender spends most of its time idle waiting for acknowledgements. The sliding window protocol allows multiple frames to be in flight simultaneously, utilising the link far more efficiently: ideal utilisation = min(1, W / (1 + 2a)), where W is the frame window and a is one-way propagation time divided by frame transmission time. This assumes error-free delivery and negligible ACK transmission/processing time. [Pe legături cu produs lățime de bandă-întârziere ridicat, emițătorul petrece cea mai mare parte a timpului inactiv așteptând confirmări. Protocolul cu fereastră glisantă permite trimiterea simultană a mai multor cadre, utilizând legătura mult mai eficient: utilizarea ideală = min(1, W / (1 + 2a)), unde W este fereastra în cadre, iar a este timpul de propagare într-un sens împărțit la timpul de transmisie al cadrului. Se presupun livrare fără erori și timp neglijabil de transmitere/procesare a ACK.]* --- @@ -378,9 +379,10 @@ A developer writes a chat application where the client sends messages using sock ### Q23. `N04.T00.Q02` — Purpose of magic bytes in binary protocols / Scopul octeților magici în protocoalele binare +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* -The Week 4 BINARY protocol begins each message with the bytes b'NP'. If a receiver reads a header where the first two bytes are not b'NP', what should it do and why? [Protocolul BINAR din Săptămâna 4 începe fiecare mesaj cu octeții b'NP'. Dacă un receptor citește un antet unde primii doi octeți nu sunt b'NP', ce ar trebui să facă și de ce?] +The hypothetical binary protocol in this item begins each message with the bytes b'NP'. If a receiver reads a header where the first two bytes are not b'NP', what should it do and why? [Protocolul binar ipotetic din acest item începe fiecare mesaj cu octeții b'NP'. Dacă un receptor citește un antet unde primii doi octeți nu sunt b'NP', ce ar trebui să facă și de ce?] - **a)** Reject the message — magic mismatch indicates corruption or wrong protocol [Respingerea mesajului — nepotrivirea magic-ului indică corupere sau protocol greșit] - **b)** Process the message normally since magic bytes are optional identification data [Procesarea mesajului normal deoarece octeții magici sunt date opționale de identificare] @@ -390,11 +392,11 @@ The Week 4 BINARY protocol begins each message with the bytes b'NP'. If a receiv > 💡 **Feedback:** > *Magic bytes serve as a protocol identifier and synchronisation marker. Mismatched magic indicates either a corrupt message, wrong protocol version, or stream desynchronisation. The receiver should reject the message and potentially reset the connection. [Octeții magici servesc ca identificator de protocol și marcator de sincronizare. Un magic nepotrivit indică fie un mesaj corupt, fie o versiune greșită de protocol, fie desincronizarea fluxului. Receptorul ar trebui să respingă mesajul și, potențial, să reseteze conexiunea.]* - --- ### Q24. `N04.T00.Q03` — CRC detection versus correction / Detecția CRC versus corecție +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* A student claims: 'Our binary protocol uses CRC-32, so if a packet arrives corrupted, the server can fix the error automatically.' Is this claim correct? [Un student afirmă: 'Protocolul nostru binar folosește CRC-32, deci dacă un pachet ajunge corupt, serverul poate repara automat eroarea.' Este corectă această afirmație?] @@ -407,7 +409,6 @@ A student claims: 'Our binary protocol uses CRC-32, so if a packet arrives corru > 💡 **Feedback:** > *The claim is incorrect. CRC-32 is an error detection mechanism only — it can identify that corruption occurred but cannot determine which bits changed. Error correction requires FEC codes like Reed-Solomon or Hamming codes. When CRC fails, the appropriate action is to discard and request retransmission. [Afirmația este incorectă. CRC-32 este doar un mecanism de detecție a erorilor — poate identifica faptul că a avut loc coruperea dar nu poate determina ce biți s-au schimbat. Corecția erorilor necesită coduri FEC precum Reed-Solomon sau Hamming. Când CRC eșuează, acțiunea adecvată este eliminarea și cererea de retransmisie.]* - --- ### Q25. `N04.T00.Q05` — Endianness impact on sensor readings / Impactul endianness asupra citirilor senzorilor @@ -422,25 +423,26 @@ A UDP sensor client sends temperature 23.5°C using big-endian float. A misconfi - **d)** The CRC check should have caught this error before the receiver processed the data [Verificarea CRC ar fi trebuit să detecteze această eroare înainte ca receptorul să proceseze datele] > 💡 **Feedback:** -> *Network byte order convention requires big-endian for all protocol fields. When the receiver applies little-endian interpretation to big-endian data, the IEEE 754 float bytes are reversed, producing a completely different floating-point value. Both endpoints must agree on byte order. [Convenția ordinii octeților în rețea necesită big-endian pentru toate câmpurile de protocol. Când receptorul aplică interpretare little-endian datelor big-endian, octeții float IEEE 754 sunt inversați, producând o valoare cu virgulă mobilă complet diferită. Ambele capete trebuie să fie de acord asupra ordinii octeților.]* - +> *Both endpoints must implement the byte order defined for each field by their application protocol; big-endian is not mandatory for every application protocol. When the receiver applies little-endian interpretation to big-endian data, the IEEE 754 float bytes are reversed, producing a completely different floating-point value. Both endpoints must agree on byte order. [Ambele capete trebuie să implementeze ordinea octeților definită pentru fiecare câmp de protocolul aplicației; big-endian nu este obligatoriu pentru orice protocol de aplicație. Când receptorul aplică interpretare little-endian datelor big-endian, octeții float IEEE 754 sunt inversați, producând o valoare cu virgulă mobilă complet diferită. Ambele capete trebuie să fie de acord asupra ordinii octeților.]* --- ### Q26. `N04.T00.Q08` — CSMA/CD versus CSMA/CA rationale / Motivația CSMA/CD versus CSMA/CA -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -Wired Ethernet uses CSMA/CD while Wi-Fi uses CSMA/CA. Why cannot CSMA/CD be used in wireless networks? [Ethernet cu fir folosește CSMA/CD iar Wi-Fi folosește CSMA/CA. De ce nu poate fi folosit CSMA/CD în rețelele wireless?] +Why does ordinary Wi-Fi use collision avoidance rather than the CSMA/CD mechanism of legacy shared, half-duplex Ethernet? [De ce Wi-Fi obișnuit folosește evitarea coliziunilor în locul CSMA/CD din Ethernet partajat, half-duplex tradițional?] -- **a)** Wireless stations cannot detect collisions while transmitting (hidden terminal problem) [Stațiile wireless nu pot detecta coliziunile în timpul transmisiei (problema terminalului ascuns)] -- **b)** Wi-Fi operates at lower physical-layer speeds where collision detection is computationally infeasible [Wi-Fi operează la viteze fizice mai mici unde detecția coliziunilor este imposibilă din punct de vedere computațional] -- **c)** The IEEE 802.11 standard deliberately chose CA over CD for marketing differentiation purposes [Standardul IEEE 802.11 a ales deliberat CA în locul CD în scopuri de diferențiere de marketing] -- **d)** CSMA/CD requires dedicated hardware only available in wired network adapters [CSMA/CD necesită hardware dedicat disponibil doar în adaptoarele de rețea cu fir] +- **a)** A transmitter cannot reliably detect another weak radio transmission while its own strong signal is being sent. [Emițătorul nu poate detecta fiabil o altă transmisie radio slabă în timpul propriei transmisii puternice.] +- **b)** All modern full-duplex switched Ethernet still needs CSMA/CD. [Orice Ethernet modern comutat full-duplex încă necesită CSMA/CD.] +- **c)** CSMA/CA guarantees that collisions never occur. [CSMA/CA garantează că nu există niciodată coliziuni.] +- **d)** Wireless bandwidth is too low to compute a checksum. [Lățimea de bandă wireless este prea mică pentru un checksum.] -> 💡 **Feedback:** -> *In wireless networks, a station cannot simultaneously transmit and listen for collisions (the hidden terminal problem). The transmitted signal is much stronger than any received collision signal. CSMA/CA avoids collisions proactively using RTS/CTS handshakes and acknowledgements. [În rețelele wireless, o stație nu poate transmite și asculta simultan pentru coliziuni (problema terminalului ascuns). Semnalul transmis este mult mai puternic decât orice semnal de coliziune recepționat. CSMA/CA evită coliziunile proactiv folosind handshake-uri RTS/CTS și confirmări.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Full-duplex switched Ethernet does not use collision detection. Radio self-interference explains the detection difficulty; hidden terminals are a distinct problem. CSMA/CA uses contention/backoff, with optional RTS/CTS, and does not eliminate every collision. [Ethernet comutat full-duplex nu folosește detecția coliziunilor. Interferența proprie explică dificultatea detecției; terminalele ascunse reprezintă altă problemă. CSMA/CA folosește contendență/backoff, cu RTS/CTS opțional, fără a elimina toate coliziunile.] +
    --- @@ -463,18 +465,19 @@ A binary protocol has monotonically increasing 4-byte sequence numbers but no du ### Q28. `N04.T00.Q10` — Protocol overhead analysis scenario / Scenariu de analiză a overhead-ului protocoalelor -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -A system sends the command 'SET counter 42' (14 bytes) using both TEXT and BINARY protocols. TEXT adds a length-prefix frame ('14 SET counter 42' = 17 bytes). BINARY uses a 14-byte header plus the payload (14+14 = 28 bytes). Which protocol is more efficient for this specific message, and when does the comparison reverse? [Un sistem trimite comanda 'SET counter 42' (14 octeți) folosind ambele protocoale TEXT și BINAR. TEXT adaugă un cadru cu prefix de lungime ('14 SET counter 42' = 17 octeți). BINAR folosește un antet de 14 octeți plus sarcina utilă (14+14 = 28 octeți). Care protocol este mai eficient pentru acest mesaj specific și când se inversează comparația?] +For S04 text and pickle-based binary messages, which method correctly compares application byte overhead? [Pentru mesajele text și binare bazate pe pickle din S04, ce metodă compară corect overhead-ul în octeți al aplicației?] -- **a)** TEXT is more efficient here (17 vs 28 bytes); BINARY wins for large or numeric-heavy payloads [TEXT este mai eficient aici (17 vs 28 octeți); BINAR câștigă pentru sarcini utile mari sau cu multe date numerice] -- **b)** BINARY is always more efficient regardless of payload size due to its fixed-width header [BINAR este întotdeauna mai eficient indiferent de dimensiunea sarcinii utile datorită antetului cu lățime fixă] -- **c)** TEXT and BINARY have identical overhead because both transmit the same application data [TEXT și BINAR au overhead identic deoarece ambele transmit aceleași date de aplicație] -- **d)** The overhead comparison is irrelevant since modern networks have unlimited bandwidth [Comparația overhead-ului este irelevantă deoarece rețelele moderne au lățime de bandă nelimitată] +- **a)** Encode equivalent data with each actual serializer, include its framing and compare measured byte lengths. [Codificați date echivalente cu fiecare serializator real, includeți cadrajul și comparați lungimile măsurate în octeți.] +- **b)** Assume every binary encoding is smaller and encrypted. [Presupuneți că orice codificare binară este mai mică și criptată.] +- **c)** Count Python string characters and ignore the prefix. [Numărați caracterele șirului Python și ignorați prefixul.] -> 💡 **Feedback:** -> *For this small payload, TEXT is more efficient (17 vs 28 bytes). The BINARY protocol's 14-byte fixed header dominates. The comparison reverses for large payloads: as payload grows, the fixed 14 bytes becomes a smaller percentage of total, and binary values are more compact than their ASCII text equivalents. [Pentru această sarcină utilă mică, TEXT este mai eficient (17 vs 28 octeți). Antetul fix de 14 octeți al protocolului BINAR domină. Comparația se inversează pentru sarcini utile mari: pe măsură ce sarcina utilă crește, cei 14 octeți fixi devin un procent mai mic din total, iar valorile binare sunt mai compacte decât echivalentele lor text ASCII.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Pickle contains representation metadata and can be larger than a short text command. It is neither encryption nor compression. S04 binary frames add one total-length byte and are limited to 255 bytes; text uses a decimal total-byte length and UTF-8. [Pickle conține metadate de reprezentare și poate fi mai mare decât o comandă text scurtă. Nu este criptare sau compresie. Cadrele binare S04 adaugă un octet de lungime totală și sunt limitate la 255 de octeți; textul folosește lungimea totală în octeți exprimată zecimal și UTF-8.] + +
    --- @@ -485,35 +488,40 @@ A system sends the command 'SET counter 42' (14 bytes) using both TEXT and BINAR ### Q29. `N04.S01.Q03` — TEXT protocol frame format / Formatul cadrului protocolului TEXT -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -In the Week 4 TEXT protocol, the frame format is " " where LENGTH is an ASCII decimal number. For the command "SET name Alice" (13 bytes), what is the complete frame transmitted? [În protocolul TEXT din Săptămâna 4, formatul cadrului este " " unde LENGTH este un număr zecimal ASCII. Pentru comanda "SET name Alice" (13 octeți), care este cadrul complet transmis?] +S04 text framing is `TOTAL_LENGTH SP PAYLOAD`, where the decimal total includes its own digits, the space and UTF-8 payload bytes. What is the frame for the 13-byte command `add key value`? [Cadrajul text S04 este `TOTAL_LENGTH SP PAYLOAD`, unde totalul zecimal include propriile cifre, spațiul și octeții UTF-8 ai payloadului. Care este cadrul pentru comanda de 13 octeți `add key value`?] -- **a)** "13 SET name Alice" — ASCII length prefix, space separator, then payload ["13 SET name Alice" — prefix de lungime ASCII, separator spațiu, apoi sarcina utilă] -- **b)** "SET name Alice\\r\\n" — the payload followed by a CRLF delimiter at the end ["SET name Alice\\r\\n" — sarcina utilă urmată de un delimitator CRLF la final] -- **c)** "\\x00\\x0dSET name Alice" — 2-byte binary length prefix in big-endian ["\\x00\\x0dSET name Alice" — prefix de lungime binar pe 2 octeți în big-endian] -- **d)** "SET name Alice" — raw payload without any framing or length prefix ["SET name Alice" — sarcina utilă brută fără cadraj sau prefix de lungime] +- **a)** `16 add key value` +- **b)** `13 add key value` +- **c)** `add key value +` +- **d)** `14 add key value` -> 💡 **Feedback:** -> *The frame consists of the ASCII string "13" followed by a space separator and then the 13-byte payload. Total: "13 SET name Alice" — a 16-byte frame (2 digits + 1 space + 13 payload). [Cadrul constă din șirul ASCII "13" urmat de un separator spațiu și apoi sarcina utilă de 13 octeți. Total: "13 SET name Alice" — un cadru de 16 octeți (2 cifre + 1 spațiu + 13 sarcină utilă).]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Two ASCII digits + one space + thirteen payload bytes = sixteen bytes. Receivers parse the prefix and read exactly the remaining bytes. Character count is not byte count for non-ASCII text. [Două cifre ASCII + un spațiu + treisprezece octeți de payload = șaisprezece octeți. Receptorul parsează prefixul și citește exact octeții rămași. Numărul caracterelor nu este numărul octeților pentru text non-ASCII.] +
    --- ### Q30. `N04.S01.Q05` — TEXT protocol supported commands / Comenzile suportate de protocolul TEXT -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -The TEXT protocol server in Exercise 4.01 supports several commands. Which set correctly lists valid commands? [Serverul protocolului TEXT din Exercițiul 4.01 suportă mai multe comenzi. Care set listează corect comenzile valide?] +Which commands are implemented by the unmodified S04 text example server? [Ce comenzi sunt implementate de serverul text exemplu S04 nemodificat?] -- **a)** PING, SET, GET, DEL, COUNT, KEYS, QUIT [PING, SET, GET, DEL, COUNT, KEYS, QUIT] -- **b)** CONNECT, SEND, RECEIVE, CLOSE, STATUS [CONNECT, SEND, RECEIVE, CLOSE, STATUS] -- **c)** PUT, POST, DELETE, PATCH, OPTIONS, HEAD [PUT, POST, DELETE, PATCH, OPTIONS, HEAD] -- **d)** HELO, MAIL FROM, RCPT TO, DATA, QUIT [HELO, MAIL FROM, RCPT TO, DATA, QUIT] +- **a)** `add`, `get`, `remove` +- **b)** `PING`, `SET`, `GET`, `DEL`, `QUIT` +- **c)** `CONNECT`, `SEND`, `LIST`, `DISCONNECT` +- **d)** `GET`, `POST`, `PUT`, `DELETE` -> 💡 **Feedback:** -> *The TEXT server supports: PING (connectivity test), SET key value (store), GET key (retrieve), DEL key (delete), COUNT (number of keys), KEYS (list all), and QUIT (close connection). [Serverul TEXT suportă: PING (test de conectivitate), SET key value (stocare), GET key (recuperare), DEL key (ștergere), COUNT (număr de chei), KEYS (listare toate) și QUIT (închidere conexiune).]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** The reference text server provides add/get/remove. The scenario asks students to implement count; exit is handled locally by the client and is not transmitted. The uppercase CONNECT/SEND/LIST/DISCONNECT names belong to the separate UDP lesson. [Serverul text de referință oferă add/get/remove. Scenariul cere implementarea count; exit este tratat local de client și nu se transmite. Numele CONNECT/SEND/LIST/DISCONNECT aparțin lecției UDP separate.] + +
    --- @@ -536,6 +544,7 @@ What hex string does struct.pack('\>H', 1000).hex() produce in Python? [Ce șir ### Q32. `N04.S02.Q02` — Binary header total size calculation / Calculul dimensiunii totale a antetului binar +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* The BINARY protocol header uses format '\>2sBBHII'. What is the total header size in bytes? [Antetul protocolului BINAR folosește formatul '\>2sBBHII'. Care este dimensiunea totală a antetului în octeți?] @@ -548,31 +557,32 @@ The BINARY protocol header uses format '\>2sBBHII'. What is the total header siz > 💡 **Feedback:** > *Calculation: 2s = 2 bytes (magic), B = 1 byte (version), B = 1 byte (type), H = 2 bytes (payload_len), I = 4 bytes (seq), I = 4 bytes (CRC32). Total: 2+1+1+2+4+4 = 14 bytes. [Calcul: 2s = 2 octeți (magic), B = 1 octet (versiune), B = 1 octet (tip), H = 2 octeți (payload_len), I = 4 octeți (seq), I = 4 octeți (CRC32). Total: 2+1+1+2+4+4 = 14 octeți.]* - --- -### Q33. `N04.S02.Q05` — struct format '\>' versus '\<' meaning / Semnificația '\>' versus '\<' în formatul struct +### Q33. `N04.S02.Q05` — struct byte-order prefixes / Prefixele de ordine a octeților în struct -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -In a struct.pack() call, the prefix character '\>' and '' și '\<' controlează ordinea octeților. Ce specifică ele?] +What do the prefixes `>` and `<` select in Python `struct.pack`? [Ce selectează prefixele `>` și `<` în `struct.pack` din Python?] -- **a)** '\>' is big-endian (MSB first); '' este big-endian (MSB primul); '\<' este little-endian (LSB primul)] -- **b)** '\>' compresses the output data; '' comprimă datele; '\<' decomprimă datele binare împachetate] -- **c)** '\>' adds field padding bytes; '' adaugă octeți de completare; '\<' elimină completarea de aliniere] -- **d)** '\>' enables signed integer values; '' activează valori de întregi cu semn; '\<' forțează interpretarea fără semn] +- **a)** `>` selects big-endian; `<` selects little-endian, both with standard sizes and no alignment padding. [`>` selectează big-endian; `<` selectează little-endian, ambele cu dimensiuni standard și fără padding de aliniere.] +- **b)** `>` compresses and `<` decompresses. [`>` comprimă și `<` decomprimă.] +- **c)** `>` encrypts and `<` decrypts. [`>` criptează și `<` decriptează.] -> 💡 **Feedback:** -> *'\>' means big-endian (network byte order, MSB first). '' (network order). Using native order ('@' or '=') risks interoperability issues. ['\>' înseamnă big-endian (ordinea octeților în rețea, MSB primul). '' (ordinea rețelei). Folosirea ordinii native ('@' sau '=') riscă probleme de interoperabilitate.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** The `!` prefix also selects standard-size big-endian (network order). `@` uses native size and alignment; `=` uses native byte order with standard sizes and no alignment padding. [Prefixul `!` selectează tot big-endian cu dimensiuni standard (ordinea rețelei). `@` folosește dimensiuni și aliniere native; `=` folosește ordinea nativă a octeților, dimensiuni standard și fără padding de aliniere.] + +
    --- ### Q34. `N04.S03.Q03` — CRC computation scope in binary header / Domeniul de calcul CRC în antetul binar +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* -When building a BINARY protocol message, over which data is the CRC-32 checksum calculated? [La construirea unui mesaj de protocol BINAR, peste ce date se calculează suma de control CRC-32?] +A hypothetical protocol computes `crc = zlib.crc32(header_without_crc + payload)`, with a 10-byte header_without_crc. Which bytes does this checksum cover? [Un protocol ipotetic calculează `crc = zlib.crc32(header_without_crc + payload)`, cu header_without_crc de 10 octeți. Ce octeți acoperă suma de control?] - **a)** Over the header without the CRC field (10 bytes) plus the entire payload [Peste antetul fără câmpul CRC (10 octeți) plus întreaga sarcină utilă] - **b)** Over the payload only, excluding all header fields from the calculation [Doar peste sarcina utilă, excluzând toate câmpurile antetului din calcul] @@ -582,11 +592,11 @@ When building a BINARY protocol message, over which data is the CRC-32 checksum > 💡 **Feedback:** > *CRC is calculated over the header (WITHOUT the CRC field itself) concatenated with the payload. The header is first packed without CRC (10 bytes), then CRC is computed over those 10 bytes + payload, and finally the full 14-byte header is assembled with the CRC included. [CRC-ul se calculează peste antetul (FĂRĂ câmpul CRC în sine) concatenat cu sarcina utilă. Antetul este mai întâi împachetat fără CRC (10 octeți), apoi CRC-ul se calculează peste acei 10 octeți + sarcina utilă, iar în final antetul complet de 14 octeți este asamblat cu CRC-ul inclus.]* - --- ### Q35. `N04.S03.Q04` — Hex representation of NP magic bytes / Reprezentarea hexazecimală a octeților magici NP +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* The BINARY protocol magic bytes are b'NP'. What is their hexadecimal representation? [Octeții magici ai protocolului BINAR sunt b'NP'. Care este reprezentarea lor hexazecimală?] @@ -599,11 +609,11 @@ The BINARY protocol magic bytes are b'NP'. What is their hexadecimal representat > 💡 **Feedback:** > *In ASCII: 'N' = 0x4E (78 decimal), 'P' = 0x50 (80 decimal). Therefore b'NP' in hex is 4e50. This can be verified with b'NP'.hex() in Python. [În ASCII: 'N' = 0x4E (78 zecimal), 'P' = 0x50 (80 zecimal). Prin urmare, b'NP' în hex este 4e50. Se poate verifica cu b'NP'.hex() în Python.]* - --- ### Q36. `N04.S03.Q05` — Sequence number purpose in binary protocol / Scopul numărului de secvență în protocolul binar +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* Each BINARY protocol message contains a 4-byte sequence number. What primary purpose does it serve? [Fiecare mesaj de protocol BINAR conține un număr de secvență pe 4 octeți. Ce scop principal servește?] @@ -614,13 +624,13 @@ Each BINARY protocol message contains a 4-byte sequence number. What primary pur - **d)** Compressing repeated fields by referencing previously sent sequence values [Comprimarea câmpurilor repetate prin referirea valorilor de secvență trimise anterior] > 💡 **Feedback:** -> *Sequence numbers correlate requests with their corresponding responses (request-response matching) and enable detection of duplicate or lost messages. The number is monotonically increasing and allows a receiver to identify gaps or replays. [Numerele de secvență corelează cererile cu răspunsurile corespunzătoare (potrivirea cerere-răspuns) și permit detectarea mesajelor duplicate sau pierdute. Numărul este crescător monoton și permite receptorului să identifice goluri sau reluări.]* - +> *Sequence numbers correlate requests with their corresponding responses (request-response matching) and enable detection of duplicate or lost messages. With a defined numbering and wraparound policy, receiver-side state can identify duplicates and gaps; a sequence field alone neither prevents replay nor proves packet loss. [Numerele de secvență corelează cererile cu răspunsurile corespunzătoare (potrivirea cerere-răspuns) și permit detectarea mesajelor duplicate sau pierdute. Cu o politică definită de numerotare și revenire la zero, starea receptorului poate identifica duplicate și goluri; un câmp de secvență singur nu previne replay și nu dovedește pierderea pachetelor.]* --- ### Q37. `N04.S04.Q01` — UDP sensor datagram size / Dimensiunea datagramei senzorului UDP +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* The UDP sensor protocol datagram structure has fields: version(1B), sensor_id(4B), temperature(4B float), location(10B), CRC32(4B). What is the total datagram size? [Structura datagramei protocolului senzorului UDP are câmpurile: version(1O), sensor_id(4O), temperature(4O float), location(10O), CRC32(4O). Care este dimensiunea totală a datagramei?] @@ -633,23 +643,24 @@ The UDP sensor protocol datagram structure has fields: version(1B), sensor_id(4B > 💡 **Feedback:** > *Sum of all fields: 1 + 4 + 4 + 10 + 4 = 23 bytes. This compact, fixed-size format is ideal for high-frequency sensor transmissions over UDP. [Suma tuturor câmpurilor: 1 + 4 + 4 + 10 + 4 = 23 octeți. Acest format compact de dimensiune fixă este ideal pentru transmisii de senzori de frecvență ridicată peste UDP.]* - --- -### Q38. `N04.S04.Q02` — ECHO_REQ message type code / Codul tipului de mesaj ECHO_REQ +### Q38. `N04.S04.Q02` — S04 UDP request enum / Enum-ul cererilor UDP S04 -*[Multiple Choice]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -In the BINARY protocol, message types are encoded as single-byte integers. What numeric value corresponds to ECHO_REQ? [În protocolul BINAR, tipurile de mesaje sunt codificate ca întregi pe un singur octet. Ce valoare numerică corespunde tipului ECHO_REQ?] +In `S04_Part03_Script_Transfer_Units.py`, what is the value of `RequestMessageType.CONNECT`? [În `S04_Part03_Script_Transfer_Units.py`, ce valoare are `RequestMessageType.CONNECT`?] -- **a)** 1 — ECHO_REQ is assigned type code 1, with ECHO_RESP being type code 2 [1 — ECHO_REQ are codul de tip 1, cu ECHO_RESP fiind codul de tip 2] -- **b)** 0 — type codes start from zero for the first defined message type [0 — codurile de tip pornesc de la zero pentru primul tip de mesaj definit] -- **c)** 255 — this value is reserved for ERROR responses, not echo requests [255 — această valoare este rezervată pentru răspunsuri ERROR, nu cereri echo] -- **d)** 3 — this is the code for PUT_REQ, not for echo request messages [3 — acesta este codul pentru PUT_REQ, nu pentru mesajele de cerere echo] +- **a)** 1 +- **b)** 0 +- **c)** 255 +- **d)** 5 -> 💡 **Feedback:** -> *TYPE_ECHO_REQ = 1, TYPE_ECHO_RESP = 2, TYPE_PUT_REQ = 3, TYPE_PUT_RESP = 4, TYPE_GET_REQ = 5, TYPE_GET_RESP = 6, TYPE_ERROR = 255. Response types are always request type + 1. [TYPE_ECHO_REQ = 1, TYPE_ECHO_RESP = 2, TYPE_PUT_REQ = 3, TYPE_PUT_RESP = 4, TYPE_GET_REQ = 5, TYPE_GET_RESP = 6, TYPE_ERROR = 255. Tipurile de răspuns sunt întotdeauna tipul cererii + 1.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** CONNECT=1, SEND=2, LIST=3 and DISCONNECT=4. CLEAR=5 is the student extension. These are enum values serialised by pickle; they are not a fixed one-byte sensor packet layout. [CONNECT=1, SEND=2, LIST=3 și DISCONNECT=4. CLEAR=5 este extensia studentului. Acestea sunt valori enum serializate prin pickle; nu reprezintă un format fix de pachet de senzor pe un octet.] +
    --- @@ -674,16 +685,15 @@ Which Wireshark display filter isolates traffic for the Week 4 TEXT protocol ser *[Multiple Choice]* -Which tcpdump command captures TEXT protocol packets on TCP port 3333 in ASCII mode without resolving hostnames? [Care comandă tcpdump capturează pachetele protocolului TEXT pe portul TCP 3333 în mod ASCII fără rezoluția numelor de gazdă?] +Which tcpdump command captures TEXT protocol packets between the client and server on 127.0.0.1:3333 in ASCII mode without resolving hostnames? [Care comandă tcpdump capturează pachetele protocolului TEXT între clientul și serverul de pe 127.0.0.1:3333 în mod ASCII fără rezoluția numelor de gazdă?] -- **a)** sudo tcpdump -i eth0 -nn -A 'tcp port 3333' [sudo tcpdump -i eth0 -nn -A 'tcp port 3333'] -- **b)** tcpdump -i eth0 -verbose port 3333 \--ascii [tcpdump -i eth0 -verbose port 3333 \--ascii] -- **c)** sudo tcpdump -i eth0 -XX 'udp port 3333' [sudo tcpdump -i eth0 -XX 'udp port 3333'] +- **a)** sudo tcpdump -i lo -nn -A 'tcp port 3333' [sudo tcpdump -i lo -nn -A 'tcp port 3333'] +- **b)** tcpdump -i lo -verbose port 3333 \--ascii [tcpdump -i lo -verbose port 3333 \--ascii] +- **c)** sudo tcpdump -i lo -XX 'udp port 3333' [sudo tcpdump -i lo -XX 'udp port 3333'] - **d)** tcpdump -capture -port 3333 -format text [tcpdump -capture -port 3333 -format text] > 💡 **Feedback:** -> *sudo tcpdump -i eth0 -nn -A 'tcp port 3333' — the -nn flag disables host and port name resolution, -A shows ASCII content, and the BPF filter 'tcp port 3333' isolates the TEXT protocol traffic. [sudo tcpdump -i eth0 -nn -A 'tcp port 3333' — indicatorul -nn dezactivează rezoluția numelor de gazdă și port, -A arată conținutul ASCII, iar filtrul BPF 'tcp port 3333' izolează traficul protocolului TEXT.]* - +> *sudo tcpdump -i lo -nn -A 'tcp port 3333' — the -nn flag disables host and port name resolution, -A shows ASCII content, and the BPF filter 'tcp port 3333' isolates the TEXT protocol traffic. [sudo tcpdump -i lo -nn -A 'tcp port 3333' — indicatorul -nn dezactivează rezoluția numelor de gazdă și port, -A arată conținutul ASCII, iar filtrul BPF 'tcp port 3333' izolează traficul protocolului TEXT.]* --- @@ -774,6 +784,7 @@ Before calling bind(), the TEXT protocol server sets SO_REUSEADDR on the socket. ### Q46. `N04.S04.Q03` — Location field padding in UDP datagram / Completarea câmpului locație în datagrama UDP +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Multiple Choice]* The UDP sensor datagram allocates exactly 10 bytes for the location field. If the location string is 'Lab1' (4 bytes), how is it stored? [Datagrama senzorului UDP alocă exact 10 octeți pentru câmpul locație. Dacă șirul de locație este 'Lab1' (4 octeți), cum este stocat?] @@ -784,8 +795,7 @@ The UDP sensor datagram allocates exactly 10 bytes for the location field. If th - **d)** Base64-encoded and then stored, expanding from 4 to approximately 8 bytes [Codificată Base64 și apoi stocată, expandându-se de la 4 la aproximativ 8 octeți] > 💡 **Feedback:** -> *The location is left-justified and padded with null bytes (\\x00) to fill the 10-byte field: b'Lab1\\x00\\x00\\x00\\x00\\x00\\x00'. This is implemented with location.encode('utf-8').ljust(10)[:10]. [Locația este aliniată la stânga și completată cu octeți nuli (\\x00) pentru a umple câmpul de 10 octeți: b'Lab1\\x00\\x00\\x00\\x00\\x00\\x00'. Se implementează cu location.encode('utf-8').ljust(10)[:10].]* - +> *The location is left-justified and padded with null bytes (\\x00) to fill the 10-byte field: b'Lab1\\x00\\x00\\x00\\x00\\x00\\x00'. This is implemented with location.encode('utf-8').ljust(10, b'\x00')[:10]. [Locația este aliniată la stânga și completată cu octeți nuli (\\x00) pentru a umple câmpul de 10 octeți: b'Lab1\\x00\\x00\\x00\\x00\\x00\\x00'. Se implementează cu location.encode('utf-8').ljust(10, b'\x00')[:10].]* --- @@ -868,6 +878,7 @@ What is the size of a UDP header in bytes? [Care este dimensiunea antetului UDP ### Q53. `N04.D03.Q01` — Binary header size in bytes / Dimensiunea antetului binar în octeți +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Numerical]* The BINARY protocol header format is '\>2sBBHII'. How many bytes is the total header? Enter a whole number. [Formatul antetului protocolului BINAR este '\>2sBBHII'. Câți octeți are antetul total? Introduceți un număr întreg.] @@ -875,11 +886,11 @@ The BINARY protocol header format is '\>2sBBHII'. How many bytes is the total he > 💡 **Feedback:** > *2(2s) + 1(B) + 1(B) + 2(H) + 4(I) + 4(I) = (\...) bytes. [2(2s) + 1(B) + 1(B) + 2(H) + 4(I) + 4(I) = (\...) octeți.]* - --- ### Q54. `N04.D03.Q02` — UDP sensor datagram size / Dimensiunea datagramei senzorului UDP +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Numerical]* The UDP sensor datagram has fields: version(1B), sensor_id(4B), temp(4B), location(10B), CRC32(4B). Total size in bytes? [Datagrama senzorului UDP are câmpurile: version(1O), sensor_id(4O), temp(4O), location(10O), CRC32(4O). Dimensiunea totală în octeți?] @@ -887,30 +898,33 @@ The UDP sensor datagram has fields: version(1B), sensor_id(4B), temp(4B), locati > 💡 **Feedback:** > *1 + 4 + 4 + 10 + 4 = (\...) bytes. [1 + 4 + 4 + 10 + 4 = (\...) octeți.]* - --- ### Q55. `N04.D03.Q03` — Endianness misinterpretation of 1000 / Interpretarea greșită a 1000 din cauza endianness -*[Numerical]* +*Numerical / Numeric* -Value 1000 is packed as big-endian unsigned short ('\>H'). If the receiver reads it as little-endian ('H'). Dacă receptorul o citește ca little-endian ('\H", 1000))[0]`? [Care este rezultatul expresiei `struct.unpack("H", 1000))[0]`?] -> 💡 **Feedback:** -> *1000 = 0x03E8. Big-endian: [03][E8]. Read as little-endian: 0xE803 = 232\*3 + 8\*256 = (\...). [1000 = 0x03E8. Big-endian: [03][E8]. Citit ca little-endian: 0xE803 = (\...).]* +
    💡 Feedback + +**59395**. `1000 = 0x03E8`; the bytes are `03 E8`. Little-endian interpretation gives `0xE803 = 232 × 256 + 3 = 59395`. [Interpretarea little-endian produce `0xE803 = 232 × 256 + 3 = 59395`.] +
    --- ### Q56. `N04.D03.Q04` — TEXT protocol frame size for 13-byte payload / Dimensiunea cadrului TEXT pentru sarcină utilă de 13 octeți -*[Numerical]* +*Numerical / Numeric* -The TEXT protocol uses " " framing where LENGTH is ASCII decimal. For payload "SET key value" (13 bytes), how many bytes is the complete frame? [Protocolul TEXT folosește cadrajul " " unde LUNGIME este zecimal ASCII. Pentru sarcina utilă "SET key value" (13 octeți), câți octeți are cadrul complet?] +S04 uses `TOTAL_LENGTH SP PAYLOAD`, counting all UTF-8 bytes including the prefix and space. How many bytes are in the frame for `add key value` (13 ASCII bytes)? [S04 folosește `TOTAL_LENGTH SP PAYLOAD`, numărând toți octeții UTF-8, inclusiv prefixul și spațiul. Câți octeți are cadrul pentru `add key value` (13 octeți ASCII)?] -> 💡 **Feedback:** -> *"13 SET key value" = 2 (ASCII digits "13") + 1 (space) + 13 (payload) = (\...) bytes total. ["13 SET key value" = 2 (cifrele ASCII "13") + 1 (spațiu) + 13 (sarcină utilă) = (\...) octeți total.]* +
    💡 Feedback +**16**. The complete frame is `16 add key value`: 2 + 1 + 13 = 16. [Cadrul complet este `16 add key value`: 2 + 1 + 13 = 16.] + +
    --- @@ -976,37 +990,41 @@ A sender packs the value {a} as a 2-byte big-endian unsigned short. The receiver ### Q62. `N04.D04.Q04` — Text frame total size / Dimensiunea totală a cadrului text -*[Calculated]* +*Calculated / Calculat* -In the TEXT protocol, a message is framed as " ". If the payload is "{a} SET key value" ({a} characters), the length prefix is the ASCII representation of {a} followed by a space. How many bytes is the complete frame? (Length prefix chars + 1 space + payload bytes) [În protocolul TEXT, un mesaj este încadrat ca " ". Dacă payloadul este "{a} SET key value" ({a} caractere), prefixul de lungime este reprezentarea ASCII a lui {a} urmată de un spațiu. Câți octeți are cadrul complet? (Caractere prefix lungime + 1 spațiu + octeți payload)] +In S04, `TOTAL_LENGTH SP PAYLOAD` counts all bytes. Let `{a}` be the UTF-8 payload length, restricted to integer values from **10 through 96 inclusive**. How many bytes are in the complete frame? [În S04, `TOTAL_LENGTH SP PAYLOAD` numără toți octeții. `{a}` este lungimea payloadului UTF-8, limitată la valori întregi între **10 și 96 inclusiv**. Câți octeți are cadrul complet?] -> 💡 **Feedback:** -> *The length prefix "{a}" is ceil(log10({a}+1)) ASCII digits, plus 1 space, plus {a} payload bytes. For a two-digit length like 13: "13 " (3 bytes) + 13 bytes = 16 total. [Prefixul de lungime "{a}" este ceil(log10({a}+1)) cifre ASCII, plus 1 spațiu, plus {a} octeți payload. Pentru o lungime de două cifre ca 13: "13 " (3 octeți) + 13 octeți = 16 total.]* +
    💡 Feedback + +**Formula: `{a} + 3`**, because the total lies between 13 and 99 and therefore always has two ASCII digits plus one space. Outside this supplied range, solve `T = payload_bytes + 1 + len(str(T))`; do not assume a constant digit count. [Totalul se află între 13 și 99, deci are două cifre ASCII și un spațiu. În afara intervalului dat, rezolvați `T = payload_bytes + 1 + len(str(T))`; numărul cifrelor nu este constant.] +
    --- ### Q63. `N04.D04.Q05` — Binary message total bytes / Total octeți mesaj binar -*[Calculated]* +*Calculated / Calculat* -A binary protocol message consists of a 14-byte header followed by the payload. If the key is {a} characters and the value is {b} characters, and the payload encoding uses 1 byte for key_length + key + value, how many total bytes does the entire message occupy? [Un mesaj de protocol binar constă dintr-un antet de 14 octeți urmat de payload. Dacă cheia are {a} caractere și valoarea are {b} caractere, iar codificarea payload-ului folosește 1 octet pentru lungime_cheie + cheie + valoare, câți octeți totali ocupă întregul mesaj?] +The S04 binary protocol prefixes a pickle payload with **one byte containing the total frame length**. If serialisation has already produced `{a}` bytes, with integer `1 ≤ {a} ≤ 254`, how many bytes are sent? [Protocolul binar S04 prefixează payloadul pickle cu **un octet care conține lungimea totală a cadrului**. Dacă serializarea a produs deja `{a}` octeți, cu valoare întreagă `1 ≤ {a} ≤ 254`, câți octeți se trimit?] -> 💡 **Feedback:** -> *Total = 14 (header) + 1 (key_length byte) + {a} (key) + {b} (value) = 15 + {a} + {b}. The key_length field uses 1 byte (struct 'B') as defined in proto_common.py encode_kv(). [Total = 14 (antet) + 1 (octet lungime_cheie) + {a} (cheie) + {b} (valoare) = 15 + {a} + {b}. Câmpul lungime_cheie folosește 1 octet (struct 'B') conform definiției din proto_common.py encode_kv().]* +
    💡 Feedback +**Formula: `1 + {a}`**. Do not infer the pickle length from the number of characters in the key and value; measure the serialised bytes. A payload longer than 254 bytes is rejected before transmission. [Nu deduceți lungimea pickle din numărul caracterelor cheii și valorii; măsurați octeții serializați. Un payload mai lung de 254 de octeți este respins înainte de transmisie.] + +
    --- ### Q64. `N04.D04.Q06` — UDP sensor useful data ratio / Raportul datelor utile senzor UDP +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Calculated]* -The UDP sensor datagram is 23 bytes total. The useful data fields are: sensor_id (4 bytes) and temperature ({a} bytes). The remaining fields (version, location, CRC32) are protocol overhead. What percentage of the datagram carries useful sensor readings? Round to one decimal. [Datagrama senzorului UDP are 23 de octeți în total. Câmpurile de date utile sunt: sensor_id (4 octeți) și temperatură ({a} octeți). Câmpurile rămase (versiune, locație, CRC32) sunt overhead de protocol. Ce procent din datagramă transportă citiri utile ale senzorilor? Rotunjiți la o zecimală.] +In this hypothetical layout, the UDP payload has 15 bytes of fixed protocol overhead. The useful data fields are: sensor_id (4 bytes) and temperature ({a} bytes). The remaining fields (version, location, CRC32) are protocol overhead. What percentage of the datagram carries useful sensor readings? Round to one decimal. [În acest format ipotetic, payload-ul UDP are 15 octeți de overhead fix. Câmpurile de date utile sunt: sensor_id (4 octeți) și temperatură ({a} octeți). Câmpurile rămase (versiune, locație, CRC32) sunt overhead de protocol. Ce procent din datagramă transportă citiri utile ale senzorilor? Rotunjiți la o zecimală.] > 💡 **Feedback:** -> *Useful = 4 + {a} bytes. Percentage = (4 + {a}) / 23 × 100. For the standard 4-byte float: (4+4)/23 × 100 = 34.8%. The location field (10B) and CRC (4B) are overhead necessary for identification and integrity. [Util = 4 + {a} octeți. Procent = (4 + {a}) / 23 × 100. Pentru float-ul standard de 4 octeți: (4+4)/23 × 100 = 34.8%. Câmpul locație (10B) și CRC (4B) sunt overhead necesar pentru identificare și integritate.]* - +> *Useful = 4 + {a} bytes; total payload = 19 + {a} bytes. Percentage = (4 + {a}) / (19 + {a}) × 100. For the standard 4-byte float: (4+4)/23 × 100 = 34.8%. The location field (10B) and CRC (4B) are overhead necessary for identification and integrity. [Util = 4 + {a} octeți; payload total = 19 + {a} octeți. Procent = (4 + {a}) / (19 + {a}) × 100. Pentru float-ul standard de 4 octeți: (4+4)/23 × 100 = 34.8%. Câmpul locație (10B) și CRC (4B) sunt overhead necesar pentru identificare și integritate.]* --- @@ -1039,22 +1057,28 @@ A sensor sends {a} readings per minute. The text protocol frame is 35 bytes per --- -### Q67. `N04.D05.Q03` — Complete struct.pack call for binary header / Completați apelul struct.pack pentru antetul binar +### Q67. `N04.D05.Q03` — Equivalent standard big-endian prefixes / Prefixe big-endian standard echivalente -*[Drag & Drop into Text]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -Complete the struct.pack() call to build the binary header with CRC: [Completați apelul struct.pack() pentru a construi antetul binar cu CRC:] -header = struct.pack('[[1]]2sBBHII', MAGIC, VERSION, msg_type, payload_len, seq, [[2]]) -*Available choices / Variante disponibile:* \> | crc | \< | seq | ! | version +For an independent 14-byte header with fields `2sBBHII`, which prefixes give standard-size big-endian encoding? [Pentru un antet independent de 14 octeți cu câmpurile `2sBBHII`, ce prefixe produc codificare big-endian cu dimensiuni standard?] -> 💡 **Feedback:** -> *The format prefix '\>' specifies big-endian (network byte order). The last field is the CRC32 value. Format: \>2sBBHII = magic(2) + ver(1) + type(1) + len(2) + seq(4) + crc(4) = 14 bytes. [Prefixul de format '\>' specifică big-endian (ordinea octeților în rețea). Ultimul câmp este valoarea CRC32. Format: \>2sBBHII = magic(2) + ver(1) + tip(1) + lungime(2) + seq(4) + crc(4) = 14 octeți.]* +- **a)** Both `>` and `!`. [Atât `>`, cât și `!`.] +- **b)** Only `<`. [Doar `<`.] +- **c)** Only `@`, on every platform. [Doar `@`, pe orice platformă.] +- **d)** Only `=` guarantees big-endian. [Doar `=` garantează big-endian.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** `struct.calcsize(">2sBBHII")` and `struct.calcsize("!2sBBHII")` both equal 14. This hypothetical header is not the S04 pickle wire format, which has one total-length prefix byte. [`struct.calcsize(">2sBBHII")` și `struct.calcsize("!2sBBHII")` sunt ambele 14. Antetul ipotetic nu este formatul pickle S04, care are un octet prefix de lungime totală.] + +
    --- ### Q68. `N04.D05.Q06` — Complete UDP sensor pack call / Completați apelul de împachetare al senzorului UDP +> Independent design exercise. The layout stated in this item is hypothetical; it is not the one-byte-prefix/pickle implementation in S04. [Exercițiu independent de proiectare. Contractul definit aici nu este implementarea S04 distribuită.] *[Drag & Drop into Text]* Complete the struct.pack for the UDP sensor datagram (without CRC): [Completați struct.pack pentru datagrama senzorului UDP (fără CRC):] @@ -1064,41 +1088,52 @@ payload = struct.pack('\>[[1]][[2]]f[[3]]', VERSION, sensor_id, temp, location_b > 💡 **Feedback:** > *Format: \>BIf10s — B for version (1 byte), I for sensor_id (4 bytes unsigned int), f for temperature (4 bytes float), 10s for location (10 bytes string). [Format: \>BIf10s — B pentru versiune (1 octet), I pentru sensor_id (4 octeți unsigned int), f pentru temperatură (4 octeți float), 10s pentru locație (10 octeți șir).]* - --- ### Q69. `N04.D05.Q01` — Build tcpdump command for binary protocol / Construiți comanda tcpdump pentru protocolul binar -*[Drag & Drop into Text]* +*Drag and Drop / Trageți și plasați* -Build the tcpdump command that captures BINARY protocol traffic in hex dump mode without hostname resolution: [Construiți comanda tcpdump care capturează traficul protocolului BINAR în mod hex dump fără rezoluție de nume de gazdă:] -sudo [[1]] -i eth0 [[2]] [[3]] 'tcp port [[4]]' -*Available choices / Variante disponibile:* tcpdump | -nn | -XX | 5401 | curl | -A | 3333 | 5402 +Build a capture for the S04 binary example running on `127.0.0.1:3333`. [Construiți captura pentru exemplul binar S04 care rulează pe `127.0.0.1:3333`.] -> 💡 **Feedback:** -> *tcpdump -nn -XX captures TCP port 5401 traffic in hex+ASCII mode without name resolution. -nn disables both host and port resolution. [tcpdump -nn -XX capturează traficul TCP portul 5401 în mod hex+ASCII fără rezoluție de nume. -nn dezactivează rezoluția numelor de gazdă și port.]* +```bash +sudo [[1]] -i lo [[2]] [[3]] 'tcp port [[4]]' +``` + +Choices / Variante: `tcpdump`, `-nn`, `-XX`, `3333`, `curl`, `-A`, `5401`, `5402`. + +
    💡 Feedback +`sudo tcpdump -i lo -nn -XX 'tcp port 3333'`. `-nn` disables name and service resolution; `-XX` prints hexadecimal and ASCII including the link header. The text and binary examples both default to 3333, so run them separately. [Comanda dezactivează rezoluția de nume și servicii și afișează hexazecimal și ASCII inclusiv antetul legăturii. Exemplele text și binar folosesc implicit același port 3333, deci rulați-le separat.] + +
    --- ### Q70. `N04.D05.Q05` — Build recv_exact function call / Construiți apelul funcției recv_exact -*[Drag & Drop into Text]* +*Drag and Drop / Trageți și plasați* -Complete the recv_exact helper to receive exactly n bytes: [Completați helper-ul recv_exact pentru a primi exact n octeți:] +Complete this helper for a non-negative integer `n`. [Completați acest helper pentru un întreg nenegativ `n`.] ```python -while len(data) < n: - chunk = sock.[[1]](n - [[2]](data)) - if not chunk: - raise [[3]]("closed") +def recv_exact(sock, n): + data = bytearray() + while len(data) < n: + chunk = sock.[[1]](n - [[2]](data)) + if not chunk: + raise [[3]]("connection closed before the frame ended") + data.extend(chunk) + return bytes(data) ``` -*Available choices / Variante disponibile:* recv | len | ConnectionError | send | size | ValueError +Choices / Variante: `recv`, `len`, `ConnectionError`, `send`, `size`, `ValueError`. -> 💡 **Feedback:** -> *sock.recv(n - len(data)) requests at most the remaining bytes needed. An empty chunk (not chunk) means the peer closed the connection, raising ConnectionError. [sock.recv(n - len(data)) solicită cel mult octeții rămași necesari. Un fragment gol (not chunk) înseamnă că partenerul a închis conexiunea, ridicând ConnectionError.]* +
    💡 Feedback + +1 = `recv`; 2 = `len`; 3 = `ConnectionError`. Accumulating each chunk is essential. Reading only the remaining count avoids consuming bytes belonging to the next frame. [Acumularea fiecărui fragment este esențială. Citirea numai a numărului rămas evită consumarea octeților cadrului următor.] +
    --- diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W05_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W05_Questions.md index 30136c3..c296b73 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W05_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W05_Questions.md @@ -222,18 +222,20 @@ IPv6 link-local addresses (fe80::/10) are automatically configured on every IPv6 ### Q14. `N05.C04.Q04` — IPv6 Address Type Identification / Identificarea tipului de adresă IPv6 -*[Multiple Choice — Alegere multiplă]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -An IPv6 address beginning with 2001:0db8: belongs to which address category? [O adresă IPv6 care începe cu 2001:0db8: aparține cărei categorii de adrese?] +What is the intended use of IPv6 prefix 2001:db8::/32? [Care este utilizarea destinată prefixului IPv6 2001:db8::/32?] -- **a)** Global unicast — routable on the Internet (2000::/3) [Unicast global — rutabilă pe Internet (2000::/3)] -- **b)** Link-local — confined to a single segment (fe80::/10) [Link-local — limitată la un singur segment (fe80::/10)] -- **c)** Unique local — private use, not globally routable (fc00::/7) [Locală unică — utilizare privată, nerutabilă global (fc00::/7)] -- **d)** Multicast — one-to-many group communication (ff00::/8) [Multicast — comunicare de grup unu-la-mulți (ff00::/8)] +- **a)** Documentation and examples; it is not a public deployment prefix. [Documentație și exemple; nu este un prefix pentru implementare publică.] +- **b)** Globally reachable production addresses assigned to this university. [Adrese de producție accesibile global atribuite universității.] +- **c)** Link-local communication on every interface. [Comunicare link-local pe orice interfață.] +- **d)** IPv6 multicast group addressing. [Adresare multicast IPv6.] -> 💡 **Feedback:** -> *2001:0db8: falls within the 2000::/3 global unicast range. Note: 2001:db8::/32 is specifically the documentation range (RFC 3849), but it is structurally a global unicast address. [2001:0db8: se încadrează în intervalul unicast global 2000::/3. Notă: 2001:db8::/32 este specific intervalul de documentare (RFC 3849), dar este structural o adresă unicast globală.]* +
    💡 Feedback +**Correct answer / Răspuns corect: a.** RFC 3849 reserves this block for documentation. Its appearance within the larger unicast address space does not make it globally reachable. [RFC 3849 rezervă blocul pentru documentație. Apartenența la spațiul mai larg de unicast nu îl face accesibil global.] + +
    --- @@ -258,7 +260,7 @@ What is the recommended prefix length for end-user IPv6 subnets, and why? [Care *[Multiple Choice — Alegere multiplă]* -The full IPv6 address 2001:0db8:0000:0000:0000:0085:0000:7334 can be correctly compressed to which form? [Adresa IPv6 completă 2001:0db8:0000:0000:0000:0085:0000:7334 poate fi comprimată corect în care formă?] +The full IPv6 address 2001:0db8:0000:0000:0000:0085:0000:7334 has which canonical representation under RFC 5952? [Adresa IPv6 completă 2001:0db8:0000:0000:0000:0085:0000:7334 are care reprezentare canonică potrivit RFC 5952?] - **a)** 2001:db8::85:0:7334 — leading zeros removed, longest zero run replaced by :: [2001:db8::85:0:7334 — zerourile din față eliminate, cea mai lungă serie de zerouri înlocuită cu ::] - **b)** 2001:db8::85::7334 — using :: twice for both zero sequences [2001:db8::85::7334 — folosind :: de două ori pentru ambele secvențe de zerouri] @@ -266,8 +268,7 @@ The full IPv6 address 2001:0db8:0000:0000:0000:0085:0000:7334 can be correctly c - **d)** 2001:db8:0::85:0:7334 — :: replaces only two zero groups [2001:db8:0::85:0:7334 — :: înlocuiește doar două grupuri de zerouri] > 💡 **Feedback:** -> *The longest consecutive all-zero run (positions 3-5, three groups) gets replaced by ::. The single zero group at position 7 stays as :0:. The :: can only appear once. [Cea mai lungă serie consecutivă de zerouri (pozițiile 3-5, trei grupuri) se înlocuiește cu ::. Grupul singular de zerouri de la poziția 7 rămâne ca :0:. :: poate apărea doar o singură dată.]* - +> *The longest consecutive all-zero run (positions 3-5, three groups) gets replaced by ::. The single zero group at position 7 stays as :0:. The :: can only appear once. Options c and d are valid spellings of the address but do not use the required canonical longest-run compression. [Cea mai lungă serie consecutivă de zerouri (pozițiile 3-5, trei grupuri) se înlocuiește cu ::. Grupul singular de zerouri de la poziția 7 rămâne ca :0:. :: poate apărea doar o singură dată. Variantele c și d sunt scrieri valide ale adresei, dar nu folosesc compresia canonică cerută a celei mai lungi secvențe.]* --- @@ -348,12 +349,11 @@ For a point-to-point router link, a network engineer considers both /30 and /31. - **a)** /31 is valid for point-to-point links since broadcast is unnecessary between two endpoints [/31 este valid pentru legături punct-la-punct deoarece broadcast-ul este inutil între două puncte finale] - **b)** /31 has zero usable addresses and cannot be assigned to any interface [/31 are zero adrese utilizabile și nu poate fi atribuit niciunei interfețe] - **c)** /30 is always required because /31 violates the network/broadcast reservation rule defined in the original IPv4 specification [/30 este întotdeauna necesar deoarece /31 încalcă regula de rezervare rețea/broadcast definită în specificația originală IPv4] -- **d)** Both /30 and /31 provide exactly the same number of usable host addresses [Atât /30, cât și /31 oferă exact același număr de adrese de gazdă utilizabile] +- **d)** /31 requires four address values for its two endpoints [/31 necesită patru valori de adresă pentru cele două capete] > 💡 **Feedback:** > *RFC 3021 allows /31 for P2P links: 2 addresses, both usable (no broadcast needed). /30 gives 4 addresses, 2 usable. Both provide 2 usable, but /31 saves 2 addresses. [RFC 3021 permite /31 pentru legături P2P: 2 adrese, ambele utilizabile (nu este nevoie de broadcast). /30 oferă 4 adrese, 2 utilizabile. Ambele oferă 2 utilizabile, dar /31 economisește 2 adrese.]* - --- ### Q22. `N05.T00.Q07` — Subnetting: Non-Octet Broadcast / Subrețelare: broadcast non-octet @@ -560,8 +560,7 @@ What subnet mask corresponds to a /27 prefix? [Ce mască de subrețea corespunde - **d)** 255.255.255.128 — this corresponds to a /25 prefix instead [255.255.255.128 — aceasta corespunde unui prefix /25 în schimb] > 💡 **Feedback:** -> *For /27: 27 bits set to 1 = 24 full octets + 3 bits in the fourth octet. Binary: 11100000 = 224. [Pentru /27: 27 de biți setați la 1 = 24 de octeți completi + 3 biți în al patrulea octet. Binar: 11100000 = 224.]* - +> *For /27: 27 bits set to 1 = 24 bits in three complete octets + 3 bits in the fourth octet. Binary: 11100000 = 224. [Pentru /27: 27 de biți setați la 1 = 24 de biți în trei octeți compleți + 3 biți în al patrulea octet. Binar: 11100000 = 224.]* --- @@ -569,7 +568,7 @@ What subnet mask corresponds to a /27 prefix? [Ce mască de subrețea corespunde *[Multiple Choice — Alegere multiplă]* -In the subnet 10.5.0.0/24 used by the Week 5 lab, what are the network address and broadcast address? [În subrețeaua 10.5.0.0/24 utilizată de laboratorul Săptămânii 5, care sunt adresa de rețea și adresa de broadcast?] +In the subnet 10.5.0.0/24 in this addressing exercise, what are the network address and broadcast address? [În subrețeaua 10.5.0.0/24 din acest exercițiu de adresare, care sunt adresa de rețea și adresa de broadcast?] - **a)** Network: 10.5.0.0, Broadcast: 10.5.0.255 [Rețea: 10.5.0.0, Broadcast: 10.5.0.255] - **b)** Network: 10.5.0.1, Broadcast: 10.5.0.254 [Rețea: 10.5.0.1, Broadcast: 10.5.0.254] @@ -579,7 +578,6 @@ In the subnet 10.5.0.0/24 used by the Week 5 lab, what are the network address a > 💡 **Feedback:** > *For /24 at 10.5.0.0: network = all host bits 0 = 10.5.0.0; broadcast = all host bits 1 = 10.5.0.255. The usable range is .1 through .254. [Pentru /24 la 10.5.0.0: rețea = toți biții de gazdă 0 = 10.5.0.0; broadcast = toți biții de gazdă 1 = 10.5.0.255. Intervalul utilizabil este de la .1 până la .254.]* - --- ### Q35. `N05.S01.Q10` — First Usable Address in Subnet / Prima adresă utilizabilă în subrețea @@ -686,18 +684,20 @@ Given requirements [60, 14, 30, 2] for network 10.0.0.0/24, the VLSM algorithm s ### Q41. `N05.S03.Q03` — VLSM Trace: Prefix for 14 Hosts / Trasare VLSM: prefixul pentru 14 gazde -*[Multiple Choice — Alegere multiplă]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -In code exercise T5, the function processes req=14. What prefix does 32 - (req + 2 - 1).bit_length() yield? [În exercițiul de cod T5, funcția procesează req=14. Ce prefix produce 32 - (req + 2 - 1).bit_length()?] +For `req = 14`, what does `32 - (req + 2 - 1).bit_length()` evaluate to? [Pentru `req = 14`, ce valoare produce `32 - (req + 2 - 1).bit_length()`?] -- **a)** /27 — because (14+2-1) = 15, bit_length()=4, but the actual allocation uses (16).bit_length()=5 → /27 [/27 — deoarece (14+2-1) = 15, bit_length()=4, dar alocarea reală folosește (16).bit_length()=5 → /27] -- **b)** /28 — because 14 hosts need 16 total addresses, and log2(16) = 4, so the resulting prefix = 32−4 = 28 [/28 — deoarece 14 gazde necesită 16 adrese în total, iar log2(16) = 4, deci prefixul rezultat = 32−4 = 28] -- **c)** /26 — because 14 hosts get rounded up to the next /26 block [/26 — deoarece 14 gazde sunt rotunjite la următorul bloc /26] -- **d)** /29 — because 14+2=16 and 32-3=29 [/29 — deoarece 14+2=16 și 32-3=29] +- **a)** 28 (`/28`) +- **b)** 27 (`/27`) +- **c)** 26 (`/26`) +- **d)** 29 (`/29`) -> 💡 **Feedback:** -> *req=14: (14+2-1)=15, bit_length()=4. But wait — 15.bit_length()=4, prefix=32-4=28. However, the trace solution shows /27. The exact formula depends on bit_length computation: (16).bit_length()=5, prefix=27. This matches the trace output. [req=14: (14+2-1)=15, bit_length()=4. Dar 15.bit_length()=4, prefix=32-4=28. Totuși, soluția trasării arată /27. Formula exactă depinde de calculul bit_length: (16).bit_length()=5, prefix=27. Aceasta se potrivește cu rezultatul trasării.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** (14 + 2 - 1) = 15 and (15).bit_length() = 4; 32 − 4 = 28. A conventional /28 subnet has 16 addresses and 14 usable host addresses. Substituting (16).bit_length() changes the expression and is not a valid evaluation. [(14 + 2 - 1) = 15 și (15).bit_length() = 4; 32 − 4 = 28. O subrețea convențională /28 are 16 adrese și 14 adrese utilizabile de gazdă. Substituirea cu (16).bit_length() schimbă expresia și nu reprezintă o evaluare validă.] +
    --- @@ -720,18 +720,19 @@ The align_to_boundary() function in code exercise T3 ensures that subnet startin ### Q43. `N05.S04.Q01` — IPv6 Expand Command / Comanda de expandare IPv6 -*[Multiple Choice — Alegere multiplă]* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -In the Week 5 lab, which command expands a compressed IPv6 address to its full 32-digit hexadecimal form? [În laboratorul Săptămânii 5, care comandă expandează o adresă IPv6 comprimată la forma completă de 32 de cifre hexazecimale?] +Which Python standard-library command expands `2001:db8::1` without relying on a separate exercise kit? [Ce comandă din biblioteca standard Python expandează `2001:db8::1` fără a depinde de alt kit de exerciții?] -- **a)** docker exec week5_python python /app/src/exercises/ex_5_02_vlsm_ipv6.py ipv6-expand 2001:db8::1 [docker exec week5_python python /app/src/exercises/ex_5_02_vlsm_ipv6.py ipv6-expand 2001:db8::1] -- **b)** docker exec week5_python python /app/src/exercises/ex_5_02_vlsm_ipv6.py ipv6 2001:db8::1 [docker exec week5_python python /app/src/exercises/ex_5_02_vlsm_ipv6.py ipv6 2001:db8::1] -- **c)** docker exec week5_python python /app/src/exercises/ex_5_01_cidr_flsm.py analyse 2001:db8::1 [docker exec week5_python python /app/src/exercises/ex_5_01_cidr_flsm.py analyse 2001:db8::1] -- **d)** docker exec week5_python python /app/src/exercises/ex_5_02_vlsm_ipv6.py ipv6-subnets 2001:db8::1 [docker exec week5_python python /app/src/exercises/ex_5_02_vlsm_ipv6.py ipv6-subnets 2001:db8::1] +- **a)** `python3 -c "import ipaddress; print(ipaddress.IPv6Address('2001:db8::1').exploded)"` +- **b)** `python3 -c "print('2001:db8::1'.upper())"` +- **c)** `python3 -c "print('2001:db8::1'.split(':'))"` -> 💡 **Feedback:** -> *The ipv6-expand subcommand of ex_5_02_vlsm_ipv6.py restores all leading zeros and zero groups. The ipv6 subcommand does the reverse — it compresses the address. [Subcomanda ipv6-expand a ex_5_02_vlsm_ipv6.py restaurează toate zerourile din față și grupurile de zerouri. Subcomanda ipv6 face inversul — comprimă adresa.]* +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The exploded property yields `2001:0db8:0000:0000:0000:0000:0000:0001`. No Docker container or absent ex_5_02_vlsm_ipv6.py script is required. [Proprietatea exploded produce `2001:0db8:0000:0000:0000:0000:0000:0001`. Nu este necesar un container Docker sau scriptul absent ex_5_02_vlsm_ipv6.py.] +
    --- diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W06_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W06_Questions.md index 54cfd29..e7994dd 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W06_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W06_Questions.md @@ -131,43 +131,58 @@ --- -### Q10. `Multiple Choice` -**NAT Translation Trace — Server-Visible Source / Trasarea traducerii NAT — sursa vizibilă de server** +### Q10. — SNAT source address / Adresa sursă după SNAT -> Host h1 (192.168.10.2) sends a packet to server h3 (203.0.113.2) through a NAT router with public IP 203.0.113.1. What source IP address does the server h3 observe? [Gazda h1 (192.168.10.2) trimite un pachet către serverul h3 (203.0.113.2) prin intermediul unui ruter NAT cu IP-ul public 203.0.113.1. Ce adresă IP sursă observă serverul h3?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) 192.168.10.2 (h1's private IP) [192.168.10.2 (IP-ul privat al lui h1)]** -- **b) 192.168.10.1 (the router's private interface) [192.168.10.1 (interfața privată a ruterului)]** -- **c) 203.0.113.1 (the NAT router's public IP) [203.0.113.1 (IP-ul public al ruterului NAT)]** -- **d) 203.0.113.2 (h3's own IP) [203.0.113.2 (IP-ul propriu al lui h3)]** +A configured SNAT rule rewrites source 192.168.10.2 to 203.0.113.1 on packets forwarded to 203.0.113.2. What source address is in the IP header received by that server? [O regulă SNAT configurată rescrie sursa 192.168.10.2 în 203.0.113.1 pentru pachetele către 203.0.113.2. Ce adresă sursă apare în antetul IP primit de server?] -> 💡 **Feedback:** Private addresses (RFC 1918) are never visible outside the NAT boundary. The server only sees the NAT router's public IP, 203.0.113.1, as the source. A common misconception is that private IP addresses travel across the Internet; in reality, the NAT router rewrites the source address before forwarding the packet, and external hosts have no knowledge of the internal addressing scheme. [Adresele private (RFC 1918) nu sunt niciodată vizibile în afara granței NAT. Serverul vede doar IP-ul public al ruterului NAT, 203.0.113.1, ca sursă. O concepție greșită frecventă este că adresele IP private circulă prin Internet; în realitate, ruterul NAT rescrie adresa sursă înainte de a redirecționa pachetul, iar gazdele externe nu au cunoștință despre schema de adresare internă.] +- **a)** 203.0.113.1 +- **b)** 192.168.10.2 +- **c)** 192.168.10.1 +- **d)** 203.0.113.2 + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The supplied translation rule determines the visible IP-header source. This does not prove that private addresses cannot appear in payloads, logs, tunnels or routed private networks. 203.0.113.0/24 is a documentation range. [Regula de traducere dată determină sursa vizibilă în antetul IP. Aceasta nu dovedește că adrese private nu pot apărea în payloaduri, loguri, tuneluri sau rețele private rutate. 203.0.113.0/24 este interval de documentație.] + +
    --- -### Q11. `Multiple Choice` -**Why NAT Breaks Inbound Connections / De ce NAT întrerupe conexiunile de intrare** +### Q11. — NAT mapping and filtering / Mapare NAT și filtrare + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +An unsolicited packet arrives at a NAT router public endpoint with no matching dynamic translation or static DNAT mapping. Which statement is correct? [Un pachet nesolicitat ajunge la endpointul public al unui ruter NAT fără traducere dinamică sau mapare DNAT statică potrivită. Ce afirmație este corectă?] -> Peer-to-peer applications and inbound connections often fail when traversing NAT. What is the fundamental reason for this? [Aplicațiile peer-to-peer (egal la egal) și conexiunile de intrare eșuează adesea la traversarea NAT. Care este motivul fundamental?] +- **a)** There is no supplied translation to an internal destination; routing and firewall policy still decide handling. [Nu există traducerea dată către o destinație internă; rutarea și politica firewall decid în continuare tratarea.] +- **b)** NAT automatically drops every packet addressed directly to any internal IP. [NAT elimină automat orice pachet adresat direct oricărui IP intern.] +- **c)** NAT encrypts the packet before rejecting it. [NAT criptează pachetul înainte de respingere.] -- **a) Without an existing conntrack entry, NAT cannot map unsolicited inbound packets to an internal host [Fără o intrare conntrack existentă, NAT nu poate mapa pachetele de intrare nesolicitate către o gazdă internă]** -- **b) NAT blocks all UDP traffic by default [NAT blochează tot traficul UDP implicit]** -- **c) NAT encrypts all outbound traffic at the network layer, preventing external hosts from responding or establishing reverse connections [NAT criptează tot traficul de ieșire la nivelul rețelei, împiedicând gazdele externe să răspundă sau să stabilească conexiuni inverse]** -- **d) NAT requires all applications to use TCP exclusively [NAT necesită ca toate aplicațiile să utilizeze exclusiv TCP]** +
    💡 Feedback -> 💡 **Feedback:** NAT relies on conntrack entries created by outbound connections. Without a pre-existing entry, unsolicited inbound packets cannot be mapped to any internal host and are dropped. A common misconception is that NAT blocks inbound traffic intentionally as a security feature; in reality, it simply has no mapping to route unsolicited packets, which is obscurity rather than deliberate security enforcement. [NAT se bazează pe intrările conntrack create de conexiunile de ieșire. Fără o intrare preexistentă, pachetele de intrare nesolicitate nu pot fi mapate către nicio gazdă internă și sunt eliminate. O concepție greșită frecventă este că NAT blochează traficul de intrare intenționat ca funcție de securitate; în realitate, pur și simplu nu are o mapare pentru a direcționa pachetele nesolicitate, ceea ce reprezintă obscuritate, nu aplicarea deliberată a securității.] +**Correct answer / Răspuns corect: a.** Translation and filtering are different operations. Static port forwarding can supply a mapping; a packet routed directly to an internal address can avoid the need for DNAT. Enforce the intended inbound policy with explicit firewall rules. [Traducerea și filtrarea sunt operații distincte. Redirecționarea statică poate furniza o mapare; un pachet rutat direct la o adresă internă poate să nu necesite DNAT. Aplicați politica de intrare prin reguli firewall explicite.] + +
    --- -### Q12. `True / False` -**NAT Provides Security / NAT oferă securitate** +### Q12. — NAT and firewall roles / Rolurile NAT și firewall -> NAT is an adequate replacement for a firewall because it hides internal IP addresses and blocks all inbound attacks. [NAT este un înlocuitor adecvat al unui firewall (paravan de protecție) deoarece ascunde adresele IP interne și blochează toate atacurile de intrare.] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) true** -- **b) false** +Does address translation alone replace a firewall policy? [Traducerea adreselor înlocuiește singură politica unui firewall?] + +- **a)** No. NAT changes addressing; filtering rules define permitted traffic. [Nu. NAT schimbă adresarea; regulile de filtrare definesc traficul permis.] +- **b)** Yes. NAT blocks every possible inbound attack. [Da. NAT blochează orice atac posibil de intrare.] +- **c)** Yes. NAT authenticates and encrypts every application message. [Da. NAT autentifică și criptează fiecare mesaj al aplicației.] + +
    💡 Feedback -> 💡 **Feedback:** NAT provides obscurity, not security. While it blocks unsolicited inbound connections (no conntrack entry), it does not inspect packet contents, block outbound malware, detect intrusions, or encrypt traffic. A proper stateful firewall is still required. The key question to consider: if an employee clicks a malicious link, does NAT stop the malware from calling home? The [NAT oferă obscuritate, nu securitate. Deși blochează conexiunile de intrare nesolicitate (fără intrare conntrack), nu inspectează conținutul pachetelor, nu blochează programele malware de ieșire, nu detectează intruziunile și nu criptează traficul. Un firewall (paravan de protecție) cu inspecție de stare rămâne necesar. Întrebarea cheie de considerat: dacă un angajat accesează un link malițios, oprește NAT-ul programul malware să comunice cu serverul de comandă? Răspunsul este nu.] +**Correct answer / Răspuns corect: a.** NAT is not a general access-control policy. It does not inherently block malware communicating through permitted outbound connections. Use explicit stateful filtering and application controls appropriate to the intended policy. [NAT nu este o politică generală de control al accesului. Nu blochează implicit malware care comunică prin conexiuni de ieșire permise. Folosiți filtrare cu stare și controale ale aplicației potrivite politicii dorite.] + +
    --- @@ -279,17 +294,21 @@ --- -### Q21. `Multiple Choice` -**When Packet-In Messages Are Sent / Când se trimit mesajele Packet-In** +### Q21. — OpenFlow 1.3 table miss / Table-miss în OpenFlow 1.3 + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +In an OpenFlow 1.3 table, a packet matches no specific entry. When does this path send it to the controller? [Într-o tabelă OpenFlow 1.3, un pachet nu corespunde niciunei intrări specifice. Când îl trimite această cale la controler?] -> Under what condition does an OpenFlow switch send a Packet-In message to the SDN controller? [În ce condiție un comutator OpenFlow trimite un mesaj Packet-In către controlerul SDN?] +- **a)** When a matching table-miss entry explicitly outputs it to CONTROLLER. [Când o intrare table-miss potrivită îl trimite explicit la CONTROLLER.] +- **b)** Always, even if the table has no table-miss entry. [Întotdeauna, chiar dacă tabela nu are intrare table-miss.] +- **c)** Only when it is TCP. [Numai dacă este TCP.] -- **a) When the switch runs out of flow table memory and cannot allocate new entries for incoming packets [Când comutatorul rămâne fără memorie pentru tabela de fluxuri și nu poate aloca intrări noi]** -- **b) When a packet does not match any existing flow rule (table-miss) [Când un pachet nu corespunde niciunei reguli de flux existente (table-miss)]** -- **c) Only for TCP packets [Doar pentru pachete TCP]** -- **d) For every packet that passes through the switch [Pentru fiecare pachet care trece prin comutator]** +
    💡 Feedback -> 💡 **Feedback:** A Packet-In is triggered when a packet matches no existing flow rule (table-miss). The controller then decides what action to take and may install a new flow rule (reactive flow installation). A common misconception is that the controller processes every packet; if this were the case, SDN would be prohibitively slow — the controller only intervenes when no matching rule exists. [Un Packet-In este declanșat când un pachet nu corespunde niciunei reguli de flux existente (table-miss). Controlerul decide apoi ce acțiune să întreprindă și poate instala o nouă regulă de flux (instalare reactivă de flux). O concepție greșită frecventă este că controlerul procesează fiecare pachet; dacă ar fi așa, SDN ar fi prohibitiv de lent — controlerul intervine doar când nu există nicio regulă care să corespundă.] +**Correct answer / Răspuns corect: a.** In OpenFlow 1.3 a missing table-miss entry causes an unmatched packet to be dropped. A wildcard priority-zero table-miss entry can instead output to the controller or continue processing. Other explicit rules can also output to CONTROLLER. [În OpenFlow 1.3, absența intrării table-miss duce la eliminarea pachetului nepotrivit. O intrare table-miss wildcard de prioritate zero poate trimite la controler sau continua procesarea. Și alte reguli explicite pot trimite la CONTROLLER.] + +
    --- @@ -315,7 +334,7 @@ - **a) true** - **b) false** -> 💡 **Feedback:** OpenFlow uses a numerical priority system where higher numbers indicate higher importance. Priority 300 takes precedence over priority 30. The maximum is 65535, and 0 is reserved for the table-miss rule (lowest possible). This is the opposite of everyday language where "Priority 1" typically means most important. [OpenFlow folosește un sistem numeric de priorități în care numerele mai mari indică importanță mai mare. Prioritatea 300 are precedență față de prioritatea 30. Maximul este 65535, iar 0 este rezervat regulii table-miss (cea mai scăzută posibilă). Aceasta este opusul limbajului curent unde „Prioritatea 1" înseamnă de obicei cea mai importantă.] +> 💡 **Feedback:** OpenFlow uses a numerical priority system where higher numbers indicate higher importance. Priority 300 takes precedence over priority 30. The maximum is 65535, and 0 is the lowest possible priority. A table-miss entry combines priority 0 with an all-wildcard match; priority 0 is not reserved exclusively for that entry. This is the opposite of everyday language where "Priority 1" typically means most important. [OpenFlow folosește un sistem numeric de priorități în care numerele mai mari indică importanță mai mare. Prioritatea 300 are precedență față de prioritatea 30. Maximul este 65535, iar 0 este cea mai mică prioritate. Intrarea table-miss combină prioritatea 0 cu o potrivire complet wildcard; prioritatea 0 nu este rezervată exclusiv acestei intrări. Aceasta este opusul limbajului curent unde „Prioritatea 1" înseamnă de obicei cea mai importantă.] --- @@ -341,7 +360,7 @@ - **a) true** - **b) false** -> 💡 **Feedback:** The controller only installs rules in switches. The data plane (switches) performs the actual forwarding at line rate. Once a flow rule is installed, matching packets are forwarded directly by the switch without controller involvement. An analogy: the controller is like a GPS navigator — it tells you where to go but does not drive the car. [Controlerul doar instalează reguli în comutatoare. Planul de date (comutatoarele) efectuează redirecționarea (forwarding) efectivă la viteza liniei. Odată ce o regulă de flux este instalată, pachetele corespunzătoare sunt redirecționate direct de comutator fără implicarea controlerului. O analogie: controlerul este ca un navigator GPS — îți spune unde să mergi, dar nu conduce mașina.] +> 💡 **Feedback:** The controller usually programmes switch behaviour and may also handle selected packets using Packet-In and Packet-Out. The data plane (switches) performs the actual forwarding at line rate. Once a flow rule is installed, matching packets are forwarded directly by the switch without controller involvement. An analogy: the controller is like a GPS navigator — it tells you where to go but does not drive the car. [Controlerul programează de regulă comportamentul comutatoarelor și poate trata pachete selectate prin Packet-In și Packet-Out. Planul de date (comutatoarele) efectuează redirecționarea (forwarding) efectivă la viteza liniei. Odată ce o regulă de flux este instalată, pachetele corespunzătoare sunt redirecționate direct de comutator fără implicarea controlerului. O analogie: controlerul este ca un navigator GPS — îți spune unde să mergi, dar nu conduce mașina.] --- @@ -371,15 +390,21 @@ --- -### Q28. `True / False` -**Volatility of OpenFlow Rules / Volatilitatea regulilor OpenFlow** +### Q28. — OpenFlow timeout and disconnection / Timeout și deconectare OpenFlow -> By default, OpenFlow flow rules are stored in the switch's volatile memory, meaning they may be lost when the controller restarts or the connection drops, unless the controller proactively reinstalls them upon reconnection. [Implicit, regulile de flux OpenFlow sunt stocate în memoria volatilă a comutatorului, ceea ce înseamnă că pot fi pierdute când controlerul repornește sau conexiunea se întrerupe, cu excepția cazului în care controlerul le reinstalează proactiv la reconectare.] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) true** -- **b) false** +A switch remains running but loses its controller connection. Its rule has hard_timeout=0 and idle_timeout=10. Which statement follows? [Comutatorul continuă să ruleze, dar pierde conexiunea cu controlerul. Regula sa are hard_timeout=0 și idle_timeout=10. Ce afirmație rezultă?] + +- **a)** It has no hard expiry, but can expire after ten seconds without matching traffic; controller disconnection alone does not require deletion. [Nu are expirare hard, dar poate expira după zece secunde fără trafic potrivit; deconectarea controlerului singură nu impune ștergerea.] +- **b)** hard_timeout=0 guarantees permanence under all conditions. [hard_timeout=0 garantează permanența în orice condiții.] +- **c)** Every controller disconnect immediately erases every rule. [Orice deconectare a controlerului șterge imediat toate regulile.] + +
    💡 Feedback -> 💡 **Feedback:** OpenFlow flow rules reside in the switch's volatile memory (typically TCAM or software tables). When the controller restarts, crashes, or the TCP connection between controller and switch drops, existing rules may be lost depending on switch implementation. Robust SDN applications handle this by proactively reinstalling rules upon reconnection. Rules with hard_timeout=0 do not expire automatically but remain volatile across restarts. [Regulile de flux OpenFlow se află în memoria volatilă a comutatorului (de obicei TCAM sau tabele software). Când controlerul repornește, se blochează sau conexiunea TCP se întrerupe, regulile existente pot fi pierdute. Aplicațiile SDN robuste gestionează aceasta reinstalând proactiv regulile la reconectare. Regulile cu hard_timeout=0 nu expiră automat, dar rămân volatile la repornire.] +**Correct answer / Răspuns corect: a.** Hard and idle timeouts are independent. Fail-secure behaviour can retain eligible entries after control-channel loss. A switch restart, explicit deletion, eviction or a controller policy can change state. State reconciliation is needed on reconnect. [Timeout-urile hard și idle sunt independente. Comportamentul fail-secure poate păstra intrările eligibile după pierderea canalului de control. Repornirea comutatorului, ștergerea explicită, evacuarea sau politica controlerului pot schimba starea. La reconectare este necesară reconcilierea.] + +
    --- @@ -467,17 +492,21 @@ --- -### Q35. `Multiple Choice` -**Primary Purpose of PAT / Scopul principal al PAT** +### Q35. — Purpose of PAT / Scopul PAT + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> What is the primary purpose of Port Address Translation (PAT) in modern networks? [Care este scopul principal al Port Address Translation (PAT) în rețelele moderne?] +What is the primary role of Port Address Translation? [Care este rolul principal al Port Address Translation?] -- **a) Encrypt traffic between internal and external networks [Criptează traficul între rețelele interne și cele externe]** -- **b) Provide comprehensive network security by hiding internal addresses from external threats and inspecting all inbound traffic [Asigură securitate completă a rețelei prin ascunderea adreselor interne față de amenințările externe și inspectarea întregului trafic de intrare]** -- **c) Allow multiple internal hosts to share a single public IP via port multiplexing [Permite mai multor gazde interne să partajeze o singură adresă IP publică prin multiplexarea porturilor]** -- **d) Accelerate packet forwarding through hardware offloading [Accelerează dirijarea pachetelor prin descărcare hardware]** +- **a)** Allow multiple private endpoints to share a public address using translated transport endpoints. [Permite mai multor endpointuri private să partajeze o adresă publică folosind endpointuri de transport traduse.] +- **b)** Encrypt the payload. [Criptează payloadul.] +- **c)** Replace all firewall and intrusion-detection rules. [Înlocuiește toate regulile firewall și de detecție a intruziunilor.] -> 💡 **Feedback:** PAT's primary purpose is enabling multiple internal hosts to share a single public IP address by multiplexing through unique port numbers. This directly addresses IPv4 address exhaustion. A common wrong Encrypting traffic is a function of protocols like TLS, not NAT. [Scopul principal al PAT este de a permite mai multor gazde interne să partajeze o singură adresă IP publică prin multiplexarea cu numere de port unice. Aceasta adresează direct epuizarea adreselor IPv4. Un răspuns greșit frecvent este „asigurarea securității rețelei" — deși NAT blochează conexiunile de intrare nesolicitate ca efect secundar, scopul său este conservarea adreselor, nu securitatea. Criptarea traficului este o funcție a protocoalelor precum TLS, nu a NAT.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** PAT conserves public IPv4 addresses by maintaining translation mappings. It does not provide comprehensive security or encryption; filtering is a separate policy. [PAT economisește adrese IPv4 publice prin menținerea mapărilor de traducere. Nu oferă securitate completă sau criptare; filtrarea reprezintă o politică separată.] + +
    --- @@ -498,14 +527,14 @@ ### Q37. `Multiple Choice` **SDN Controller vs Switch Roles / Rolurile controlerului SDN vs comutatorului** -> In an SDN deployment, 1000 packets matching an already-installed flow rule pass through switch S1. How many of these packets does the SDN controller process? [Într-un deployment SDN, 1000 de pachete care corespund unei reguli de flux deja instalate trec prin comutatorul S1. Câte dintre aceste pachete procesează controlerul SDN?] +> In an SDN deployment, 1000 packets matching an already-installed rule whose only action is output to a physical port (no controller output or sampling) pass through switch S1. How many of these packets does the SDN controller process? [Într-un deployment SDN, 1000 de pachete care corespund unei reguli deja instalate cu unica acțiune output către un port fizic (fără output la controler sau eșantionare) trec prin comutatorul S1. Câte dintre aceste pachete procesează controlerul SDN?] - **a) 500 — the controller samples half the traffic using a statistical round-robin method [500 — controlerul eșantionează jumătate din trafic utilizând o metodă statistică round-robin]** - **b) 0 — the switch forwards all matching packets independently [0 — comutatorul dirijează toate pachetele corespunzătoare independent]** - **c) 1 — the controller processes only the first packet [1 — controlerul procesează doar primul pachet]** - **d) 1000 — the controller processes every packet [1000 — controlerul procesează fiecare pachet]** -> 💡 **Feedback:** Once a flow rule is installed, the switch forwards matching packets at line rate without involving the controller. The controller is only contacted during table-miss events (when no rule matches). This is what makes SDN scalable — the data plane operates independently. A common misconception is that every packet passes through the controller, which would make SDN extremely slow. [Odată ce o regulă de flux este instalată, comutatorul dirijează pachetele corespunzătoare la viteză de linie fără a implica controlerul. Controlerul este contactat doar în timpul evenimentelor table-miss (când nicio regulă nu corespunde). Aceasta este ceea ce face SDN scalabil — planul de date funcționează independent. O concepție greșită frecventă este că fiecare pachet trece prin controler, ceea ce ar face SDN extrem de lent.] +> 💡 **Feedback:** Once a flow rule is installed, the switch forwards matching packets at line rate without involving the controller. Under this supplied rule no matching data packet is sent to the controller. Other rules can explicitly request controller output; table misses reach it only when configured to do so. This is what makes SDN scalable — the data plane operates independently. A common misconception is that every packet passes through the controller, which would make SDN extremely slow. [Odată ce o regulă de flux este instalată, comutatorul dirijează pachetele corespunzătoare la viteză de linie fără a implica controlerul. Conform regulii date, niciun pachet potrivit nu este trimis controlerului. Alte reguli pot solicita explicit output la controler; table-miss ajunge la el numai când este configurat astfel. Aceasta este ceea ce face SDN scalabil — planul de date funcționează independent. O concepție greșită frecventă este că fiecare pachet trece prin controler, ceea ce ar face SDN extrem de lent.] --- @@ -523,17 +552,21 @@ --- -### Q39. `Multiple Choice` -**NAT Impact on End-to-End Connectivity / Impactul NAT asupra conectivității capăt-la-capăt** +### Q39. — NAT traversal / Traversare NAT + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Two peers behind separate NAT/firewall devices cannot establish a direct connection. Which explanation is plausible without assuming a universal NAT rule? [Doi participanți aflați în spatele unor dispozitive NAT/firewall separate nu pot stabili o conexiune directă. Ce explicație este plauzibilă fără a presupune o regulă NAT universală?] + +- **a)** The required mapping or inbound permission is absent; traversal or a relay may be needed. [Lipsește maparea sau permisiunea de intrare necesară; poate fi necesară traversare NAT sau un releu.] +- **b)** Every NAT device encrypts the transport payload. [Orice dispozitiv NAT criptează payloadul de transport.] +- **c)** NAT always prevents all peer-to-peer communication. [NAT împiedică întotdeauna orice comunicare peer-to-peer.] -> A developer discovers that their peer-to-peer application fails to establish direct connections between two users, both behind separate NAT routers. What is the most likely explanation? [Un dezvoltator descoperă că aplicația sa peer-to-peer nu reușește să stabilească conexiuni directe între doi utilizatori, ambii în spatele unor rutere NAT separate. Care este explicația cea mai probabilă?] +
    💡 Feedback -- **a) Both NAT routers occupy all available ports, leaving none for P2P [Ambele rutere NAT ocupă toate porturile disponibile, nelăsând niciunul pentru P2P]** -- **b) Neither host can initiate inbound connections without existing conntrack entries [Niciuna dintre gazde nu poate iniția conexiuni de intrare fără intrări conntrack existente]** -- **c) NAT reduces bandwidth below the threshold needed for P2P connections [NAT reduce lățimea de bandă sub pragul necesar pentru conexiuni P2P]** -- **d) NAT encrypts the packets at the transport layer, preventing the P2P protocol from reading source addresses [NAT criptează pachetele la nivelul transport, împiedicând protocolul P2P să citească adresele sursă]** +**Correct answer / Răspuns corect: a.** Translation mappings and filtering policies both affect reachability. Static forwarding, coordinated traversal (such as ICE) or a relay can help depending on deployment. The failed attempt alone does not identify the exact cause. [Mapările de traducere și politicile de filtrare afectează conectivitatea. Redirecționarea statică, traversarea coordonată (precum ICE) sau un releu pot ajuta în funcție de implementare. Tentativa eșuată singură nu identifică exact cauza.] -> 💡 **Feedback:** NAT breaks end-to-end connectivity because without an existing conntrack entry, unsolicited inbound packets are dropped. Neither host can initiate a direct connection to the other because both are behind NAT. This is why techniques like STUN, TURN, and ICE were developed for NAT traversal in P2P and VoIP applications. The issue is not about ports being "occupied" or bandwidth — it is fundamentally about the absence of conntrack entries for inbound connections. [NAT întrerupe conectivitatea capăt-la-capăt deoarece fără o intrare conntrack existentă, pachetele de intrare nesolicitate sunt abandonate. Niciuna dintre gazde nu poate iniția o conexiune directă cu cealaltă deoarece ambele sunt în spatele NAT. De aceea au fost dezvoltate tehnici precum STUN, TURN și ICE pentru traversarea NAT în aplicații P2P și VoIP. Problema nu este despre porturi „ocupate" sau lățime de bandă — este fundamental despre absența intrărilor conntrack pentru conexiunile de intrare.] +
    --- @@ -568,12 +601,12 @@ ### Q42. `Multiple Choice` **SDN Policy Priority Design / Proiectarea priorităților politicii SDN** -> A network administrator wants to: (1) allow SSH to server 10.0.10.2, (2) block all other traffic to 10.0.10.2, and (3) allow all remaining traffic. Which priority assignment correctly implements this policy? [Un administrator de rețea dorește să: (1) permită SSH la serverul 10.0.10.2, (2) blocheze tot celălalt trafic la 10.0.10.2 și (3) permită tot traficul rămas. Care atribuire de priorități implementează corect această politică?] +> A network administrator wants to: (1) allow SSH to server 10.0.10.2, (2) block all other traffic to 10.0.10.2, and (3) allow all remaining IPv4 traffic. Assume ARP is handled separately and all rules are in one table. Which priority assignment correctly implements this policy? [Un administrator de rețea dorește să: (1) permită SSH la serverul 10.0.10.2, (2) blocheze tot celălalt trafic la 10.0.10.2 și (3) permită restul traficului IPv4. Presupuneți că ARP este tratat separat și toate regulile sunt în aceeași tabelă. Care atribuire de priorități implementează corect această politică?] - **a) All three rules at priority=100 with installation order determining matching [Toate cele trei reguli la prioritate=100 cu ordinea instalării determinând potrivirea]** -- **b) SSH allow: priority=100, Block to .12: priority=50, Default allow: priority=10 [Permisiune SSH: prioritate=100, Blocare la .12: prioritate=50, Permisiune implicită: prioritate=10]** -- **c) Block to .12: priority=100, SSH allow: priority=50, Default allow: priority=10 [Blocare la .12: prioritate=100, Permisiune SSH: prioritate=50, Permisiune implicită: prioritate=10]** -- **d) Default allow: priority=100, SSH allow: priority=50, Block to .12: priority=10 [Permisiune implicită: prioritate=100, Permisiune SSH: prioritate=50, Blocare la .12: prioritate=10]** +- **b) SSH allow: priority=100, Block to .2: priority=50, Default allow: priority=10 [Permisiune SSH: prioritate=100, Blocare la .2: prioritate=50, Permisiune implicită: prioritate=10]** +- **c) Block to .2: priority=100, SSH allow: priority=50, Default allow: priority=10 [Blocare la .2: prioritate=100, Permisiune SSH: prioritate=50, Permisiune implicită: prioritate=10]** +- **d) Default allow: priority=100, SSH allow: priority=50, Block to .2: priority=10 [Permisiune implicită: prioritate=100, Permisiune SSH: prioritate=50, Blocare la .2: prioritate=10]** > 💡 **Feedback:** The correct pattern is: specific permit at highest priority (100) > general deny at medium priority (50) > default allow at lowest priority (10). The SSH allow rule must have higher priority than the block rule so it is matched first for SSH packets. If the block rule had the highest priority, even SSH packets would be dropped. [Modelul corect este: permisiune specifică la cea mai mare prioritate (100) > interdicție generală la prioritate medie (50) > permisiune implicită la cea mai mică prioritate (10). Regula de permisiune SSH trebuie să aibă o prioritate mai mare decât regula de blocare pentru a fi potrivită prima pentru pachetele SSH. Dacă regula de blocare ar avea cea mai mare prioritate, chiar și pachetele SSH ar fi abandonate.] @@ -603,11 +636,10 @@ - **c) SDN eliminates the need for routing protocols entirely [SDN elimină complet necesitatea protocoalelor de rutare]** - **d) Centralised global network view enables consistent policies and optimal path computation [Viziunea globală centralizată a rețelei permite politici consistente și calculul optim al căilor]** -> 💡 **Feedback:** SDN's centralised controller maintains a global view of the entire network, enabling consistent policy enforcement and optimal path computation. Traditional networking only provides each device with a local view (neighbour information from routing protocols). This global visibility is SDN's primary operational advantage. SDN does not inherently provide faster hardware switching — the data plane hardware is often the same. [Controlerul centralizat SDN menține o viziune globală a întregii rețele, permițând aplicarea consistentă a politicilor și calculul optim al căilor. Rețeaua tradițională oferă fiecărui dispozitiv doar o viziune locală (informații despre vecini de la protocoale de rutare). Această vizibilitate globală este principalul avantaj operațional al SDN. SDN nu oferă în mod inerent comutare hardware mai rapidă — hardware-ul planului de date este adesea același.] +> 💡 **Feedback:** SDN's centralised controller maintains a global view of the entire network, enabling consistent policy enforcement and optimal path computation. Distributed link-state protocols such as OSPF also build a topology database for the area, beyond immediate neighbours. SDN supports logically centralised programmability and policy coordination; its visibility depends on collected information. This global visibility is SDN's primary operational advantage. SDN does not inherently provide faster hardware switching — the data plane hardware is often the same. [Controlerul centralizat SDN menține o viziune globală a întregii rețele, permițând aplicarea consistentă a politicilor și calculul optim al căilor. Protocoalele distribuite link-state precum OSPF construiesc și o bază de date topologică a ariei, nu doar informații despre vecinii direcți. SDN permite programabilitate logic centralizată și coordonarea politicilor; vizibilitatea sa depinde de informațiile colectate. Această vizibilitate globală este principalul avantaj operațional al SDN. SDN nu oferă în mod inerent comutare hardware mai rapidă — hardware-ul planului de date este adesea același.] --- - ## §2. Laborator / Lab (16 questions) ### Q45. `Multiple Choice` @@ -725,7 +757,7 @@ ### Q53. `Multiple Choice` **Table-Miss Packet Handling / Gestionarea pachetelor table-miss** -> A flow table contains rules for h1-h2 ICMP traffic and a drop rule for h3, plus a table-miss rule at priority 0 with action CONTROLLER. A packet from an unknown host 10.0.10.99 arrives at the switch. What happens? [O tabelă de fluxuri conține reguli pentru traficul ICMP h1-h2 și o regulă de eliminare pentru h3, plus o regulă table-miss cu prioritatea 0 și acțiunea CONTROLLER. Un pachet de la o gazdă necunoscută 10.0.10.99 sosește la comutator. Ce se întâmplă?] +> A flow table contains rules for h1-h2 ICMP traffic and a drop rule for h3, plus a table-miss rule at priority 0 with action CONTROLLER. A packet from 10.0.10.99 arrives and matches none of the specific permit or drop rules. What happens? [O tabelă de fluxuri conține reguli pentru traficul ICMP h1-h2 și o regulă de eliminare pentru h3, plus o regulă table-miss cu prioritatea 0 și acțiunea CONTROLLER. Un pachet de la 10.0.10.99 sosește și nu corespunde niciuneia dintre regulile specifice de permitere sau eliminare. Ce se întâmplă?] - **a) The packet is silently dropped [Pachetul este eliminat în tăcere]** - **b) The switch generates an error message [Comutatorul generează un mesaj de eroare]** @@ -788,7 +820,7 @@ - **c) Priority 30 — same level allows both rules to coexist [Prioritatea 30 — același nivel permite ambelor reguli să coexiste]** - **d) Priority 0 — table-miss priority [Prioritatea 0 — prioritatea table-miss]** -> 💡 **Feedback:** The permit rule must have a higher priority number than the block rule (30) to override it. Any value above 30 works. A common misconception is that priority 0 could override other rules; priority 0 is the lowest possible priority, reserved for the table-miss default action. [Regula de permitere trebuie să aibă un număr de prioritate mai mare decât regula de blocare (30) pentru a o suprascrie. Orice valoare peste 30 funcționează. O concepție greșită frecventă este că prioritatea 0 ar putea suprascrie alte reguli; prioritatea 0 este cea mai mică prioritate posibilă, rezervată acțiunii implicite table-miss.] +> 💡 **Feedback:** The permit rule must have a higher priority number than the block rule (30) to override it. Any valid priority from 31 through 65535 works for this comparison, assuming no higher conflicting entry in the same table. A common misconception is that priority 0 could override other rules; priority 0 is the lowest possible priority, used by a table-miss entry when its match is all-wildcard. [Regula de permitere trebuie să aibă un număr de prioritate mai mare decât regula de blocare (30) pentru a o suprascrie. Orice prioritate validă între 31 și 65535 funcționează pentru această comparație, presupunând că nu există altă regulă conflictuală mai prioritară în aceeași tabelă. O concepție greșită frecventă este că prioritatea 0 ar putea suprascrie alte reguli; prioritatea 0 este cea mai mică prioritate posibilă, folosită de o intrare table-miss când potrivirea este complet wildcard.] --- @@ -820,20 +852,23 @@ --- -### Q60. `Multiple Choice` -**SDN Host Access Levels in Lab Topology / Nivelurile de acces ale gazdelor SDN în topologia laboratorului** +### Q60. — Basic S06 controller policy / Politica controlerului S06 de bază -> In the Week 6 SDN topology (10.0.10.0/24), three hosts are connected to switch s1. According to the lab's default policy, which host has restricted access — meaning most inbound traffic to it is dropped? [În topologia SDN din săptămâna 6 (10.0.10.0/24), trei gazde sunt conectate la comutatorul s1. Conform politicii implicite a laboratorului, care gazdă are acces restricționat — adică majoritatea traficului de intrare către ea este eliminat?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) All three hosts have identical access levels [Toate cele trei gazde au niveluri de acces identice]** -- **b) h1 (10.0.10.1)** -- **c) h3 (10.0.10.3)** -- **d) h2 (10.0.10.2)** +In `S06_Part02C_Script_SDNOS_Ken_Controller.py`, which IPv4 destination causes the controller to install a drop flow at priority 20? [În `S06_Part02C_Script_SDNOS_Ken_Controller.py`, ce destinație IPv4 determină instalarea unei reguli drop cu prioritatea 20?] -> 💡 **Feedback:** In the SDN topology, h3 (10.0.10.3) has restricted access. The default policy drops IP traffic destined for h3 at priority 50, while h1 (10.0.10.1) has full access and h2 (10.0.10.2) acts as the server. A common misconception is that all three hosts have identical access; the SDN policy explicitly differentiates access levels using priority-based flow rules. [În topologia SDN, h3 (10.0.10.3) are acces restricționat. Politica implicită elimină traficul IP destinat lui h3 la prioritatea 50, în timp ce h1 (10.0.10.1) are acces complet, iar h2 (10.0.10.2) acționează ca server. O concepție greșită frecventă este că toate cele trei gazde au acces identic; politica SDN diferențiază explicit nivelurile de acces folosind reguli de flux bazate pe priorități.] +- **a)** h3 — 10.0.10.3 +- **b)** h1 — 10.0.10.1 +- **c)** h2 — 10.0.10.2 ---- +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The basic controller permits h1↔h2 and drops IPv4 traffic destined for h3. This is the basic controller contract; the AdvancedPolicy variant has its own explicit priorities and optional UDP exception. [Controlerul de bază permite h1↔h2 și elimină traficul IPv4 destinat lui h3. Acesta este contractul controlerului de bază; varianta AdvancedPolicy are prioritățile proprii și o excepție UDP opțională.] +
    + +--- ## §3. Numerical (Răspuns numeric) (2 questions) @@ -920,19 +955,24 @@ Drag the components to form the command that displays active NAT translation ent --- -### Q66. `Drag and Drop` -**OpenFlow Flow Addition / Adăugare flux OpenFlow / Adăugare flux OpenFlow** +### Q66. — OpenFlow flow addition / Adăugarea unui flux OpenFlow -``` -Arrange the fragments to install a flow rule on switch s1 that drops all ICMP traffic from host 10.0.10.1 using OpenFlow 1.3. [Aranjați fragmentele pentru a instala o regulă de flux pe comutatorul s1 care blochează tot traficul ICMP de la gazda 10.0.10.1 folosind OpenFlow 1.3.] [[1]] [[2]] [[3]] [[4]] "priority=100,icmp,nw_src=10.0.10.1,actions=[[5]]" +*Drag and Drop / Trageți și plasați* + +Complete this OpenFlow 1.3 drop rule for switch s1, from a root shell. [Completați regula drop OpenFlow 1.3 pentru comutatorul s1, dintr-un shell root.] + +```bash +[[1]] [[2]] [[3]] [[4]] [[5]] "priority=100,icmp,nw_src=10.0.10.1,actions=[[6]]" ``` -**Available items / Elemente disponibile:** +Choices / Variante: `ovs-ofctl`, `-O`, `OpenFlow13`, `add-flow`, `s1`, `drop`, `CONTROLLER`, `del-flows`. - `[ ovs-ofctl ] [ -O ] [ OpenFlow13 ] [ add-flow ] [ drop ] [ s1 ] [ CONTROLLER ] [ del-flows ] [ output:1 ]` +
    💡 Feedback +`ovs-ofctl -O OpenFlow13 add-flow s1 "priority=100,icmp,nw_src=10.0.10.1,actions=drop"`. +There are five tokens before the quoted flow and one action token inside it. [Sunt cinci tokenuri înaintea fluxului între ghilimele și un token de acțiune în interior.] -> 💡 **Feedback:** The correct command is: ovs-ofctl -O OpenFlow13 add-flow s1 "priority=100,icmp,nw_src=10.0.10.1,actions=drop". The -O flag specifies the OpenFlow version, and actions=drop silently discards matching packets. [Comanda corectă este: ovs-ofctl -O OpenFlow13 add-flow s1 "priority=100,icmp,nw_src=10.0.10.1,actions=drop". Flagul -O specifică versiunea OpenFlow, iar actions=drop elimină silențios pachetele care corespund.] +
    --- @@ -999,7 +1039,7 @@ In SDN, the [[1]] makes forwarding decisions, while the [[2]] performs actual pa - Gap [[1]]: [ control plane [planul de control] ] [ data plane [planul de date] ] - Gap [[2]]: [ data plane [planul de date] ] [ control plane [planul de control] ] -> 💡 **Feedback:** The control plane (centralised controller) computes paths and installs rules. The data plane (distributed switches) forwards packets based on installed flow rules. A common misconception is that the controller forwards packets directly — it only installs rules. [Planul de control (controlerul centralizat) calculează căile și instalează regulile. Planul de date (comutatoarele distribuite) dirijează pachetele pe baza regulilor de flux instalate. O concepție greșită frecventă este că controlerul dirijează pachetele direct — acesta doar instalează reguli.] +> 💡 **Feedback:** The control plane (centralised controller) computes paths and installs rules. The data plane (distributed switches) forwards packets based on installed flow rules. A common misconception is that the controller forwards packets directly — ordinary matching traffic is forwarded by switches; the controller may also handle selected packets through Packet-In/Packet-Out. [Planul de control (controlerul centralizat) calculează căile și instalează regulile. Planul de date (comutatoarele distribuite) dirijează pachetele pe baza regulilor de flux instalate. O concepție greșită frecventă este că controlerul dirijează pachetele direct — traficul obișnuit potrivit este redirecționat de comutatoare; controlerul poate trata și pachete selectate prin Packet-In/Packet-Out.] --- @@ -1071,21 +1111,21 @@ The MASQUERADE target operates in the [[1]] chain of the [[2]] table. It dynamic --- -### Q75. `Gap Select` -**Traditional vs SDN Architecture / Arhitectura tradițională vs SDN / Arhitectura tradițională vs SDN** +### Q75. — OSPF and SDN network knowledge / Cunoașterea rețelei în OSPF și SDN -``` -In traditional networking, each device maintains a [[1]] view of the network and uses [[2]] protocols like OSPF for routing. In SDN, the controller has a [[3]] view and pushes rules to switches via the [[4]] interface. [În rețelistica tradițională, fiecare dispozitiv menține o viziune ___ asupra rețelei și folosește protocoale de ___ precum OSPF pentru rutare. În SDN, controlerul are o viziune ___ și transmite reguli comutatoarelor prin interfața ___.] -``` +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -**Options per gap / Opțiuni pentru fiecare spațiu:** +Which statement correctly compares OSPF and a logically centralised SDN controller? [Ce afirmație compară corect OSPF și un controler SDN logic centralizat?] + +- **a)** OSPF routers exchange link state and compute routes from an area topology database; SDN can coordinate policy through a controller that programmes switches. [Ruterele OSPF schimbă starea legăturilor și calculează rute din baza topologică a ariei; SDN poate coordona politica printr-un controler care programează comutatoarele.] +- **b)** OSPF routers know only their immediate neighbours and no topology. [Ruterele OSPF cunosc doar vecinii direcți și nicio topologie.] +- **c)** An SDN controller automatically knows every external network and fault without telemetry. [Un controler SDN cunoaște automat orice rețea externă și defect fără telemetrie.] + +
    💡 Feedback -- Gap [[1]]: [ local ] [ global ] [ partial ] [ cached ] -- Gap [[2]]: [ distributed ] [ centralised ] [ static ] [ manual ] -- Gap [[3]]: [ global ] [ local ] [ partial ] [ distributed ] -- Gap [[4]]: [ southbound ] [ northbound ] [ eastbound ] [ management ] +**Correct answer / Răspuns corect: a.** Distributed control does not imply neighbour-only knowledge. The scope and freshness of both architectures depend on protocol exchanges and monitoring. [Controlul distribuit nu implică informații doar despre vecini. Domeniul și actualitatea informațiilor ambelor arhitecturi depind de schimburile de protocol și de monitorizare.] -> 💡 **Feedback:** Traditional networking: each device has local knowledge and uses distributed routing protocols. SDN: centralised controller has a global network view and programmes switches via the southbound interface (OpenFlow). [Rețelistica tradițională: fiecare dispozitiv are cunoștințe locale și folosește protocoale de rutare distribuite. SDN: controlerul centralizat are o viziune globală asupra rețelei și programează comutatoarele prin interfața southbound (OpenFlow).] +
    --- diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W07_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W07_Questions.md index 28b3b98..4e45830 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W07_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W07_Questions.md @@ -8,16 +8,21 @@ ## W07 — Curs / Lecture (15 questions) -### 1. `Multiple Choice` -**N01.T00.Q13: Choosing Capture Strategy for TCP vs UDP / Alegerea strategiei de captură pentru TCP vs UDP** +### Q1. `N01.T00.Q13` — One loopback capture / O captură loopback -> A student needs to demonstrate both the TCP three-way handshake on port 12345 and a UDP datagram exchange on port 12345 inside week1_lab. The resulting PCAP must clearly distinguish both flows for grading. Which capture approach produces the cleanest evidence? [Un student trebuie să demonstreze atât handshake-ul TCP cu trei căi pe portul 12345, cât și un schimb de datagrame UDP pe portul 12345 în week1_lab. Fișierul PCAP rezultat trebuie să distingă clar ambele fluxuri pentru notare. Ce abordare de captură produce cele mai curate dovezi?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) Run tcpdump -i lo -w capture.pcap port 12345 or port 12345, then use Wireshark display filters to separate the TCP and UDP flows in the single capture file [Rulați tcpdump -i lo -w capture.pcap port 12345 or port 12345, apoi folosiți filtre de afișare Wireshark pentru a separa fluxurile TCP și UDP]** -- **b) Run two separate tcpdump instances simultaneously, one filtering tcp port 12345 and the other filtering udp port 12345, writing to different PCAP files [Rulați două instanțe tcpdump separat simultan, una filtrând tcp port 12345 și cealaltă filtrând udp port 12345, scriind în fișiere PCAP diferite]** -- **c) Capture on eth0 with no filter to ensure all traffic is captured, then apply display filters in Wireshark to isolate the relevant ports [Capturați pe eth0 fără filtru pentru a vă asigura că tot traficul este capturat, apoi aplicați filtre de afișare în Wireshark]** +Both test endpoints run on 127.0.0.1 in the same VM. TCP and UDP each use port 12345. Which command creates one PCAP containing both? [Ambele endpointuri de test rulează pe 127.0.0.1 în aceeași VM. TCP și UDP folosesc fiecare portul 12345. Ce comandă creează un singur PCAP care le conține pe ambele?] -> 💡 **Feedback:** A single capture on loopback with a compound BPF filter (port 12345 or port 12345) captures both flows interleaved. The display filters tcp.port==12345 and udp.port==12345 cleanly separate them in Wireshark. Separate captures create file management overhead and risk missing interleaved traffic. Capturing on eth0 misses loopback-only traffic. [O singură captură pe loopback cu un filtru BPF compus surprinde ambele fluxuri intercalate. Filtrele de afișare le separă curat în Wireshark.] +- **a)** `sudo tcpdump -i lo -w capture.pcap 'port 12345'` +- **b)** `sudo tcpdump -i eth0 -w capture.pcap 'port 12345'` +- **c)** `sudo tcpdump -i lo -w capture.pcap 'tcp port 12345'` + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The loopback interface carries this traffic. The capture filter port 12345 includes both transport protocols; display filters tcp.port == 12345 and udp.port == 12345 separate them afterwards. Start capture before the exchanges and stop it cleanly. [Interfața loopback transportă acest trafic. Filtrul de captură port 12345 include ambele protocoale; filtrele de afișare tcp.port == 12345 și udp.port == 12345 le separă ulterior. Porniți captura înaintea schimburilor și opriți-o curat.] + +
    --- @@ -31,47 +36,61 @@ - **c) SYN → ACK → SYN-ACK** - **d) SYN-ACK → SYN → ACK** -> 💡 **Feedback:** The client initiates with SYN, the server responds with SYN-ACK, and the client completes with ACK. This three-step process synchronises sequence numbers on both endpoints before any data is exchanged. A common misconception is that the handshake occurs for every message sent; in reality, it happens only once when connect() is called, and all subsequent data flows over the established connection. [Clientul inițiază cu SYN, serverul răspunde cu SYN-ACK, iar clientul finalizează cu ACK. Acest proces în trei pași sincronizează numerele de secvență la ambele capete înainte de orice schimb de date. O concepție greșită frecventă este că handshake-ul are loc pentru fiecare mesaj trimis; în realitate, acesta se produce o singură dată la apelul connect(), iar toate datele ulterioare circulă pe conexiunea deja stabilită.] +> 💡 **Feedback:** The client initiates with SYN, the server responds with SYN-ACK, and the client completes with ACK. This three-step process synchronises sequence numbers on both endpoints for the ordinary connection establishment used in this lab; data can accompany the final ACK, and TCP Fast Open is a separate extension. A common misconception is that the handshake occurs for every message sent; in reality, it happens only once when connect() is called, and all subsequent data flows over the established connection. [Clientul inițiază cu SYN, serverul răspunde cu SYN-ACK, iar clientul finalizează cu ACK. Acest proces în trei pași sincronizează numerele de secvență la ambele capete pentru stabilirea obișnuită folosită în laborator; datele pot însoți ACK-ul final, iar TCP Fast Open este o extensie separată. O concepție greșită frecventă este că handshake-ul are loc pentru fiecare mesaj trimis; în realitate, acesta se produce o singură dată la apelul connect(), iar toate datele ulterioare circulă pe conexiunea deja stabilită.] --- -### 3. `True / False` -**N07.C01.Q02: TCP Connection-Oriented Nature / Natura orientată pe conexiune a TCP** +### Q3. `N07.C01.Q02` — TCP establishment scope / Domeniul stabilirii TCP -> TCP requires a three-way handshake (SYN, SYN-ACK, ACK) to be completed before any application data can be transmitted. [TCP necesită finalizarea unui handshake în trei pași (SYN, SYN-ACK, ACK) înainte ca orice date ale aplicației să fie transmise.] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) true** -- **b) false** +Is “TCP can never transmit application data during connection establishment” universally correct? [Este universal corectă afirmația „TCP nu poate transmite niciodată date de aplicație în timpul stabilirii conexiunii”?] -> 💡 **Feedback:** TCP is connection-oriented — unlike UDP, it cannot send application data until the three-way handshake synchronises initial sequence numbers on both sides. [TCP este orientat pe conexiune — spre deosebire de UDP, nu poate trimite date ale aplicației până când handshake-ul în trei pași nu sincronizează numerele de secvență inițiale pe ambele părți.] +- **a)** No. The final ACK can carry data and TCP Fast Open permits data in the SYN under its defined conditions. [Nu. ACK-ul final poate conține date, iar TCP Fast Open permite date în SYN în condițiile definite.] +- **b)** Yes. Every TCP packet in a handshake must have zero payload. [Da. Orice pachet TCP din handshake trebuie să aibă payload zero.] +- **c)** No, because UDP performs the TCP handshake. [Nu, deoarece UDP realizează handshake-ul TCP.] + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The ordinary SYN/SYN-ACK/ACK teaching model establishes sequence-number state. Do not turn the simplified sequence into a prohibition on all data-bearing establishment segments. [Modelul didactic SYN/SYN-ACK/ACK stabilește starea numerelor de secvență. Secvența simplificată nu trebuie transformată într-o interdicție universală a segmentelor cu date în timpul stabilirii.] + +
    --- -### 4. `Multiple Choice` -**N07.C03.Q03: connect_ex vs connect Distinction / Distincția între connect_ex și connect** +### Q4. `N07.C03.Q03` — connect_ex result / Rezultatul connect_ex + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +For an AF_INET/SOCK_STREAM socket, what does connect_ex return on a successful connection? [Pentru un socket AF_INET/SOCK_STREAM, ce returnează connect_ex la conectare reușită?] -> In the port probe code, connect_ex() is used instead of connect(). What practical advantage does connect_ex() provide for port probing? [În codul de sondare a porturilor, se folosește connect_ex() în loc de connect(). Ce avantaj practic oferă connect_ex() pentru sondarea porturilor?] +- **a)** 0 +- **b)** The remote process PID [PID-ul procesului distant] +- **c)** The number of application bytes read [Numărul octeților de aplicație citiți] -- **a) It returns an error code (0 for success, non-zero for failure) instead of raising an exception, simplifying state classification [Returnează un cod de eroare (0 pentru succes, non-zero pentru eșec) în loc să ridice o excepție, simplificând clasificarea stării]** -- **b) It automatically handles both TCP and UDP probing in a single function call [Gestionează automat sondarea atât TCP cât și UDP într-un singur apel de funcție]** -- **c) It supports asynchronous connections, allowing multiple ports to be probed simultaneously [Suportă conexiuni asincrone, permițând sondarea simultană a mai multor porturi]** -- **d) It bypasses firewall rules by using raw sockets at the kernel level, giving more accurate probe results and revealing the true state of every port regardless of iptables configuration [Ocolește regulile de firewall folosind socketuri raw la nivelul nucleului, oferind rezultate de sondare mai precise și dezvăluind starea reală a fiecărui port indiferent de configurația iptables]** +
    💡 Feedback -> 💡 **Feedback:** connect_ex() returns an integer error code rather than raising an exception. A return of 0 means the port is open; a non-zero value (e.g. 111 = ECONNREFUSED) means closed. socket.timeout exceptions still indicate filtered ports. This avoids wrapping every probe in try/except for the normal closed-port case. [connect_ex() returnează un cod de eroare întreg în loc să ridice o excepție. Un retur de 0 înseamnă că portul este deschis; o valoare non-zero (de ex. 111 = ECONNREFUSED) înseamnă închis. Excepțiile socket.timeout indică în continuare porturile filtrate. Aceasta evită încadrarea fiecărei sondări într-un try/except pentru cazul normal de port închis.] +**Correct answer / Răspuns corect: a.** It returns zero for success and errno-style codes for connection errors. Some errors, such as name resolution problems, can still raise exceptions. Non-zero does not uniquely mean “closed”: record refusal, timeout and unreachable outcomes separately. [Returnează zero la succes și coduri de tip errno pentru erori de conectare. Unele erori, precum rezoluția numelui, pot produce excepții. Non-zero nu înseamnă unic „închis”: înregistrați separat refuzul, timeout-ul și inaccesibilitatea.] + +
    --- -### 5. `Multiple Choice` -**N07.C03.Q04: Port Probe Timeout Interpretation / Interpretarea timeout-ului sondării de porturi** +### Q5. `N07.C03.Q04` — Timeout evidence / Dovezi pentru timeout + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +A TCP connection attempt expires without completing. What is the justified observation? [O tentativă de conectare TCP expiră fără finalizare. Care este observația justificată?] -> The port probe script sets sock.settimeout(2.0) and attempts connect_ex(). A socket.timeout exception is raised. How does the script classify this port? [Scriptul de sondare a porturilor setează sock.settimeout(2.0) și încearcă connect_ex(). O excepție socket.timeout este ridicată. Cum clasifică scriptul acest port?] +- **a)** No connection completed before the deadline; filtering, loss, an unreachable host or other causes remain possible. [Nicio conexiune nu s-a finalizat până la termen; filtrarea, pierderea, o gazdă inaccesibilă sau alte cauze rămân posibile.] +- **b)** A firewall DROP rule has been proved. [A fost demonstrată o regulă firewall DROP.] +- **c)** The port is certainly closed and sent RST. [Portul este sigur închis și a trimis RST.] -- **a) Filtered — the timeout indicates no response was received, likely due to a firewall DROP rule [Filtrat — timeout-ul indică că nu s-a primit niciun răspuns, probabil din cauza unei reguli DROP de la firewall]** -- **b) Open — the timeout means the server is busy processing the connection and needs more time [Deschis — timeout-ul înseamnă că serverul este ocupat procesând conexiunea și are nevoie de mai mult timp]** -- **c) Closed — the timeout is functionally equivalent to receiving a TCP RST packet [Închis — timeout-ul este echivalent funcțional cu primirea unui pachet TCP RST]** -- **d) Error — the timeout indicates an unreachable network rather than a filtering decision [Eroare — timeout-ul indică o rețea inaccesibilă și nu o decizie de filtrare]** +
    💡 Feedback -> 💡 **Feedback:** When connect_ex() times out, it means no response was received — neither SYN-ACK (open) nor RST (closed). This is consistent with a firewall DROP rule silently discarding the probe. The code uses the try/except block to classify timeouts as "filtered". [Când connect_ex() expiră, înseamnă că nu s-a primit niciun răspuns — nici SYN-ACK (deschis), nici RST (închis). Aceasta este consistentă cu o regulă DROP care elimină în tăcere sondarea. Codul folosește blocul try/except pentru a clasifica timeout-urile ca 'filtrat'.] +**Correct answer / Răspuns corect: a.** connect_ex may return a timeout-related errno rather than raise socket.timeout. Inspect returned codes and handle exceptions. A timeout describes the observation, not a unique remote port state. [connect_ex poate întoarce un errno asociat timeout-ului în loc să ridice socket.timeout. Inspectați codurile returnate și tratați excepțiile. Timeout-ul descrie observația, nu o stare unică a portului distant.] + +
    --- @@ -101,45 +120,57 @@ --- -### 8. `Multiple Choice` -**N07.C05.Q01: External Service Filtering Choice / Alegerea filtrării pentru servicii externe** +### Q8. `N07.C05.Q01` — DROP behaviour / Comportamentul DROP + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> An attacker is scanning your public-facing network to discover which services are running. Which filtering action makes it hardest for the attacker to identify active hosts and open ports? [Un atacator scanează rețeaua dvs. publică pentru a descoperi ce servicii rulează. Care acțiune de filtrare face cel mai dificil pentru atacator să identifice gazdele active și porturile deschise?] +For packets matching a firewall rule, which action silently discards them without generating a rejection response from that rule? [Pentru pachetele potrivite unei reguli firewall, ce acțiune le elimină fără a genera prin acea regulă un răspuns de respingere?] -- **a) DROP — all probed ports appear "filtered" with timeouts, so the attacker cannot distinguish active services from non-existent hosts [DROP — toate porturile sondate apar 'filtrate' cu timeout-uri, astfel încât atacatorul nu poate distinge serviciile active de gazdele inexistente]** -- **b) REJECT — the attacker receives explicit refusal messages for each probed port, but these do not reveal which specific services are running behind the firewall [REJECT — atacatorul primește mesaje explicite de refuz pentru fiecare port sondat, dar acestea nu dezvăluie ce servicii specifice rulează în spatele paravanului de protecție]** -- **c) ACCEPT with rate limiting — allowing connections but throttling them prevents effective reconnaissance [ACCEPT cu limitare de rată — permiterea conexiunilor dar limitarea lor previne recunoașterea eficientă]** -- **d) LOG without any action — recording the probes deters the attacker without blocking anything [LOG fără nicio acțiune — înregistrarea sondărilor descurajează atacatorul fără a bloca nimic]** +- **a)** DROP +- **b)** REJECT +- **c)** ACCEPT -> 💡 **Feedback:** DROP makes all ports appear identically "filtered" — the attacker sees timeouts everywhere and cannot distinguish between a host with DROP on port 80 versus a non-existent host. REJECT reveals that a firewall (and therefore a host) exists by sending back RST or ICMP. [DROP face toate porturile să apară identic ca 'filtrate' — atacatorul vede timeout-uri peste tot și nu poate distinge între o gazdă cu DROP pe portul 80 și o gazdă inexistentă. REJECT dezvăluie că un paravan de protecție (și prin urmare o gazdă) există prin trimiterea înapoi a RST sau ICMP.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** DROP is silent for those matched packets. It does not make a host invisible to all other probes or guarantee that every scan times out. Other services, paths and network errors can expose information. [DROP este silențios pentru pachetele potrivite. Nu face gazda invizibilă la toate celelalte probe și nu garantează că orice scanare expiră. Alte servicii, căi și erori de rețea pot furniza informații.] + +
    --- -### 9. `Multiple Choice` -**N07.T00.Q04: Closed vs Filtered Port / Port închis vs port filtrat** +### Q9. `N07.T00.Q04` — Refusal and silence / Refuz și absența răspunsului + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +In a controlled reachable TCP test, no listener and no filtering produces RST; replacing this with a confirmed silent DROP rule produces no reply. What distinction is demonstrated? [Într-un test TCP controlat și accesibil, lipsa listenerului și a filtrării produce RST; o regulă DROP silențioasă confirmată produce absența răspunsului. Ce distincție este demonstrată?] -> What distinguishes a closed TCP port from a filtered TCP port when probed with a SYN packet? [Ce distinge un port TCP închis de un port TCP filtrat când este sondat cu un pachet SYN?] +- **a)** Active refusal versus silence in this configured experiment. [Refuz activ față de absența răspunsului în experimentul configurat.] +- **b)** Any RST proves the remote application is absent. [Orice RST dovedește absența aplicației distante.] +- **c)** Any timeout proves a firewall rule. [Orice timeout dovedește o regulă firewall.] -- **a) A closed port sends RST immediately; a filtered port produces no response (timeout) [Un port închis trimite RST imediat; un port filtrat nu produce niciun răspuns (timeout)]** -- **b) A closed port sends ICMP unreachable after consulting the routing table; a filtered port sends TCP RST back to the sender [Un port închis trimite ICMP unreachable după consultarea tabelei de rutare; un port filtrat trimite TCP RST înapoi expeditorului]** -- **c) Both send RST, but a filtered port includes an ICMP warning [Ambele trimit RST, dar un port filtrat include o avertizare ICMP]** -- **d) A closed port produces a timeout; a filtered port sends FIN-ACK [Un port închis produce un timeout; un port filtrat trimite FIN-ACK]** +
    💡 Feedback -> 💡 **Feedback:** Closed = host reachable, no service listening → kernel sends RST. Filtered = firewall DROP → no response, client times out. This distinction is critical for network diagnosis: RST confirms host reachability. [Închis = gazdă accesibilă, niciun serviciu activ → nucleul trimite RST. Filtrat = DROP de la paravan → niciun răspuns, clientul dă timeout. Această distincție este critică pentru diagnosticul rețelei: RST confirmă accesibilitatea gazdei.] +**Correct answer / Răspuns corect: a.** A firewall can also reject with TCP RST. Packet loss and routing failures can also prevent completion. General diagnosis needs the error code, captures and configuration evidence. [Un firewall poate respinge și prin TCP RST. Pierderile și problemele de rutare pot împiedica finalizarea. Diagnosticul general necesită codul erorii, capturi și dovezi de configurație.] + +
    --- -### 10. `Multiple Choice` -**N07.T00.Q05: connect_ex() Port Probe Advantage / Avantajul connect_ex() pentru sondarea porturilor** +### Q10. `N07.T00.Q05` — Socket type and connect_ex / Tipul socketului și connect_ex + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Does connect_ex on a SOCK_DGRAM socket perform a UDP handshake that proves a server is listening? [connect_ex pe un socket SOCK_DGRAM realizează un handshake UDP care dovedește existența unui server?] -> Why is socket.connect_ex() preferred over socket.connect() for port scanning scripts? [De ce este socket.connect_ex() preferat față de socket.connect() pentru scripturile de scanare a porturilor?] +- **a)** No. UDP connect sets a default peer locally; UDP has no transport handshake. [Nu. Connect UDP stabilește local un corespondent implicit; UDP nu are handshake de transport.] +- **b)** Yes, the same three-way handshake as TCP. [Da, același handshake în trei pași ca TCP.] +- **c)** The API cannot be called on any UDP socket. [API-ul nu poate fi apelat pe niciun socket UDP.] -- **a) It returns an error code instead of raising an exception, simplifying control flow [Returnează un cod de eroare în loc să ridice o excepție, simplificând fluxul de control]** -- **b) It bypasses firewall rules at the kernel level to detect services hidden behind DROP policies [Ocolește regulile de paravan la nivelul nucleului pentru a detecta servicii ascunse în spatele politicilor DROP]** -- **c) It automatically retries on timeout, improving detection accuracy [Reîncearcă automat la timeout, îmbunătățind acuratețea detecției]** -- **d) It supports both TCP and UDP probing in a single call [Suportă sondarea atât TCP cât și UDP într-un singur apel]** +
    💡 Feedback -> 💡 **Feedback:** connect_ex() returns 0 on success or an errno value on failure. This allows clean if/else logic instead of try/except blocks. It does NOT bypass firewalls, retry automatically, or support UDP. [connect_ex() returnează 0 la succes sau o valoare errno la eșec. Aceasta permite logică if/else curată în loc de blocuri try/except. NU ocolește paravanele, nu reîncearcă automat și nu suportă UDP.] +**Correct answer / Răspuns corect: a.** The socket type determines transport semantics. Successful UDP connect is not a service reachability test. The S07 connect scanner uses SOCK_STREAM to attempt TCP connections. [Tipul socketului determină semantica transportului. Succesul connect UDP nu testează disponibilitatea serviciului. Scannerul S07 folosește SOCK_STREAM pentru a încerca conexiuni TCP.] + +
    --- @@ -157,17 +188,21 @@ --- -### 12. `Multiple Choice` -**N07.C02.Q04: DROP vs REJECT for Debugging / DROP vs REJECT pentru depanare** +### Q12. `N07.C02.Q04` — Explicit TCP rejection / Respingere TCP explicită + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> During development on an internal network, a colleague cannot connect to your test server. You suspect a firewall rule is blocking the traffic. Which filtering action would have made the problem easier to diagnose? [În timpul dezvoltării pe o rețea internă, un coleg nu se poate conecta la serverul dvs. de test. Suspectați că o regulă de firewall blochează traficul. Care acțiune de filtrare ar fi făcut problema mai ușor de diagnosticat?] +During a controlled TCP firewall lesson, which rejection setting sends an immediate reset for matching TCP probes? [Într-o lecție firewall TCP controlată, ce setare de respingere trimite imediat reset pentru probele TCP potrivite?] -- **a) REJECT — the immediate "Connection refused" error clearly indicates a firewall is active and blocking traffic [REJECT — eroarea imediată 'Conexiune refuzată' indică clar că un paravan de protecție este activ și blochează traficul]** -- **b) DROP — the timeout behaviour provides more security, which is the top priority even for internal debugging [DROP — comportamentul de timeout oferă mai multă securitate, care este prioritatea principală chiar și pentru depanarea internă]** -- **c) LOG — logging alone resolves the connectivity issue without any additional configuration changes [LOG — doar logarea rezolvă problema de conectivitate fără nicio modificare suplimentară de configurare]** -- **d) ACCEPT — switching all rules to ACCEPT is the only reliable diagnostic approach for internal networks [ACCEPT — schimbarea tuturor regulilor la ACCEPT este singura abordare de diagnostic fiabilă pentru rețelele interne]** +- **a)** `REJECT --reject-with tcp-reset` +- **b)** `DROP` +- **c)** `LOG` -> 💡 **Feedback:** For internal debugging, REJECT is preferable because the immediate feedback (connection refused) saves considerable diagnostic time compared to waiting for DROP timeouts. DROP is better suited for external-facing services where concealing the firewall's presence is more important than fast diagnosis. [Pentru depanarea internă, REJECT este preferabil deoarece feedback-ul imediat (conexiune refuzată) economisește timp considerabil de diagnostic comparativ cu așteptarea timeout-urilor DROP. DROP este mai potrivit pentru serviciile expuse extern, unde ascunderea prezenței paravanului de protecție este mai importantă decât diagnosticul rapid.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The explicit tcp-reset form requests RST. A default REJECT can use an ICMP error instead. Immediate refusal helps observe the policy, but a refused connection alone does not prove which device or rule generated it. [Forma explicită tcp-reset solicită RST. REJECT implicit poate folosi o eroare ICMP. Refuzul imediat ajută observarea politicii, dar o conexiune refuzată singură nu dovedește ce dispozitiv sau regulă l-a generat.] + +
    --- @@ -195,14 +230,14 @@ - **c) Python's socket library intercepts the DROP and automatically retries the datagram until it is delivered [Biblioteca socket din Python interceptează DROP-ul și reîncearcă automat datagrama până când este livrată]** - **d) The firewall acknowledges receipt to the sender before silently discarding the datagram [Paravanul de protecție confirmă primirea către expeditor înainte de a elimina în tăcere datagrama]** -> 💡 **Feedback:** UDP has no delivery confirmation. The sendto() call completes successfully the moment the packet leaves the local network stack. Whether a firewall DROPs it, the network loses it, or the receiver is offline — the sender never learns of the failure without an application-layer acknowledgement protocol. [UDP nu are confirmare de livrare. Apelul sendto() se finalizează cu succes în momentul în care pachetul părăsește stiva locală de rețea. Fie că un paravan de protecție îl elimină, rețeaua îl pierde sau receptorul este offline — expeditorul nu află niciodată de eșec fără un protocol de confirmare la nivel de aplicație.] +> 💡 **Feedback:** UDP has no delivery confirmation. A successful sendto() reports local acceptance of the datagram, not delivery. Some failures may be reported through socket errors or ICMP; silence gives no application acknowledgement. Remote DROP usually provides no direct error feedback. [UDP nu are confirmare de livrare. Succesul sendto() raportează acceptarea locală a datagramei, nu livrarea. Unele eșecuri pot fi raportate prin erori de socket sau ICMP; lipsa răspunsului nu este confirmare de aplicație. DROP distant nu furnizează de regulă feedback direct de eroare.] --- ### 15. `Multiple Choice` **N07.T00.Q03: UDP Delivery Guarantee / Garanția de livrare UDP** -> A Python program calls sendto() to send a UDP datagram to a host with a DROP rule on the destination port. What value does sendto() return? [Un program Python apelează sendto() pentru a trimite o datagramă UDP către o gazdă cu o regulă DROP pe portul destinație. Ce valoare returnează sendto()?] +> A Python program calls sendto() to send a UDP datagram to a host with a DROP rule on the destination port. Assume local transmission succeeds and no earlier asynchronous error is pending. What does sendto() return? [Un program Python apelează sendto() pentru a trimite o datagramă UDP către o gazdă cu o regulă DROP pe portul destinație. Presupuneți că transmisia locală reușește și nu există o eroare asincronă anterioară în așteptare. Ce returnează sendto()?] - **a) The number of bytes sent (success), because UDP has no delivery confirmation [Numărul de octeți trimiși (succes), deoarece UDP nu are confirmare de livrare]** - **b) Zero, indicating the packet was blocked by the firewall [Zero, indicând că pachetul a fost blocat de paravan]** @@ -213,7 +248,6 @@ --- - ## W07 — Laborator / Lab (16 questions) ### 16. `Multiple Choice` @@ -226,7 +260,7 @@ - **c) tcp.port == 12345** - **d) tcp.flags.rst == 1** -> 💡 **Feedback:** The filter tcp.flags.syn == 1 and tcp.flags.ack == 0 matches only the initial SYN packet from the client (not the SYN-ACK from the server). Using only tcp.flags.syn == 1 (also matches SYN-ACK packets / potrivește și pachetele SYN-ACK) would also match SYN-ACK packets (which have both SYN and ACK flags set), giving false positives. This is a critical distinction in Wireshark analysis for counting the number of new TCP connections. [Filtrul tcp.flags.syn == 1 and tcp.flags.ack == 0 corespunde doar pachetului SYN inițial de la client (nu SYN-ACK de la server). Utilizarea doar a tcp.flags.syn == 1 ar corespunde și pachetelor SYN-ACK (care au ambii indicatori SYN și ACK setați), producând rezultate fals pozitive. Aceasta este o distincție critică în analiza Wireshark pentru numărarea conexiunilor TCP noi.] +> 💡 **Feedback:** The filter tcp.flags.syn == 1 and tcp.flags.ack == 0 matches only the initial SYN packet from the client (not the SYN-ACK from the server). Using only tcp.flags.syn == 1 (also matches SYN-ACK packets / potrivește și pachetele SYN-ACK) would also match SYN-ACK packets (which have both SYN and ACK flags set), giving false positives. Retransmitted SYN packets also match: correlate TCP streams and sequence numbers before counting distinct connection attempts. [Filtrul tcp.flags.syn == 1 and tcp.flags.ack == 0 corespunde doar pachetului SYN inițial de la client (nu SYN-ACK de la server). Utilizarea doar a tcp.flags.syn == 1 ar corespunde și pachetelor SYN-ACK (care au ambii indicatori SYN și ACK setați), producând rezultate fals pozitive. Retransmisiile SYN corespund și ele: corelați fluxurile TCP și numerele de secvență înainte de a număra tentative distincte.] --- @@ -240,14 +274,14 @@ - **c) Look for a packet with the RST flag set [Căutați un pachet cu indicatorul RST setat]** - **d) Look for the packet with the smallest sequence number in the capture [Căutați pachetul cu cel mai mic număr de secvență din captură]** -> 💡 **Feedback:** The first packet of a TCP connection is a SYN packet with no ACK flag set. The filter tcp.flags.syn == 1 and tcp.flags.ack == 0 isolates these initial SYN packets. The second packet (SYN-ACK) has both SYN and ACK set, so it would not match this filter. A common error is looking for the packet with the smallest sequence number, but sequence numbers are random initial values, not ordered from zero. [Primul pachet al unei conexiuni TCP este un pachet SYN fără indicatorul ACK setat. Filtrul tcp.flags.syn == 1 and tcp.flags.ack == 0 izolează aceste pachete SYN inițiale. Al doilea pachet (SYN-ACK) are ambii indicatori SYN și ACK setați, deci nu ar corespunde acestui filtru. O eroare frecventă este căutarea pachetului cu cel mai mic număr de secvență, dar numerele de secvență sunt valori inițiale aleatoare, nu ordonate de la zero.] +> 💡 **Feedback:** The first packet of a TCP connection is a SYN packet with no ACK flag set. The filter tcp.flags.syn == 1 and tcp.flags.ack == 0 matches SYN packets without ACK, including retransmissions; it does not alone prove a new or completed connection. The second packet (SYN-ACK) has both SYN and ACK set, so it would not match this filter. A common error is looking for the packet with the smallest sequence number, but sequence numbers are random initial values, not ordered from zero. [Primul pachet al unei conexiuni TCP este un pachet SYN fără indicatorul ACK setat. Filtrul tcp.flags.syn == 1 and tcp.flags.ack == 0 selectează SYN fără ACK, inclusiv retransmisii; singur nu dovedește o conexiune nouă sau completă. Al doilea pachet (SYN-ACK) are ambii indicatori SYN și ACK setați, deci nu ar corespunde acestui filtru. O eroare frecventă este căutarea pachetului cu cel mai mic număr de secvență, dar numerele de secvență sunt valori inițiale aleatoare, nu ordonate de la zero.] --- ### 18. `Multiple Choice` **N03.S03.Q02: Direct vs Tunnel Test / Test direct vs prin tunel** -> Exercise 3 first tests a direct connection with echo 'DIRECT TEST' | nc server 8080, then tests the tunnel with echo 'TUNNEL TEST' | nc router 9090. Both return the echoed message. What is the key difference observable in Wireshark? [Exercițiul 3 testează mai întâi o conexiune directă cu echo 'DIRECT TEST' | nc server 8080, apoi testează tunelul cu echo 'TUNNEL TEST' | nc router 9090. Ambele returnează mesajul ecou. Care este diferența cheie observabilă în Wireshark?] +> In this self-contained relay scenario, an unencrypted TCP relay on router:9090 opens a separate TCP connection to server:8080. A capture covers both legs. The student first tests a direct connection with echo 'DIRECT TEST' | nc server 8080, then tests the tunnel with echo 'TUNNEL TEST' | nc router 9090. Both return the echoed message. What is the key difference observable in Wireshark? [În acest scenariu autonom, un releu TCP necriptat de pe router:9090 deschide o conexiune TCP separată către server:8080. Captura acoperă ambele segmente. Studentul testează mai întâi o conexiune directă cu echo 'DIRECT TEST' | nc server 8080, apoi testează tunelul cu echo 'TUNNEL TEST' | nc router 9090. Ambele returnează mesajul ecou. Care este diferența cheie observabilă în Wireshark?] - **a) The tunnel creates two separate TCP streams (ports 9090 and 8080) whereas direct creates one stream on port 8080 [Tunelul creează două fluxuri TCP separate (porturile 9090 și 8080) în timp ce directul creează un singur flux pe portul 8080]** - **b) The tunnel adds encryption headers visible as TLS records while the direct connection sends plain text in practice [Tunelul adaugă anteturi de criptare vizibile ca înregistrări TLS în timp ce conexiunea directă trimite text simplu în practică]** @@ -276,7 +310,7 @@ > In a Wireshark capture, you observe [SYN] → [RST,ACK]. What does this indicate? [Într-o captură Wireshark, observați [SYN] → [RST,ACK]. Ce indică acest lucru?] -- **a) The destination port is closed or blocked — no service is listening there [Portul destinație este închis sau blocat — niciun serviciu nu ascultă acolo]** +- **a) The connection attempt was actively refused; a closed endpoint or a TCP-reset firewall rule may be responsible [Tentativa a fost refuzată activ; cauza poate fi un endpoint închis sau o regulă firewall TCP-reset]** - **b) A successful TCP three-way handshake has been completed normally [Un handshake TCP cu trei căi a fost finalizat cu succes]** - **c) The server is performing load balancing by redirecting the connection [Serverul efectuează echilibrarea încărcăturii prin redirecționarea conexiunii]** - **d) The client has requested a half-close of the TCP connection [Clientul a solicitat o semi-închidere a conexiunii TCP]** @@ -290,24 +324,30 @@ > Which tcpdump filter expression captures only TCP SYN packets (the first step of the three-way handshake)? [Care expresie de filtru tcpdump capturează doar pachetele TCP SYN (primul pas al handshake-ului tripartit)?] -- **a) tcp[tcpflags] & tcp-syn != 0 [tcp[tcpflags] & tcp-syn != 0]** +- **a) tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn [tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn]** - **b) tcp.flags.syn == 1 and not tcp.flags.ack [tcp.flags.syn == 1 and not tcp.flags.ack]** - **c) tcp filter syn [tcp filter syn]** - **d) tcp --syn-only [tcp --syn-only]** -> 💡 **Feedback:** tcpdump uses BPF (Berkeley Packet Filter) syntax: 'tcp[tcpflags] & tcp-syn != 0'. The option 'tcp.flags.syn == 1' is Wireshark/tshark display filter syntax, not tcpdump capture syntax. [tcpdump folosește sintaxa BPF (Berkeley Packet Filter): 'tcp[tcpflags] & tcp-syn != 0'. Opțiunea 'tcp.flags.syn == 1' este sintaxa de filtru de afișare Wireshark/tshark, nu sintaxa de captură tcpdump.] +> 💡 **Feedback:** tcpdump uses BPF (Berkeley Packet Filter) syntax: 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'. The option 'tcp.flags.syn == 1' is Wireshark/tshark display filter syntax, not tcpdump capture syntax. [tcpdump folosește sintaxa BPF (Berkeley Packet Filter): 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'. Opțiunea 'tcp.flags.syn == 1' este sintaxa de filtru de afișare Wireshark/tshark, nu sintaxa de captură tcpdump.] --- -### 22. `True / False` -**N07.S03.Q05: tcpdump Requires Root Privileges / tcpdump necesită privilegii root** +### Q22. `N07.S03.Q05` — Capture privileges / Privilegii pentru captură -> The tcpdump command requires root (sudo) privileges because it needs raw socket access to capture packets at the network interface level. [Comanda tcpdump necesită privilegii root (sudo) deoarece are nevoie de acces la socket-uri brute pentru a captura pachete la nivelul interfeței de rețea.] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) true** -- **b) false** +On Linux, must a packet-capture process always run with UID 0? [Pe Linux, procesul de captură a pachetelor trebuie întotdeauna să ruleze cu UID 0?] -> 💡 **Feedback:** Raw packet capture operates below the normal socket API, reading frames directly from the network interface. This privileged operation requires CAP_NET_RAW, hence the sudo requirement. [Captura de pachete brute operează sub API-ul normal de socket, citind cadre direct de la interfața de rețea. Această operațiune privilegiată necesită CAP_NET_RAW, de aici cerința sudo.] +- **a)** No. Appropriate capabilities and capture configuration can authorise a non-root process. [Nu. Capabilitățile și configurația de captură potrivite pot autoriza un proces non-root.] +- **b)** Yes. CAP_NET_RAW can only exist for UID 0. [Da. CAP_NET_RAW poate exista numai pentru UID 0.] +- **c)** No privileges or capabilities are ever needed. [Nu sunt necesare niciodată privilegii sau capabilități.] + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Creating Linux packet/raw sockets requires CAP_NET_RAW in the relevant namespace; other capture operations may need additional privileges. The lab uses sudo for a simple known configuration. Do not equate that teaching choice with a universal requirement to run the whole analyser as root. [Crearea socketurilor packet/raw Linux necesită CAP_NET_RAW în namespace-ul relevant; alte operații pot necesita privilegii suplimentare. Laboratorul folosește sudo pentru o configurație simplă cunoscută. Alegerea didactică nu înseamnă că întregul analizor trebuie universal rulat ca root.] + +
    --- @@ -367,76 +407,96 @@ --- -### 27. `Multiple Choice` -**N07.S02.Q06: mixed_filtering Default Policy / Politica implicită mixed_filtering** +### Q27. `N07.S02.Q06` — Explicit firewall rule set / Set explicit de reguli firewall + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +A hypothetical FORWARD chain accepts ICMP and UDP destination port 12345, explicitly rejects TCP destination port 12345 and silently drops everything unmatched. Which default policy implements the last clause? [Un lanț FORWARD ipotetic acceptă ICMP și UDP către portul 12345, respinge explicit TCP către portul 12345 și elimină silențios orice nu se potrivește. Ce politică implicită implementează ultima clauză?] -> In the lab's 'mixed_filtering' firewall profile, what is the FORWARD chain default policy (forward_policy)? [În profilul de firewall 'mixed_filtering' al laboratorului, care este politica implicită a lanțului FORWARD (forward_policy)?] +- **a)** DROP +- **b)** ACCEPT +- **c)** REJECT +- **d)** LOG -- **a) DROP (all traffic blocked unless explicitly allowed) [DROP (tot traficul blocat dacă nu este permis explicit)]** -- **b) ACCEPT (all traffic allowed unless explicitly blocked) [ACCEPT (tot traficul permis dacă nu este blocat explicit)]** -- **c) REJECT (all traffic refused with ICMP notification) [REJECT (tot traficul refuzat cu notificare ICMP)]** -- **d) LOG (all traffic recorded but still forwarded) [LOG (tot traficul înregistrat dar încă redirecționat)]** +
    💡 Feedback -> 💡 **Feedback:** The mixed_filtering profile sets forward_policy: DROP, making it a whitelist configuration. Only explicitly allowed traffic passes (ICMP and UDP 12345 are ACCEPTed; TCP 12345 is REJECTed; everything else is DROPped). [Profilul mixed_filtering setează forward_policy: DROP, făcându-l o configurație de tip whitelist. Doar traficul permis explicit trece (ICMP și UDP 12345 sunt acceptate; TCP 12345 este REJECT; orice altceva este DROP).] +**Correct answer / Răspuns corect: a.** DROP is the specified default policy. This question defines its own rules and does not require an absent mixed_filtering profile. [DROP este politica implicită specificată. Itemul își definește propriile reguli și nu necesită un profil mixed_filtering absent.] + +
    --- -### 28. `Multiple Choice` -**N07.S05.Q01: connect_ex() vs connect() / connect_ex() vs connect()** +### Q28. `N07.S05.Q01` — Connection-probe error handling / Tratarea erorilor la conectare + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Why can connect_ex simplify a TCP connection-probe loop? [De ce poate connect_ex simplifica o buclă de probe de conectare TCP?] + +- **a)** Connection errors are generally returned as errno codes, allowing explicit classification; exceptions still need handling. [Erorile de conectare sunt în general returnate drept coduri errno, permițând clasificare explicită; excepțiile trebuie în continuare tratate.] +- **b)** It is always non-blocking. [Este întotdeauna neblocant.] +- **c)** It automatically retries every failed connection. [Reîncearcă automat orice conexiune eșuată.] -> In the lab's port_probe.py, the probe() function uses sock.connect_ex() instead of sock.connect(). What is the practical difference? [În port_probe.py din laborator, funcția probe() folosește sock.connect_ex() în loc de sock.connect(). Care este diferența practică?] +
    💡 Feedback -- **a) connect_ex() returns an error code (0 for success) instead of raising an exception, allowing programmatic status checking [connect_ex() returnează un cod de eroare (0 pentru succes) în loc să ridice o excepție, permițând verificarea programatică a stării]** -- **b) connect_ex() performs an extended connection with automatic retry on failure, unlike connect() which tries once [connect_ex() realizează o conexiune extinsă cu reîncercare automată la eșec, spre deosebire de connect() care încearcă o singură dată]** -- **c) connect_ex() establishes a connection in non-blocking mode regardless of the socket timeout setting [connect_ex() stabilește o conexiune în mod non-blocant indiferent de setarea timeout-ului socket-ului]** -- **d) connect_ex() sends an extended TCP handshake with additional diagnostic headers [connect_ex() trimite un handshake TCP extins cu antete de diagnosticare suplimentare]** +**Correct answer / Răspuns corect: a.** The return contract changes error handling, not timeout or blocking semantics. Use errno constants rather than assuming a numeric error is portable across platforms. [Contractul de retur schimbă tratarea erorilor, nu semantica de blocare sau timeout. Folosiți constante errno, nu presupuneți că un cod numeric este portabil între platforme.] -> 💡 **Feedback:** connect_ex() returns 0 on success or an OS error code (e.g., 111 ECONNREFUSED on Linux) on failure. connect() raises socket.error on failure. The 'ex' suffix means 'extended error reporting', not 'extended connection'. [connect_ex() returnează 0 la succes sau un cod de eroare OS (ex: 111 ECONNREFUSED pe Linux) la eșec. connect() ridică socket.error la eșec. Sufixul 'ex' înseamnă 'raportare extinsă a erorilor', nu 'conexiune extinsă'.] +
    --- -### 29. `Multiple Choice` -**N07.S05.Q02: Port Probe: Filtered State Detection / Sondare port: Detectarea stării filtered** +### Q29. `N07.S05.Q02` — Timeout evidence / Dovezi pentru timeout -> In port_probe.py, when does the probe() function return 'timeout' (indicating a filtered port)? [În port_probe.py, când returnează funcția probe() valoarea 'timeout' (indicând un port filtrat)?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) When socket.timeout exception is caught, meaning the connect_ex() call blocked until the timeout expired with no response [Când excepția socket.timeout este capturată, însemnând că apelul connect_ex() a blocat până la expirarea timeout-ului fără răspuns]** -- **b) When connect_ex() returns error code 110 (ETIMEDOUT), which the function maps to the timeout string [Când connect_ex() returnează codul de eroare 110 (ETIMEDOUT), pe care funcția îl mapează la șirul timeout]** -- **c) When the TCP handshake completes successfully but the server does not respond to the application data payload within the configured timeout period [Când handshake-ul TCP se completează cu succes dar serverul nu răspunde la sarcina utilă de date a aplicației în perioada de timeout configurată]** -- **d) When connect_ex() returns 0 but subsequent recv() times out, distinguishing open but unresponsive services [Când connect_ex() returnează 0 dar recv() ulterior expiră, distingând serviciile deschise dar care nu răspund]** +A TCP connection attempt expires without completing. What is the justified observation? [O tentativă de conectare TCP expiră fără finalizare. Care este observația justificată?] -> 💡 **Feedback:** In port_probe.py, the try/except catches socket.timeout. This occurs when a firewall DROP rule silently discards the SYN — the socket waits for a response that never arrives until the configured timeout. [În port_probe.py, blocul try/except captează socket.timeout. Aceasta apare când o regulă firewall DROP elimină silențios SYN-ul — socket-ul așteaptă un răspuns care nu vine niciodată până la timeout-ul configurat.] +- **a)** No connection completed before the deadline; filtering, loss, an unreachable host or other causes remain possible. [Nicio conexiune nu s-a finalizat până la termen; filtrarea, pierderea, o gazdă inaccesibilă sau alte cauze rămân posibile.] +- **b)** A firewall DROP rule has been proved. [A fost demonstrată o regulă firewall DROP.] +- **c)** The port is certainly closed and sent RST. [Portul este sigur închis și a trimis RST.] + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** connect_ex may return a timeout-related errno rather than raise socket.timeout. Inspect returned codes and handle exceptions. A timeout describes the observation, not a unique remote port state. [connect_ex poate întoarce un errno asociat timeout-ului în loc să ridice socket.timeout. Inspectați codurile returnate și tratați excepțiile. Timeout-ul descrie observația, nu o stare unică a portului distant.] + +
    --- -### 30. `Multiple Choice` -**N07.S05.Q04: Code Tracing: Closed Port Path / Trasare cod: Calea pentru port închis** +### Q30. `N07.S05.Q04` — Controlled refusal case / Caz controlat de refuz + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +For a reachable local TCP endpoint with no listener, no firewall rejection and no race with another process, what result is normally expected from connect_ex? [Pentru un endpoint TCP local accesibil fără listener, fără respingere firewall și fără cursă cu alt proces, ce rezultat este așteptat în mod normal de la connect_ex?] -> In the code_tracing.md Exercise T2, when probe_port() is called on port 9999 with no server and no firewall, what execution path is followed? [În Exercițiul T2 din code_tracing.md, când probe_port() este apelat pe portul 9999 fără server și fără firewall, ce cale de execuție este urmată?] +- **a)** `errno.ECONNREFUSED` +- **b)** `0` +- **c)** An application response body [Un corp de răspuns al aplicației] -- **a) Lines 1→2→3→4→6→9→10, returning 'closed' (connect_ex returns non-zero ECONNREFUSED) [Liniile 1→2→3→4→6→9→10, returnând 'closed' (connect_ex returnează non-zero ECONNREFUSED)]** -- **b) Lines 1→2→3→7→8→9→10, returning 'filtered' (socket.timeout exception is raised after blocking) [Liniile 1→2→3→7→8→9→10, returnând 'filtered' (excepția socket.timeout se ridică după blocare)]** -- **c) Lines 1→2→3→4→5→9→10, returning 'open' (connect_ex returns 0) [Liniile 1→2→3→4→5→9→10, returnând 'open' (connect_ex returnează 0)]** -- **d) Lines 1→2→3→7→10, returning 'error' (generic exception is raised) [Liniile 1→2→3→7→10, returnând 'error' (se ridică excepție generică)]** +
    💡 Feedback -> 💡 **Feedback:** With no server listening and no firewall, the OS kernel responds with RST (ECONNREFUSED, code 111 on Linux). connect_ex() returns non-zero, so result != 0 at Line 4, branching to Line 6 (status = 'closed'). The finally block (Line 9) always executes. [Fără server care ascultă și fără firewall, kernel-ul OS răspunde cu RST (ECONNREFUSED, cod 111 pe Linux). connect_ex() returnează non-zero, deci result != 0 la Linia 4, ramificând la Linia 6 (status = 'closed'). Blocul finally (Linia 9) se execută întotdeauna.] +**Correct answer / Răspuns corect: a.** In this controlled setup the operating system refuses the connection. Outside these assumptions, the same observed refusal can have other causes, including an explicit firewall reset. [În configurația controlată, sistemul de operare refuză conexiunea. În afara ipotezelor, același refuz observat poate avea alte cauze, inclusiv un reset firewall explicit.] + +
    --- -### 31. `Multiple Choice` -**N07.S05.Q05: Rule Order in Firewall Processing / Ordinea regulilor în procesarea firewall** +### Q31. `N07.S05.Q05` — First terminating firewall rule / Prima regulă firewall terminală -> In code_tracing.md Exercise T3, if the default DROP rule (rule index 3, port=None) were moved to position 0, what would happen to TCP traffic on port 12345? [În Exercițiul T3 din code_tracing.md, dacă regula DROP implicită (indexul 3, port=None) ar fi mutată la poziția 0, ce s-ar întâmpla cu traficul TCP pe portul 12345?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) TCP 12345 would be DROPped because the general-purpose rule (port=None) matches all TCP before specific port rules are checked [TCP 12345 ar fi eliminat cu DROP deoarece regula cu scop general (port=None) potrivește tot TCP-ul înainte ca regulile specifice de port să fie verificate]** -- **b) TCP 12345 would still be ACCEPTed because iptables automatically prioritizes specific port-match rules over general catch-all rules regardless of their declared insertion order [TCP 12345 ar fi tot ACCEPT deoarece iptables prioritizează automat regulile cu potrivire specifică de port față de regulile generale de tip catch-all indiferent de ordinea lor declarată de inserare]** -- **c) TCP 12345 would be REJECTed because the REJECT rule has higher priority than DROP regardless of position [TCP 12345 ar fi REJECT deoarece regula REJECT are prioritate mai mare decât DROP indiferent de poziție]** -- **d) The firewall would raise an error because a None-port rule cannot precede port-specific rules [Paravanul de protecție ar genera o eroare deoarece o regulă cu port None nu poate preceda regulile specifice de port]** +In a chain evaluated in order, a terminating DROP rule matching all TCP precedes an ACCEPT rule for TCP destination port 12345. What happens to a matching TCP packet for that port? [Într-un lanț evaluat în ordine, o regulă DROP terminală pentru tot TCP precede o regulă ACCEPT pentru TCP către portul 12345. Ce se întâmplă cu un pachet TCP potrivit pentru acel port?] -> 💡 **Feedback:** Firewall rules are evaluated sequentially — first match wins. A general rule (port=None) at position 0 matches ALL TCP traffic before any specific port rule can be reached. This is why specific rules must always precede general/default rules. [Regulile de firewall sunt evaluate secvențial — prima potrivire câștigă. O regulă generală (port=None) la poziția 0 potrivește TOT traficul TCP înainte ca vreo regulă specifică de port să fie atinsă. De aceea regulile specifice trebuie întotdeauna să preceadă regulile generale/implicite.] +- **a)** It is dropped by the first rule; the later ACCEPT is not reached. [Este eliminat de prima regulă; ACCEPT ulterior nu este atins.] +- **b)** The more specific ACCEPT always overrides insertion order. [ACCEPT mai specific suprascrie mereu ordinea inserării.] +- **c)** Both terminal actions execute. [Se execută ambele acțiuni terminale.] ---- +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The ordering applies to matching terminating rules in this specified chain. Non-terminating operations such as LOG can continue processing. [Ordinea se aplică regulilor potrivite cu verdict terminal din lanțul specificat. Operații neterminale precum LOG pot continua procesarea.] +
    + +--- ## W07 — Drag & Drop (9 questions) @@ -475,7 +535,7 @@ ### 34. `Drag & Drop into Text` **N03.D05.Q07: tcpdump Save Capture / Salvare captură tcpdump** -> Complete the tcpdump command to capture tunnel traffic on port 12345 and save it to a pcap file. [Completați comanda tcpdump pentru a captura traficul tunelului pe portul 12345 și a-l salva într-un fișier pcap.] +> Complete the tcpdump command to capture test traffic known to traverse eth0 on port 12345 and save it to a pcap file. [Completați comanda tcpdump pentru a captura traficul de test despre care se știe că traversează eth0 pe portul 12345 și a-l salva într-un fișier pcap.] ``` tcpdump -i [[1]] [[2]] capture.pcap 'port [[3]]' @@ -484,7 +544,7 @@ tcpdump -i [[1]] [[2]] capture.pcap 'port [[3]]' **Available choices / Variante disponibile: eth0 | -w | 12345 | lo | -r | 8080** -> 💡 **Feedback:** The command is: tcpdump -i eth0 -w capture.pcap 'port 12345'. The -w flag writes raw packets to a file for later analysis in Wireshark. Port 12345 is the tunnel listen port on the router. [Comanda este: tcpdump -i eth0 -w capture.pcap 'port 12345'. Opțiunea -w scrie pachetele brute într-un fișier pentru analiză ulterioară în Wireshark. Portul 12345 este portul de ascultare al tunelului pe ruter.] +> 💡 **Feedback:** The command is: tcpdump -i eth0 -w capture.pcap 'port 12345'. The -w flag writes raw packets to a file for later analysis in Wireshark. The port and interface are assumptions supplied by this item; choose the actual traffic interface for a different topology. [Comanda este: tcpdump -i eth0 -w capture.pcap 'port 12345'. Opțiunea -w scrie pachetele brute într-un fișier pentru analiză ulterioară în Wireshark. Portul și interfața sunt ipoteze date de item; pentru altă topologie alegeți interfața traversată efectiv.] --- @@ -542,7 +602,7 @@ tcpdump -i [[1]] [[2]] capture.pcap 'port [[3]]' > Build a tcpdump filter for TCP traffic on port 9090 from host 10.0.7.100: [Construiți un filtru tcpdump pentru traficul TCP pe portul 9090 de la gazda 10.0.7.100:] ``` -sudo tcpdump -i eth0 '[[1]] port 9090 [[2]] host 10.0.7.100' +sudo tcpdump -i eth0 '[[1]] port 9090 [[2]] src host 10.0.7.100' ``` **Available choices / Variante disponibile: tcp | and | udp | or** @@ -552,27 +612,21 @@ sudo tcpdump -i eth0 '[[1]] port 9090 [[2]] host 10.0.7.100' --- -### 39. `Drag & Drop into Text` -**N07.D05.Q02: Port Probe Results / Rezultatele sondării porturilor** +### Q39. `N07.D05.Q02` — Probe result interpretation / Interpretarea rezultatului probei -> The port_probe.py script classifies ports into states. Complete the mapping: [Scriptul port_probe.py clasifică porturile în stări. Completați maparea:] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -``` -connect_ex() returns 0 → port is [[1]] [connect_ex() returnează 0 → portul este ___] -``` +Which interpretation of TCP connect_ex outcomes is justified? [Ce interpretare a rezultatelor connect_ex pentru TCP este justificată?] -``` -connect_ex() returns non-zero → port is [[2]] [connect_ex() returnează non-zero → portul este ___] -``` +- **a)** 0: connection completed; ECONNREFUSED: active refusal; a timeout: no completed connection within the deadline. [0: conexiune finalizată; ECONNREFUSED: refuz activ; timeout: nicio conexiune finalizată până la termen.] +- **b)** Every non-zero return means closed and every exception means filtered. [Orice retur non-zero înseamnă închis și orice excepție înseamnă filtrat.] +- **c)** Any timeout proves the host does not exist. [Orice timeout dovedește că gazda nu există.] -``` -socket.timeout is raised → port is [[3]] [socket.timeout este ridicat → portul este ___] -``` - -**Available choices / Variante disponibile: open | closed | filtered | unknown** +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Record the exact errno or exception. A timeout may be returned as an error code; refusal may originate at a firewall. These observations are not exhaustive diagnoses of the service or path. [Înregistrați errno-ul exact sau excepția. Timeout-ul poate fi returnat drept cod de eroare; refuzul poate proveni de la firewall. Observațiile nu constituie diagnostice exhaustive ale serviciului sau căii.] -> 💡 **Feedback:** connect_ex() returns 0 for successful connection (open), non-zero error code for refused connection (closed), and socket.timeout indicates no response (filtered by DROP). [connect_ex() returnează 0 pentru conexiune reușită (deschis), cod de eroare non-zero pentru conexiune refuzată (închis), iar socket.timeout indică absența răspunsului (filtrat cu DROP).] +
    --- @@ -609,13 +663,13 @@ result = s.[[3]](('host', port)) > Select the correct Wireshark display filter components. [Selectați componentele corecte ale filtrului de afișare Wireshark.] ``` -To filter TCP traffic on port 12345: [[1]]. To filter only SYN packets: [[2]]. To filter packets to the lab container IP: [[3]]. +To filter TCP traffic on port 12345: [[1]]. To filter only SYN packets: [[2]]. To filter packets to the supplied destination IP 10.0.2.10: [[3]]. ``` -**Available choices / Variante disponibile: tcp.port == 12345 | tcp.flags.syn == 1 | ip.addr == 10.0.2.10 | tcp port 12345 | tcp.syn = true | dst 10.0.2.10** +**Available choices / Variante disponibile: tcp.port == 12345 | tcp.flags.syn == 1 | ip.dst == 10.0.2.10 | tcp port 12345 | tcp.syn = true | dst 10.0.2.10** -> 💡 **Feedback:** Wireshark display filters use dot notation (tcp.port, tcp.flags.syn, ip.addr). Capture filters (BPF syntax like 'tcp port 12345') are different from display filters. [Filtrele de afișare Wireshark folosesc notația cu puncte (tcp.port, tcp.flags.syn, ip.addr). Filtrele de captură (sintaxă BPF precum „tcp port 12345") sunt diferite de filtrele de afișare.] +> 💡 **Feedback:** Wireshark display filters use dot notation (tcp.port, tcp.flags.syn, ip.dst). Capture filters (BPF syntax like 'tcp port 12345') are different from display filters. [Filtrele de afișare Wireshark folosesc notația cu puncte (tcp.port, tcp.flags.syn, ip.dst). Filtrele de captură (sintaxă BPF precum „tcp port 12345") sunt diferite de filtrele de afișare.] --- @@ -657,74 +711,58 @@ CLI analysis with display filters and field extraction: [[3]]. [Analiză CLI cu --- -### 44. `Gap Select` -**N07.D10.Q02: Firewall Action Effects / Efectele acțiunilor de paravan** +### Q44. `N07.D10.Q02` — Known firewall actions / Acțiuni firewall cunoscute -> Match each firewall effect to its action: [Potriviți fiecare efect al paravanului cu acțiunea sa:] - -``` -Client experiences timeout: [[1]]. [Clientul experimentează timeout: ___.] -``` +*Matching / Asociere* -``` -Client receives RST (TCP): [[2]]. [Clientul primește RST (TCP): ___.] -``` +Match the configured action to its effect on a matching TCP packet. [Asociați acțiunea configurată cu efectul asupra unui pachet TCP potrivit.] -``` -Packet passes through: [[3]]. [Pachetul trece prin: ___.] -``` +| Action / Acțiune | Effect / Efect | +|---|---| +| `DROP` | Silently discard this packet / Elimină silențios acest pachet | +| `REJECT --reject-with tcp-reset` | Send TCP RST / Trimite TCP RST | +| `ACCEPT` | Permit processing past this filter verdict / Permite continuarea după acest verdict de filtrare | -**Available choices / Variante disponibile: DROP | REJECT | ACCEPT** +
    💡 Feedback +The table is the answer key. Predict effects from a known rule; do not infer a unique cause from a timeout or reset observed without configuration evidence. ACCEPT in one chain also does not prove end-to-end delivery. [Tabelul reprezintă cheia. Preziceți efectele unei reguli cunoscute; nu deduceți o cauză unică dintr-un timeout sau reset fără dovezi de configurație. ACCEPT într-un lanț nu dovedește livrarea capăt-la-capăt.] -> 💡 **Feedback:** DROP = silence → timeout. REJECT = active refusal → RST (TCP) or ICMP (UDP). ACCEPT = packet is allowed through. [DROP = tăcere → timeout. REJECT = refuz activ → RST (TCP) sau ICMP (UDP). ACCEPT = pachetul trece.] +
    --- -### 45. `Gap Select` -**N07.D10.Q03: Port Probe Results Mapping / Maparea rezultatelor sondării porturilor** +### Q45. `N07.D10.Q03` — Probe result interpretation / Interpretarea rezultatului probei -> Map each connect_ex() outcome to the port state: [Mapați fiecare rezultat connect_ex() la starea portului:] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -``` -Returns 0: port is [[1]]. [Returnează 0: portul este ___.] -``` +Which interpretation of TCP connect_ex outcomes is justified? [Ce interpretare a rezultatelor connect_ex pentru TCP este justificată?] -``` -Returns 111 (ECONNREFUSED): port is [[2]]. [Returnează 111 (ECONNREFUSED): portul este ___.] -``` +- **a)** 0: connection completed; ECONNREFUSED: active refusal; a timeout: no completed connection within the deadline. [0: conexiune finalizată; ECONNREFUSED: refuz activ; timeout: nicio conexiune finalizată până la termen.] +- **b)** Every non-zero return means closed and every exception means filtered. [Orice retur non-zero înseamnă închis și orice excepție înseamnă filtrat.] +- **c)** Any timeout proves the host does not exist. [Orice timeout dovedește că gazda nu există.] -``` -Raises socket.timeout: port is [[3]]. [Ridică socket.timeout: portul este ___.] -``` - -**Available choices / Variante disponibile: open | closed | filtered** +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Record the exact errno or exception. A timeout may be returned as an error code; refusal may originate at a firewall. These observations are not exhaustive diagnoses of the service or path. [Înregistrați errno-ul exact sau excepția. Timeout-ul poate fi returnat drept cod de eroare; refuzul poate proveni de la firewall. Observațiile nu constituie diagnostice exhaustive ale serviciului sau căii.] -> 💡 **Feedback:** 0 = connection succeeded (open). 111/ECONNREFUSED = RST received (closed, host reachable but no service). socket.timeout = no response within deadline (filtered by DROP rule). [0 = conexiune reușită (deschis). 111/ECONNREFUSED = RST primit (închis, gazdă accesibilă dar fără serviciu). socket.timeout = niciun răspuns în termenul limită (filtrat de regulă DROP).] +
    --- -### 46. `Gap Select` -**N07.D10.Q07: Recommended Firewall Strategies / Strategii recomandate de paravan de protecție** +### Q46. `N07.D10.Q07` — DROP and REJECT trade-off / Compromisul DROP și REJECT -> Select the recommended firewall action for each scenario: [Selectați acțiunea de paravan recomandată pentru fiecare scenariu:] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -``` -External-facing services (minimise reconnaissance): [[1]]. [Servicii expuse extern (minimizare recunoaștere): ___.] -``` +Which trade-off between DROP and REJECT is defensible? [Ce compromis între DROP și REJECT este justificat?] -``` -Internal debugging (fast error feedback): [[2]]. [Depanare internă (feedback rapid la erori): ___.] -``` - -``` -Honeypot deception (mimic non-existent host): [[1]]. [Deceptare honeypot (imitare gazdă inexistentă): ___.] -``` +- **a)** DROP withholds a rejection for matched packets; REJECT gives faster negative feedback. Choose policy for the stated service and environment. [DROP nu emite respingere pentru pachetele potrivite; REJECT oferă feedback negativ mai rapid. Alegeți politica pentru serviciul și mediul date.] +- **b)** DROP guarantees no information about the host can be learned. [DROP garantează că nu se poate afla nicio informație despre gazdă.] +- **c)** REJECT proves a listening service is present. [REJECT dovedește prezența unui serviciu care ascultă.] -**Available choices / Variante disponibile: DROP | REJECT** +
    💡 Feedback +**Correct answer / Răspuns corect: a.** Neither action is a universal security ranking. Scope the rule and assess operational needs; other traffic can reveal the host and rejection can be generated by an intermediate device. [Nicio acțiune nu reprezintă un clasament universal de securitate. Delimitați regula și evaluați nevoile operaționale; alt trafic poate dezvălui gazda, iar respingerea poate fi generată de un dispozitiv intermediar.] -> 💡 **Feedback:** External + honeypot = DROP (stealthy, no information leakage). Internal debugging = REJECT (immediate error response aids diagnosis). [Extern + honeypot = DROP (discret, fără scurgeri de informații). Depanare internă = REJECT (răspunsul imediat la erori ajută diagnosticarea).] +
    --- diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W08_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W08_Questions.md index a0abc4e..6881c60 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W08_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W08_Questions.md @@ -45,7 +45,7 @@ - **c) 11** - **d) 12** -> 💡 **Feedback:** The three-way handshake occurs only once, at the time connect() is called. After that, the connection remains open for all data transfers until close() initiates the FIN teardown sequence. A common misconception (Misconception #7) is that each send() triggers a new handshake, similar to how each HTTP request in HTTP/(...).0 required a new connection. In reality, TCP maintains a persistent connection. [Handshake-ul în trei pași are loc o singură dată, în momentul apelului connect(). După aceea, conexiunea rămâne deschisă pentru toate transferurile de date până când close() inițiază secvența de terminare cu FIN. O concepție greșită frecventă (Concepția greșită nr. 7) este că fiecare send() declanșează un nou handshake, similar modului în care fiecare cerere HTTP în HTTP/(...).0 necesita o nouă conexiune. În realitate, TCP menține o conexiune persistentă.] +> 💡 **Feedback:** One normal connection establishment is needed for one successful connect(), irrespective of the number of application writes. send() may write fewer bytes than requested and does not create message boundaries. Retransmissions can increase the number of observed packets; graceful close normally uses FIN, while some close/error paths reset the connection. [Este necesară o singură stabilire normală a conexiunii pentru un connect() reușit, indiferent de numărul scrierilor aplicației. send() poate scrie mai puțini octeți decât se cer și nu creează delimitări de mesaje. Retransmisiile pot crește numărul de pachete observate; închiderea normală folosește de regulă FIN, dar unele căi de închidere/eroare resetează conexiunea.] --- @@ -80,14 +80,14 @@ ### 6. `Multiple Choice` **N07.T00.Q01: TCP Connection Establishment / Stabilirea conexiunii TCP** -> How many distinct packets are exchanged during a successful TCP three-way handshake? [Câte pachete distincte sunt schimbate în timpul unei negocieri TCP în trei pași reușite?] +> How many distinct packets are exchanged in the standard TCP three-way handshake with no loss or retransmission? [Câte pachete distincte sunt schimbate în negocierea TCP standard în trei pași fără pierderi sau retransmisii?] - **a) Three (SYN, SYN-ACK, ACK) [Trei (SYN, SYN-ACK, ACK)]** - **b) Two (SYN, ACK) [Două (SYN, ACK)]** - **c) Four (SYN, SYN-ACK, ACK, DATA) [Patru (SYN, SYN-ACK, ACK, DATE)]** - **d) One (combined SYN-ACK-DATA) [Unul (SYN-ACK-DATE combinat)]** -> 💡 **Feedback:** The TCP three-way handshake requires exactly 3 packets: SYN (client → server), SYN-ACK (server → client), ACK (client → server). Data transfer begins only after all three complete. [Negocierea TCP în trei pași necesită exact 3 pachete: SYN (client → server), SYN-ACK (server → client), ACK (client → server). Transferul de date începe doar după finalizarea tuturor celor trei.] +> 💡 **Feedback:** Three segments in this specified case: SYN, SYN-ACK and ACK. Retransmissions can add packets, and the final ACK may also carry application data. Therefore three handshake steps are not an unconditional packet-count or no-data-until-later rule. [Trei segmente în cazul specificat: SYN, SYN-ACK și ACK. Retransmisiile pot adăuga pachete, iar ultimul ACK poate transporta și date ale aplicației. Prin urmare, cei trei pași nu reprezintă o regulă necondiționată despre numărul pachetelor sau interzicerea datelor până la un moment ulterior.] --- @@ -119,17 +119,22 @@ --- -### 9. `Multiple Choice` -**N08.C03.Q02: Behaviour of HTTP HEAD method / Comportamentul metodei HTTP HEAD** +### Q9. `N08.C03.Q02` — Behaviour of HTTP HEAD method / Comportamentul metodei HTTP HEAD -> What does an HTTP server return in response to a HEAD request? [Ce returnează un server HTTP ca răspuns la o cerere HEAD?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) The same headers that a GET request would produce, but without any response body [Aceleași antete pe care o cerere GET le-ar produce, dar fără niciun corp al răspunsului]** -- **b) Only the first 1 KB of the response body as a truncated preview of the resource [Doar primii 1 KO din corpul răspunsului ca previzualizare trunchiată a resursei]** -- **c) Metadata about the HEAD request itself, such as processing time and server load [Metadate despre cererea HEAD în sine, precum timpul de procesare și încărcarea serverului]** -- **d) A list of all HTTP methods the server supports for the requested resource [O listă a tuturor metodelor HTTP pe care serverul le acceptă pentru resursa cerută]** +Which statement correctly describes a response to HTTP HEAD? [Care afirmație descrie corect un răspuns HTTP HEAD?] -> 💡 **Feedback:** HEAD is identical to GET in every way except the server MUST NOT return a body. Content-Length still reports the size a GET would produce. Useful for cache validation and link checking. [HEAD este identic cu GET în orice privință, cu excepția că serverul NU TREBUIE să returneze un corp. Content-Length raportează totuși dimensiunea pe care GET ar produce-o. Util pentru validarea cache-ului și verificarea linkurilor.] +- **a)** No response content; normally the corresponding GET headers, with permitted omissions for fields determined only while generating content [Fără conținut în răspuns; în mod normal antetele GET corespunzătoare, cu omisiunile permise pentru câmpurile calculate doar la generarea conținutului] +- **b)** The first 1 KiB of the resource is returned [Se returnează primul 1 KiB al resursei] +- **c)** The server must omit every representation header [Serverul trebuie să omită toate antetele reprezentării] +- **d)** HEAD lists the supported methods instead of describing the resource [HEAD enumeră metodele acceptate în loc să descrie resursa] + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** RFC 9110 §9.3.2 forbids response content for HEAD and recommends the GET header fields while allowing specified omissions. If Content-Length is sent, it must equal the octet count of the corresponding GET content; its presence is not mandatory. [RFC 9110 §9.3.2 interzice conținutul răspunsului HEAD și recomandă antetele GET, permițând omisiunile specificate. Dacă se trimite Content-Length, valoarea trebuie să fie numărul de octeți al conținutului GET corespunzător; prezența sa nu este obligatorie.] + +
    --- @@ -138,26 +143,31 @@ > In the request line GET /index.html HTTP/1.1, which three components appear in order, separated by a single space? [În linia de cerere GET /index.html HTTP/1.1, care sunt cele trei componente care apar în ordine, separate de un singur spațiu?] -- **a) Method, request-target (path), and HTTP version — the three mandatory fields [Metoda, ținta cererii (calea) și versiunea HTTP — cele trei câmpuri obligatorii]** +- **a) Method, request-target, and HTTP version — the three mandatory fields [Metoda, ținta cererii și versiunea HTTP — cele trei câmpuri obligatorii]** - **b) Host, method, and request-target — with the host always appearing first [Gazda, metoda și ținta cererii — cu gazda apărând întotdeauna prima]** - **c) HTTP version, method, and request-target — version always precedes the method [Versiunea HTTP, metoda și ținta cererii — versiunea precedă întotdeauna metoda]** - **d) Method, HTTP version, and Content-Type — defining both action and format [Metoda, versiunea HTTP și Content-Type — definind atât acțiunea, cât și formatul]** -> 💡 **Feedback:** The request line follows METHOD SP REQUEST-TARGET SP HTTP-VERSION CRLF. For example: GET /index.html HTTP/1.1. The Host header is separate, not part of the request line. [Linia de cerere urmează schema METODA SP ȚINTA-CERERII SP VERSIUNE-HTTP CRLF. De exemplu: GET /index.html HTTP/1.1. Antetul Host este separat, nu face parte din linia de cerere.] +> 💡 **Feedback:** The request line is METHOD SP REQUEST-TARGET SP HTTP-VERSION CRLF. In this example the target is the origin-form path /index.html. Other forms exist, including absolute-form for proxies, authority-form for CONNECT and asterisk-form for server-wide OPTIONS. Host is a separate field. [Linia cererii este METHOD SP REQUEST-TARGET SP HTTP-VERSION CRLF. Aici ținta este calea /index.html în forma origin-form. Există și absolute-form pentru proxy, authority-form pentru CONNECT și asterisk-form pentru OPTIONS aplicat serverului. Host este un câmp separat.] --- -### 11. `Multiple Choice` -**N08.C03.Q05: Status code for unsupported HTTP method / Codul de stare pentru o metodă HTTP neacceptată** +### Q11. `N08.C03.Q05` — Status code for unsupported HTTP method / Codul de stare pentru o metodă HTTP neacceptată + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +A server recognises DELETE and supports it on some resources, but /index.html permits only GET and HEAD. What response is appropriate for DELETE /index.html? [Serverul recunoaște DELETE și îl acceptă pentru unele resurse, dar /index.html permite doar GET și HEAD. Ce răspuns este adecvat pentru DELETE /index.html?] + +- **a)** 405 Method Not Allowed, including Allow: GET, HEAD [405 Method Not Allowed, cu Allow: GET, HEAD] +- **b)** 400 because DELETE is invalid HTTP syntax [400 deoarece DELETE este sintaxă HTTP invalidă] +- **c)** 404 solely because this method is disallowed [404 doar pentru că această metodă nu este permisă] +- **d)** 501 because every resource must implement every method [501 deoarece orice resursă trebuie să implementeze toate metodele] -> A client sends a DELETE request to an HTTP server that only implements GET and HEAD. What status code should the server return? [Un client trimite o cerere DELETE către un server HTTP care implementează doar GET și HEAD. Ce cod de stare ar trebui să returneze serverul?] +
    💡 Feedback -- **a) 405 Method Not Allowed — the method is recognised but not supported for this resource [405 Method Not Allowed — metoda este recunoscută, dar nu este acceptată pentru această resursă]** -- **b) 400 Bad Request — the server cannot understand what the client is asking [400 Bad Request — serverul nu poate înțelege ce cere clientul]** -- **c) 404 Not Found — the DELETE endpoint does not exist on this server [404 Not Found — endpoint-ul DELETE nu există pe acest server]** -- **d) 501 Not Implemented — the server does not recognise the DELETE method at all, and the server logs the attempt as a protocol violation before closing the connection [501 Not Implemented — serverul nu recunoaște deloc metoda DELETE, iar serverul înregistrează încercarea ca o violare de protocol înainte de a închide conexiunea]** +**Correct answer / Răspuns corect: a.** 405 concerns a known method that the target resource does not allow; RFC 9110 requires an Allow field. 501 concerns unsupported functionality, such as a method the server does not recognise and cannot support for any resource. [405 privește o metodă cunoscută pe care resursa țintă nu o permite; RFC 9110 cere antetul Allow. 501 privește funcționalitate neimplementată, de exemplu o metodă nerecunoscută pe care serverul nu o poate accepta pentru nicio resursă.] -> 💡 **Feedback:** 405 indicates the server knows the method but the target resource does not support it. The response SHOULD include an Allow header listing accepted methods (e.g., Allow: GET, HEAD). [405 indică faptul că serverul cunoaște metoda, dar resursa țintă nu o acceptă. Răspunsul AR TREBUI să includă un antet Allow care listează metodele acceptate (de ex., Allow: GET, HEAD).] +
    --- @@ -423,7 +433,7 @@ - **c) Both the headers and body are identical, with HEAD being merely an alias for GET [Atât antetele cât și corpul sunt identice, HEAD fiind doar un alias pentru GET]** - **d) The server omits all headers and returns only the status line for HEAD requests [Serverul omite toate antetele și returnează doar linia de stare pentru cererile HEAD]** -> 💡 **Feedback:** The exercise code computes headers including Content-Length from the file, then sets response_body = b'' for HEAD. This matches RFC 9110 which requires identical headers but no body. [Codul exercițiului calculează antetele inclusiv Content-Length din fișier, apoi setează response_body = b'' pentru HEAD. Aceasta respectă RFC 9110 care necesită antete identice dar fără corp.] +> 💡 **Feedback:** For a successful static-file response in S08_Part03B_Example_Socket_HTTP_Server.py, HEAD uses the file size for Content-Length and sends no content. RFC 9110 permits this but does not require every HEAD header to be identical to GET: some fields determined only during content generation may be omitted. [Pentru un răspuns reușit cu fișier static în S08_Part03B_Example_Socket_HTTP_Server.py, HEAD folosește dimensiunea fișierului pentru Content-Length și nu trimite conținut. RFC 9110 permite acest comportament, dar nu cere identitatea tuturor antetelor HEAD și GET: anumite câmpuri calculate doar la generarea conținutului pot fi omise.] --- @@ -437,7 +447,7 @@ - **c) A NULL byte (0x00) — signalling the end of text-based header content [Un octet NULL (0x00) — semnalând sfârșitul conținutului text al antetelor]** - **d) The string END-HEADERS — an explicit delimiter defined in the HTTP specification [Șirul END-HEADERS — un delimitator explicit definit în specificația HTTP]** -> 💡 **Feedback:** The blank line (CRLF after headers + one more CRLF) is the only way HTTP/1.1 delineates headers from body. The exercise code appends '\r\n' after the last header line. [Linia goală (CRLF după antete + încă un CRLF) este singura modalitate prin care HTTP/1.1 delimitează antetele de corp. Codul exercițiului adaugă '\r\n' după ultima linie de antet.] +> 💡 **Feedback:** For the shown HTTP/1.1 message, each field line ends with CRLF and the following empty line ends the header section. This is distinct from message-body length, which depends on method/status and framing fields. HTTP/2 and HTTP/3 use binary framing, not this text separator. [În mesajul HTTP/1.1 prezentat, fiecare linie de antet se termină cu CRLF, iar linia goală următoare încheie secțiunea antetelor. Acest lucru este distinct de lungimea corpului, determinată de metodă/cod și câmpurile de încadrare. HTTP/2 și HTTP/3 folosesc încadrare binară, nu acest separator textual.] --- @@ -626,7 +636,7 @@ Step 3 (Client → Server): [[3]] ### 46. `Drag & Drop into Text` **N08.D05.Q02: TCP server socket lifecycle / Ciclul de viață al socket-ului server TCP** -> Complete the correct order of socket calls to set up a TCP server in 3b_socket-http-server_example.py. [Completați ordinea corectă a apelurilor socket pentru configurarea unui server TCP în 3b_socket-http-server_example.py.] +> Complete the correct order of socket calls to set up a TCP server in 04_SEMINARS/S08/3_socket-http/S08_Part03B_Example_Socket_HTTP_Server.py. [Completați ordinea corectă a apelurilor socket pentru configurarea unui server TCP în 04_SEMINARS/S08/3_socket-http/S08_Part03B_Example_Socket_HTTP_Server.py.] > s = socket.socket(AF_INET, SOCK_STREAM) @@ -734,27 +744,27 @@ In the TCP handshake, the client first sends [[1]], the server responds with [[2 **N08.D10.Q02: Socket option preventing address reuse errors / Opțiunea de socket care previne erorile de reutilizare a adresei** ``` -Before calling bind(), the exercise sets the [[1]] socket option to value [[2]] to prevent port reuse errors after server restart. [Înainte de apelul bind(), exercițiul setează opțiunea de socket ___ la valoarea ___ pentru a preveni erorile de reutilizare a portului după repornirea serverului.] +Before calling bind(), the exercise sets the [[1]] socket option to value [[2]] to support rebinding an address after restart, subject to the operating system's binding rules. [Înainte de apelul bind(), exercițiul setează opțiunea de socket ___ la valoarea ___ pentru a permite relegarea adresei după repornire, conform regulilor sistemului de operare.] ``` **Available choices / Variante disponibile: SO_REUSEADDR | 1 | SO_KEEPALIVE | 0** -> 💡 **Feedback:** SO_REUSEADDR with value 1 allows immediate port reuse. Without it, the port stays in TIME_WAIT state after server shutdown. [SO_REUSEADDR cu valoarea 1 permite reutilizarea imediată a portului. Fără ea, portul rămâne în starea TIME_WAIT după oprirea serverului.] +> 💡 **Feedback:** Fill SO_REUSEADDR and 1. It can permit rebinding when previous accepted TCP connections leave relevant TIME_WAIT state. A listening port itself is not a TIME_WAIT connection, and restart does not always fail without this option. It does not generally permit a second active listener to take an occupied address; semantics vary by operating system. [Completați SO_REUSEADDR și 1. Poate permite relegarea când conexiuni TCP acceptate anterior lasă stare TIME_WAIT relevantă. Portul de ascultare în sine nu este o conexiune TIME_WAIT, iar repornirea nu eșuează întotdeauna fără această opțiune. În general nu permite unui al doilea listener activ să preia o adresă ocupată; semantica diferă între sisteme.] --- ### 53. `Gap Select` **N08.D10.Q03: HTTP message separator / Separatorul mesajelor HTTP** +```text +In HTTP/1.1, field lines end with [[1]]. An additional empty line produces [[2]] after the final field line and ends the header section. +[În HTTP/1.1, liniile câmpurilor se termină cu [[1]]. O linie goală suplimentară produce [[2]] după ultimul câmp și încheie secțiunea antetelor.] ``` -HTTP headers are separated from the body by a blank line, which consists of two consecutive [[1]] sequences, forming the pattern [[2]]. [Antetele HTTP sunt separate de corp printr-o linie goală, care constă din două secvențe ___ consecutive, formând modelul ___.] -``` - -**Available choices / Variante disponibile: CRLF | \r\n\r\n | LF | \n\n** +**Available choices / Variante disponibile: CRLF | \r\n\r\n | LF | \n\n** -> 💡 **Feedback:** Headers end with CRLF, then the blank line is another CRLF, making \r\n\r\n the boundary between headers and body. [Antetele se termină cu CRLF, apoi linia goală este un alt CRLF, făcând \r\n\r\n limita dintre antete și corp.] +> 💡 **Feedback:** CRLF and \r\n\r\n. This identifies the header boundary, not the length or existence of response content; HEAD and some status codes have no content. [CRLF și \r\n\r\n. Acesta identifică limita antetelor, nu lungimea sau existența conținutului; HEAD și unele coduri de stare nu au conținut.] --- @@ -785,3 +795,10 @@ In the three-way handshake, the client first sends [[1]], the server responds wi > 💡 **Feedback:** Three-way handshake: SYN (client initiates) -> SYN-ACK (server acknowledges and synchronises) -> ACK (client confirms, connection established). [Handshake în trei pași: SYN (clientul inițiază) -> SYN-ACK (serverul confirmă și sincronizează) -> ACK (clientul confirmă, conexiunea este stabilită).] --- + + +## Repository context and reference points + +Canonical practical material: [S08](../../04_SEMINARS/S08/README.md) — HTTP testing, built-in and socket servers, Nginx. Code-tracing models explicitly introduced in this question pool are self-contained exercises, not promises of additional files or features in that seminar. [Material practic canonic: S08. Modelele de trasare introduse explicit sunt exerciții autonome, nu promisiuni de fișiere sau funcții suplimentare în seminar.] + +Protocol semantics: RFC 9110, *HTTP Semantics*. https://doi.org/10.17487/RFC9110 diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W09_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W09_Questions.md index 30b91e3..1b42398 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W09_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W09_Questions.md @@ -119,17 +119,22 @@ --- -### Q9. `Multiple Choice` -**Variable-Length Data Encoding Approaches / Abordări de codificare a datelor cu lungime variabilă** +### Q9. — Variable-Length Data Encoding Approaches / Abordări de codificare a datelor cu lungime variabilă -> A developer needs to transmit variable-length strings over a binary protocol. Which approach correctly handles arbitrary-length data in a Presentation Layer encoding scheme? [Un dezvoltator trebuie să transmită șiruri de caractere cu lungime variabilă printr-un protocol binar. Care abordare gestionează corect datele cu lungime arbitrară într-o schemă de codificare a Stratului prezentare?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) Length-prefixed: a 4-byte integer indicating string length, then that many UTF-8 bytes [Cu prefix de lungime: un întreg pe 4 octeți indicând lungimea șirului, apoi acel număr de octeți UTF-8]** -- **b) Fixed-width: pad all strings to 256 bytes regardless of actual length [Lățime fixă: completarea tuturor șirurilor la 256 de octeți indiferent de lungimea reală]** -- **c) Delimiter-based: end every string with the reserved byte 0xFF, which cannot appear inside payload data [Bazat pe delimitator: terminarea fiecărui șir cu octetul rezervat 0xFF, care nu poate apărea în datele utile]** -- **d) Implicit-length: the receiver infers the string length from the TCP segment size [Lungime implicită: receptorul deduce lungimea șirului din dimensiunea segmentului TCP]** +A protocol must encode arbitrary byte strings, including every possible byte value, up to 1 MiB. It forbids delimiters and padding. Which design meets these constraints? [Un protocol trebuie să codifice șiruri arbitrare de octeți, inclusiv orice valoare de octet, până la 1 MiB. Nu permite delimitatori sau completare. Ce proiectare respectă cerințele?] -> 💡 **Feedback:** Length-prefixed encoding (e.g., a 4-byte length field followed by that many bytes of UTF-8 data) is the standard Presentation Layer approach for variable-length data. A common misconception is that inferring message length from the TCP segment size works — but TCP is a byte stream with no message boundaries, so segment sizes are unreliable indicators of application message length. [Codificarea cu prefix de lungime (de ex. un câmp de 4 octeți indicând lungimea, urmat de acel număr de octeți de date UTF-8) este abordarea standard a Stratului prezentare pentru date cu lungime variabilă. O concepție greșită frecventă este că lungimea mesajului poate fi dedusă din dimensiunea segmentului TCP — dar TCP este un flux de octeți fără delimitarea mesajelor, deci dimensiunile segmentelor nu sunt indicatori fiabili ai lungimii mesajelor aplicației.] +- **a)** A four-byte unsigned length in a specified byte order, followed by exactly that many bytes, with a 1 MiB receiver limit [O lungime fără semn pe patru octeți în ordinea specificată, urmată de exact acel număr de octeți, cu limită de 1 MiB la receptor] +- **b)** Pad every payload to exactly 256 bytes [Completează orice payload până la exact 256 de octeți] +- **c)** Append unescaped 0xFF as the only delimiter [Adaugă 0xFF ne-escapat drept unic delimitator] +- **d)** Infer the message length from the TCP segment size [Deduce lungimea mesajului din dimensiunea segmentului TCP] + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The explicit contract makes length-prefixing the unique valid choice here. Delimiter protocols can also be valid when their alphabet or escaping rules guarantee an unambiguous delimiter; 0xFF does not occur in valid UTF-8, so the earlier UTF-8-only wording admitted another answer. A four-byte field is bounded, not an unlimited-length encoding. [Contractul explicit face prefixul de lungime unica opțiune validă aici. Și delimitatorii pot fi corecți dacă alfabetul sau regulile de escapare garantează delimitarea neambiguă; 0xFF nu apare în UTF-8 valid, deci formularea anterioară limitată la UTF-8 admitea alt răspuns. Un câmp pe patru octeți este limitat, nu o codificare de lungime nelimitată.] + +
    --- @@ -361,7 +366,7 @@ - **a) true** - **b) false** -> 💡 **Feedback:** True. CRC-32 reliably detects all single-bit errors, all double-bit errors, and all burst errors shorter than 32 bits. It is purpose-built for accidental error detection at the Presentation Layer. A common misconception is that CRC-32 also provides security against intentional tampering, but it only addresses random transmission errors. [Adevărat. CRC-32 detectează fiabil toate erorile de un singur bit, toate erorile de doi biți și toate erorile de tip rafală mai scurte de 32 de biți. Este construit special pentru detecția erorilor accidentale la Stratul prezentare. O concepție greșită frecventă este că CRC-32 oferă și securitate împotriva falsificării intenționate, dar abordează doar erorile aleatoare de transmisie.] +> 💡 **Feedback:** True for the standard CRC-32 polynomial used by zlib: all single-bit errors are detected. A degree 32 CRC also detects every burst of length at most 32 bits. Multi-bit guarantees depend on the generator and protected length. CRC is used at several layers and provides no cryptographic authenticity. [Adevărat pentru polinomul CRC-32 standard folosit de zlib: toate erorile de un bit sunt detectate. Un CRC de grad 32 detectează și orice rafală de lungime cel mult 32 de biți. Garanțiile pentru mai mulți biți depind de polinom și lungimea protejată. CRC este folosit la mai multe niveluri și nu oferă autenticitate criptografică.] --- @@ -427,12 +432,12 @@ ### Q31. `True / False` **Closing FTP Control Channel Immediately Stops Data Transfer / Închiderea canalului de control FTP oprește imediat transferul de date** -> If the FTP control connection is closed during an active file download, the data transfer stops immediately. [Dacă conexiunea de control FTP este închisă în timpul unei descărcări active de fișier, transferul de date se oprește imediat.] +> Closing the FTP control TCP connection automatically closes the separate data TCP connection at the transport layer, at the same instant. [Închiderea conexiunii TCP de control FTP închide automat conexiunea TCP separată de date la nivel de transport, în același moment.] -- **a) true** -- **b) false** +- **a) true** +- **b) false** -> 💡 **Feedback:** False. The data channel is a separate TCP connection with its own state. Closing the control channel does not immediately terminate an in-progress data transfer, though you lose the ability to receive the 226 completion confirmation or issue an ABOR command. A common misconception is that closing the control channel kills all associated connections, but TCP connections are independent at the transport level. [Fals. Canalul de date este o conexiune TCP separată cu propria stare. Închiderea canalului de control nu termină imediat un transfer de date în curs, deși pierdeți capacitatea de a primi confirmarea de finalizare 226 sau de a emite o comandă ABOR. O concepție greșită frecventă este că închiderea canalului de control oprește toate conexiunile asociate, dar conexiunile TCP sunt independente la nivelul de transport.] +> 💡 **Feedback:** False. TCP connections are independent. However, this does not guarantee that an FTP server will let the transfer continue: RFC 959 permits the server to abort a transfer when control closes without a command; orderly QUIT during a transfer has different handling. Application policy and event timing determine the observable behaviour. [Fals. Conexiunile TCP sunt independente. Aceasta nu garantează însă continuarea transferului FTP: RFC 959 permite serverului să anuleze transferul când controlul se închide fără comandă; QUIT ordonat în timpul transferului are alt tratament. Politica aplicației și temporizarea evenimentelor determină comportamentul observabil.] --- @@ -450,17 +455,22 @@ --- -### Q33. `Multiple Choice` -**When Session Layer Becomes Active in a Wireshark Capture / Când devine activ Stratul sesiune într-o captură Wireshark** +### Q33. — When Session Layer Becomes Active in a Wireshark Capture / Când devine activ Stratul sesiune într-o captură Wireshark + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In a Wireshark capture of an FTP connection, you observe: Packet 1–3: TCP three-way handshake; Packet 4: "220 FTP Server Ready"; Packet 5: "USER test". At which packet does Session Layer activity begin? [Într-o captură Wireshark a unei conexiuni FTP, observați: Pachetele 1–3: handshake TCP în trei pași; Pachetul 4: «220 FTP Server Ready»; Pachetul 5: «USER test». La care pachet începe activitatea Stratului sesiune?] +A trace shows TCP SYN/SYN-ACK/ACK, then an FTP 220 greeting, then USER test. Which is the first listed FTP application-protocol message? [O captură arată TCP SYN/SYN-ACK/ACK, apoi salutul FTP 220, apoi USER test. Care este primul mesaj FTP de aplicație din listă?] -- **a) Packet 5 — when the USER command initiates authentication [Pachetul 5 — când comanda USER inițiază autentificarea]** -- **b) Packet 1 — when the TCP SYN initiates the connection [Pachetul 1 — când TCP SYN inițiază conexiunea]** -- **c) Packet 3 — when the TCP three-way handshake completes [Pachetul 3 — când se completează handshake-ul TCP în trei pași]** -- **d) Packet 4 — when the FTP server sends its welcome banner [Pachetul 4 — când serverul FTP trimite banner-ul de întâmpinare]** +- **a)** The220 greeting [Salutul220] +- **b)** The TCP SYN [SYN-ul TCP] +- **c)** Only USER test counts as application data [Doar USER test este date de aplicație] +- **d)** None: FTP is a TCP control flag [Niciunul: FTP este un fanion de control TCP] -> 💡 **Feedback:** The TCP handshake (packets 1–3) is Transport Layer. The server banner (packet 4) is still transport-level data delivery. Session Layer activity begins with the USER command (packet 5), which initiates the authentication dialogue. A common misconception is that the TCP handshake constitutes session establishment, but TCP only establishes a transport connection — the session begins when application-level authentication starts. [Handshake-ul TCP (pachetele 1–3) este la Stratul de transport. Banner-ul serverului (pachetul 4) este încă livrare de date la nivel de transport. Activitatea Stratului sesiune începe cu comanda USER (pachetul 5), care inițiază dialogul de autentificare. O concepție greșită frecventă este că handshake-ul TCP constituie stabilirea sesiunii, dar TCP stabilește doar o conexiune de transport — sesiunea începe când pornește autentificarea la nivel de aplicație.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** FTP greeting and commands are application messages carried by TCP. Session/presentation functions can be discussed conceptually, but there is no separate OSI-session packet whose universal start can be inferred from USER. Transport delivery does not turn a 220 FTP greeting into transport-layer control. [Salutul și comenzile FTP sunt mesaje de aplicație transportate prin TCP. Funcțiile de sesiune/prezentare pot fi discutate conceptual, dar nu există un pachet separat OSI-sesiune al cărui început universal să fie dedus din USER. Transportul nu transformă salutul FTP 220 în control la nivel de transport.] + +
    --- @@ -495,7 +505,7 @@ ### Q36. `Multiple Choice` **Correct recv_exactly Implementation / Implementarea corectă a funcției recv_exactly** -> Which implementation correctly receives exactly n bytes from a TCP socket, handling partial reads? [Care implementare primește corect exact n octeți de la un socket TCP, gestionând citirile parțiale?] +> Which implementation correctly receives exactly n bytes from a TCP socket, handling partial reads and raising an error on premature EOF? [Care implementare primește corect exact n octeți de la un socket TCP, gestionând citirile parțiale și semnalând EOF prematur prin eroare?] - **a) Loop calling sock.recv(n - len(data)) until n bytes are accumulated, raising on empty recv [Iterare apelând sock.recv(n - len(data)) până la n octeți acumulați, eroare la recv gol]** - **b) A single call to sock.recv(n) which always returns exactly n bytes [Un singur apel la sock.recv(n) care returnează întotdeauna exact n octeți]** @@ -506,18 +516,28 @@ --- -### Q37. `Multiple Choice` -**Output of struct.pack("<H", 0x1234) / Rezultatul struct.pack("<H", 0x1234)** +### Q37. — Output of struct.pack("< H", 0x1234) / Rezultatul struct.pack("< H", 0x1234) + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +What bytes does this complete Python example produce? [Ce octeți produce acest exemplu Python complet?] + +```python +import struct +data = struct.pack(" What byte sequence does the following Python code produce? [Ce secvență de octeți produce următorul cod Python?]import struct -data = struct.pack(" +- **a)** 34 12 +- **b)** 12 34 +- **c)** 00 12 34 +- **d)** 34 12 00 00 -- **a) 34 12** -- **b) 12 34** -- **c) 00 12 34** -- **d) 34 12 00 00** +
    💡 Feedback -> 💡 **Feedback:** The format " +**Correct answer / Răspuns corect: a.** The < prefix specifies little-endian standard sizes and H is an unsigned two-byte integer. The low byte0x34 precedes 0x12, independently of native byte order. [Prefixul < specifică little-endian cu dimensiuni standard, iar H este un întreg fără semn pe doi octeți. Octetul inferior0x34 precedă 0x12, independent de ordinea nativă.] + +
    --- @@ -549,20 +569,24 @@ data = struct.pack(" --- -### Q40. `Multiple Choice` -**CRC-32 Mask in Python / Masca CRC-32 în Python** +### Q40. — CRC-32 Mask in Python / Masca CRC-32 în Python -> When computing CRC-32 in Python with zlib.crc32(data) , why is the result masked with & 0xFFFFFFFF ? [Când se calculează CRC-32 în Python cu zlib.crc32(data) , de ce se aplică masca & 0xFFFFFFFF asupra rezultatului?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) To ensure the result is unsigned 32-bit, since some platforms return a signed integer [Pentru a asigura un rezultat fără semn pe 32 de biți, deoarece unele platforme returnează un întreg cu semn]** -- **b) To truncate the CRC from 64 bits to 32 bits for efficiency [Pentru a trunchia CRC-ul de la 64 biți la 32 biți pentru eficiență]** -- **c) To add cryptographic security to the checksum [Pentru a adăuga securitate criptografică sumei de control]** -- **d) To convert the CRC-32 checksum from big-endian network order to little-endian host format [Pentru a converti suma de control CRC-32 din ordinea de rețea big-endian în formatul little-endian al gazdei]** +For Python 3 zlib.crc32(data), what effect does &0xFFFFFFFF have on the returned checksum? [Pentru zlib.crc32(data) în Python 3, ce efect are &0xFFFFFFFF asupra sumei returnate?] -> 💡 **Feedback:** On some Python versions, zlib.crc32() may return a signed integer. Masking with 0xFFFFFFFF ensures a consistent unsigned 32-bit result across all platforms. A common misconception is that this mask adds cryptographic security or performs byte-order conversion — it is purely a cross-platform compatibility measure. [Pe unele versiuni Python, zlib.crc32() poate returna un întreg cu semn. Mascarea cu 0xFFFFFFFF asigură un rezultat consistent fără semn pe 32 de biți pe toate platformele. O concepție greșită frecventă este că această mască adaugă securitate criptografică sau efectuează conversia ordinii octeților — este pur și simplu o măsură de compatibilitate între platforme.] +- **a)** It leaves the already unsigned 32-bit result unchanged; it remains useful in code also supporting old Python 2 behaviour [Lasă neschimbat rezultatul deja fără semn pe 32 de biți; rămâne util în cod care acceptă și comportamentul vechi Python 2] +- **b)** It converts the checksum to little-endian bytes [Convertește suma în octeți little-endian] +- **c)** It adds cryptographic authentication [Adaugă autentificare criptografică] +- **d)** It doubles the checksum width [Dublează lățimea sumei] ---- +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Python documentation states that crc32 returns an unsigned value since Python 3.0. The mask is redundant for a normal Python 3 result; masking an integer does not serialise it or provide a secret key. [Documentația Python precizează că crc32 returnează o valoare fără semn începând cu Python 3.0. Masca este redundantă pentru rezultatul normal Python 3; mascarea unui întreg nu îl serializează și nu introduce o cheie secretă.] +
    + +--- ## §3. Numerical (Răspuns numeric) (13 questions) @@ -721,3 +745,12 @@ data = struct.pack(" > 💡 **Feedback:** Header = 2+1+1+4+4 = 12 bytes. Payload = 5 bytes ("Hello"). Total = 12 + 5 = (...) bytes. A common misconception is to assume padding is added to align the total to a power of 2, but binary protocols typically use exact sizes without padding. [Antet = 2+1+1+4+4 = 12 octeți. Sarcină utilă = 5 octeți («Hello»). Total = 12 + 5 = (...) octeți. O concepție greșită frecventă este presupunerea că se adaugă spațiere (padding) pentru a alinia totalul la o putere a lui 2, dar protocoalele binare folosesc de obicei dimensiuni exacte fără padding.] --- + + +## Repository context and reference points + +Canonical practical material: [S09](../../04_SEMINARS/S09/README.md) — FTP and the custom pseudo-FTP exercises. Code-tracing models explicitly introduced in this question pool are self-contained exercises, not promises of additional files or features in that seminar. [Material practic canonic: S09. Modelele de trasare introduse explicit sunt exerciții autonome, nu promisiuni de fișiere sau funcții suplimentare în seminar.] + +Protocol semantics: RFC 959, *File Transfer Protocol*. https://doi.org/10.17487/RFC0959 + +Python3 checksum and encoding API: [zlib](https://docs.python.org/3/library/zlib.html) and [struct](https://docs.python.org/3/library/struct.html). diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W10_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W10_Questions.md index 1e5a970..93bafe3 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W10_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W10_Questions.md @@ -48,17 +48,22 @@ --- -### 4. `Multiple Choice – Alegere multiplă` -**N10.C01.Q05: TLS handshake step ordering / Ordinea pașilor handshake-ului TLS** +### Q4. `N10.C01.Q05` — TLS handshake step ordering / Ordinea pașilor handshake-ului TLS -> Which sequence correctly describes the TLS handshake steps? [Care secvență descrie corect pașii handshake-ului TLS?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) Client Hello → Server Hello + Certificate → Key Exchange → Encrypted Data [Client Hello → Server Hello + Certificat → Schimb de chei → Date criptate]** -- **b) Key Exchange → Client Hello → Server Hello → Encrypted Data — an assertion that does not align with the actual specification requirements [Schimb de chei → Client Hello → Server Hello → Date criptate — o afirmație ce nu corespunde cerințelor reale ale specificației]** -- **c) Server Hello → Client Hello → Encrypted Data → Key Exchange [Server Hello → Client Hello → Date criptate → Schimb de chei]** -- **d) Client Hello → Encrypted Data → Server Hello → Key Exchange [Client Hello → Date criptate → Server Hello → Schimb de chei]** +Which simplified message ordering is valid for a full, server-authenticated TLS 1.3 handshake with no resumption, HelloRetryRequest, client certificate or 0-RTT? Application data is omitted. [Ce ordine simplificată este validă pentru un handshake TLS 1.3 complet, cu autentificarea serverului, fără reluare, HelloRetryRequest, certificat client sau 0-RTT? Datele aplicației sunt omise.] -> 💡 **Feedback:** The TLS handshake proceeds: Client Hello (offering cipher suites) → Server Hello (choosing cipher suite and sending certificate) → Key exchange (deriving symmetric key) → Encrypted data begins. A common misconception is that encryption starts immediately or that the key exchange occurs before the hello messages, but the hello phase must first negotiate parameters before any cryptographic material is exchanged. [Handshake-ul TLS se desfășoară astfel: Client Hello (propunând suite de cifrare) → Server Hello (alegând suita de cifrare și trimițând certificatul) → Schimb de chei (derivând cheia simetrică) → Încep datele criptate. O concepție greșită frecventă este că criptarea începe imediat sau că schimbul de chei are loc înaintea mesajelor hello, dar faza hello trebuie să negocieze mai întâi parametrii înainte de schimbul oricărui material criptografic.] +- **a)** ClientHello (key_share) → ServerHello (key_share) → encrypted EncryptedExtensions, Certificate, CertificateVerify, Finished → client Finished +- **b)** ServerHello → ClientHello → client Finished → Certificate +- **c)** ClientHello → plaintext Certificate → ServerHello → ClientKeyExchange +- **d)** ClientHello → application plaintext → ServerHello → Finished + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** TLS 1.3 exchanges ephemeral key shares in the hello messages. Handshake messages after ServerHello are encrypted; CertificateVerify authenticates the server signature and Finished authenticates the handshake transcript. ClientKeyExchange is a TLS 1.2 message, not a TLS 1.3 step. See RFC 9846 §2 (which supersedes RFC 8446). [TLS 1.3 schimbă componentele efemere de cheie în mesajele hello. Mesajele handshake după ServerHello sunt criptate; CertificateVerify autentifică semnătura serverului, iar Finished autentifică transcrierea handshake-ului. ClientKeyExchange aparține TLS 1.2, nu TLS 1.3. Vezi RFC 9846 §2, care înlocuiește RFC 8446.] + +
    --- @@ -100,31 +105,41 @@ --- -### 8. `Multiple Choice – Alegere multiplă` -**N10.C02.Q02: Identifying Richardson Maturity Level for action-style endpoints / Identificarea nivelului de maturitate Richardson pentru endpoint-uri cu acțiuni în cale** +### Q8. `N10.C02.Q02` — Identifying Richardson Maturity Level for action-style endpoints / Identificarea nivelului de maturitate Richardson pentru endpoint-uri cu acțiuni în cale + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> An API exposes the endpoint POST /api/users/123/delete. According to the Richardson Maturity Model, which level does this represent? [Un API expune endpoint-ul POST /api/users/123/delete. Conform Modelului de Maturitate Richardson, ce nivel reprezintă?] +An API has distinct resource URIs such as /users/123 and /orders/7. Every operation uses POST and successful or failed application outcomes are returned inside 200 bodies. There are no hypermedia controls. What Richardson level is demonstrated? [Un API are URI-uri distincte pentru resurse, precum /users/123 și /orders/7. Toate operațiile folosesc POST, iar succesul sau eșecul aplicației sunt în corpuri 200. Nu există controale hypermedia. Ce nivel Richardson este demonstrat?] -- **a) Level 1 — Resources with URIs but action-style naming [Nivelul 1 — Resurse cu URI-uri, dar denumire de tip acțiune]** -- **b) Level 0 — RPC-style single endpoint [Nivelul 0 — Endpoint unic în stil RPC]** -- **c) Level 2 — Proper HTTP verbs with semantic status codes and resource-oriented URIs [Nivelul 2 — Verbe HTTP corecte cu coduri de stare semantice și URI-uri orientate pe resurse]** -- **d) Level 3 — Full HATEOAS compliance [Nivelul 3 — Conformitate HATEOAS completă]** +- **a)** Level 1: resource identities, without the method/status semantics of Level 2 [Nivelul1: identitatea resurselor, fără semantica metodelor/codurilor de la nivelul 2] +- **b)** Level 0 because every URI is identical [Nivelul0 deoarece toate URI-urile sunt identice] +- **c)** Level 2 because any use of POST proves correct HTTP semantics [Nivelul2 deoarece orice folosire POST dovedește semantica HTTP corectă] +- **d)** Level 3 because numeric IDs are hypermedia [Nivelul3 deoarece ID-urile numerice sunt hypermedia] -> 💡 **Feedback:** The endpoint uses resource URIs (/api/users/123) but encodes the action in the URL path (/delete) instead of using the HTTP DELETE verb. This is characteristic of Level 1, where resources are identified but HTTP verbs are not used semantically. A common misconception is placing this at Level 2, but Level 2 requires proper use of HTTP verbs (DELETE instead of POST with /delete in the path). [Endpoint-ul folosește URI-uri de resurse (/api/users/123), dar codifică acțiunea în calea URL (/delete) în loc să utilizeze verbul HTTP DELETE. Aceasta este caracteristic Nivelului 1, unde resursele sunt identificate, dar verbele HTTP nu sunt utilizate semantic. O concepție greșită frecventă este plasarea acestuia la Nivelul 2, dar Nivelul 2 necesită utilizarea corectă a verbelor HTTP (DELETE în loc de POST cu /delete în cale).] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The complete API description supports Level 1. A single action-like path does not establish a maturity level; HTTP POST can legitimately perform application-specific actions. Level 2 adds meaningful HTTP methods/statuses and Level 3 adds hypermedia controls. [Descrierea completă a API-ului susține nivelul 1. O singură cale denumită ca acțiune nu stabilește nivelul; POST poate efectua legitim acțiuni specifice aplicației. Nivelul2 adaugă semantica HTTP a metodelor/codurilor, iar nivelul 3 controale hypermedia.] + +
    --- -### 9. `Multiple Choice – Alegere multiplă` -**N10.C02.Q03: HTTP status code for successful resource creation / Codul de stare HTTP pentru crearea cu succes a unei resurse** +### Q9. `N10.C02.Q03` — HTTP status code for successful resource creation / Codul de stare HTTP pentru crearea cu succes a unei resurse -> In a REST Level 2 API, a client sends POST /api/resources with a valid JSON body and a new resource is created. What HTTP status code should the server return? [Într-un API REST de Nivelul 2, un client trimite POST /api/resources cu un corp JSON valid și o nouă resursă este creată. Ce cod de stare HTTP ar trebui să returneze serverul?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) 201 Created** -- **b) 200 OK** -- **c) 204 No Content** -- **d) 301 Moved Permanently** +A request has completed and created a new resource. Which status explicitly communicates that outcome? [O cerere s-a încheiat și a creat o resursă nouă. Ce cod comunică explicit acest rezultat?] + +- **a)** 201 Created +- **b)** 200 OK +- **c)** 204 No Content +- **d)** 301 Moved Permanently -> 💡 **Feedback:** HTTP 201 Created is the semantically correct status code for successful resource creation. 200 OK is used for successful GET/PUT, and 204 No Content is typically used for DELETE. A common misconception is using 200 OK for all successful operations, but REST Level 2 requires using specific status codes that convey precise semantics about the outcome. [HTTP 201 Created este codul de stare semantic corect pentru crearea cu succes a unei resurse. 200 OK se folosește pentru GET/PUT reușite, iar 204 No Content se folosește de obicei pentru DELETE. O concepție greșită frecventă este utilizarea 200 OK pentru toate operațiunile reușite, dar REST de Nivelul 2 necesită utilizarea codurilor de stare specifice care transmit semantici precise despre rezultat.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** 201 identifies successful creation. Location can identify the primary new resource.200 is general success and 204 is success without response content; neither is universally tied to GET/PUT or DELETE. Status choice follows the actual outcome, not a rigid one-method/one-code mapping. [201 identifică o creare reușită. Location poate identifica resursa principală nouă.200 reprezintă succes general, iar 204 succes fără conținut în răspuns; acestea nu sunt legate universal de GET/PUT sau DELETE. Codul se alege după rezultat, nu printr-o corespondență rigidă metodă/cod.] + +
    --- @@ -138,21 +153,26 @@ - **c) All endpoints require OAuth 2.0 authentication [Toate endpoint-urile necesită autentificare OAuth 2.0]** - **d) The API supports real-time WebSocket push connections alongside standard request-response patterns [API-ul acceptă conexiuni WebSocket în timp real alături de modelele standard cerere-răspuns]** -> 💡 **Feedback:** Level 3 adds HATEOAS — responses include hypermedia links (e.g., _links) that tell the client what actions and related resources are available, enabling discovery without hardcoded URLs. A common misconception is that using JSON as the response format or adding authentication qualifies as Level 3, but HATEOAS specifically requires navigable hypermedia links in every response. [Nivelul 3 adaugă HATEOAS — răspunsurile includ legături hypermedia (de ex., _links) care informează clientul despre acțiunile și resursele asociate disponibile, permițând descoperirea fără URL-uri codificate fix. O concepție greșită frecventă este că utilizarea JSON ca format de răspuns sau adăugarea autentificării califică un API la Nivelul 3, dar HATEOAS necesită în mod specific legături hypermedia navigabile în fiecare răspuns.] +> 💡 **Feedback:** Richardson Level 3 adds hypermedia controls describing available transitions and related resources. Clients still need an entry point and knowledge of media types/link relations. It does not require a body containing links in literally every response: for example,204 has no content. JSON or authentication alone does not establish Level 3. [Nivelul Richardson3 adaugă controale hypermedia care descriu tranzițiile disponibile și resursele asociate. Clienții au nevoie în continuare de un punct de intrare și de semantica tipurilor media/relațiilor. Nu cere un corp cu legături în absolut fiecare răspuns: de exemplu 204 nu are conținut. JSON sau autentificarea singure nu stabilesc nivelul 3.] --- -### 11. `Multiple Choice – Alegere multiplă` -**N10.C02.Q05: Idempotency of HTTP methods / Idempotența metodelor HTTP** +### Q11. `N10.C02.Q05` — Idempotency of HTTP methods / Idempotența metodelor HTTP + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Which method does HTTP not guarantee to be idempotent: repeated identical requests need not have the same intended server effect as one request? [Pentru care metodă HTTP nu garantează idempotența: cererile identice repetate nu trebuie să aibă același efect intenționat ca una singură?] -> Which HTTP method is not idempotent, meaning multiple identical requests may produce different results each time? [Care metodă HTTP nu este idempotentă, ceea ce înseamnă că mai multe cereri identice pot produce rezultate diferite de fiecare dată?] +- **a)** POST +- **b)** GET +- **c)** PUT +- **d)** DELETE -- **a) POST** -- **b) GET** -- **c) PUT** -- **d) DELETE** +
    💡 Feedback -> 💡 **Feedback:** POST is not idempotent — sending the same POST request twice creates two separate resources. GET, PUT, and DELETE are all idempotent: repeating them yields the same outcome. A common misconception is that PUT and POST are interchangeable, but PUT is idempotent (replacing a resource at a specific URI produces the same result regardless of repetition) while POST is not. [POST nu este idempotent — trimiterea aceleiași cereri POST de două ori creează două resurse separate. GET, PUT și DELETE sunt toate idempotente: repetarea lor produce același rezultat. O concepție greșită frecventă este că PUT și POST sunt interschimbabile, dar PUT este idempotent (înlocuirea unei resurse la un URI specific produce același rezultat indiferent de repetare), în timp ce POST nu este.] +**Correct answer / Răspuns corect: a.** POST is not guaranteed idempotent by its method semantics, although an application may provide idempotent operations or an idempotency-key contract. GET, PUT and DELETE are idempotent in intended effect. Responses, timestamps and incidental logging can differ across repetitions. [POST nu garantează idempotența prin semantica metodei, deși aplicația poate oferi operații idempotente sau un contract cu cheie de idempotență. GET, PUT și DELETE sunt idempotente ca efect intenționat. Răspunsurile, marcajele de timp și jurnalizarea incidentală pot diferi între repetări.] + +
    --- @@ -182,17 +202,22 @@ --- -### 14. `Multiple Choice – Alegere multiplă` -**N10.C02.Q09: CRUD to HTTP verb mapping / Corespondența CRUD cu verbele HTTP** +### Q14. `N10.C02.Q09` — CRUD to HTTP verb mapping / Corespondența CRUD cu verbele HTTP + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +For an API that creates a resource at a server-selected URI, retrieves a representation, fully replaces a resource at a known URI and removes that resource, which conventional mapping fits? [Pentru un API care creează o resursă la un URI ales de server, citește reprezentarea, înlocuiește complet resursa de la un URI cunoscut și o elimină, ce corespondență convențională este adecvată?] + +- **a)** Create via collection POST; read via GET; full replacement via PUT; remove via DELETE +- **b)** Create via GET; read via POST; replace via DELETE; remove via PUT +- **c)** Create via HEAD; read via OPTIONS; replace via GET; remove via PATCH +- **d)** Use GET for every state-changing operation -> In a RESTful API, the CRUD operations map to HTTP verbs. Which mapping is correct? [Într-un API RESTful, operațiunile CRUD corespund verbelor HTTP. Care corespondență este corectă?] +
    💡 Feedback -- **a) Create → POST, Read → GET, Update → PUT, Delete → DELETE** -- **b) Create → PUT, Read → GET, Update → POST, Delete → DELETE** -- **c) Create → POST, Read → HEAD, Update → PATCH, Delete → OPTIONS** -- **d) Create → GET, Read → POST, Update → DELETE, Delete → PUT** +**Correct answer / Răspuns corect: a.** These assumptions make the mapping unambiguous. PUT may also create a resource at a client-chosen URI; POST is a general processing method, not a synonym for create. PATCH applies partial modification instructions and is not guaranteed idempotent. [Ipotezele fac corespondența neambiguă. PUT poate și crea o resursă la un URI ales de client; POST este o metodă generală de procesare, nu un sinonim pentru creare. PATCH aplică instrucțiuni de modificare parțială și nu garantează idempotența.] -> 💡 **Feedback:** The standard CRUD-to-HTTP mapping is: Create → POST, Read → GET, Update → PUT (full replacement) or PATCH (partial), Delete → DELETE. A common misconception is reversing Create and Update verbs or confusing PUT with POST, but POST creates new resources (non-idempotent) while PUT replaces an entire resource at a specific URI (idempotent). [Corespondența standard CRUD-HTTP este: Create → POST, Read → GET, Update → PUT (înlocuire completă) sau PATCH (parțial), Delete → DELETE. O concepție greșită frecventă este inversarea verbelor Create și Update sau confundarea PUT cu POST, dar POST creează resurse noi (non-idempotent), în timp ce PUT înlocuiește o resursă întreagă la un URI specific (idempotent).] +
    --- @@ -206,7 +231,7 @@ - **c) TCP only for reliability [Doar TCP pentru fiabilitate]** - **d) UDP on port 53 for standard queries with TCP on port 80 for larger responses [UDP pe portul 53 pentru interogări standard cu TCP pe portul 80 pentru răspunsuri mai mari]** -> 💡 **Feedback:** DNS uses both UDP (for standard queries, efficient for small responses) and TCP (for large responses exceeding 512 bytes, zone transfers via AXFR/IXFR, and when the TC bit is set). A common misconception is that DNS uses only UDP, but TCP is essential for zone transfers and large responses such as those with DNSSEC records. [DNS folosește atât UDP (pentru interogări standard, eficient pentru răspunsuri mici), cât și TCP (pentru răspunsuri mari care depășesc 512 de octeți, transferuri de zonă prin AXFR/IXFR și când bitul TC este setat). O concepție greșită frecventă este că DNS folosește doar UDP, dar TCP este esențial pentru transferurile de zonă și răspunsurile mari, precum cele cu înregistrări DNSSEC.] +> 💡 **Feedback:** Conventional DNS supports UDP and TCP on port 53. 512 octets is the historical UDP limit without EDNS; EDNS can advertise larger UDP messages. A truncated UDP response normally triggers TCP retry. AXFR uses TCP; an IXFR response may fit in UDP. TCP can also be chosen without prior truncation. [DNS convențional acceptă UDP și TCP pe portul 53. 512 octeți este limita istorică UDP fără EDNS; EDNS poate anunța mesaje UDP mai mari. Un răspuns UDP trunchiat determină în mod normal reîncercarea TCP. AXFR folosește TCP; un răspuns IXFR poate încăpea în UDP. TCP poate fi ales și fără trunchiere prealabilă.] --- @@ -220,7 +245,7 @@ - **c) Switch to a different DNS server [Schimbarea la un alt server DNS]** - **d) Increase the local UDP buffer size and retry over UDP [Mărirea dimensiunii buffer-ului UDP local și reîncercarea prin UDP]** -> 💡 **Feedback:** The TC bit signals that the UDP response was too large and was truncated. The client should retry the same query over TCP, which has no practical size limit for DNS responses. A common misconception is that the truncated response should be accepted as-is or that changing the DNS server resolves the issue, but the correct procedure is to retry via TCP to receive the complete response. [Bitul TC semnalează că răspunsul UDP a fost prea mare și a fost trunchiat. Clientul trebuie să reîncerce aceeași interogare prin TCP, care nu are o limită practică de dimensiune pentru răspunsurile DNS. O concepție greșită frecventă este că răspunsul trunchiat ar trebui acceptat ca atare sau că schimbarea serverului DNS rezolvă problema, dar procedura corectă este reîncercarea prin TCP pentru a primi răspunsul complet.] +> 💡 **Feedback:** TC in the UDP response indicates truncation, so a conventional client normally retries over TCP for the complete answer. DNS over TCP uses a two-byte length prefix and supports at most 65535 octets per DNS message; a zone transfer can contain multiple messages. EDNS permits UDP payloads above the old 512-octet limit. [TC în răspunsul UDP indică trunchiere, deci un client convențional reîncearcă în mod normal prin TCP pentru răspunsul complet. DNS prin TCP folosește un prefix de lungime pe doi octeți și permite cel mult 65535 de octeți pe mesaj DNS; un transfer de zonă poate conține mai multe mesaje. EDNS permite payload-uri UDP peste vechea limită de 512 octeți.] --- @@ -255,26 +280,31 @@ ### 19. `True/False – Adevărat/Fals` **N10.C03.Q05: DNS caching improves privacy / Memorarea în cache DNS îmbunătățește confidențialitatea** -> Using a local DNS cache protects user privacy because queries are answered locally. [Utilizarea unui cache DNS local protejează confidențialitatea utilizatorului deoarece interogările primesc răspuns local.] +> A local DNS cache alone guarantees that an upstream resolver or network observer cannot learn any queried domain. [Un cache DNS local singur garantează că un resolver din amonte sau observator de rețea nu poate afla niciun domeniu interogat.] -- **a) True / Adevărat** -- **b) False / Fals** +- **a) true** +- **b) false** -> 💡 **Feedback:** DNS caching reduces query frequency but does not improve privacy. Initial queries still go to upstream resolvers in plaintext, and cached results reveal browsing patterns if examined. Actual DNS privacy requires DoH (DNS over HTTPS) or DoT (DNS over TLS). A common misconception is that fewer queries mean better privacy, but the initial lookup still exposes the domain name to the upstream resolver. [Memorarea în cache DNS reduce frecvența interogărilor, dar nu îmbunătățește confidențialitatea. Interogările inițiale ajung în continuare la rezolvoarele din amonte în text clar, iar rezultatele din cache dezvăluie tiparele de navigare dacă sunt examinate. Confidențialitatea DNS reală necesită DoH (DNS over HTTPS) sau DoT (DNS over TLS). O concepție greșită frecventă este că mai puține interogări înseamnă confidențialitate mai bună, dar interogarea inițială expune în continuare numele de domeniu către rezolvorul din amonte.] +> 💡 **Feedback:** False. Cache hits reduce repeated upstream queries and can therefore reduce exposure, but cache misses still require resolution. DoT/DoH protect the client-to-resolver transport against passive observers; the selected resolver still sees the queries it handles. Cache contents themselves also need appropriate access controls. [Fals. Răspunsurile din cache reduc interogările repetate în amonte și pot reduce expunerea, dar cazurile absente cer rezolvare. DoT/DoH protejează transportul client-resolver față de observatori pasivi; resolverul ales vede interogările pe care le gestionează. Și conținutul cache-ului necesită control adecvat al accesului.] --- -### 20. `Multiple Choice – Alegere multiplă` -**N10.C04.Q03: SSH key authentication versus password authentication / Autentificarea SSH prin chei versus autentificarea prin parolă** +### Q20. `N10.C04.Q03` — SSH key authentication versus password authentication / Autentificarea SSH prin chei versus autentificarea prin parolă + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +What is a security advantage of correctly configured SSH public-key authentication compared with a reusable password? [Care este un avantaj de securitate al autentificării SSH cu cheie publică configurate corect față de o parolă reutilizabilă?] -> Why is SSH key authentication considered more secure than password authentication? [De ce este autentificarea SSH prin chei considerată mai sigură decât autentificarea prin parolă?] +- **a)** The authentication exchange sends a signature proving possession of the private key, not the private key itself [Schimbul de autentificare trimite o semnătură care demonstrează posesia cheii private, nu cheia privată] +- **b)** Every SSH key has 2048 bits of security regardless of algorithm [Orice cheie SSH are 2048 de biți de securitate indiferent de algoritm] +- **c)** A private key cannot be stolen or copied [O cheie privată nu poate fi furată sau copiată] +- **d)** Host-key verification is unnecessary when public keys are used [Verificarea cheii gazdei nu este necesară când se folosesc chei publice] -- **a) SSH keys are much longer (2048+ bits) and the private key is never sent to the server [Cheile SSH sunt mult mai lungi (2048+ biți) și cheia privată nu este niciodată trimisă serverului]** -- **b) SSH keys use symmetric encryption exclusively throughout the session, which provides inherently greater computational security [Cheile SSH folosesc criptare simetrică exclusiv pe parcursul întregii sesiuni, ceea ce oferă o securitate computațională inerent mai mare]** -- **c) SSH keys automatically expire after 30 days, reducing exposure [Cheile SSH expiră automat după 30 de zile, reducând expunerea]** -- **d) SSH keys encrypt the entire session including all commands, while passwords only protect the initial authentication exchange [Cheile SSH criptează întreaga sesiune inclusiv toate comenzile, în timp ce parolele protejează doar schimbul inițial de autentificare]** +
    💡 Feedback -> 💡 **Feedback:** SSH keys provide 2048+ bits of entropy, are resistant to brute-force attacks, and the private key never leaves the client machine — eliminating phishing and network-exposure risks inherent to passwords. A common misconception is that SSH key authentication is less secure than passwords because keys can be copied, but the private key is protected locally and never transmitted over the network, unlike passwords. [Cheile SSH oferă peste 2048 de biți de entropie, sunt rezistente la atacuri de tip forță brută, iar cheia privată nu părăsește niciodată mașina clientului — eliminând riscurile de phishing și de expunere în rețea inerente parolelor. O concepție greșită frecventă este că autentificarea prin chei SSH este mai puțin sigură decât parolele deoarece cheile pot fi copiate, dar cheia privată este protejată local și nu este niciodată transmisă prin rețea, spre deosebire de parole.] +**Correct answer / Răspuns corect: a.** The private key is not transmitted by SSH authentication; the client signs session-bound authentication data. Key length depends on the algorithm and is not equivalent to security strength. Protect private keys/agents and verify host keys: endpoint compromise, malicious hosts and agent misuse remain risks. Password authentication also uses the encrypted SSH transport. [Cheia privată nu este transmisă de autentificarea SSH; clientul semnează date de autentificare legate de sesiune. Lungimea cheii depinde de algoritm și nu este echivalentă cu rezistența criptografică. Protejați cheile/agenții și verificați cheile gazdei: compromiterea endpoint-ului, gazdele malițioase și utilizarea abuzivă a agentului rămân riscuri. Și autentificarea cu parolă folosește transportul SSH criptat.] + +
    --- @@ -398,35 +428,40 @@ - **c) The query contained an error; the client should reformulate with a different record type [Interogarea conținea o eroare; clientul ar trebui să reformuleze cu un alt tip de înregistrare]** - **d) The response was corrupted in transit; the client should query a different DNS server [Răspunsul a fost corupt în tranzit; clientul ar trebui să interogheze un alt server DNS]** -> 💡 **Feedback:** The TC bit indicates the response was too large for a single UDP datagram. The client should retry the same query using TCP, which has no message size limit. This is specified in RFC 1035 and is standard DNS behaviour. A common error is thinking DNS always uses UDP — TCP is essential for large responses (DNSSEC, many records) and zone transfers. [Bitul TC indică faptul că răspunsul a fost prea mare pentru o singură datagramă UDP. Clientul ar trebui să reîncerce aceeași interogare folosind TCP, care nu are limită de dimensiune a mesajului. Aceasta este specificată în RFC 1035 și este un comportament DNS standard. O eroare frecventă este credința că DNS folosește întotdeauna UDP — TCP este esențial pentru răspunsuri mari (DNSSEC, multe înregistrări) și transferuri de zonă.] +> 💡 **Feedback:** TC in the UDP response indicates truncation, so a conventional client normally retries over TCP for the complete answer. DNS over TCP uses a two-byte length prefix and supports at most 65535 octets per DNS message; a zone transfer can contain multiple messages. EDNS permits UDP payloads above the old 512-octet limit. [TC în răspunsul UDP indică trunchiere, deci un client convențional reîncearcă în mod normal prin TCP pentru răspunsul complet. DNS prin TCP folosește un prefix de lungime pe doi octeți și permite cel mult 65535 de octeți pe mesaj DNS; un transfer de zonă poate conține mai multe mesaje. EDNS permite payload-uri UDP peste vechea limită de 512 octeți.] --- -### 30. `Multiple Choice – Alegere multiplă` -**N10.T00.Q05: HTTPS padlock misconception / Concepția greșită despre lacătul HTTPS** +### Q30. `N10.T00.Q05` — HTTPS padlock misconception / Concepția greșită despre lacătul HTTPS + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +A browser reports a successfully validated HTTPS connection to bank.example. What can be concluded from that connection indicator alone? [Un browser raportează o conexiune HTTPS validată reușit către bank.example. Ce se poate deduce doar din indicatorul conexiunii?] + +- **a)** The connection has TLS protection and certificate identity validation for that hostname; the site may still be deceptive or harmful [Conexiunea are protecție TLS și validarea identității certificatului pentru acel nume; site-ul poate fi totuși înșelător sau dăunător] +- **b)** The operator's business practices have been audited [Practicile comerciale ale operatorului au fost auditate] +- **c)** All downloads are harmless [Toate descărcările sunt inofensive] +- **d)** The site cannot be used for phishing [Site-ul nu poate fi folosit pentru phishing] -> A user sees a padlock icon in their browser when visiting https://totally-legit-bank.com. Which statement most accurately describes what the padlock guarantees? [Un utilizator vede o pictogramă de lacăt în browser când vizitează https://totally-legit-bank.com. Care afirmație descrie cel mai exact ce garantează lacătul?] +
    💡 Feedback -- **a) The connection is encrypted and the server has a valid TLS certificate, but the site could still be malicious [Conexiunea este criptată și serverul are un certificat TLS valid, dar site-ul ar putea fi în continuare malițios]** -- **b) The website has been verified as safe and legitimate by a trusted authority [Site-ul web a fost verificat ca sigur și legitim de o autoritate de încredere]** -- **c) The website operator's identity and business practices have been thoroughly verified by the certificate authority that issued the TLS certificate [Identitatea și practicile comerciale ale operatorului site-ului web au fost verificate amănunțit de autoritatea de certificare care a emis certificatul TLS]** -- **d) The website's data storage practices comply with privacy regulations [Practicile de stocare a datelor ale site-ului sunt conforme cu reglementările de confidențialitate]** +**Correct answer / Răspuns corect: a.** TLS authenticates the endpoint identity according to the certificate trust model and protects the connection. It does not certify honesty, application security or data-storage practices. Browser icon designs vary, so reason from the validated connection, not a particular padlock graphic. [TLS autentifică identitatea endpoint-ului conform modelului de încredere al certificatelor și protejează conexiunea. Nu certifică onestitatea, securitatea aplicației sau practicile de stocare. Grafica indicatoarelor diferă între browsere, deci raționați pornind de la conexiunea validată, nu de la un anumit lacăt.] -> 💡 **Feedback:** The HTTPS padlock only means the connection between the browser and server is encrypted and the server presented a valid certificate. It says nothing about the trustworthiness, safety, or legitimacy of the website itself. Phishing sites routinely obtain valid HTTPS certificates from free CAs like Let's Encrypt. Equating the padlock with website safety is one of the most dangerous misconceptions in web security. [Lacătul HTTPS înseamnă doar că conexiunea dintre browser și server este criptată și serverul a prezentat un certificat valid. Nu spune nimic despre încrederea, siguranța sau legitimitatea site-ului web în sine. Site-urile de phishing obțin în mod curent certificate HTTPS valide de la CA-uri gratuite precum Let's Encrypt. Echivalarea lacătului cu siguranța site-ului este una dintre cele mai periculoase concepții greșite în securitatea web.] +
    --- ### 31. `Multiple Choice – Alegere multiplă` **N10.T00.Q06: HTTP idempotency and method semantics / Idempotența HTTP și semantica metodelor** -> A developer accidentally sends the same PUT /api/users/10 request three times due to a network retry. A second developer sends the same POST /api/users request three times. What is the most likely outcome for each? [Un dezvoltator trimite accidental aceeași cerere PUT /api/users/10 de trei ori din cauza unei reîncercări de rețea. Un al doilea dezvoltator trimite aceeași cerere POST /api/users de trei ori. Care este rezultatul cel mai probabil pentru fiecare?] +> Assume each successful POST creates a fresh user and there is no application deduplication or idempotency key. A developer accidentally sends the same PUT /api/users/10 request three times due to a network retry. A second developer sends the same POST /api/users request three times. What is the most likely outcome for each? [Presupuneți că fiecare POST reușit creează un utilizator nou și nu există deduplicare sau cheie de idempotență. Un dezvoltator trimite accidental aceeași cerere PUT /api/users/10 de trei ori din cauza unei reîncercări de rețea. Un al doilea dezvoltator trimite aceeași cerere POST /api/users de trei ori. Care este rezultatul cel mai probabil pentru fiecare?] - **a) PUT: user 10 is updated to the same state (one user); POST: three new users are created [PUT: utilizatorul 10 este actualizat la aceeași stare (un utilizator); POST: trei utilizatori noi sunt creați]** - **b) Both create three separate entries because HTTP has no built-in duplicate detection [Ambele creează trei intrări separate deoarece HTTP nu are detecție de duplicate integrată]** - **c) PUT: three versions of user 10 are stored; POST: only one user is created [PUT: trei versiuni ale utilizatorului 10 sunt stocate; POST: doar un utilizator este creat]** - **d) Both update a single record because the server detects identical request bodies, which does not accurately reflect how modern implementations handle the key exchange procedure [Ambele actualizează o singură înregistrare deoarece serverul detectează corpuri de cerere identice, ceea ce nu reflectă cu acuratețe modul în care implementările moderne gestionează procedura de schimb de chei]** -> 💡 **Feedback:** PUT is idempotent — sending the same PUT to the same URI multiple times produces the same result (user 10 is updated once). POST is not idempotent — each POST creates a new resource, resulting in three separate users. This semantic distinction is fundamental to REST Level 2 and affects how clients handle retries. [PUT este idempotent — trimiterea aceluiași PUT la același URI de mai multe ori produce același rezultat (utilizatorul 10 este actualizat o singură dată). POST nu este idempotent — fiecare POST creează o resursă nouă, rezultând în trei utilizatori separați. Această distincție semantică este fundamentală pentru Nivelul 2 REST și afectează modul în care clienții gestionează reîncercările.] +> 💡 **Feedback:** Under the stated application contract, the three PUTs leave user 10 with the same intended state and the three POSTs create three users. Idempotence concerns intended state, not identical response bodies or the absence of logging. POST behaviour is application-defined, so the creation/deduplication assumptions are necessary. [Conform contractului aplicației, cele trei PUT-uri lasă utilizatorul 10 în aceeași stare intenționată, iar cele trei POST-uri creează trei utilizatori. Idempotența privește starea intenționată, nu identitatea răspunsurilor sau absența jurnalizării. Comportamentul POST este definit de aplicație, deci ipotezele despre creare/deduplicare sunt necesare.] --- @@ -458,31 +493,41 @@ --- -### 34. `Multiple Choice – Alegere multiplă` -**N10.T00.Q09: SSH key authentication security / Securitatea autentificării SSH bazate pe chei** +### Q34. `N10.T00.Q09` — SSH key authentication security / Securitatea autentificării SSH bazate pe chei -> In the context of SSH authentication, what is the primary security advantage of public-key authentication over password authentication? [În contextul autentificării SSH, care este principalul avantaj de securitate al autentificării bazate pe cheie publică față de autentificarea cu parolă?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) The private key never leaves the client; the server only verifies a cryptographic proof of possession [Cheia privată nu părăsește niciodată clientul; serverul verifică doar o dovadă criptografică a posesiei]** -- **b) SSH keys use stronger encryption algorithms than password-based authentication [Cheile SSH folosesc algoritmi de criptare mai puternici decât autentificarea bazată pe parole]** -- **c) SSH keys automatically expire after a set period, forcing regular rotation [Cheile SSH expiră automat după o perioadă stabilită, forțând rotația regulată]** -- **d) SSH keys encrypt the entire session with the user's public key for end-to-end security — a formulation that incorrectly suggests a synchronous process where the standard defines asynchronous operation [Cheile SSH criptează întreaga sesiune cu cheia publică a utilizatorului pentru securitate capăt-la-capăt — o formulare ce sugerează incorect un proces sincron unde standardul definește operare asincronă]** +In SSH public-key authentication, what does the client prove without transmitting the reusable private key? [În autentificarea SSH cu cheie publică, ce dovedește clientul fără transmiterea cheii private reutilizabile?] -> 💡 **Feedback:** With SSH key authentication, the private key never leaves the client machine. The server only stores the public key. Authentication uses a challenge-response mechanism where the client proves possession of the private key without transmitting it. This eliminates phishing, brute-force (2048+ bit keys), and credential reuse risks. Passwords, by contrast, are sent to the server and can be captured, guessed, or reused. [Cu autentificarea SSH bazată pe chei, cheia privată nu părăsește niciodată mașina client. Serverul stochează doar cheia publică. Autentificarea folosește un mecanism provocare-răspuns prin care clientul dovedește posesia cheii private fără a o transmite. Aceasta elimină riscurile de phishing, brute-force (chei de 2048+ biți) și reutilizare a datelor de autentificare. Parolele, în schimb, sunt trimise serverului și pot fi capturate, ghicite sau reutilizate.] +- **a)** Possession of the signing key through a signature bound to the SSH session [Posesia cheii de semnare printr-o semnătură legată de sesiunea SSH] +- **b)** That the server is honest without checking its host key [Că serverul este onest fără verificarea cheii gazdei] +- **c)** That its private key cannot exist on another computer [Că cheia privată nu poate exista pe alt calculator] +- **d)** That all SSH algorithms have the same key length [Că toți algoritmii SSH au aceeași lungime a cheii] + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The signature proof is the authentication mechanism. It does not eliminate credential theft, unsafe agent forwarding or malicious-server risks. Host-key verification and local private-key protection remain necessary;2048-bit RSA is not 2048-bit security and other SSH algorithms use different sizes. [Dovada prin semnătură este mecanismul de autentificare. Nu elimină furtul de credențiale, redirecționarea nesigură a agentului sau riscurile serverelor malițioase. Verificarea cheii gazdei și protecția locală a cheii private rămân necesare; RSA pe 2048 de biți nu înseamnă 2048 de biți de securitate, iar alți algoritmi SSH folosesc alte dimensiuni.] + +
    --- -### 35. `Multiple Choice – Alegere multiplă` -**N10.T00.Q10: DNS record type selection / Selectarea tipului de înregistrare DNS** +### Q35. `N10.T00.Q10` — DNS record type selection / Selectarea tipului de înregistrare DNS + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> A company wants to redirect www.example.com to example.com at the DNS level so both names resolve to the same IP address. Which DNS record type is most appropriate? [O companie dorește să redirecționeze www.example.com către example.com la nivel DNS astfel încât ambele nume să se rezolve la aceeași adresă IP. Ce tip de înregistrare DNS este cel mai potrivit?] +www.example.com has no other ordinary records and must follow the address records of example.com automatically when they change. Which DNS record expresses that alias? [www.example.com nu are alte înregistrări obișnuite și trebuie să urmeze automat înregistrările de adresă pentru example.com când acestea se schimbă. Ce înregistrare DNS exprimă aliasul?] -- **a) CNAME — creates an alias so www.example.com resolves to whatever example.com resolves to [CNAME — creează un alias astfel încât www.example.com se rezolvă la orice se rezolvă example.com]** -- **b) A — maps www.example.com directly to the same IPv4 address [A — mapează www.example.com direct la aceeași adresă IPv4]** -- **c) MX — redirects traffic between domain names for any protocol [MX — redirecționează traficul între numele de domeniu pentru orice protocol]** -- **d) NS — delegates www.example.com to the same authoritative name server that handles the example.com zone [NS — deleghează www.example.com către același server de nume autoritativ care gestionează zona example.com]** +- **a)** www.example.com. CNAME example.com. +- **b)** A second A record whose address must be edited separately +- **c)** An MX record naming an email destination +- **d)** An NS record delegating a child zone -> 💡 **Feedback:** A CNAME (Canonical Name) record creates an alias from one domain to another. Setting www.example.com CNAME example.com makes www resolve to wherever example.com points. An A record maps directly to an IP address (requires updating both if IP changes). MX is for mail routing, and NS delegates DNS authority — neither serves as a domain alias. [O înregistrare CNAME (Canonical Name) creează un alias de la un domeniu la altul. Setarea www.example.com CNAME example.com face ca www să se rezolve la orice adresă indică example.com. O înregistrare A mapează direct la o adresă IP (necesită actualizarea ambelor dacă IP-ul se schimbă). MX este pentru rutarea e-mailului, iar NS deleagă autoritatea DNS — niciunul nu servește ca alias de domeniu.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** CNAME makes the owner name an alias. Duplicating an A value could produce the same address now but would not encode the requested alias relationship. DNS aliasing is not an HTTP redirect and does not change the URL displayed by a browser. [CNAME face din numele proprietar un alias. Duplicarea unei valori A poate produce aceeași adresă acum, dar nu exprimă relația de alias cerută. Aliasul DNS nu este o redirecționare HTTP și nu modifică URL-ul afișat de browser.] + +
    --- @@ -545,31 +590,54 @@ ## Lab Questions / Întrebări de laborator -### 40. `Multiple Choice – Alegere multiplă` -**N10.S01.Q03: TLS state machine — calling server_hello before client_hello / Mașina de stări TLS — apelarea server_hello înainte de client_hello** +### Q40. `N10.S01.Q03` — TLS state machine — calling server_hello before client_hello / Mașina de stări TLS — apelarea server_hello înainte de client_hello + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Run this independent state-machine illustration. What does the final call return? It is not a TLS implementation. [Rulați această ilustrare independentă de mașină de stări. Ce returnează ultimul apel? Nu este o implementare TLS.] -> In the code-tracing exercise modelling a TLS connection as a state machine, what happens if server_hello() is called immediately after object initialisation (state = INIT)? [În exercițiul de trasare a codului care modelează o conexiune TLS ca mașină de stări, ce se întâmplă dacă server_hello() este apelat imediat după inițializarea obiectului (state = INIT)?] +```python +class HandshakeModel: + def __init__(self): + self.state = "INIT" + def server_hello(self): + if self.state != "CLIENT_HELLO": + return f"error: invalid state {self.state}" + self.state = "SERVER_HELLO" + return self.state -- **a) It returns an error string indicating invalid state INIT [Returnează un șir de eroare indicând starea invalidă INIT]** -- **b) It proceeds normally and transitions to SERVER_HELLO, which incorrectly implies a capability that the protocol was deliberately designed not to provide [Continuă normal și trece la SERVER_HELLO, ceea ce implică incorect o capacitate pe care protocolul a fost proiectat în mod deliberat să nu o ofere]** -- **c) It raises a Python exception and crashes [Aruncă o excepție Python și se oprește]** -- **d) It automatically calls client_hello() first [Apelează automat client_hello() mai întâi]** +print(HandshakeModel().server_hello()) +``` -> 💡 **Feedback:** The state machine enforces strict ordering. server_hello() expects state CLIENT_HELLO, so calling it from state INIT returns an error because the handshake steps must proceed in order. A common misconception is that the state machine automatically corrects the sequence, but enforcing strict ordering mirrors the real TLS protocol where steps cannot be skipped. [Mașina de stări impune o ordine strictă. server_hello() așteaptă starea CLIENT_HELLO, deci apelarea din starea INIT returnează o eroare deoarece pașii handshake-ului trebuie să se desfășoare în ordine. O concepție greșită frecventă este că mașina de stări corectează automat secvența, dar impunerea ordinii stricte reflectă protocolul TLS real, unde pașii nu pot fi omisi.] +- **a)** "error: invalid state INIT" +- **b)** "SERVER_HELLO" +- **c)** None +- **d)** An automatic call to client_hello() + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The guard requires CLIENT_HELLO; the new object is in INIT, so the stated error string is returned. This is a deliberately small code-tracing contract, not a claim about all TLS states or wire messages. [Garda cere CLIENT_HELLO; obiectul nou este în INIT, deci returnează șirul de eroare indicat. Este un contract mic pentru trasarea codului, nu o afirmație despre toate stările sau mesajele TLS.] + +
    --- -### 41. `Multiple Choice – Alegere multiplă` -**N10.S01.Q04: SSL context wrap_socket and server_hostname parameter / Contextul SSL wrap_socket și parametrul server_hostname** +### Q41. `N10.S01.Q04` — SSL context wrap_socket and server_hostname parameter / Contextul SSL wrap_socket și parametrul server_hostname + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the Parsons problem for certificate verification, the call context.wrap_socket(sock, server_hostname=hostname) is used. What is the purpose of the server_hostname parameter? [În problema Parsons pentru verificarea certificatului, se folosește apelul context.wrap_socket(sock, server_hostname=hostname). Care este scopul parametrului server_hostname?] +Assume sock is connected and context = ssl.create_default_context(). What does context.wrap_socket(sock, server_hostname="www.example.test") use that DNS hostname for? [Presupuneți că sock este conectat și context = ssl.create_default_context(). La ce folosește context.wrap_socket(sock, server_hostname="www.example.test") acel nume DNS?] -- **a) It enables SNI so the server knows which certificate to present [Activează SNI astfel încât serverul să știe ce certificat să prezinte]** -- **b) It sets the DNS server to use for hostname resolution [Setează serverul DNS utilizat pentru rezoluția numelor de gazdă]** -- **c) It specifies the encryption algorithm to use [Specifică algoritmul de criptare de utilizat]** -- **d) It disables certificate verification for self-signed certificates [Dezactivează verificarea certificatului pentru certificatele auto-semnate]** +- **a)** Certificate hostname verification and SNI for the requested DNS hostname [Verificarea numelui din certificat și SNI pentru numele DNS cerut] +- **b)** Choosing a DNS resolver address [Alegerea adresei resolverului DNS] +- **c)** Disabling certificate-chain validation [Dezactivarea validării lanțului certificatului] +- **d)** Selecting an encryption algorithm by hostname spelling [Alegerea algoritmului de criptare după forma numelui] -> 💡 **Feedback:** The server_hostname parameter enables SNI (Server Name Indication), telling the server which hostname the client is connecting to so it can present the correct certificate. This is essential for virtual hosting where multiple domains share the same IP address. A common misconception is that this parameter sets the DNS server or controls encryption, but it specifically enables the SNI extension in the TLS handshake. [Parametrul server_hostname activează SNI (Server Name Indication), informând serverul la ce nume de gazdă se conectează clientul, astfel încât acesta să poată prezenta certificatul corect. Acest lucru este esențial pentru găzduirea virtuală, unde mai multe domenii partajează aceeași adresă IP. O concepție greșită frecventă este că acest parametru setează serverul DNS sau controlează criptarea, dar el activează specific extensia SNI în handshake-ul TLS.] +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** With the validating default client context, server_hostname supplies the reference identity for hostname verification. A DNS name also enables SNI so a virtual-host server can select a certificate. It does not resolve the name or make an untrusted certificate trustworthy. [Cu contextul client implicit care validează, server_hostname furnizează identitatea de referință pentru verificarea numelui. Un nume DNS permite și SNI pentru selectarea certificatului pe serverul virtual. Nu rezolvă numele și nu transformă un certificat neacceptat într-unul de încredere.] + +
    --- @@ -587,17 +655,42 @@ --- -### 43. `Multiple Choice – Alegere multiplă` -**N10.S02.Q02: Code tracing — route_request output for non-numeric user ID / Trasarea codului — rezultatul route_request pentru un ID de utilizator non-numeric** +### Q43. `N10.S02.Q02` — Code tracing — route_request output for non-numeric user ID / Trasarea codului — rezultatul route_request pentru un ID de utilizator non-numeric + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +In this self-contained dispatcher example, what does route_request('GET','/api/users/abc') return? [În acest dispatcher autonom, ce returnează route_request('GET','/api/users/abc')?] -> In the code-tracing exercise, the function route_request parses URL paths and checks if a user ID segment is numeric using isdigit(). What does route_request("GET", "/api/users/abc") return? [În exercițiul de trasare a codului, funcția route_request parsează căile URL și verifică dacă segmentul ID de utilizator este numeric folosind isdigit(). Ce returnează route_request("GET", "/api/users/abc")?] +```python +def route_request(method, path): + if path == "/api/users": + if method == "GET": + return "List all users", 200 + if method == "POST": + return "Create user", 201 + return "Method not allowed", 405 + parts = path.split("/") + if len(parts) == 4 and parts[1:3] == ["api", "users"] and parts[3].isdigit(): + if method == "GET": + return f"Get user {parts[3]}", 200 + if method in ("PUT", "DELETE"): + return "Updated or deleted", 200 + return "Method not allowed", 405 + return "Not found", 404 -- **a) ("Not found", 404)** -- **b) ("Get user abc", 200)** -- **c) ("Method not allowed", 405)** -- **d) A ValueError exception is raised [Se aruncă o excepție ValueError]** +print(route_request('GET', '/api/users/abc')) +``` -> 💡 **Feedback:** The path splits into ['', 'api', 'users', 'abc']. Since 'abc'.isdigit() returns False, the request falls through to the default return: ("Not found", 404). A common misconception is that the router would return a 405 Method Not Allowed, but the issue is not the method — it is the non-numeric ID segment failing the isdigit() check. [Calea se împarte în ['', 'api', 'users', 'abc']. Deoarece 'abc'.isdigit() returnează False, cererea cade la returnarea implicită: ("Not found", 404). O concepție greșită frecventă este că routerul ar returna un 405 Method Not Allowed, dar problema nu este metoda — ci segmentul ID non-numeric care nu trece verificarea isdigit().] +- **a)** ("Not found",404) +- **b)** ("List all users",200) +- **c)** ("Create user",201) +- **d)** A ValueError exception + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** Follow the explicit path and method guards. This function returns a teaching tuple, not a complete HTTP response; a real 405 response must also include Allow. No omitted repository exercise is needed to determine the answer. [Urmăriți gărzile explicite pentru cale și metodă. Funcția returnează un tuplu didactic, nu un răspuns HTTP complet; un răspuns 405 real trebuie să includă și Allow. Răspunsul nu depinde de un exercițiu omis din repository.] + +
    --- @@ -615,59 +708,108 @@ --- -### 45. `Multiple Choice – Alegere multiplă` -**N10.S02.Q04: Code tracing — route_request output for PATCH on /api/users / Trasarea codului — rezultatul route_request pentru PATCH pe /api/users** +### Q45. `N10.S02.Q04` — Code tracing — route_request output for PATCH on /api/users / Trasarea codului — rezultatul route_request pentru PATCH pe /api/users + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +In this self-contained dispatcher example, what does route_request('PATCH','/api/users') return? [În acest dispatcher autonom, ce returnează route_request('PATCH','/api/users')?] + +```python +def route_request(method, path): + if path == "/api/users": + if method == "GET": + return "List all users", 200 + if method == "POST": + return "Create user", 201 + return "Method not allowed", 405 + parts = path.split("/") + if len(parts) == 4 and parts[1:3] == ["api", "users"] and parts[3].isdigit(): + if method == "GET": + return f"Get user {parts[3]}", 200 + if method in ("PUT", "DELETE"): + return "Updated or deleted", 200 + return "Method not allowed", 405 + return "Not found", 404 + +print(route_request('PATCH', '/api/users')) +``` + +- **a)** ("Method not allowed",405) +- **b)** ("List all users",200) +- **c)** ("Create user",201) +- **d)** A ValueError exception -> In the code-tracing exercise, the function route_request handles GET, POST, PUT, and DELETE for user resources. A client sends PATCH /api/users. What does route_request("PATCH", "/api/users") return? [În exercițiul de trasare a codului, funcția route_request gestionează GET, POST, PUT și DELETE pentru resursele utilizatorilor. Un client trimite PATCH /api/users. Ce returnează route_request("PATCH", "/api/users")?] +
    💡 Feedback -- **a) ("Method not allowed", 405)** -- **b) ("Not found", 404)** -- **c) ("List all users", 200)** -- **d) ("Create user", 201)** +**Correct answer / Răspuns corect: a.** Follow the explicit path and method guards. This function returns a teaching tuple, not a complete HTTP response; a real 405 response must also include Allow. No omitted repository exercise is needed to determine the answer. [Urmăriți gărzile explicite pentru cale și metodă. Funcția returnează un tuplu didactic, nu un răspuns HTTP complet; un răspuns 405 real trebuie să includă și Allow. Răspunsul nu depinde de un exercițiu omis din repository.] -> 💡 **Feedback:** The routing function checks if path == "/api/users", then only matches GET and POST methods. Since PATCH does not match either branch, execution falls to the else clause which returns ("Method not allowed", 405). This demonstrates that the router only implements a subset of HTTP verbs for the collection endpoint. A common misconception is confusing 404 (resource not found) with 405 (method not allowed) — the path exists but the method is not supported. [Funcția de rutare verifică dacă path == "/api/users", apoi potrivește doar metodele GET și POST. Deoarece PATCH nu se potrivește cu niciuna dintre ramuri, execuția cade la clauza else care returnează ("Method not allowed", 405). Aceasta demonstrează că routerul implementează doar un subset de verbe HTTP pentru endpoint-ul de colecție. O concepție greșită frecventă este confundarea 404 (resursă negăsită) cu 405 (metodă nepermisă) — calea există, dar metoda nu este acceptată.] +
    --- -### 46. `Multiple Choice – Alegere multiplă` -**N10.S03.Q03: Code tracing — DNS resolver with trailing dot / Trasarea codului — rezolvor DNS cu punct final** +### Q46. `N10.S03.Q03` — Code tracing — DNS resolver with trailing dot / Trasarea codului — rezolvor DNS cu punct final -> In the DNS code-tracing exercise, the function resolve_dns calls query_name.rstrip(".") before looking up the record. What does resolve_dns("web.lab.local.") return for the status field? [În exercițiul de trasare a codului DNS, funcția resolve_dns apelează query_name.rstrip(".") înainte de căutarea înregistrării. Ce returnează resolve_dns("web.lab.local.") pentru câmpul status?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) "NOERROR" — the trailing dot is removed before lookup [punctul final este eliminat înainte de căutare]** -- **b) "NXDOMAIN" — the dot makes it a different domain [punctul îl face un domeniu diferit]** -- **c) An exception is raised because of the trailing dot — this confuses the purpose of the handshake mechanism with that of the data transfer phase [Se aruncă o excepție din cauza punctului final — aceasta confundă scopul mecanismului de handshake cu cel al fazei de transfer de date]** -- **d) None — the function cannot handle FQDNs [funcția nu poate gestiona FQDN-uri]** +In this standalone dictionary model, which status does the final call produce? [În acest model autonom bazat pe dicționar, ce status produce ultimul apel?] -> 💡 **Feedback:** The trailing dot is stripped by rstrip("."), making "web.lab.local." resolve identically to "web.lab.local", returning status "NOERROR". A common misconception is that the trailing dot makes it a different, non-existent domain, but in DNS the trailing dot denotes the FQDN (Fully Qualified Domain Name) root and the code normalises this. [Punctul final este eliminat de rstrip("."), făcând "web.lab.local." să se rezolve identic cu "web.lab.local", returnând statusul "NOERROR". O concepție greșită frecventă este că punctul final face din acesta un domeniu diferit, inexistent, dar în DNS punctul final denotă rădăcina FQDN (Fully Qualified Domain Name), iar codul normalizează acest lucru.] +```python +records = {"web.lab.local": "192.0.2.10"} +def resolve_dns(query_name): + key = query_name.rstrip(".").lower() + return {"status": "NOERROR" if key in records else "NXDOMAIN"} + +print(resolve_dns("web.lab.local.")["status"]) +``` + +- **a)** NOERROR +- **b)** NXDOMAIN +- **c)** SERVFAIL +- **d)** None + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** rstrip removes the trailing dot before dictionary lookup, so the key exists. The terminal dot represents the DNS root in an absolute name. This toy model does not perform DNS traffic, implement delegation or model every DNS response case. [rstrip elimină punctul final înaintea căutării în dicționar, deci cheia există. Punctul terminal reprezintă rădăcina DNS într-un nume absolut. Modelul simplificat nu generează trafic DNS, nu implementează delegare și nu acoperă toate răspunsurile DNS.] + +
    --- -### 47. `Multiple Choice – Alegere multiplă` -**N10.S03.Q05: Socket type for UDP DNS queries in Python / Tipul de socket pentru interogări DNS UDP în Python** +### Q47. `N10.S03.Q05` — Socket type for UDP DNS queries in Python / Tipul de socket pentru interogări DNS UDP în Python + +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Which type creates a UDP/IPv4 socket in socket.socket(socket.AF_INET, type)? [Ce tip creează un socket UDP/IPv4 în socket.socket(socket.AF_INET, type)?] + +- **a)** socket.SOCK_DGRAM +- **b)** socket.SOCK_STREAM +- **c)** socket.SOCK_RAW +- **d)** socket.SOCK_SEQPACKET -> In the Parsons problem for building a DNS query function, what socket type constant is used to create a UDP socket? [În problema Parsons pentru construirea unei funcții de interogare DNS, ce constantă de tip socket se folosește pentru a crea un socket UDP?] +
    💡 Feedback -- **a) socket.SOCK_DGRAM** -- **b) socket.SOCK_STREAM** -- **c) socket.SOCK_RAW** -- **d) socket.SOCK_SEQPACKET** +**Correct answer / Răspuns corect: a.** For AF_INET with the default protocol, SOCK_DGRAM selects UDP. The address family matters: datagram sockets also exist for other families. Conventional DNS can use both UDP and TCP; this question explicitly asks for UDP. [Pentru AF_INET cu protocolul implicit, SOCK_DGRAM selectează UDP. Familia de adrese contează: există socket-uri de datagramă și pentru alte familii. DNS convențional poate folosi UDP și TCP; aici se cere explicit UDP.] -> 💡 **Feedback:** socket.SOCK_DGRAM creates a UDP datagram socket, appropriate for DNS queries. SOCK_STREAM would create a TCP socket instead. A common misconception is confusing SOCK_DGRAM (datagrame — connectionless, UDP) with SOCK_STREAM (flux de octeți — orientat pe conexiune, TCP). The naming reflects the underlying transport: datagrams are discrete message units while streams are continuous byte flows. [socket.SOCK_DGRAM creează un socket de datagramă UDP, potrivit pentru interogările DNS. SOCK_STREAM ar crea în schimb un socket TCP. O concepție greșită frecventă este confundarea SOCK_DGRAM (datagrame — fără conexiune, UDP) cu SOCK_STREAM (flux de octeți — orientat pe conexiune, TCP). Denumirea reflectă transportul subiacent: datagramele sunt unități de mesaje discrete, în timp ce fluxurile sunt fluxuri continue de octeți.] +
    --- -### 48. `Multiple Choice – Alegere multiplă` -**N10.S04.Q02: Python library for SSH automation / Biblioteca Python pentru automatizarea SSH** +### Q48. `N10.S04.Q02` — Python library for SSH automation / Biblioteca Python pentru automatizarea SSH -> Which Python library is used in the lab exercises to establish SSH connections and execute remote commands? [Ce bibliotecă Python este folosită în exercițiile de laborator pentru a stabili conexiuni SSH și a executa comenzi la distanță?] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -- **a) paramiko** -- **b) pexpect** -- **c) fabric** -- **d) subprocess** +Which library does 04_SEMINARS/S10/3_ssh/ssh-client/S10_Part03_Script_Paramiko_Client.py import for SSHClient? [Ce bibliotecă importă 04_SEMINARS/S10/3_ssh/ssh-client/S10_Part03_Script_Paramiko_Client.py pentru SSHClient?] -> 💡 **Feedback:** Paramiko is the Python library used in the exercises for SSH operations. It provides an SSHClient class for connecting, authenticating, and running remote commands. A common misconception is confusing Paramiko (dedicated SSH library) with subprocess (local process execution) — subprocess can invoke the ssh command but does not provide native SSH protocol support. [Paramiko este biblioteca Python folosită în exerciții pentru operațiunile SSH. Oferă o clasă SSHClient pentru conectare, autentificare și executarea comenzilor la distanță. O concepție greșită frecventă este confundarea Paramiko (bibliotecă SSH dedicată) cu subprocess (execuția proceselor locale) — subprocess poate invoca comanda ssh, dar nu oferă suport nativ pentru protocolul SSH.] +- **a)** paramiko +- **b)** pexpect +- **c)** fabric +- **d)** subprocess + +
    💡 Feedback + +**Correct answer / Răspuns corect: a.** The canonical S10 client imports Paramiko and creates paramiko.SSHClient(). subprocess could run an external ssh executable, but it is not the library used by this file. [Clientul canonic S10 importă Paramiko și creează paramiko.SSHClient(). subprocess ar putea lansa un executabil ssh extern, dar nu este biblioteca utilizată de acest fișier.] + +
    --- @@ -726,3 +868,12 @@ > 💡 **Feedback:** Standard FTP (port 21) transmits all data in plaintext, including USER and PASS commands. FTPS or SFTP should be used for sensitive data. This is inherent to the FTP protocol, not a misconfiguration. A common misconception is that visible credentials indicate a server misconfiguration, but plaintext transmission is the fundamental design of the FTP protocol — encryption was never part of the original specification. [FTP standard (portul 21) transmite toate datele în text clar, inclusiv comenzile USER și PASS. FTPS sau SFTP trebuie utilizate pentru date sensibile. Aceasta este o caracteristică inerentă protocolului FTP, nu o eroare de configurare. O concepție greșită frecventă este că datele de autentificare vizibile indică o eroare de configurare a serverului, dar transmisia în text clar este designul fundamental al protocolului FTP — criptarea nu a fost niciodată parte din specificația originală.] --- + + +## Repository context and reference points + +Canonical practical material: [S10](../../04_SEMINARS/S10/README.md) — DNS, SSH automation and forwarding. Code-tracing models explicitly introduced in this question pool are self-contained exercises, not promises of additional files or features in that seminar. [Material practic canonic: S10. Modelele de trasare introduse explicit sunt exerciții autonome, nu promisiuni de fișiere sau funcții suplimentare în seminar.] + +Protocol semantics: RFC 9110, *HTTP Semantics*. https://doi.org/10.17487/RFC9110 + +TLS 1.3: [RFC 9846](https://www.rfc-editor.org/rfc/rfc9846), superseding RFC 8446. SSH authentication: RFC 4252. https://doi.org/10.17487/RFC4252 diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W11_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W11_Questions.md index 172e1af..15e5220 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W11_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W11_Questions.md @@ -107,41 +107,39 @@ L7 operates at the application layer and can parse HTTP headers, cookies, URI pa --- -### Q6. `N11.C02.Q01` -**First Request to Crashed Backend / Prima cerere către un server căzut** +### Q6. `N11.C02.Q01` — First Request to Crashed Backend / Prima cerere către un server căzut -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Nginx uses default settings with three backends. Backend web2 crashes. A client sends a request that Nginx routes to web2. What does the client receive? [Nginx folosește setările implicite cu trei servere. Serverul web2 se oprește. Un client trimite o cerere pe care Nginx o direcționează către web2. Ce primește clientul?] +An HTTP GET reaches Nginx with the default proxy_next_upstream error timeout. Connecting to the selected backend is refused before anything is sent to the client. Another eligible backend returns 200, and no retry/time limit blocks that attempt. What can the client receive? [Un HTTP GET ajunge la Nginx cu proxy_next_upstream error timeout implicit. Conectarea la serverul ales este refuzată înainte de a trimite ceva clientului. Alt server eligibil returnează 200, iar limitele nu împiedică încercarea. Ce poate primi clientul?] -- **a)** 200 OK, because Nginx instantly reroutes to a healthy backend before the client notices [200 OK, deoarece Nginx redirecționează instant către un server sănătos înainte ca clientul să observe] -- **b)** 504 Gateway Timeout after waiting for the configurable proxy_read_timeout interval to expire [504 Gateway Timeout după așteptarea expirării intervalului configurabil proxy_read_timeout] -- **c)** 503 Service Unavailable, which Nginx sends immediately upon detecting any failed backend [503 Service Unavailable, pe care Nginx îl trimite imediat la detectarea oricărui server eșuat] -- **d)** 502 Bad Gateway, because Nginx discovers the failure only upon forwarding the actual request [502 Bad Gateway, deoarece Nginx descoperă eșecul doar la redirecționarea cererii reale] +- **a)** 200 from the second backend after Nginx retries the connection error [200 de la al doilea server după ce Nginx reîncearcă eroarea de conectare] +- **b)** Always 504, regardless of the successful retry [Întotdeauna 504, indiferent de reîncercarea reușită] +- **c)** Always 503 whenever one backend is unavailable [Întotdeauna 503 când un server este indisponibil] +- **d)** Always 502 because the first attempt failed [Întotdeauna 502 deoarece prima încercare a eșuat]
    💡 Feedback -Nginx uses passive health checks by default: it detects failure only when a real request fails. The first request to the dead backend returns 502. After max_fails (default 1), Nginx marks web2 as unhealthy for fail_timeout seconds. [Nginx folosește verificări pasive de sănătate implicit: detectează eșecul doar când o cerere reală eșuează. Prima cerere către serverul căzut returnează 502. După max_fails (implicit 1), Nginx marchează web2 ca nesănătos pentru fail_timeout secunde.] +**Correct answer / Răspuns corect: a.** Default passive failure detection does not imply that the client sees the first upstream error. error and timeout are retry conditions by default. Whether a retry succeeds depends on method, response progress, eligible peers and configured limits; failover is not instantaneous or universally successful. [Detectarea pasivă implicită nu implică afișarea primei erori upstream către client. error și timeout sunt condiții implicite de reîncercare. Succesul depinde de metodă, progresul răspunsului, serverele eligibile și limitele configurate; comutarea nu este instantanee sau universal reușită.]
    --- -### Q7. `N11.C02.Q03` -**Meaning of HTTP 502 from Nginx / Semnificația HTTP 502 de la Nginx** +### Q7. `N11.C02.Q03` — Meaning of HTTP 502 from Nginx / Semnificația HTTP 502 de la Nginx -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> An Nginx reverse proxy returns HTTP 502 Bad Gateway. What does this status code indicate about the system state? [Un proxy invers Nginx returnează HTTP 502 Bad Gateway. Ce indică acest cod de stare despre starea sistemului?] +What is a defensible interpretation of HTTP502 returned through an Nginx reverse proxy? [Care este o interpretare justificată a HTTP502 returnat printr-un proxy invers Nginx?] -- **a)** The client sent a malformed HTTP request that Nginx cannot parse correctly [Clientul a trimis o cerere HTTP malformată pe care Nginx nu o poate analiza corect] -- **b)** The Nginx process itself has crashed and the operating system is generating the error page [Procesul Nginx s-a prăbușit și sistemul de operare generează pagina de eroare] -- **c)** Nginx is running but the upstream backend is unreachable or returned an invalid response [Nginx funcționează dar serverul din amonte este inaccesibil sau a returnat un răspuns invalid] -- **d)** The Nginx configuration file contains a syntax error discovered at runtime [Fișierul de configurare Nginx conține o eroare de sintaxă descoperită la rulare] +- **a)** The client must have sent malformed request syntax [Clientul trebuie să fi trimis sintaxă invalidă] +- **b)** The operating system proves that every Nginx worker crashed [Sistemul de operare dovedește că toate procesele Nginx au căzut] +- **c)** An upstream/gateway response problem was reported; logs and upstream_status are needed to identify the cause [A fost raportată o problemă upstream/gateway; jurnalele și upstream_status sunt necesare pentru cauză] +- **d)** The configuration parser has necessarily found a syntax error [Parserul configurației a găsit neapărat o eroare sintactică]
    💡 Feedback -502 means Nginx itself is operational but received an invalid response (or no response) from the upstream backend. It does not indicate an Nginx crash. 503 would mean all backends are unavailable; 504 would mean the backend was too slow. [502 înseamnă că Nginx este operațional dar a primit un răspuns invalid (sau niciun răspuns) de la serverul din amonte. Nu indică o cădere a Nginx. 503 ar însemna că toate serverele sunt indisponibile; 504 ar însemna că serverul a fost prea lent.] +**Correct answer / Răspuns corect: c.** 502 is a gateway/upstream error category, not a unique diagnosis. It can arise from connection or invalid-response failures, or be a status relayed from an upstream.504 concerns a timeout;503 can indicate overload, maintenance or configured policies and does not universally mean all backends are down. [502 este o categorie de eroare gateway/upstream, nu un diagnostic unic. Poate rezulta din eșecul conectării sau un răspuns invalid ori poate fi preluat de la un upstream.504 privește un timeout;503 poate indica supraîncărcare, mentenanță sau politici configurate și nu înseamnă universal că toate serverele sunt căzute.]
    @@ -315,21 +313,20 @@ DNS resolution follows a delegation chain: root servers → .ro TLD servers → --- -### Q16. `N11.C04.Q03` -**TTL Caching Behaviour / Comportamentul de caching TTL** +### Q16. `N11.C04.Q03` — TTL Caching Behaviour / Comportamentul de caching TTL -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> You set a DNS record TTL to 60 seconds. A user reports seeing the old IP address 5 minutes later. What is the most probable explanation? [Setați TTL-ul unei înregistrări DNS la 60 de secunde. Un utilizator raportează că vede adresa IP veche 5 minute mai târziu. Care este cea mai probabilă explicație?] +A resolver caches an A record at t=0 with TTL 600. At t=60 the authority changes the address and lowers its new TTL to 60. At t=300 the resolver still returns the old address. Which explanation follows from these facts? [Un resolver memorează o înregistrare A la t=0 cu TTL 600. La t=60 autoritatea schimbă adresa și reduce noul TTL la 60. La t=300 resolverul încă returnează adresa veche. Ce explicație rezultă?] -- **a)** The user's ISP resolver enforces a minimum cache duration longer than the configured TTL [Resolverul ISP al utilizatorului impune o durată minimă de cache mai lungă decât TTL-ul configurat] -- **b)** The DNS update definitively failed and the old record is still active on the authoritative server [Actualizarea DNS a eșuat definitiv și înregistrarea veche este încă activă pe serverul autoritativ] -- **c)** The user must manually flush their local DNS cache using the ipconfig /flushdns command [Utilizatorul trebuie să golească manual cache-ul DNS local folosind comanda ipconfig /flushdns] -- **d)** DNS propagation universally requires 24 to 48 hours regardless of TTL configuration settings [Propagarea DNS necesită universal 24 până la 48 de ore indiferent de setările de configurare TTL] +- **a)** The previously cached record has not reached its original 600-second expiry [Înregistrarea memorată anterior nu a ajuns la expirarea originală de 600 de secunde] +- **b)** DNS TTLs are merely suggestions that a compliant cache may ignore arbitrarily [TTL-urile DNS sunt simple sugestii ignorabile arbitrar de un cache conform] +- **c)** All DNS changes take 48 hours [Toate schimbările DNS durează 48 de ore] +- **d)** The authoritative update must have failed [Actualizarea autoritativă trebuie să fi eșuat]
    💡 Feedback -TTL is advisory, not mandatory. ISP resolvers, OS caches, and browsers may enforce minimum TTL values (often 5 minutes) that override the record's own TTL setting. [TTL este consultativ, nu obligatoriu. Resolverele ISP, cache-urile OS și browserele pot impune valori TTL minime (adesea 5 minute) care suprascriu setarea TTL proprie a înregistrării.] +**Correct answer / Răspuns corect: a.** Changing an authoritative TTL does not retroactively shorten a record already cached under its old TTL. At t=300 the original record has 300 seconds left. Ordinary cached DNS data expires according to its received TTL; serve-stale and application caching have separate policies and must be identified explicitly. [Modificarea TTL-ului autoritativ nu scurtează retroactiv înregistrarea deja memorată cu TTL-ul vechi. La t=300 mai rămân 300 de secunde. Datele DNS obișnuite expiră conform TTL-ului primit; serve-stale și cache-ul aplicației au politici distincte care trebuie identificate explicit.]
    @@ -555,21 +552,20 @@ SSH's Transport Layer Protocol (RFC 4253) provides server authentication, confid --- -### Q28. `N11.T00.Q01` -**Scenario: Backend Failure Diagnosis / Scenariu: diagnosticarea eșecului serverului** +### Q28. `N11.T00.Q01` — Scenario: Backend Failure Diagnosis / Scenariu: diagnosticarea eșecului serverului -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> A student configures Nginx with 3 backends and default settings. After stopping Backend 2, they send 6 requests and observe one 502 error followed by successful responses alternating between Backends 1 and 3. Explain what happened. [Un student configurează Nginx cu 3 servere și setări implicite. După oprirea Backend 2, trimite 6 cereri și observă o eroare 502 urmată de răspunsuri de succes alternând între Backend 1 și 3. Explicați ce s-a întâmplat.] +For this experiment Nginx has proxy_next_upstream off, max_fails=1 and fail_timeout=10s. Backend 2 refuses the first connection. Six requests finish within those 10 seconds; the other two backends succeed. Why can the trace contain one 502 followed by successful requests to the remaining peers? [În acest experiment Nginx are proxy_next_upstream off, max_fails=1 și fail_timeout=10s. Backend 2 refuză prima conectare. Șase cereri se încheie în acele 10 secunde, iar celelalte servere reușesc. De ce poate captura arăta un 502 urmat de cereri reușite către serverele rămase?] -- **a)** Backend 2 continues receiving requests because Nginx does not track backend health states [Backend 2 continuă să primească cereri deoarece Nginx nu urmărește stările de sănătate ale serverelor] -- **b)** The 502 results from passive health check detection; Nginx marks Backend 2 down and redistributes to the remaining healthy backends [502 rezultă din detectarea pasivă; Nginx marchează Backend 2 ca inactiv și redistribuie către serverele sănătoase rămase] -- **c)** Nginx detected the failure before any request reached Backend 2 using active health probes that periodically test each upstream endpoint independently [Nginx a detectat eșecul înainte ca vreo cerere să ajungă la Backend 2 folosind sonde active de sănătate care testează periodic fiecare punct final upstream în mod independent] -- **d)** The 502 error indicates that Nginx itself crashed and restarted automatically [Eroarea 502 indică faptul că Nginx s-a prăbușit și s-a repornit automat] +- **a)** Nginx never records backend failures [Nginx nu înregistrează niciodată eșecurile serverelor] +- **b)** Retry is disabled for the failed request; passive detection excludes that peer temporarily for later requests [Reîncercarea este dezactivată pentru cererea eșuată; detectarea pasivă exclude temporar acel server pentru cererile ulterioare] +- **c)** Active probes predicted the failure before it happened [Sondele active au prezis eșecul înainte să apară] +- **d)** 502 proves Nginx itself crashed [502 dovedește că Nginx însuși a căzut]
    💡 Feedback -When Backend 2 receives its first request and fails, Nginx returns 502 (passive detection). Nginx marks Backend 2 as down (max_fails=1). Subsequent requests distribute between the two remaining healthy backends via round-robin. [Prima cerere direcționată către Backend 2 eșuează cu 502 (detecție pasivă). Nginx marchează Backend 2 ca inactiv (max_fails=1). Cererile ulterioare se distribuie între cele două servere sănătoase rămase prin round-robin.] +**Correct answer / Răspuns corect: b.** The explicit retry setting makes the first client-visible error plausible. With the usual error/timeout retry behaviour, another healthy upstream might instead satisfy that same request. Passive exclusion is time-limited and is not a guarantee of a permanent down state. [Setarea explicită de reîncercare face plauzibilă prima eroare vizibilă clientului. Cu comportamentul uzual error/timeout, alt upstream sănătos ar putea satisface chiar acea cerere. Excluderea pasivă este temporară, nu o stare down permanentă.]
    @@ -615,21 +611,20 @@ After pool changes, the client may be routed to any remaining backend (A, B, or --- -### Q31. `N11.T00.Q04` -**Scenario: DNS TTL and Caching Behaviour / Scenariu: TTL DNS și comportamentul de caching** +### Q31. `N11.T00.Q04` — Scenario: DNS TTL and Caching Behaviour / Scenariu: TTL DNS și comportamentul de caching -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> A DNS record has TTL=300 (5 minutes). You change the IP at the authoritative server. After 10 minutes, one user sees the new IP but another does not. What explains this inconsistency? [O înregistrare DNS are TTL=300 (5 minute). Schimbați IP-ul la serverul autoritativ. După 10 minute, un utilizator vede noul IP dar altul nu. Ce explică această inconsistență?] +An authority currently returns TTL 300. Ten minutes after an address change, one user sees the old IP and another the new IP. Previous TTLs, queried servers, application caching and serve-stale settings are unknown. What conclusion is justified? [Autoritatea returnează acum TTL 300. La zece minute după schimbare, un utilizator vede IP-ul vechi, altul pe cel nou. TTL-urile anterioare, serverele interogate, cache-ul aplicației și setările serve-stale sunt necunoscute. Ce concluzie este justificată?] -- **a)** The DNS change failed partially, updating some authoritative servers but not others [Schimbarea DNS a eșuat parțial, actualizând unele servere autoritative dar nu pe toate] -- **b)** The user who sees the old IP has a corrupted DNS cache that requires manual intervention such as running ipconfig /flushdns or restarting the resolver service [Utilizatorul care vede IP-ul vechi are un cache DNS corupt care necesită intervenție manuală precum rularea ipconfig /flushdns sau repornirea serviciului de rezolvare] -- **c)** DNS propagation is inherently random and unpredictable regardless of TTL settings [Propagarea DNS este inerent aleatorie și imprevizibilă indiferent de setările TTL] -- **d)** Different resolvers enforce different minimum TTL policies, causing inconsistent cache expiration times [Resolvere diferite impun politici diferite de TTL minim, cauzând timpi inconsistenți de expirare a cache-ului] +- **a)** The authoritative update certainly failed [Actualizarea autoritativă a eșuat sigur] +- **b)** The old cache is necessarily corrupted [Cache-ul vechi este neapărat corupt] +- **c)** Every resolver is entitled to ignore TTL indefinitely [Orice resolver are dreptul să ignore TTL nelimitat] +- **d)** More evidence is needed: compare authoritative answers, remaining cached TTL, lookup path and documented stale/application policies [Sunt necesare dovezi: comparați răspunsurile autoritative, TTL-ul rămas, traseul rezolvării și politicile documentate stale/aplicație]
    💡 Feedback -Different resolvers cache independently and may apply different minimum TTL policies. Browser caches, OS caches, and ISP resolvers each have their own TTL enforcement rules that may extend caching beyond the record's specified TTL. [Resolvere diferite memorează independent și pot aplica politici diferite de TTL minim. Cache-urile browserelor, cache-urile OS și resolverele ISP au fiecare regulile proprii de impunere TTL care pot extinde memorarea dincolo de TTL-ul specificat al înregistrării.] +**Correct answer / Răspuns corect: d.** Independent observations do not establish a unique cause. A pre-change long TTL, inconsistent authorities, a hosts override, application cache or an explicit serve-stale policy can produce different observations. Do not teach arbitrary minimum TTL as the general DNS rule. [Observațiile nu stabilesc o cauză unică. Un TTL vechi mai lung, autorități nealiniate, o suprascriere hosts, cache-ul aplicației sau o politică serve-stale explicită pot produce observații diferite. Un TTL minim arbitrar nu este regula generală DNS.]
    @@ -675,41 +670,39 @@ Encoding: \x04mail (5) + \x06google (7) + \x03com (4) + \x00 (1) = 17 bytes. Eac --- -### Q34. `N11.T00.Q08` -**Scenario: proxy_next_upstream Retry Limits / Scenariu: limitele de reîncercare proxy_next_upstream** +### Q34. `N11.T00.Q08` — Scenario: proxy_next_upstream Retry Limits / Scenariu: limitele de reîncercare proxy_next_upstream -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Nginx is configured with proxy_next_upstream_tries 3; and 5 backends. If the first 3 backends all return 502, what happens to the request? [Nginx este configurat cu proxy_next_upstream_tries 3; și 5 servere. Dacă primele 3 servere returnează toate 502, ce se întâmplă cu cererea?] +A GET has proxy_next_upstream error timeout http_502 and proxy_next_upstream_tries 3. Five peers are eligible; each of the first three contacted peers returns 502 before any response reaches the client. What happens when no other limit intervenes? [Un GET are proxy_next_upstream error timeout http_502 și proxy_next_upstream_tries 3. Cinci servere sunt eligibile; primele trei contactate returnează 502 înainte să ajungă un răspuns la client. Ce se întâmplă dacă nu intervine altă limită?] -- **a)** The client receives 502 — Nginx stops after 3 tries even though 2 healthy backends remain untried [Clientul primește 502 — Nginx se oprește după 3 încercări chiar dacă 2 servere sănătoase rămân neîncercate] -- **b)** Nginx queues the request until one of the failed backends recovers and can serve it [Nginx pune cererea în coadă până când unul dintre serverele eșuate se recuperează și o poate servi] -- **c)** Nginx automatically tries all 5 backends regardless of the proxy_next_upstream_tries setting [Nginx încearcă automat toate cele 5 servere indiferent de setarea proxy_next_upstream_tries] -- **d)** Nginx returns 503 Service Unavailable once any retry limit is reached during request processing, regardless of whether other healthy backends remain available in the pool [Nginx returnează 503 Service Unavailable odată ce orice limită de reîncercare este atinsă, indiferent dacă alte servere sănătoase rămân disponibile în grup] +- **a)** After three total upstream attempts, Nginx stops and returns the final 502; two peers remain untried [După trei încercări upstream în total, Nginx se oprește și returnează ultimul 502; două servere rămân neîncercate] +- **b)** It makes the initial attempt plus three retries, so four total attempts [Face încercarea inițială plus trei reîncercări, adică patru în total] +- **c)** It must contact all five peers [Trebuie să contacteze toate cele cinci servere] +- **d)** It changes every final upstream error into 503 [Transformă orice eroare upstream finală în 503]
    💡 Feedback -After 3 retry attempts (the configured limit), Nginx stops trying additional backends and returns the last error (502) to the client. The remaining 2 backends are not contacted for this request. [După 3 încercări de reîncercare (limita configurată), Nginx oprește încercarea serverelor suplimentare și returnează ultima eroare (502) clientului. Cele 2 servere rămase nu sunt contactate pentru această cerere.] +**Correct answer / Răspuns corect: a.** The tries value bounds the total upstream attempts, including the first. http_502 must be included to make a returned 502 a retry condition; it is not enabled by the default error timeout alone. Retries also require that nothing has already been sent to the client. [Valoarea tries limitează totalul încercărilor upstream, inclusiv prima. http_502 trebuie inclus pentru ca un 502 returnat să declanșeze reîncercarea; nu este activat doar de error timeout implicit. Reîncercarea cere și să nu fi fost trimis deja ceva clientului.]
    --- -### Q35. `N11.T00.Q09` -**Scenario: Least Connections with Slow Backend / Scenariu: least connections cu server lent** +### Q35. `N11.T00.Q09` — Scenario: Least Connections with Slow Backend / Scenariu: least connections cu server lent -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Three backends start with 0 active connections. Backend 3 has --delay 2.0 (2 second response time). After 10 rapid requests, which backend has the most active connections? [Trei servere pornesc cu 0 conexiuni active. Backend 3 are --delay 2.0 (timp de răspuns de 2 secunde). După 10 cereri rapide, care server are cele mai multe conexiuni active?] +At the decision instant, three healthy equal-weight peers have active connection counts B1=0, B2=0, B3=2. Where does least_conn send the next eligible request? [La momentul deciziei, trei servere sănătoase cu ponderi egale au conexiuni active B1=0, B2=0, B3=2. Unde trimite least_conn următoarea cerere eligibilă?] -- **a)** Backend 3 accumulates the most active connections because its 2-second delay keeps them open longer [Backend 3 acumulează cele mai multe conexiuni active deoarece întârzierea de 2 secunde le menține deschise mai mult] -- **b)** All three backends have equal active connections because least_conn distributes them evenly [Toate cele trei servere au conexiuni active egale deoarece least_conn le distribuie uniform] -- **c)** Backend 1 has the most because least_conn always prefers the first listed server [Backend 1 are cele mai multe deoarece least_conn preferă întotdeauna primul server listat] -- **d)** Connection counts cannot be predicted because they depend on operating system scheduling and kernel-level thread allocation policies that vary between operating systems [Numărătoarea conexiunilor nu poate fi prezisă deoarece depinde de planificarea sistemului de operare și politicile de alocare a firelor la nivel de kernel care variază între sistemele de operare] +- **a)** B1 or B2, using the tie-breaking policy between the two least-loaded peers [B1 sau B2, folosind politica de departajare între cele două servere cu încărcarea minimă] +- **b)** Always B3 because it is the slowest [Întotdeauna B3 deoarece este cel mai lent] +- **c)** Always the first listed peer, regardless of counts [Întotdeauna primul server, indiferent de numărători] +- **d)** All three peers receive the same request simultaneously [Toate trei primesc simultan aceeași cerere]
    💡 Feedback -Backend 3's 2-second delay means its connections stay open longer. Least connections initially distributes evenly, but as Backend 3 accumulates connections (slow to release), it stops receiving new ones — Backends 1 and 2 process and release faster. [Întârzierea de 2 secunde a Backend 3 înseamnă că conexiunile sale rămân deschise mai mult. Least connections distribuie inițial uniform, dar pe măsură ce Backend 3 acumulează conexiuni (lent la eliberare), oprește primirea de noi — Backend 1 și 2 procesează și eliberează mai repede.] +**Correct answer / Răspuns corect: a.** With equal weights, the active connection counts drive this selection. A two-second response delay alone does not determine counts after ten requests: arrival times, overlap and completion times must also be known. A slow peer may receive fewer new requests while its existing connections remain active. [Cu ponderi egale, numărul conexiunilor active determină această selecție. O întârziere de două secunde nu determină singură numărătorile după zece cereri: trebuie cunoscute sosirile, suprapunerea și finalizările. Un server lent poate primi mai puține cereri noi cât timp conexiunile sale rămân active.]
    @@ -839,61 +832,86 @@ In active mode, the server initiates the data connection back to the client — --- -### Q42. `N11.S01.Q01` -**Round-Robin Modulo Operation Result / Rezultatul operației modulo round-robin** +### Q42. `N11.S01.Q01` — Round-Robin Modulo Operation Result / Rezultatul operației modulo round-robin -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +For a single call to this round-robin selection fragment, what is backend_index after selecting web3? [Pentru un singur apel al acestui fragment round-robin, ce valoare are backend_index după selectarea web3?] -> The Python load balancer exercise uses a round-robin method with self._rr_idx = (self._rr_idx + 1) % n where n = 3. After selecting the third backend (index 2), what is the value of _rr_idx? [Exercițiul cu echilibratorul de încărcare Python utilizează o metodă round-robin cu self._rr_idx = (self._rr_idx + 1) % n unde n = 3. După selectarea celui de-al treilea server (index 2), care este valoarea _rr_idx?] +```python +backends = ["web1", "web2", "web3"] +backend_index = 2 +selected = backends[backend_index] +backend_index = (backend_index + 1) % len(backends) +print(backend_index) +``` -- **a)** 0, because (2 + 1) % 3 wraps back to the beginning of the backend list [0, deoarece (2 + 1) % 3 revine la începutul listei de servere] -- **b)** 3, because the index simply increments without any wraparound applied [3, deoarece indexul pur și simplu crește fără nicio revenire aplicată] -- **c)** 1, because modulo 3 of the value 3 produces a remainder of 1 [1, deoarece modulo 3 din valoarea 3 produce un rest de 1] -- **d)** 2, because the index stays at the current position until the next request arrives [2, deoarece indexul rămâne la poziția curentă până când sosește următoarea cerere] +- **a)** 0 +- **b)** 3 +- **c)** 1 +- **d)** 2
    💡 Feedback -After selecting index 2, the expression evaluates to (2 + 1) % 3 = 0, wrapping back to the first backend. This modulo wraparound is the core mechanism that creates the cyclic pattern. [După selectarea indexului 2, expresia evaluează la (2 + 1) % 3 = 0, revenind la primul server. Această revenire prin modulo este mecanismul central care creează modelul ciclic.] +**Correct answer / Răspuns corect: a.** The updated index is(2+1)%3=0. The fragment uses the backend_index convention of S11_Part02_Script_Simple_Lb.py. This question assumes one call; concurrent allocation requires synchronisation. [Indicele actualizat este(2+1)%3=0. Fragmentul folosește convenția backend_index din S11_Part02_Script_Simple_Lb.py. Se presupune un singur apel; alocarea concurentă necesită sincronizare.]
    --- -### Q43. `N11.S01.Q02` -**IP Hash Determinism Property / Proprietatea de determinism a IP hash** +### Q43. `N11.S01.Q02` — IP Hash Determinism Property / Proprietatea de determinism a IP hash -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +Consider this independent IP-hash extension. The ordered backend list and health state remain unchanged. How many distinct backends do five calls with the same address select? [Considerați această extensie independentă IP-hash. Lista ordonată a serverelor și starea lor rămân neschimbate. Câte servere distincte selectează cinci apeluri cu aceeași adresă?] -> The code h = (h * 131 + ord(ch)) & 0xFFFFFFFF computes the hash. If the same client IP sends 5 consecutive requests, how many distinct backends will be selected? [Codul h = (h * 131 + ord(ch)) & 0xFFFFFFFF calculează hash-ul. Dacă aceeași adresă IP de client trimite 5 cereri consecutive, câte servere distincte vor fi selectate?] +```python +backends = ["web1", "web2", "web3"] +def choose(ip): + h = 0 + for ch in ip: + h = (h * 131 + ord(ch)) & 0xFFFFFFFF + return backends[h % len(backends)] -- **a)** Three — requests distribute evenly across all backends regardless of client IP address [Trei — cererile se distribuie uniform între toate serverele indiferent de adresa IP a clientului] -- **b)** Exactly one — the deterministic hash always maps the same IP to the same backend [Exact unul — hash-ul determinist asociază întotdeauna aceeași adresă IP cu același server] -- **c)** It varies unpredictably because the bitwise AND introduces non-deterministic truncation [Variază imprevizibil deoarece AND pe biți introduce o trunchiere nedeterministă] -- **d)** Five — each request produces a different hash because the algorithm uses random seeding [Cinci — fiecare cerere produce un hash diferit deoarece algoritmul folosește inițializare aleatorie] +print(len({choose("192.0.2.10") for _ in range(5)})) +``` + +- **a)** Three, because every call advances a round-robin counter [Trei, deoarece orice apel avansează un contor round-robin] +- **b)** Exactly one [Exact unul] +- **c)** An unpredictable count because integer AND is random [Un număr imprevizibil deoarece AND întreg este aleatoriu] +- **d)** Five, because each call uses a new random seed [Cinci, deoarece fiecare apel folosește o nouă inițializare aleatorie]
    💡 Feedback -Hash functions are deterministic: identical input always produces the same output. All 5 requests from the same IP select the same backend, providing session affinity. The & 0xFFFFFFFF constrains the hash to 32 bits. [Funcția hash este deterministă: aceeași intrare produce întotdeauna aceeași ieșire. Toate cele 5 cereri de la aceeași adresă IP selectează același server, asigurând afinitatea sesiunii. Operatorul & 0xFFFFFFFF constrânge hash-ul la 32 de biți.] +**Correct answer / Răspuns corect: b.** The hash starts from zero for each call and depends only on the same input. With the same ordered pool, h modulo its length selects one index. Pool/health changes can alter real load-balancer affinity; this toy hash is not claimed to be Nginx ip_hash or the supplied basic round-robin script. [Hash-ul pornește de la zero la fiecare apel și depinde doar de aceeași intrare. Cu același grup ordonat, h modulo lungimea sa selectează un singur indice. Schimbările grupului/stării pot modifica afinitatea reală; acest model nu pretinde că este Nginx ip_hash sau scriptul round-robin de bază.]
    --- -### Q44. `N11.S01.Q03` -**Health Check State Transition / Tranziția de stare a verificării de sănătate** +### Q44. `N11.S01.Q03` — Health Check State Transition / Tranziția de stare a verificării de sănătate -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +In this independent passive-failure model, after how many consecutive calls is down first True? No success/reset occurs between calls. [În acest model independent de eșec pasiv, după câte apeluri consecutive devine down prima dată True? Nu apare succes/reset între apeluri.] -> In the Python LB, mark_failure() increments fails and marks the backend down when fails >= passive_failures. If passive_failures=2, after how many consecutive failures is the backend marked down? [În echilibratorul Python, mark_failure() incrementează fails și marchează serverul ca inactiv când fails >= passive_failures. Dacă passive_failures=2, după câte eșecuri consecutive este serverul marcat ca inactiv?] +```python +fails = 0 +passive_failures = 2 +def mark_failure(): + global fails + fails += 1 + return fails >= passive_failures +``` -- **a)** After 2 consecutive failures, since the condition fails >= 2 becomes true at that point [După 2 eșecuri consecutive, deoarece condiția fails >= 2 devine adevărată în acel moment] -- **b)** The backend is never marked down — passive_failures only logs warnings without action [Serverul nu este niciodată marcat ca inactiv — passive_failures doar jurnalizează avertismente fără acțiune] -- **c)** After 3 failures, because >= actually requires one extra failure beyond the threshold [După 3 eșecuri, deoarece >= necesită de fapt un eșec suplimentar peste prag] -- **d)** After 1 failure, because the >= operator triggers on the first increment above zero [După 1 eșec, deoarece operatorul >= se declanșează la prima incrementare peste zero] +- **a)** Two [Două] +- **b)** Never [Niciodată] +- **c)** Three [Trei] +- **d)** One [Unul]
    💡 Feedback -Nginx marks the backend as down on the second consecutive failure (fails reaches 2, satisfying >= 2). After marking, down_until is set to current_time + fail_timeout_s. [Serverul este marcat ca inactiv la al doilea eșec consecutiv (fails ajunge la 2, satisfăcând >= 2). După marcare, down_until este setat la timpul_curent + fail_timeout_s.] +**Correct answer / Răspuns corect: a.** fails starts at 0 and reaches the threshold 2 on the second increment. The snippet defines the entire answer and is not presented as the implementation of the supplied S11 proxy or as Nginx internal code. Real timeout windows and recovery rules must be specified separately. [fails pornește de la 0 și ajunge la pragul 2 la a doua incrementare. Fragmentul definește complet răspunsul și nu este prezentat ca implementarea proxy-ului S11 sau drept cod intern Nginx. Ferestrele de timp și regulile reale de recuperare trebuie specificate separat.]
    @@ -928,12 +946,12 @@ HTTP Content-Length specifies the body size in bytes, not characters. For ASCII - **a)** It enables the socket to accept connections from multiple clients simultaneously [Permite socket-ului să accepte conexiuni de la mai mulți clienți simultan] - **b)** It disables Nagle's algorithm to reduce latency for small HTTP response packets [Dezactivează algoritmul Nagle pentru a reduce latența pentru pachetele mici de răspuns HTTP] -- **c)** It allows binding to a port still in TIME_WAIT state from a previous process instance [Permite legarea la un port încă în starea TIME_WAIT de la o instanță anterioară a procesului] +- **c)** It allows binding to an address affected by TIME_WAIT connections from a previous instance, subject to operating-system rules [Permite legarea la o adresă afectată de conexiuni TIME_WAIT ale unei instanțe anterioare, conform regulilor sistemului de operare] - **d)** It increases the maximum buffer size for receiving large HTTP request bodies [Crește dimensiunea maximă a buffer-ului pentru primirea corpurilor mari de cereri HTTP]
    💡 Feedback -SO_REUSEADDR allows the server to bind immediately after a restart, even if the previous socket is still in TIME_WAIT state. Without it, restarting the backend would fail with 'Address already in use' for up to 60 seconds. [SO_REUSEADDR permite serverului să se lege imediat după o repornire, chiar dacă socket-ul anterior este încă în starea TIME_WAIT. Fără aceasta, repornirea serverului ar eșua cu 'Address already in use' până la 60 de secunde.] +**Correct answer / Răspuns corect: c.** SO_REUSEADDR can permit rebinding an address affected by old TCP connections under the operating system's rules. A listening socket itself does not enter TIME_WAIT, restart does not always fail without this option, and it does not generally let a second live listener take the same address. [SO_REUSEADDR poate permite relegarea unei adrese afectate de conexiuni TCP vechi, conform regulilor sistemului. Socket-ul de ascultare nu intră el însuși în TIME_WAIT, repornirea nu eșuează întotdeauna fără opțiune, iar aceasta nu permite în general unui al doilea listener activ să preia aceeași adresă.]
    @@ -1019,41 +1037,39 @@ nginx -t tests the configuration syntax and reports errors without modifying the --- -### Q51. `N11.S02.Q05` -**Nginx X-Served-By Header Source / Sursa antetului X-Served-By Nginx** +### Q51. `N11.S02.Q05` — Nginx X-Served-By Header Source / Sursa antetului X-Served-By Nginx -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> The Week 11 nginx.conf includes add_header X-Served-By $upstream_addr always;. What value does the client see in this header? [Fișierul nginx.conf din săptămâna 11 include add_header X-Served-By $upstream_addr always;. Ce valoare vede clientul în acest antet?] +You add add_header X-Served-By $upstream_addr always; to the relevant Nginx location. What can the value contain when an upstream attempt is retried? [Adăugați add_header X-Served-By $upstream_addr always; în locația Nginx relevantă. Ce poate conține valoarea când o încercare upstream este repetată?] -- **a)** The round-robin counter value indicating the position in the distribution sequence [Valoarea contorului round-robin indicând poziția în secvența de distribuție] -- **b)** The public hostname of the Nginx load balancer itself as configured in server_name [Numele de gazdă public al echilibratorului de încărcare Nginx însuși conform server_name] -- **c)** The total number of requests processed by the upstream pool since the last restart [Numărul total de cereri procesate de grupul din amonte de la ultima repornire] -- **d)** The IP address and port of the specific backend server that processed the request [Adresa IP și portul serverului specific care a procesat cererea] +- **a)** Only a round-robin counter [Doar un contor round-robin] +- **b)** Only the proxy's public hostname [Doar numele public al proxy-ului] +- **c)** The cumulative number of requests [Numărul cumulativ al cererilor] +- **d)** The address:port values for upstream attempts, possibly a comma-separated list containing failed attempts as well as the successful one [Valorile adresă:port ale încercărilor upstream, posibil o listă separată prin virgulă cu încercări eșuate și cea reușită]
    💡 Feedback -The $upstream_addr variable contains the IP address and port of the backend that actually served the request. This allows verifying which backend handled each request when testing load distribution. [Variabila $upstream_addr conține adresa IP și portul serverului care a servit efectiv cererea. Aceasta permite verificarea care server a gestionat fiecare cerere la testarea distribuției încărcării.] +**Correct answer / Răspuns corect: d.** $upstream_addr can identify several attempted peers; it is not guaranteed to be one backend that successfully served the response. Pair it with $upstream_status and timing/log evidence when analysing retries. The header is an explicit diagnostic extension in this question, not a claim that the baseline S11 configuration already contains it. [$upstream_addr poate identifica mai multe servere încercate; nu este garantat un singur backend care a servit cu succes. Corelați cu $upstream_status și timpi/jurnale la analizarea reîncercărilor. Antetul este o extensie diagnostică explicită aici, nu o afirmație că apare deja în configurația S11 de bază.]
    --- -### Q52. `N11.S02.Q06` -**Lab Service Port Mapping Convention / Convenția de mapare a porturilor serviciilor de laborator** +### Q52. `N11.S02.Q06` — Lab Service Port Mapping Convention / Convenția de mapare a porturilor serviciilor de laborator -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> The Week 11 lab maps Nginx container port 80 to host port 8080 (ports: "8080:80"). Why is port 9000 never used for lab services? [Laboratorul din săptămâna 11 mapează portul 80 al containerului Nginx la portul host 8080 (ports: "8080:80"). De ce nu este folosit niciodată portul 9000 pentru serviciile de laborator?] +Suppose a local Portainer instance already binds 127.0.0.1:9000/TCP. Why should another lab service use a different host mapping, such as 8080:80, on that address? [Presupuneți că un Portainer local ascultă deja pe 127.0.0.1:9000/TCP. De ce trebuie alt serviciu de laborator să folosească o altă mapare gazdă, precum 8080:80, pe acea adresă?] -- **a)** Port 9000 exceeds the range supported by Docker Compose port mapping configuration [Portul 9000 depășește intervalul suportat de configurarea mapării porturilor Docker Compose] -- **b)** Port 9000 is blocked by the Windows firewall and cannot be mapped through WSL [Portul 9000 este blocat de paravanul de protecție Windows și nu poate fi mapat prin WSL] -- **c)** Port 9000 is reserved for Portainer, the persistent Docker management service across all weeks [Portul 9000 este rezervat pentru Portainer, serviciul persistent de gestionare Docker din toate săptămânile] -- **d)** Port 9000 is a well-known protocol port assigned to a specific IANA-registered service [Portul 9000 este un port de protocol bine-cunoscut atribuit unui serviciu specific înregistrat IANA] +- **a)** Docker cannot map ports above 8999 [Docker nu poate mapa porturi peste 8999] +- **b)** Windows universally blocks 9000 [Windows blochează universal 9000] +- **c)** The chosen host address/TCP port is occupied; the conflict depends on the actual local bindings [Adresa și portul TCP alese sunt ocupate; conflictul depinde de legările locale reale] +- **d)** Port9000 is permanently forbidden to every other application [Portul9000 este interzis permanent oricărei alte aplicații]
    💡 Feedback -Port 9000 is permanently reserved for Portainer, the Docker management interface that runs as a global service across all lab weeks. Using it for any other service would create a port conflict. [Portul 9000 este rezervat permanent pentru Portainer, interfața de gestionare Docker care rulează ca serviciu global în toate săptămânile de laborator. Folosirea lui pentru orice alt serviciu ar crea un conflict de porturi.] +**Correct answer / Răspuns corect: c.** Port use is a local configuration decision. Portainer may use other ports, and another scenario can use 9000 when its host binding is free. Check actual listeners and Compose mappings; do not infer a universal IANA or repository reservation from one installation. [Utilizarea porturilor este o decizie de configurare locală. Portainer poate folosi alte porturi, iar alt scenariu poate utiliza 9000 când legarea gazdei este liberă. Verificați listener-ele și mapările Compose reale; nu deduceți o rezervare universală IANA sau a repository-ului dintr-o instalare.]
    @@ -1079,21 +1095,20 @@ Nginx's proxy_next_upstream directive specifies which upstream failures trigger --- -### Q54. `N11.S03.Q01` -**Wireshark Interface Selection for Docker Traffic / Selectarea interfeței Wireshark pentru traficul Docker** +### Q54. `N11.S03.Q01` — Wireshark Interface Selection for Docker Traffic / Selectarea interfeței Wireshark pentru traficul Docker -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> To capture traffic between Docker containers running in WSL, which Wireshark capture interface should you select? [Pentru a captura traficul între containerele Docker care rulează în WSL, ce interfață de captură Wireshark trebuie selectată?] +You need to capture traffic between two Docker containers on the same Linux bridge, with the engine running in a WSL/VM environment. Which approach follows the actual packet path? [Trebuie capturat traficul între două containere Docker de pe același bridge Linux, cu motorul în WSL/VM. Ce abordare urmează traseul real al pachetelor?] -- **a)** Any interface works — Wireshark automatically detects and captures Docker traffic universally [Orice interfață funcționează — Wireshark detectează și capturează automat traficul Docker universal] -- **b)** The physical Ethernet adapter, since Docker traffic exits through the hardware NIC [Adaptorul fizic Ethernet, deoarece traficul Docker iese prin placa de rețea hardware] -- **c)** Loopback Adapter, because all Docker containers communicate via localhost only [Adaptorul Loopback, deoarece toate containerele Docker comunică doar prin localhost] -- **d)** vEthernet (WSL), because Docker container traffic in WSL traverses this virtual interface [vEthernet (WSL), deoarece traficul containerelor Docker din WSL traversează această interfață virtuală] +- **a)** Choose any Windows interface because all see every packet [Alegeți orice interfață Windows deoarece toate văd toate pachetele] +- **b)** Always use the physical Wi-Fi adapter [Folosiți întotdeauna adaptorul Wi-Fi fizic] +- **c)** Always use Windows loopback because containers use only 127.0.0.1 [Folosiți întotdeauna loopback Windows deoarece containerele folosesc doar 127.0.0.1] +- **d)** Capture on the relevant Linux bridge/veth or in a container network namespace; verify where the Docker engine runs before selecting an interface [Capturați pe bridge/veth Linux relevant sau în namespace-ul de rețea al containerului; verificați unde rulează motorul Docker înainte de alegerea interfeței]
    💡 Feedback -Docker containers in WSL generate traffic visible on the vEthernet (WSL) virtual interface. The physical Ethernet/Wi-Fi adapter carries only host traffic; the Loopback adapter only handles 127.0.0.1. [Containerele Docker din WSL generează trafic vizibil pe interfața virtuală vEthernet (WSL). Adaptorul fizic Ethernet/Wi-Fi transportă doar traficul gazdei; adaptorul Loopback gestionează doar 127.0.0.1.] +**Correct answer / Răspuns corect: d.** Same-bridge container traffic may remain entirely inside the Linux engine environment. It need not traverse a Windows vEthernet or physical adapter. Capturing traffic to a published host port is a different path. Interface names and visibility depend on the Docker/WSL/VM architecture. [Traficul între containere pe același bridge poate rămâne complet în mediul Linux al motorului. Nu trebuie să traverseze vEthernet Windows sau adaptorul fizic. Captura traficului către un port publicat al gazdei privește alt traseu. Numele și vizibilitatea interfețelor depind de arhitectura Docker/WSL/VM.]
    @@ -1179,21 +1194,20 @@ Encoding: \x03www (4 bytes) + \x03ase (4 bytes) + \x02ro (3 bytes) + \x00 (1 byt --- -### Q59. `N11.S03.Q06` -**Python vs Nginx Performance Comparison / Comparația de performanță Python vs Nginx** +### Q59. `N11.S03.Q06` — Python vs Nginx Performance Comparison / Comparația de performanță Python vs Nginx -*Multiple Choice – Alegere multiplă* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> When benchmarking the Python load balancer from the lab exercises against Nginx, which typically achieves higher throughput and why? [La evaluarea comparativă a echilibratorului de încărcare Python din exercițiile de laborator față de Nginx, care atinge de obicei un debit mai mare și de ce?] +Before any controlled benchmark of the course Python proxy and Nginx has been run, which performance claim is justified? [Înainte de un benchmark controlat al proxy-ului Python din curs și Nginx, ce afirmație de performanță este justificată?] -- **a)** Python, because its threading model handles concurrent connections more efficiently than C [Python, deoarece modelul său de threading gestionează conexiunile concurente mai eficient decât C] -- **b)** Both achieve comparable throughput since the network I/O is the true bottleneck, not the language [Ambele ating un debit comparabil deoarece I/O-ul de rețea este blocajul real, nu limbajul] -- **c)** Nginx, because its optimised C code and event-driven architecture vastly outperform interpreted Python [Nginx, deoarece codul său C optimizat și arhitectura bazată pe evenimente depășesc cu mult Python-ul interpretat] -- **d)** The result depends entirely on the algorithm selected — Python wins with round-robin due to simpler scheduling overhead, while Nginx outperforms only with least_conn [Rezultatul depinde în întregime de algoritmul selectat — Python câștigă cu round-robin datorită costului de planificare mai simplu, în timp ce Nginx depășește doar cu least_conn] +- **a)** Python must win because threads always outperform event loops [Python trebuie să câștige deoarece firele depășesc întotdeauna buclele de evenimente] +- **b)** Both must be equal because all workloads are network-bound [Trebuie să fie egale deoarece orice sarcină este limitată de rețea] +- **c)** No numeric speedup is established; compare both with the same workload and record throughput, latency, errors, concurrency, versions and environment [Nu este stabilită o accelerare numerică; comparați cu aceeași sarcină și înregistrați debitul, latența, erorile, concurența, versiunile și mediul] +- **d)** Nginx is guaranteed to be at least 10 times faster for every workload [Nginx este garantat de cel puțin 10 ori mai rapid pentru orice sarcină]
    💡 Feedback -Nginx typically achieves 10x+ more requests per second than the Python implementation. Nginx is written in optimised C with an asynchronous event-driven architecture, while Python's GIL and interpreted execution create bottlenecks. [Nginx atinge de obicei de peste 10 ori mai multe cereri pe secundă decât implementarea Python. Nginx este scris în C optimizat cu o arhitectură asincronă bazată pe evenimente, în timp ce GIL-ul Python și execuția interpretată creează blocaje.] +**Correct answer / Răspuns corect: c.** An optimised event-driven design motivates a hypothesis, not a universal factor. Match backend delays, connection reuse, payloads and concurrency; repeat trials and report variability. Bottlenecks and error rates can dominate apparent requests/second. No benchmark result is supplied by this question. [Un design optimizat bazat pe evenimente justifică o ipoteză, nu un factor universal. Aliniați întârzierile backend, reutilizarea conexiunilor, payload-urile și concurența; repetați și raportați variabilitatea. Blocajele și rata erorilor pot domina cererile/secundă aparent. Întrebarea nu furnizează un rezultat de benchmark.]
    @@ -1216,3 +1230,10 @@ This command is a useful way to discover container details (including IPs) for a --- + + +## Repository context and reference points + +Canonical practical material: [S11](../../04_SEMINARS/S11/README.md) — Nginx and the basic Python round-robin proxy. Code-tracing models explicitly introduced in this question pool are self-contained exercises, not promises of additional files or features in that seminar. [Material practic canonic: S11. Modelele de trasare introduse explicit sunt exerciții autonome, nu promisiuni de fișiere sau funcții suplimentare în seminar.] + +Implementation reference: [Nginx proxy retry directives](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream) and [upstream variables](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#variables). DNS TTL and serving stale: RFC 8767. https://doi.org/10.17487/RFC8767 diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W12_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W12_Questions.md index 6d862ec..6a01fa8 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W12_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W12_Questions.md @@ -128,20 +128,19 @@ EHLO (Extended HELO) returns a multi-line 250 response listing available extensi --- ### Q7. `N12.C02.Q02` -**SMTP Port Assignments / Atribuirea porturilor SMTP** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Which port is designated for authenticated client-to-server email submission with STARTTLS? [Care port este desemnat pentru trimiterea autentificată a emailurilor de la client la server cu STARTTLS?] +Which registered SMTP submission port is conventionally used with STARTTLS, as distinct from implicit TLS submission on 465? [Ce port înregistrat de submission SMTP este folosit convențional cu STARTTLS, distinct de submission cu TLS implicit pe 465?] -- **a)** 587 — the submission port requiring STARTTLS for authenticated clients [587 — portul de trimitere care necesită STARTTLS pentru clienți autentificați] -- **b)** 25 — the original historical relay port reserved for inter-server mail routing [25 — portul istoric original de releu rezervat pentru rutarea emailurilor între servere] -- **c)** 465 — the legacy port using implicit TLS from the connection start [465 — portul vechi care utilizează TLS implicit de la începutul conexiunii] -- **d)** 443 — the standard port used for any TLS-encrypted web application [443 — portul standard utilizat pentru orice aplicație web criptată cu TLS] +- **a)** 587 +- **b)** 25 +- **c)** 465 +- **d)** 443
    💡 Feedback -Port 587 is the designated submission port for authenticated email clients, requiring STARTTLS for encryption. Port 25 is for server-to-server relay (often blocked by ISPs), and port 465 is the legacy SMTPS port with implicit TLS. The lab uses port 587 for educational purposes. [Portul 587 este portul desemnat pentru trimiterea autentificată de la clienții de email, necesitând STARTTLS pentru criptare. Portul 25 este pentru releu server-la-server (adesea blocat de ISP-uri), iar portul 465 este portul SMTPS vechi cu TLS implicit. Laboratorul folosește portul 587 în scopuri educaționale.] +**Correct answer / Răspuns corect: a.** 587 is the message submission port; encryption is negotiated with STARTTLS when the server supports and the policy requires it. Port 465 is the current registered submissions service using implicit TLS, not merely a legacy port. The number alone does not enable TLS or authentication. [587 este portul pentru submission; criptarea se negociază prin STARTTLS când serverul oferă suport și politica o cere. 465 este serviciul actual înregistrat submissions cu TLS implicit, nu doar un port vechi. Numărul singur nu activează TLS sau autentificarea.]
    @@ -208,20 +207,18 @@ SMTP requires commands in a specific order: EHLO → MAIL FROM → RCPT TO → D --- ### Q11. `N12.C03.Q01` -**Email Delivery Chain / Lanțul de livrare a emailului** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Alice sends an email from Thunderbird to Bob who reads it in Gmail. Which combination of protocols is involved? [Alice trimite un email din Thunderbird către Bob care îl citește în Gmail. Ce combinație de protocoale este implicată?] +Alice sends mail from a desktop mail client configured for SMTP. Bob reads the delivered message through Gmail in a web browser. Which client-facing protocols are stated by this scenario? [Alice trimite email dintr-un client desktop configurat pentru SMTP. Bob citește mesajul livrat prin Gmail în browser. Ce protocoale către clienți sunt precizate de scenariu?] -- **a)** SMTP to push the message between servers, then POP3/IMAP for Bob to retrieve it [SMTP pentru a trimite mesajul între servere, apoi POP3/IMAP pentru ca Bob să-l preia] -- **b)** SMTP alone handles the complete delivery from Alice's client to Bob's inbox directly [SMTP singur gestionează livrarea completă de la clientul lui Alice la inbox-ul lui Bob] -- **c)** HTTP is the only protocol needed since both clients use web-based email access [HTTP este singurul protocol necesar deoarece ambii clienți folosesc acces email bazat pe web] -- **d)** FTP transfers the email file between the two mail servers in the delivery chain [FTP transferă fișierul de email între cele două servere de email din lanțul de livrare] +- **a)** SMTP for Alice’s submission and HTTPS for Bob’s browser access. [SMTP pentru trimiterea lui Alice și HTTPS pentru accesul lui Bob în browser.] +- **b)** FTP for submission and mandatory POP3 inside Bob’s browser. [FTP pentru trimitere și POP3 obligatoriu în browserul lui Bob.] +- **c)** IMAP must be used between Gmail’s internal components. [IMAP trebuie folosit între componentele interne Gmail.]
    💡 Feedback -SMTP is used for sending (push): Alice's MUA → her MTA → Bob's MTA. Bob retrieves the message using a pull protocol (POP3 or IMAP). Gmail's web interface uses HTTP/HTTPS for the user interface, but IMAP or proprietary protocols internally for mail access. [SMTP este utilizat pentru trimitere (push): MUA-ul lui Alice → MTA-ul ei → MTA-ul lui Bob. Bob preia mesajul folosind un protocol de tip pull (POP3 sau IMAP). Interfața web Gmail folosește HTTP/HTTPS pentru interfața utilizatorului, dar IMAP sau protocoale proprietare intern pentru accesul la email.] +**Correct answer / Răspuns corect: a.** SMTP handles mail submission and inter-server relay. Browser access uses HTTPS. This scenario does not establish how the provider’s internal mail storage is accessed; do not infer IMAP or POP3 from webmail use. [SMTP gestionează submission și releul între servere. Accesul prin browser folosește HTTPS. Scenariul nu stabilește cum este accesată stocarea internă a furnizorului; folosirea webmailului nu permite deducerea IMAP sau POP3.]
    @@ -362,20 +359,18 @@ Serialisation (also called marshalling) converts in-memory objects to a wire for --- ### Q19. `N12.C05.Q01` -**JSON-RPC Error vs HTTP Status / Eroare JSON-RPC versus starea HTTP** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> A JSON-RPC 2.0 server receives a request for a method named "nonexistent". What HTTP status code does the response carry? [Un server JSON-RPC 2.0 primește o cerere pentru o metodă numită "nonexistent". Ce cod de stare HTTP poartă răspunsul?] +The supplied S12 JSON-RPC HTTP server receives a valid request with id 1 for an unknown method. Which response does this implementation produce? [Serverul HTTP JSON-RPC S12 distribuit primește o cerere validă cu id 1 pentru o metodă necunoscută. Ce răspuns produce implementarea?] -- **a)** 200 — the HTTP transport succeeded; the RPC error is inside the JSON response body [200 — transportul HTTP a reușit; eroarea RPC este în corpul răspunsului JSON] -- **b)** 404 — the requested RPC method resource was not found on the server endpoint [404 — resursa metodei RPC cerute nu a fost găsită pe endpoint-ul serverului] -- **c)** 500 — an internal server error occurred while dispatching the requested RPC method call [500 — a apărut o eroare internă a serverului în timpul expedierii apelului de metodă RPC solicitat] -- **d)** 405 — the HTTP method used was not allowed by the JSON-RPC specification [405 — metoda HTTP utilizată nu a fost permisă de specificația JSON-RPC] +- **a)** HTTP 200 with a JSON-RPC error object carrying code -32601 and id 1. [HTTP 200 cu un obiect de eroare JSON-RPC cu codul -32601 și id 1.] +- **b)** HTTP 404 is mandated by JSON-RPC itself. [HTTP 404 este impus de JSON-RPC însuși.] +- **c)** HTTP 405 because the JSON-RPC method name is an HTTP verb. [HTTP 405 deoarece numele metodei JSON-RPC este un verb HTTP.]
    💡 Feedback -JSON-RPC separates transport-level from application-level errors. A method-not-found error returns HTTP 200 with a JSON body containing an error object (code -32601). HTTP status only reflects transport success. [JSON-RPC separă erorile la nivel de transport de erorile la nivel de aplicație. O eroare method-not-found returnează HTTP 200 cu un corp JSON conținând un obiect de eroare (codul -32601). Starea HTTP reflectă doar succesul transportului.] +**Correct answer / Răspuns corect: a.** This is the HTTP mapping chosen by S12_Part01_Script_JSONRPC_Server.py. JSON-RPC 2.0 is transport-agnostic and does not prescribe HTTP status codes. The response preserves the valid request id and contains error, not result. [Aceasta este maparea HTTP aleasă de S12_Part01_Script_JSONRPC_Server.py. JSON-RPC 2.0 este independent de transport și nu prescrie codurile HTTP. Răspunsul păstrează id-ul valid și conține error, nu result.]
    @@ -525,7 +520,7 @@ gRPC uses HTTP/2, which provides multiplexing (multiple concurrent streams over *Multiple Choice* -> The calculator.proto in the Week 12 lab defines unary RPCs. gRPC also supports three additional communication patterns. Which set correctly lists them? [Fișierul calculator.proto din laboratorul Săptămânii 12 definește RPC-uri unare. gRPC suportă și alte trei modele de comunicare. Care set le listează corect?] +> The S12_Part02_Config_Calculator.proto in the Week 12 lab defines unary RPCs. gRPC also supports three additional communication patterns. Which set correctly lists them? [Fișierul S12_Part02_Config_Calculator.proto din laboratorul Săptămânii 12 definește RPC-uri unare. gRPC suportă și alte trei modele de comunicare. Care set le listează corect?] - **a)** Server streaming, client streaming, and bidirectional streaming [Streaming de la server, streaming de la client și streaming bidirecțional] - **b)** Broadcast, multicast, and publish-subscribe event-driven messaging patterns [Broadcast, multicast și modele de mesagerie publish-subscribe bazate pe evenimente] @@ -717,21 +712,19 @@ Blockchain platforms like Bitcoin and Ethereum use JSON-RPC as their standard AP --- -### Q37. `N12.T00.Q07` -**Scenario: Lab Container Investigation / Scenariu: Investigarea containerului de laborator** +### Q37. `N12.T00.Q07` — Health-check scope / Domeniul verificării de sănătate -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> After running start_lab.py, a student cannot connect to port 6200. Using docker ps, they see the container is healthy. What is the most likely diagnosis? [După rularea start_lab.py, un student nu se poate conecta la portul 6200. Folosind docker ps, vede că containerul este sănătos. Care este cel mai probabil diagnostic?] +A hypothetical container runs two services. Its health check tests only SMTP, while a separate RPC request fails. What can healthy status establish? [Un container ipotetic rulează două servicii. Health check-ul testează numai SMTP, în timp ce o cerere RPC separată eșuează. Ce poate stabili starea healthy?] -- **a)** Health check only tests port 587 (SMTP) — the JSON-RPC process may have crashed independently [Verificarea de sănătate testează doar portul 587 (SMTP) — procesul JSON-RPC poate fi căzut independent] -- **b)** Docker automatically assigns random ports so 6200 may have been remapped to a different number [Docker atribuie automat porturi aleatorii, deci 6200 poate fi fost remapat la un număr diferent] -- **c)** The student needs to wait 60 seconds after startup because all services have a warm-up period [Studentul trebuie să aștepte 60 de secunde după pornire deoarece toate serviciile au o perioadă de încălzire] -- **d)** Port 6200 is blocked by the Windows firewall and requires an administrator to open it [Portul 6200 este blocat de firewall-ul Windows și necesită un administrator pentru a-l deschide] +- **a)** Only that the configured check passed; inspect the RPC process, listener, logs and path separately. [Doar că verificarea configurată a trecut; inspectați separat procesul RPC, listenerul, logurile și calea.] +- **b)** Every service and every published port is working. [Orice serviciu și orice port publicat funcționează.] +- **c)** The Windows firewall is certainly the cause. [Firewall-ul Windows este sigur cauza.]
    💡 Feedback -The container may be healthy (SMTP health check passes on port 587) but the JSON-RPC service inside may have failed to start. Check docker logs dms for Python errors specific to the JSON-RPC server. [Containerul poate fi sănătos (verificarea de sănătate SMTP trece pe portul 587) dar serviciul JSON-RPC din interior poate să nu fi pornit. Verificați docker logs dms pentru erori Python specifice serverului JSON-RPC.] +**Correct answer / Răspuns corect: a.** A health check has a defined scope. The scenario is independent of S12, which supplies standalone JSON-RPC and gRPC scripts rather than start_lab.py or a dms compose service. [Health check-ul are un domeniu definit. Scenariul este independent de S12, care furnizează scripturi JSON-RPC și gRPC autonome, nu start_lab.py sau un serviciu compose dms.]
    @@ -804,11 +797,11 @@ gRPC bidirectional streaming maintains a persistent connection where both client > A student runs the following command against the Week 12 JSON-RPC server and is confused by the result: -curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:6200 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"nonexistent","params":[],"id":1}' +curl -s -o /dev/null -w "%{http_code}" -X POST http://127.0.0.1:8000 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"nonexistent","params":[],"id":1}' The output is 200 . The student concludes the call succeeded. What error exists in the student's reasoning? [Un student execută următoarea comandă pe serverul JSON-RPC din Săptămâna 12 și este confuz de rezultat: -curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:6200 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"nonexistent","params":[],"id":1}' +curl -s -o /dev/null -w "%{http_code}" -X POST http://127.0.0.1:8000 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"nonexistent","params":[],"id":1}' Ieșirea este 200 . Studentul concluzionează că apelul a reușit. Ce eroare există în raționamentul studentului?] @@ -826,20 +819,18 @@ JSON-RPC separates transport-level success from application-level success. HTTP --- ### Q42. `N12.T00.Q13` -**Protobuf Encoding Size Analysis / Analiza dimensiunii codificării Protobuf** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> The Week 12 calculator.proto defines CalcRequest with two double fields (tags 1 and 2). A student captures traffic on port 6251 and measures the protobuf payload for Add(a=10.0, b=32.0) at 18 bytes. The equivalent JSON-RPC payload {"jsonrpc":"2.0","method":"add","params":[10,32],"id":1} on port 6200 is approximately 56 bytes. Which analysis correctly explains the size difference? [Fișierul calculator.proto din Săptămâna 12 definește CalcRequest cu două câmpuri double (tag-uri 1 și 2). Un student capturează traficul pe portul 6251 și măsoară sarcina utilă protobuf pentru Add(a=10.0, b=32.0) la 18 octeți. Sarcina utilă JSON-RPC echivalentă pe portul 6200 are aproximativ 56 de octeți. Care analiză explică corect diferența de dimensiune?] +In the supplied S12 schema, why is the Protobuf body of `AddRequest(a=10, b=32)` four bytes? [În schema S12 distribuită, de ce corpul Protobuf al `AddRequest(a=10, b=32)` are patru octeți?] -- **a)** Protobuf encodes only field tags (1 byte each) plus raw binary double values (8 bytes each), whilst JSON-RPC carries string keys, method name and framing characters as UTF-8 text [Protobuf codifică doar tag-uri de câmp (1 octet fiecare) plus valori double binare brute (8 octeți fiecare), în timp ce JSON-RPC transportă chei text, numele metodei și caractere de încadrare ca text UTF-8] -- **b)** Protobuf applies gzip compression to the JSON payload before transmission, reducing the 56 bytes to 18 bytes through standard deflate encoding [Protobuf aplică compresie gzip asupra sarcinii utile JSON înainte de transmisie, reducând cei 56 de octeți la 18 prin codificare deflate standard] -- **c)** JSON-RPC uses 56 bytes because HTTP headers are included in the payload measurement, whilst gRPC HTTP/2 headers are counted separately [JSON-RPC folosește 56 de octeți deoarece anteturile HTTP sunt incluse în măsurarea sarcinii utile, în timp ce anteturile HTTP/2 ale gRPC sunt contorizate separat] -- **d)** Protobuf truncates floating-point values to integers when they have no decimal component, storing 10 and 32 as varints instead of 8-byte doubles [Protobuf trunchiază valorile în virgulă mobilă la întregi când nu au componentă zecimală, stocând 10 și 32 ca varint-uri în loc de double-uri de 8 octeți] +- **a)** Two one-byte field keys and two one-byte positive int32 varints. [Două chei de câmp de un octet și două varint-uri int32 pozitive de un octet.] +- **b)** Two eight-byte doubles automatically compressed by gzip. [Două double-uri de opt octeți comprimate automat cu gzip.] +- **c)** The four bytes include all gRPC and HTTP/2 headers. [Cei patru octeți includ toate antetele gRPC și HTTP/2.]
    💡 Feedback -Protocol Buffers use a compact binary encoding: each field is identified by a 1-byte field key (field_number +**Correct answer / Răspuns corect: a.** The actual schema defines `int32 a = 1` and `int32 b = 2`. A field key is `(field_number << 3) | wire_type`. For int32 the wire type is 0, so the keys are 0x08 and 0x10. Positive values 10 and 32 each fit one varint byte: `08 0a 10 20`, four bytes in the Protobuf message body. Add gRPC’s five-byte message prefix and HTTP/2 framing separately when comparing transmitted traffic. [Schema reală definește `int32 a = 1` și `int32 b = 2`. Cheia unui câmp este `(field_number << 3) | wire_type`. Pentru int32, wire type este 0, deci cheile sunt 0x08 și 0x10. Valorile pozitive 10 și 32 încap fiecare într-un octet varint: `08 0a 10 20`, patru octeți în corpul mesajului Protobuf. Adăugați separat prefixul gRPC de cinci octeți și cadrajul HTTP/2 când comparați traficul transmis.]
    @@ -919,61 +910,55 @@ The MIME_TYPES dictionary in ex_8_01 maps ".html" to "text/html; charset=utf-8". --- -### Q46. `N12.S01.Q01` -**Lab SMTP Port / Portul SMTP din laborator** +### Q46. `N12.S01.Q01` — Port 587 and bind permissions / Portul 587 și permisiunile bind -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the Week 12 Docker lab environment, on which port does the educational SMTP server listen? [În mediul Docker al laboratorului Săptămânii 12, pe ce port ascultă serverul SMTP educațional?] +On a conventional Linux configuration with the unprivileged port threshold at 1024, is TCP port 587 automatically unprivileged? [Într-o configurație Linux convențională cu pragul porturilor neprivilegiate la 1024, portul TCP 587 este automat neprivilegiat?] -- **a)** 587 — an unprivileged educational port explicitly mapped in docker-compose.yml [587 — un port educațional neprivilegiat mapat explicit în docker-compose.yml] -- **b)** 25 — the default SMTP relay port for production mail server deployments [25 — portul implicit de releu SMTP pentru implementări de servere de email în producție] -- **c)** 587 — the submission port requiring STARTTLS and user authentication [587 — portul de trimitere care necesită STARTTLS și autentificarea utilizatorului] -- **d)** 9000 — reserved for Portainer container management in this environment [9000 — rezervat pentru managementul containerelor Portainer în acest mediu] +- **a)** No. It is below 1024; binding needs the configured privilege/capability or a changed namespace policy. [Nu. Este sub 1024; bind necesită privilegiul/capabilitatea configurată sau o politică modificată a namespace-ului.] +- **b)** Yes, because it is used for education. [Da, deoarece este folosit pentru educație.] +- **c)** Yes, because all SMTP ports are unprivileged. [Da, deoarece toate porturile SMTP sunt neprivilegiate.]
    💡 Feedback -The lab SMTP server runs on port 587 (an unprivileged port for educational use). Port 25 is the standard SMTP relay port but requires root privileges and is often blocked by ISPs. [Serverul SMTP din laborator rulează pe portul 587 (un port neprivilegiat pentru uz educațional). Portul 25 este portul standard de releu SMTP, dar necesită privilegii root și este adesea blocat de ISP-uri.] +**Correct answer / Răspuns corect: a.** Port assignment and permission policy are different. CAP_NET_BIND_SERVICE and namespace settings can change who may bind. S12 does not distribute an SMTP Docker service; SMTP questions are theory examples. [Atribuirea portului și politica de permisiuni sunt diferite. CAP_NET_BIND_SERVICE și setările namespace-ului pot schimba cine poate face bind. S12 nu distribuie un serviciu Docker SMTP; întrebările SMTP sunt exemple teoretice.]
    --- -### Q47. `N12.S01.Q02` -**Lab Service Ports / Porturile serviciilor din laborator** +### Q47. `N12.S01.Q02` — S12 server ports / Porturile serverelor S12 -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Match the Week 12 lab service ports: SMTP, JSON-RPC, XML-RPC, gRPC. Which mapping is correct? [Asociați porturile serviciilor din laboratorul Săptămânii 12: SMTP, JSON-RPC, XML-RPC, gRPC. Care mapare este corectă?] +What are the default ports of the standalone S12 JSON-RPC and gRPC servers? [Care sunt porturile implicite ale serverelor autonome JSON-RPC și gRPC S12?] -- **a)** SMTP=587, JSON-RPC=6200, XML-RPC=6201, gRPC=6251 [SMTP=587, JSON-RPC=6200, XML-RPC=6201, gRPC=6251] -- **b)** SMTP=25, JSON-RPC=8080, XML-RPC=8081, gRPC=50051 [SMTP=25, JSON-RPC=8080, XML-RPC=8081, gRPC=50051] -- **c)** SMTP=587, JSON-RPC=6201, XML-RPC=6200, gRPC=6251 [SMTP=587, JSON-RPC=6201, XML-RPC=6200, gRPC=6251] -- **d)** SMTP=587, JSON-RPC=6200, XML-RPC=6201, gRPC=9000 [SMTP=587, JSON-RPC=6200, XML-RPC=6201, gRPC=9000] +- **a)** JSON-RPC: 8000; gRPC: 50051 +- **b)** JSON-RPC: 6200; gRPC: 6251 +- **c)** JSON-RPC: 587; gRPC: 465
    💡 Feedback -From docker-compose.yml: SMTP=587, JSON-RPC=6200, XML-RPC=6201, gRPC=6251. Port 9000 is reserved for Portainer and must never be used by lab services. [Din docker-compose.yml: SMTP=587, JSON-RPC=6200, XML-RPC=6201, gRPC=6251. Portul 9000 este rezervat pentru Portainer și nu trebuie folosit niciodată de serviciile laboratorului.] +**Correct answer / Răspuns corect: a.** The JSON-RPC server defaults to 127.0.0.1:8000 and accepts --host/--port. The gRPC server uses 50051. A Mininet instructor scenario may explicitly choose JSON-RPC port 8080; use its stated endpoint. [Serverul JSON-RPC folosește implicit 127.0.0.1:8000 și acceptă --host/--port. Serverul gRPC folosește 50051. Un scenariu Mininet al profesorului poate alege explicit JSON-RPC pe 8080; folosiți endpointul precizat.]
    --- -### Q48. `N12.S01.Q04` -**Docker Container Inspection / Inspectarea containerului Docker** +### Q48. `N12.S01.Q04` — Interactive container process / Proces interactiv în container -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> You need to open an interactive shell inside the running dms container to debug an issue. Which command achieves this? [Trebuie să deschideți un shell interactiv în interiorul containerului dms în execuție pentru a depana o problemă. Ce comandă realizează acest lucru?] +Assume a running example container is named demo and has /bin/sh installed. Which command starts a new interactive shell process in it? [Presupuneți că un container exemplu rulează, se numește demo și are /bin/sh instalat. Ce comandă pornește în el un nou proces shell interactiv?] -- **a)** docker exec -it dms /bin/bash — opens an interactive shell inside the running container [docker exec -it dms /bin/bash — deschide un shell interactiv în containerul care rulează] -- **b)** docker run -it dms /bin/bash — starts a brand new container instance from the same image [docker run -it dms /bin/bash — pornește o instanță de container complet nouă din aceeași imagine] -- **c)** docker attach dms — reconnects to the main process but not a new shell [docker attach dms — se reconectează la procesul principal dar nu un shell nou] -- **d)** docker start -i dms — restarts a stopped container with interactive mode [docker start -i dms — repornește un container oprit cu mod interactiv] +- **a)** `docker exec -it demo /bin/sh` +- **b)** `docker run -it demo /bin/sh` +- **c)** `docker logs demo`
    💡 Feedback -The docker exec -it command attaches to a running container with interactive mode (-i) and a pseudo-TTY (-t). The container name dms is defined in docker-compose.yml. This does not restart the container — it opens a new process inside the existing one. [Comanda docker exec -it se atașează la un container în execuție cu mod interactiv (-i) și un pseudo-TTY (-t). Numele containerului dms este definit în docker-compose.yml. Aceasta nu repornește containerul — deschide un proces nou în interiorul celui existent.] +**Correct answer / Răspuns corect: a.** exec starts a new process in an existing running container. run creates a container from an image. This is a self-contained Docker question, not a claim that S12 provides a demo/dms container. [exec pornește un proces nou într-un container existent în execuție. run creează un container dintr-o imagine. Acesta este un item Docker autonom, nu afirmația că S12 furnizează un container demo/dms.]
    @@ -986,33 +971,31 @@ The docker exec -it command attaches to a running container with interactive mod > Which curl command correctly invokes the add method with parameters [10, 32] on the Week 12 JSON-RPC server? [Care comandă curl invocă corect metoda add cu parametrii [10, 32] pe serverul JSON-RPC din Săptămâna 12?] -- **a)** curl -X POST http://localhost:6200 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"add","params":[10,32],"id":1}' [curl -X POST http://localhost:6200 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"add","params":[10,32],"id":1}'] -- **b)** curl -X GET http://localhost:6200/add?a=10&b=32 — uses REST-style query parameters to invoke the server add method [curl -X GET http://localhost:6200/add?a=10&b=32 — folosește parametri de interogare în stil REST pentru a invoca metoda de adunare de pe server] +- **a)** curl -X POST http://127.0.0.1:8000 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"add","params":[10,32],"id":1}' [curl -X POST http://127.0.0.1:8000 -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"add","params":[10,32],"id":1}'] +- **b)** curl -X GET http://127.0.0.1:8000/add?a=10&b=32 — uses REST-style query parameters to invoke the server add method [curl -X GET http://127.0.0.1:8000/add?a=10&b=32 — folosește parametri de interogare în stil REST pentru a invoca metoda de adunare de pe server] - **c)** curl -X POST http://localhost:6201 -H "Content-Type: text/xml" -d 'add...' [curl -X POST http://localhost:6201 -H "Content-Type: text/xml" -d 'add...']
    💡 Feedback -The correct call uses POST, Content-Type: application/json, and a valid JSON-RPC 2.0 payload with "jsonrpc":"2.0", "method":"add", "params":[10,32], "id":1 sent to http://localhost:6200. [Apelul corect folosește POST, Content-Type: application/json și un corp JSON-RPC 2.0 valid cu "jsonrpc":"2.0", "method":"add", "params":[10,32], "id":1 trimis la http://localhost:6200.] +The correct call uses POST, Content-Type: application/json, and a valid JSON-RPC 2.0 payload with "jsonrpc":"2.0", "method":"add", "params":[10,32], "id":1 sent to http://127.0.0.1:8000. [Apelul corect folosește POST, Content-Type: application/json și un corp JSON-RPC 2.0 valid cu "jsonrpc":"2.0", "method":"add", "params":[10,32], "id":1 trimis la http://127.0.0.1:8000.]
    --- -### Q50. `N12.S02.Q02` -**Division by Zero Error Code / Codul de eroare la împărțirea cu zero** +### Q50. `N12.S02.Q02` — S12 arithmetic error / Eroare aritmetică S12 -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> When calling divide(10, 0) on the Week 12 JSON-RPC server, which error code appears in the response? [La apelarea divide(10, 0) pe serverul JSON-RPC din Săptămâna 12, ce cod de eroare apare în răspuns?] +In the supplied S12 JSON-RPC server, what error is returned for a valid request with id 1, method evaluate and params ["10/0"]? [În serverul JSON-RPC S12 distribuit, ce eroare este returnată pentru o cerere validă cu id 1, metoda evaluate și params ["10/0"]?] -- **a)** -32000 — a server-defined application error code for division by zero [-32000 — un cod de eroare de aplicație definit de server pentru împărțirea cu zero] -- **b)** -32601 — the standard JSON-RPC Method not found error reserved by specification [-32601 — eroarea standard JSON-RPC Method not found rezervată de specificație] -- **c)** -32700 — the Parse error code indicating malformed JSON in the request [-32700 — codul Parse error indicând JSON malformat în cerere] -- **d)** -32603 — the Internal error code for unhandled exceptions on the server [-32603 — codul Internal error pentru excepții netratate pe server] +- **a)** -32602 — Invalid params / Parametri invalizi +- **b)** -32601 — Method not found / Metodă inexistentă +- **c)** -32700 — Parse error / Eroare de parsare
    💡 Feedback -Division by zero is a server-defined application error using code -32000. Standard error codes (-32700 through -32603) are reserved by JSON-RPC specification. Server-defined errors use the range -32000 to -32099. [Împărțirea cu zero este o eroare de aplicație definită de server folosind codul -32000. Codurile standard de eroare (-32700 până la -32603) sunt rezervate de specificația JSON-RPC. Erorile definite de server folosesc intervalul -32000 până la -32099.] +**Correct answer / Răspuns corect: a.** This implementation treats an unsupported or invalid arithmetic expression, including division by zero, as Invalid params and preserves id 1. JSON-RPC does not mandate a universal division-by-zero application code; inspect the server contract. [Implementarea tratează o expresie aritmetică nepermisă sau invalidă, inclusiv împărțirea la zero, drept Invalid params și păstrează id 1. JSON-RPC nu impune un cod universal de aplicație pentru împărțirea la zero; inspectați contractul serverului.]
    @@ -1039,20 +1022,18 @@ The server returns HTTP 204 No Content with an empty body. Since the request has --- ### Q52. `N12.S02.Q04` -**Available JSON-RPC Methods / Metodele JSON-RPC disponibile** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> The Week 12 JSON-RPC server exposes several methods. Which is NOT a valid method on this server? [Serverul JSON-RPC din Săptămâna 12 expune mai multe metode. Care NU este o metodă validă pe acest server?] +Which method is absent from the supplied S12 JSON-RPC server? [Ce metodă lipsește din serverul JSON-RPC S12 distribuit?] -- **a)** power — the exponentiation operation is not implemented in the Week 12 calculator server [power — operația de exponențiere nu este implementată în serverul calculator din Săptămâna 12] -- **b)** get_stats — returns call counts, uptime, and total number of method invocations [get_stats — returnează contoare de apeluri, timpul de funcționare și numărul total de invocări] -- **c)** echo — returns its input parameter unchanged for diagnostic and testing purposes [echo — returnează parametrul de intrare neschimbat pentru scopuri de diagnostic și testare] -- **d)** sort_list — sorts a given list of items with an optional reverse order parameter [sort_list — sortează o listă dată de elemente cu un parametru opțional de ordine inversă] +- **a)** get_stats +- **b)** evaluate +- **c)** add
    💡 Feedback -The server supports: add, subtract, multiply, divide, echo, sort_list, get_time, get_server_info, get_stats. There is no power or exponentiation method implemented. [Serverul suportă: add, subtract, multiply, divide, echo, sort_list, get_time, get_server_info, get_stats. Nu există o metodă power sau de exponențiere implementată.] +**Correct answer / Răspuns corect: a.** The local example supports evaluate and add. Its deliberately small interface has no get_stats, echo, sort_list or standalone divide method. [Exemplul local suportă evaluate și add. Interfața sa deliberat mică nu are get_stats, echo, sort_list sau o metodă divide separată.]
    @@ -1063,7 +1044,7 @@ The server supports: add, subtract, multiply, divide, echo, sort_list, get_time, *Multiple Choice* -> When sending an XML-RPC request using curl to the lab server on port 6201, what Content-Type header must be specified? [Când trimiteți o cerere XML-RPC folosind curl către serverul de laborator pe portul 6201, ce antet Content-Type trebuie specificat?] +> When sending an XML-RPC request using curl to a hypothetical XML-RPC endpoint, what Content-Type header must be specified? [Când trimiteți o cerere XML-RPC folosind curl către un endpoint XML-RPC ipotetic, ce antet Content-Type trebuie specificat?] - **a)** text/xml — XML-RPC payloads are XML documents requiring the XML media type [text/xml — corpurile XML-RPC sunt documente XML care necesită tipul media XML] - **b)** application/json — all RPC protocols share the same JSON-based content type [application/json — toate protocoalele RPC partajează același tip de conținut bazat pe JSON] @@ -1072,145 +1053,134 @@ The server supports: add, subtract, multiply, divide, echo, sort_list, get_time,
    💡 Feedback -XML-RPC uses XML serialisation, so the Content-Type must be text/xml. This differs from JSON-RPC which uses application/json. The lab's XML-RPC server listens on port 6201 as configured in docker-compose.yml. [XML-RPC folosește serializare XML, deci Content-Type trebuie să fie text/xml. Aceasta diferă de JSON-RPC care folosește application/json. Serverul XML-RPC al laboratorului ascultă pe portul 6201, configurat în docker-compose.yml.] +XML-RPC uses XML serialisation, so the Content-Type must be text/xml. This differs from JSON-RPC which uses application/json. This is a protocol-theory question; S12 does not supply this XML-RPC server or a compose file. [XML-RPC folosește serializare XML, deci Content-Type trebuie să fie text/xml. Aceasta diferă de JSON-RPC care folosește application/json. Acesta este un item teoretic de protocol; S12 nu furnizează acest server XML-RPC sau un fișier compose.]
    --- ### Q54. `N12.S02.Q06` -**Python smtplib Usage in Lab / Utilizarea smtplib Python în laborator** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the lab, the Python smtplib module sends email to the SMTP server. Given the code smtplib.SMTP("localhost", 587) , what does the port number 587 represent? [În laborator, modulul Python smtplib trimite email către serverul SMTP. Dat fiind codul smtplib.SMTP("localhost", 587) , ce reprezintă numărul de port 587?] +In `smtplib.SMTP("localhost", 587)`, what does 587 identify, and what does this call alone do? [În `smtplib.SMTP("localhost", 587)`, ce identifică 587 și ce face singur acest apel?] -- **a)** The unprivileged lab SMTP port — production servers use 25, 587, or 465 instead [Portul SMTP de laborator neprivilegiat — serverele de producție folosesc 25, 587 sau 465] -- **b)** The SMTP submission port standardised by RFC 6409 for authenticated client access [Portul de submission SMTP standardizat de RFC 6409 pentru accesul autentificat al clientului] -- **c)** A fallback port used when the default SMTP port 25 is blocked by a firewall [Un port de rezervă folosit când portul SMTP implicit 25 este blocat de un paravan] +- **a)** The destination submission port; establishing the connection alone neither starts TLS nor authenticates. [Portul destinație de submission; stabilirea conexiunii singură nu pornește TLS și nu autentifică.] +- **b)** An unprivileged educational port that automatically encrypts and authenticates. [Un port educațional neprivilegiat care criptează și autentifică automat.] +- **c)** The source port of the local client. [Portul sursă al clientului local.]
    💡 Feedback -Port 587 is the unprivileged lab SMTP port defined in docker-compose.yml. Production SMTP uses port 25 (relay), 587 (submission), or 465 (SMTPS). The lab uses 587 because ports below 1024 require root privileges. [Portul 587 este portul SMTP de laborator neprivilegiat definit în docker-compose.yml. SMTP-ul de producție folosește portul 25 (relay), 587 (submission) sau 465 (SMTPS). Laboratorul folosește 587 deoarece porturile sub 1024 necesită privilegii root.] +**Correct answer / Răspuns corect: a.** Use the server’s configured submission policy. A STARTTLS client needs the explicit starttls flow with certificate verification and authentication where required. Implicit TLS submission on 465 uses SMTP_SSL. [Folosiți politica de submission configurată pe server. Un client STARTTLS necesită fluxul explicit starttls cu verificarea certificatului și autentificare când este cerută. Submission cu TLS implicit pe 465 folosește SMTP_SSL.]
    --- ### Q55. `N12.S03.Q01` -**Proto File Field Tags / Etichetele de câmp din fișierul .proto** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the Week 12 calculator.proto, the CalcRequest message defines double a = 1 and double b = 2. What do the numbers 1 and 2 represent? [În calculator.proto din Săptămâna 12, mesajul CalcRequest definește double a = 1 și double b = 2. Ce reprezintă numerele 1 și 2?] +The supplied `S12_Part02_Config_Calculator.proto` defines `int32 a = 1; int32 b = 2;` in AddRequest. What are 1 and 2? [Fișierul distribuit `S12_Part02_Config_Calculator.proto` definește `int32 a = 1; int32 b = 2;` în AddRequest. Ce reprezintă 1 și 2?] -- **a)** Field tags — numeric identifiers used in the binary wire format instead of string keys [Etichete de câmp — identificatori numerici utilizați în formatul binar de rețea în loc de chei string] -- **b)** Default values assigned to each field when the sender omits them from the message [Valori implicite atribuite fiecărui câmp când expeditorul le omite din mesaj] -- **c)** Version numbers indicating which protocol revision introduced each individual field definition [Numere de versiune care indică ce revizie de protocol a introdus fiecare definiție individuală de câmp] -- **d)** Array indices specifying the memory position where each value will be stored [Indici de tablou specificând poziția în memorie unde fiecare valoare va fi stocată] +- **a)** Field numbers used with wire types to encode field keys. [Numere de câmp folosite împreună cu wire types pentru codificarea cheilor.] +- **b)** Default operand values. [Valorile implicite ale operanzilor.] +- **c)** Byte lengths of the operands. [Lungimile în octeți ale operanzilor.]
    💡 Feedback -The numbers are field tags (identifiers) used in the binary wire format. Unlike JSON which uses string keys, protobuf uses these numeric tags with wire types for compact encoding. Field 1 produces key byte 0x09 (for 64-bit wire type), field 2 produces 0x11. [Numerele sunt etichete de câmp (identificatori) utilizate în formatul binar de rețea. Spre deosebire de JSON care folosește chei de tip string, protobuf folosește aceste etichete numerice cu tipuri de codificare pentru encodare compactă. Câmpul 1 produce octetul cheie 0x09 (pentru tipul 64-bit), câmpul 2 produce 0x11.] +**Correct answer / Răspuns corect: a.** The actual schema defines `int32 a = 1` and `int32 b = 2`. A field key is `(field_number << 3) | wire_type`. For int32 the wire type is 0, so the keys are 0x08 and 0x10. Positive values 10 and 32 each fit one varint byte: `08 0a 10 20`, four bytes in the Protobuf message body. Add gRPC’s five-byte message prefix and HTTP/2 framing separately when comparing transmitted traffic. [Schema reală definește `int32 a = 1` și `int32 b = 2`. Cheia unui câmp este `(field_number << 3) | wire_type`. Pentru int32, wire type este 0, deci cheile sunt 0x08 și 0x10. Valorile pozitive 10 și 32 încap fiecare într-un octet varint: `08 0a 10 20`, patru octeți în corpul mesajului Protobuf. Adăugați separat prefixul gRPC de cinci octeți și cadrajul HTTP/2 când comparați traficul transmis.]
    --- ### Q56. `N12.S03.Q02` -**Protobuf Encoded Size / Dimensiunea codificată protobuf** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> CalcRequest(a=10.0, b=32.0) encodes to approximately how many bytes in Protocol Buffers? [CalcRequest(a=10.0, b=32.0) se codifică la aproximativ câți octeți în Protocol Buffers?] +How many bytes does the Protobuf body `AddRequest(a=10, b=32)` occupy under the supplied int32 schema, excluding gRPC and HTTP/2 framing? [Câți octeți ocupă corpul Protobuf `AddRequest(a=10, b=32)` în schema int32 distribuită, excluzând cadrajul gRPC și HTTP/2?] -- **a)** 18 bytes — two field keys (1 byte each) plus two IEEE 754 doubles (8 bytes each) [18 octeți — două chei de câmp (1 octet fiecare) plus două double-uri IEEE 754 (8 octeți fiecare)] -- **b)** 56 bytes — matching the equivalent JSON-RPC payload size for identical operation [56 octeți — egal cu dimensiunea corpului JSON-RPC echivalent pentru aceeași operație] -- **c)** 195 bytes — similar overhead to XML-RPC due to framing and metadata requirements [195 octeți — overhead similar cu XML-RPC din cauza cerințelor de încadrare și metadate] -- **d)** 4 bytes — only the two operand values without any field identification overhead [4 octeți — doar cele două valori operand fără niciun overhead de identificare a câmpurilor] +- **a)** 4 +- **b)** 18 +- **c)** 56 +- **d)** 0
    💡 Feedback -Each double occupies 8 bytes (IEEE 754), and each field key is 1 byte (field_number +**Correct answer / Răspuns corect: a.** The actual schema defines `int32 a = 1` and `int32 b = 2`. A field key is `(field_number << 3) | wire_type`. For int32 the wire type is 0, so the keys are 0x08 and 0x10. Positive values 10 and 32 each fit one varint byte: `08 0a 10 20`, four bytes in the Protobuf message body. Add gRPC’s five-byte message prefix and HTTP/2 framing separately when comparing transmitted traffic. [Schema reală definește `int32 a = 1` și `int32 b = 2`. Cheia unui câmp este `(field_number << 3) | wire_type`. Pentru int32, wire type este 0, deci cheile sunt 0x08 și 0x10. Valorile pozitive 10 și 32 încap fiecare într-un octet varint: `08 0a 10 20`, patru octeți în corpul mesajului Protobuf. Adăugați separat prefixul gRPC de cinci octeți și cadrajul HTTP/2 când comparați traficul transmis.]
    --- -### Q57. `N12.S03.Q03` -**gRPC Error for Division by Zero / Eroarea gRPC la împărțirea cu zero** +### Q57. `N12.S03.Q03` — Supplied gRPC service / Serviciul gRPC distribuit -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the Week 12 gRPC server, calling Divide with b=0 triggers which gRPC status code? [Pe serverul gRPC din Săptămâna 12, apelarea Divide cu b=0 declanșează ce cod de stare gRPC?] +Which methods are declared in the unmodified S12 Calculator service schema? [Ce metode sunt declarate în schema serviciului Calculator S12 nemodificată?] -- **a)** INVALID_ARGUMENT — the gRPC status code indicating the input parameters were invalid [INVALID_ARGUMENT — codul de stare gRPC indicând că parametrii de intrare au fost invalizi] -- **b)** INTERNAL — a generic server error code used when no specific code applies [INTERNAL — un cod generic de eroare a serverului folosit când nu se aplică niciun cod specific] -- **c)** NOT_FOUND — the error code for requests targeting a non-existent RPC method [NOT_FOUND — codul de eroare pentru cereri care vizează o metodă RPC inexistentă] -- **d)** UNAVAILABLE — signalling that the gRPC server could not process the request [UNAVAILABLE — semnalând că serverul gRPC nu a putut procesa cererea] +- **a)** Add and Multiply / Add și Multiply +- **b)** Add and Divide / Add și Divide +- **c)** Divide only / Numai Divide
    💡 Feedback -The server calls context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'Division by zero'). Unlike JSON-RPC which uses numeric error codes in the response body, gRPC uses its own status code system separate from HTTP. [Serverul apelează context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'Division by zero'). Spre deosebire de JSON-RPC care folosește coduri numerice de eroare în corpul răspunsului, gRPC folosește propriul sistem de coduri de stare separat de HTTP.] +**Correct answer / Răspuns corect: a.** Power is an extension to add to the .proto and regenerate. There is no Divide method in the supplied schema, so a question about its division-by-zero implementation would describe a different server. gRPC error behaviour must be tied to a method that actually exists. [Power este o extensie de adăugat în .proto și apoi de regenerat. Schema distribuită nu are metoda Divide, deci un item despre implementarea împărțirii la zero ar descrie alt server. Comportamentul erorilor gRPC trebuie asociat unei metode care există.]
    --- -### Q58. `N12.S03.Q04` -**grpcurl Service Discovery / Descoperirea serviciilor cu grpcurl** +### Q58. `N12.S03.Q04` — gRPC descriptor and endpoint / Descriptorul și endpointul gRPC -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> To list all gRPC services exposed by the lab server, a student uses grpcurl. Which flag is required when connecting to the lab's unencrypted gRPC endpoint on port 6251? [Pentru a lista toate serviciile gRPC expuse de serverul de laborator, un student folosește grpcurl. Ce flag este necesar la conectarea la endpoint-ul gRPC necriptat al laboratorului pe portul 6251?] +The supplied gRPC server uses plaintext HTTP/2 and does not enable server reflection. From S12/2_protobuf, which grpcurl command can use the supplied descriptor to call Add after the server is running? [Serverul gRPC distribuit folosește HTTP/2 necriptat și nu activează server reflection. Din S12/2_protobuf, ce comandă grpcurl poate folosi descriptorul distribuit pentru a apela Add după pornirea serverului?] -- **a)** -plaintext — disables TLS for unencrypted HTTP/2 connections to the lab server [-plaintext — dezactivează TLS pentru conexiuni HTTP/2 necriptate la serverul de laborator] -- **b)** -insecure — skips certificate verification but still attempts a TLS handshake [-insecure — omite verificarea certificatului dar tot încearcă un handshake TLS] -- **c)** -proto calculator.proto — loads the .proto file before connecting to the server [-proto calculator.proto — încarcă fișierul .proto înainte de conectarea la server] -- **d)** -v — enables verbose output which automatically detects the connection type [-v — activează ieșirea detaliată care detectează automat tipul conexiunii] +- **a)** `grpcurl -plaintext -import-path . -proto S12_Part02_Config_Calculator.proto -d '{"a":10,"b":32}' localhost:50051 seminar12.Calculator/Add` +- **b)** `grpcurl localhost:6251 list` +- **c)** `curl http://localhost:50051/Add`
    💡 Feedback -The -plaintext flag tells grpcurl to use an unencrypted HTTP/2 connection. Without it, grpcurl defaults to TLS, which fails against the lab's insecure_channel. The full command is: grpcurl -plaintext localhost:6251 list. [Flagul -plaintext indică grpcurl să folosească o conexiune HTTP/2 necriptată. Fără acesta, grpcurl folosește implicit TLS, care eșuează cu insecure_channel al laboratorului. Comanda completă este: grpcurl -plaintext localhost:6251 list.] +**Correct answer / Răspuns corect: a.** The optional grpcurl tool needs -plaintext for this laboratory endpoint and the .proto because reflection is not enabled. The method path includes package seminar12. The ordinary course route remains the generated Python client. [Instrumentul opțional grpcurl necesită -plaintext pentru acest endpoint de laborator și .proto deoarece reflection nu este activat. Calea metodei include pachetul seminar12. Ruta obișnuită a cursului rămâne clientul Python generat.]
    --- -### Q59. `N12.S04.Q02` -**Wireshark Filter for SMTP / Filtrul Wireshark pentru SMTP** +### Q59. `N12.S04.Q02` — Submission display filter / Filtru de afișare submission -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Which Wireshark display filter isolates only SMTP traffic from the Week 12 lab? [Ce filtru de afișare Wireshark izolează doar traficul SMTP din laboratorul Săptămânii 12?] +A hypothetical SMTP submission service is known to listen on TCP 587. Which Wireshark display filter selects traffic to or from that port? [Se știe că un serviciu SMTP submission ipotetic ascultă pe TCP 587. Ce filtru de afișare Wireshark selectează traficul către sau de la acel port?] -- **a)** tcp.port == 587 — filtering by the lab's educational SMTP server port [tcp.port == 587 — filtrare după portul serverului SMTP educațional al laboratorului] -- **b)** smtp — the protocol dissector filter that works only on standard port 25 [smtp — filtrul disector de protocol care funcționează doar pe portul standard 25] -- **c)** http contains "SMTP" — searching HTTP payloads for the SMTP protocol keyword [http contains "SMTP" — căutare în corpurile HTTP pentru cuvântul cheie al protocolului SMTP] -- **d)** tcp.port == 6200 — the port reserved for JSON-RPC traffic in this laboratory [tcp.port == 6200 — portul rezervat pentru traficul JSON-RPC în acest laborator] +- **a)** `tcp.port == 587` +- **b)** `udp.port == 587` +- **c)** `tcp port 587`
    💡 Feedback -The filter tcp.port == 587 captures all traffic to/from the educational SMTP server. The generic smtp filter may not work on non-standard ports. Port-based filtering is the most reliable approach for lab configurations. [Filtrul tcp.port == 587 capturează tot traficul către/de la serverul SMTP educațional. Filtrul generic smtp poate să nu funcționeze pe porturi non-standard. Filtrarea bazată pe port este cea mai fiabilă abordare pentru configurațiile de laborator.] +**Correct answer / Răspuns corect: a.** This is a port filter, not proof that every selected payload is plaintext SMTP. STARTTLS encrypts subsequent application traffic. The BPF form tcp port 587 belongs to capture filters, not display filters. [Acesta este un filtru de port, nu dovada că orice payload selectat este SMTP în clar. STARTTLS criptează traficul de aplicație ulterior. Forma BPF tcp port 587 aparține filtrelor de captură, nu de afișare.]
    --- -### Q60. `N12.S04.Q03` -**Combined Traffic Filter / Filtru combinat de trafic** +### Q60. `N12.S04.Q03` — S12 combined display filter / Filtru de afișare combinat S12 -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> To capture all Week 12 protocol traffic simultaneously in Wireshark, which display filter should you use? [Pentru a captura simultan tot traficul de protocol din Săptămâna 12 în Wireshark, ce filtru de afișare trebuie să folosiți?] +Using the default standalone S12 server ports, which display filter selects JSON-RPC and gRPC traffic together? [Folosind porturile implicite ale serverelor autonome S12, ce filtru de afișare selectează împreună traficul JSON-RPC și gRPC?] -- **a)** tcp.port in {587, 6200, 6201, 6251} — covers all four lab service ports [tcp.port in {587, 6200, 6201, 6251} — acoperă toate cele patru porturi de servicii de laborator] -- **b)** tcp.port == 587 || tcp.port == 6200 || tcp.port == 9000 — includes Portainer port [tcp.port == 587 || tcp.port == 6200 || tcp.port == 9000 — include portul Portainer] -- **c)** http — captures only HTTP-based protocols and misses SMTP and gRPC entirely [http — capturează doar protocoale bazate pe HTTP și omite complet SMTP și gRPC] +- **a)** `tcp.port == 8000 || tcp.port == 50051` +- **b)** `udp.port == 8000 || udp.port == 50051` +- **c)** `tcp.port == 587 || tcp.port == 6251`
    💡 Feedback -The filter tcp.port in {587, 6200, 6201, 6251} captures all four lab services in a single view: SMTP (587), JSON-RPC (6200), XML-RPC (6201), and gRPC (6251). [Filtrul tcp.port in {587, 6200, 6201, 6251} capturează toate cele patru servicii de laborator într-o singură vedere: SMTP (587), JSON-RPC (6200), XML-RPC (6201) și gRPC (6251).] +**Correct answer / Răspuns corect: a.** These are the current script defaults. If the instructor changes an endpoint, change the filter accordingly. Port filtering selects candidate traffic and does not replace protocol decoding. [Acestea sunt valorile implicite ale scripturilor actuale. Dacă profesorul schimbă un endpoint, adaptați filtrul. Filtrarea după port selectează trafic candidat și nu înlocuiește decodarea protocolului.]
    diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W13_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W13_Questions.md index cd01574..5656632 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W13_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W13_Questions.md @@ -500,20 +500,18 @@ Simple devices are prime targets because they often lack authentication, encrypt --- ### Q26. `N13.C05.Q05` -**Authentication versus encryption priority / Prioritatea autentificării față de criptare** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> According to IoT security best practices, which security measure should be prioritised first? [Conform celor mai bune practici de securitate IoT, care măsură de securitate ar trebui prioritizată prima?] +An IoT service has default credentials and transmits sensitive data without transport encryption. What is a defensible remediation plan? [Un serviciu IoT are credențiale implicite și transmite date sensibile fără criptare de transport. Care este un plan de remediere justificat?] -- **a)** Network monitoring — detecting attacks is more effective than preventing them [Monitorizarea rețelei — detectarea atacurilor este mai eficientă decât prevenirea lor] -- **b)** TLS encryption — protecting data in transit is the most fundamental security layer [Criptarea TLS — protecția datelor în tranzit este cel mai fundamental strat de securitate] -- **c)** Strong authentication — it prevents unauthorised access regardless of encryption state [Autentificarea puternică — previne accesul neautorizat indiferent de starea criptării] -- **d)** Firmware updates — keeping software current eliminates all known vulnerability classes [Actualizări de firmware — menținerea software-ului la zi elimină toate clasele de vulnerabilități cunoscute] +- **a)** Address authentication, authorisation and transport protection according to exposure and impact; coordinate the controls. [Tratați autentificarea, autorizarea și protecția transportului în funcție de expunere și impact; coordonați controalele.] +- **b)** Always postpone encryption because authentication is universally more important. [Amânați mereu criptarea deoarece autentificarea este universal mai importantă.] +- **c)** Enable TLS and keep every default credential. [Activați TLS și păstrați orice credențială implicită.]
    💡 Feedback -Authentication prevents unauthorised access, which is more critical than protecting data in transit. An encrypted channel with default password gives an attacker encrypted access. OWASP ranks weak passwords (I1) above insecure data transfer (I7). [Autentificarea previne accesul neautorizat, ceea ce este mai critic decât protecția datelor în tranzit. Un canal criptat cu parolă implicită oferă atacatorului acces criptat. OWASP clasează parolele slabe (I1) peste transferul nesigur de date (I7).] +**Correct answer / Răspuns corect: a.** A category’s position in the OWASP IoT Top 10 2018 is not a deployment-specific remediation schedule. TLS does not fix default credentials, and strong credentials alone do not protect a plaintext channel. [Poziția unei categorii în OWASP IoT Top 10 2018 nu reprezintă un calendar de remediere specific implementării. TLS nu repară credențialele implicite, iar credențialele puternice singure nu protejează un canal în clar.]
    @@ -698,25 +696,18 @@ The + wildcard matches exactly one level. factory/line1/status has exactly one l --- ### Q36. `N13.T00.Q05` -**OWASP IoT vulnerability prioritisation / Prioritizarea vulnerabilităților OWASP IoT** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> During a security audit, you discover: -> (a) the MQTT broker accepts anonymous connections, -> (b) firmware updates are unsigned, -> (c) the device web interface has a SQL injection flaw. Using OWASP IoT Top 10 ranking, which should be remediated first? [În timpul unui audit de securitate, descoperiți: (a) brokerul MQTT acceptă conexiuni anonime, -> (b) actualizările de firmware sunt nesemnate, -> (c) interfața web a dispozitivului are o vulnerabilitate de injecție SQL. Folosind clasamentul OWASP IoT Top 10, care ar trebui remediată prima?] +An audit finds anonymous MQTT access, unsigned firmware updates and SQL injection. What further information is needed before choosing a remediation order? [Un audit identifică acces MQTT anonim, actualizări firmware nesemnate și injecție SQL. Ce informații suplimentare sunt necesare înaintea ordonării remedierilor?] -- **a)** Unsigned firmware updates (I5 — enables persistent compromise through malicious updates) [Actualizări de firmware nesemnate (I5 — permite compromiterea persistentă prin actualizări malițioase)] -- **b)** SQL injection in the web interface (I3 — exploitable remotely with immediate data breach risk) [Injecție SQL în interfața web (I3 — exploatabilă de la distanță cu risc imediat de breșă de date)] -- **c)** Anonymous MQTT access (I1 — Weak Passwords is the top-ranked OWASP IoT vulnerability) [Accesul MQTT anonim (I1 — Parolele slabe este vulnerabilitatea OWASP IoT de rang cel mai înalt)] -- **d)** All three should be fixed simultaneously since they present equal risk levels [Toate trei ar trebui reparate simultan deoarece prezintă niveluri de risc egale] +- **a)** Exposure, exploitability, affected assets, impact, active exploitation and feasible containment. [Expunere, exploatabilitate, active afectate, impact, exploatare activă și posibilități de limitare.] +- **b)** Only the numeric ordering of the OWASP category identifiers. [Numai ordinea numerică a identificatorilor categoriilor OWASP.] +- **c)** None: all three necessarily have identical risk. [Niciuna: toate trei au obligatoriu risc identic.]
    💡 Feedback -OWASP ranks I1 (weak authentication) highest. Anonymous MQTT access is an I1 issue. SQL injection maps to I3 and unsigned firmware to I5. I1 takes priority. [OWASP clasează I1 (autentificare slabă) cel mai sus. Accesul MQTT anonim este o problemă I1. Injecția SQL corespunde I3 iar firmware-ul nesemnat I5. I1 are prioritate.] +**Correct answer / Răspuns corect: a.** The facts given do not determine one universal first fix. Use the category list to avoid omissions, then prioritise the actual risks and dependencies. Anonymous access can be intentional in some systems; its impact depends on permissions and exposure. [Faptele date nu determină universal prima remediere. Lista categoriilor ajută la evitarea omisiunilor; apoi prioritizați riscurile și dependențele reale. Accesul anonim poate fi intenționat în unele sisteme; impactul depinde de permisiuni și expunere.]
    @@ -863,20 +854,18 @@ Port scanning legality depends on authorisation. In this lab, all containers are --- ### Q44. `N13.S01.Q05` -**Expected open ports in Week 13 lab / Porturile deschise așteptate în laboratorul Săptămânii 13** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> When scanning the Week 13 Docker lab from the host (IoT broker + pentest services running), how many host ports are expected to be open? [La scanarea laboratorului Docker din Săptămâna 13 de pe gazdă (broker IoT + servicii de pentest pornite), câte porturi gazdă se așteaptă să fie deschise?] +Does the number of published ports in the S13 pentest compose file prove the number of successful TCP connections in a scan? [Numărul porturilor publicate în fișierul compose de pentest S13 dovedește numărul conexiunilor TCP reușite într-o scanare?] -- **a)** 4 — ports 1883, 2121, 8080, and 8888 but not the backdoor port on 6200 [4 — porturile 1883, 2121, 8080 și 8888, dar nu portul backdoor 6200] -- **b)** 7 — including SSH on port 22 and MySQL on port 3306 in addition to lab services [7 — incluzând SSH pe portul 22 și MySQL pe portul 3306 pe lângă serviciile de laborator] -- **c)** 5 — ports 1883 (MQTT), 2121 (FTP), 6200 (backdoor), 8080 (WebGoat), and 8888 (DVWA) [5 — porturile 1883 (MQTT), 2121 (FTP), 6200 (backdoor), 8080 (WebGoat) și 8888 (DVWA)] -- **d)** 3 — only 1883 (MQTT), 8080 (WebGoat), and 8888 (DVWA) are accessible [3 — doar 1883 (MQTT), 8080 (WebGoat) și 8888 (DVWA) sunt accesibile] +- **a)** No. A mapping does not prove that its service is listening or ready; measure from the stated namespace. [Nu. O mapare nu dovedește că serviciul ascultă sau este pregătit; măsurați din namespace-ul precizat.] +- **b)** Yes. Every published port is necessarily open. [Da. Orice port publicat este obligatoriu deschis.] +- **c)** Yes, and publishing 6200 automatically starts its listener. [Da, iar publicarea lui 6200 pornește automat listenerul.]
    💡 Feedback -Count only the host-exposed ports (the left side of the mappings) from the Week 13 compose files. In COMPnet, those are 1883 (MQTT broker), 8888 (DVWA), 8080 (WebGoat), 2121 (FTP), and 6200 (backdoor). [Numărați doar porturile expuse pe gazdă (partea stângă a mapărilor) din fișierele compose din Săptămâna 13. În COMPnet, acestea sunt 1883 (broker MQTT), 8888 (DVWA), 8080 (WebGoat), 2121 (FTP) și 6200 (backdoor).] +**Correct answer / Răspuns corect: a.** The supplied pentest compose defines four host mappings by default: 8888, 8080, 2121 and 6200, all on 127.0.0.1. It does not include an MQTT broker. The 6200 listener is conditional, and startup or filtering can change observations. Record actual results. [Compose-ul de pentest distribuit definește implicit patru mapări pe gazdă: 8888, 8080, 2121 și 6200, toate pe 127.0.0.1. Nu include broker MQTT. Listenerul 6200 este condițional, iar pornirea sau filtrarea pot schimba observațiile. Înregistrați rezultatele reale.]
    @@ -922,19 +911,19 @@ Plaintext MQTT reveals topic strings, payload content (sensor data, commands), a --- -### Q47. `N13.S03.Q01` -**Mosquitto anonymous access in lab / Accesul anonim Mosquitto în laborator** +### Q47. `N13.S03.Q01` — Explicit Mosquitto setting / Setare Mosquitto explicită -*True / False* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> The Mosquitto broker in the Week 13 laboratory is configured with allow_anonymous true, permitting connections without credentials. [Brokerul Mosquitto din laboratorul Săptămânii 13 este configurat cu allow_anonymous true, permițând conexiuni fără credențiale.] +In an independent Mosquitto configuration, a listener explicitly has `allow_anonymous true`. What does that setting permit? [Într-o configurație Mosquitto independentă, un listener are explicit `allow_anonymous true`. Ce permite setarea?] -- **a)** true -- **b)** false +- **a)** Clients may connect to that listener without username/password authentication, subject to the remaining configuration. [Clienții se pot conecta la listener fără autentificare cu utilizator/parolă, sub rezerva restului configurației.] +- **b)** All MQTT traffic is automatically encrypted. [Tot traficul MQTT este criptat automat.] +- **c)** The S13 pentest compose automatically creates two Mosquitto listeners. [Compose-ul de pentest S13 creează automat două listenere Mosquitto.]
    💡 Feedback -The mosquitto.conf file explicitly sets allow_anonymous true for both listeners (1883 and 8883). This is intentional for educational purposes to demonstrate the risk. [Fișierul mosquitto.conf setează explicit allow_anonymous true pentru ambele ascultătoare (1883 și 8883). Aceasta este intenționat în scopuri educaționale pentru a demonstra riscul.] +**Correct answer / Răspuns corect: a.** This is a supplied hypothetical configuration, not a mosquitto.conf shipped in S13. Check listener scope and authorisation separately; anonymous access is not equivalent to unrestricted access. [Aceasta este o configurație ipotetică dată, nu un mosquitto.conf distribuit în S13. Verificați separat domeniul listenerului și autorizarea; accesul anonim nu este echivalent cu acces nerestricționat.]
    @@ -954,27 +943,26 @@ The mosquitto.conf file explicitly sets allow_anonymous true for both listeners
    💡 Feedback -In COMPnet, the pentest lab uses network pentestnet with subnet 172.20.0.0/24 (see docker-compose.pentest.yml). [În COMPnet, laboratorul de pentest folosește rețeaua pentestnet cu subrețeaua 172.20.0.0/24 (vezi docker-compose.pentest.yml).] +In COMPnet, the pentest lab uses network pentestnet with subnet 172.20.0.0/24 (see S13_Part02_Config_Docker_Compose_Pentest.yml). [În COMPnet, laboratorul de pentest folosește rețeaua pentestnet cu subrețeaua 172.20.0.0/24 (vezi S13_Part02_Config_Docker_Compose_Pentest.yml).]
    --- -### Q49. `N13.S03.Q03` -**Mosquitto broker IP in lab network / Adresa IP a brokerului Mosquitto în rețeaua de laborator** +### Q49. `N13.S03.Q03` — DVWA container address / Adresa containerului DVWA -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> What static IP address is assigned to the DVWA container in the Week 13 pentest Docker network? [Ce adresă IP statică este atribuită containerului DVWA în rețeaua Docker de pentest din Săptămâna 13?] +What static address is assigned to DVWA in `S13_Part02_Config_Docker_Compose_Pentest.yml`? [Ce adresă statică este atribuită DVWA în `S13_Part02_Config_Docker_Compose_Pentest.yml`?] -- **a)** 172.20.0.12 [172.20.0.12] -- **b)** 172.20.0.11 [172.20.0.11] -- **c)** 172.20.0.1 [172.20.0.1] -- **d)** 172.20.0.1 [172.20.0.1] +- **a)** 172.20.0.10 +- **b)** 172.20.0.11 +- **c)** 172.20.0.12 +- **d)** 172.20.0.1
    💡 Feedback -The pentest compose assigns 172.20.0.10 to the DVWA service (172.20.0.11 for WebGoat, 172.20.0.12 for vsftpd). [Fișierul de compose pentru pentest atribuie 172.20.0.10 serviciului DVWA (172.20.0.11 pentru WebGoat, 172.20.0.12 pentru vsftpd).] +**Correct answer / Răspuns corect: a.** DVWA uses .10, WebGoat .11 and vsftpd .12 in the container network. A host-side request uses the published host endpoint, not necessarily this container IP. [DVWA folosește .10, WebGoat .11 și vsftpd .12 în rețeaua containerelor. O cerere de pe gazdă folosește endpointul publicat, nu neapărat acest IP al containerului.]
    @@ -1041,20 +1029,18 @@ socket.SOCK_STREAM creates a TCP socket. SOCK_DGRAM is for UDP datagrams. SOCK_R --- ### Q53. `N13.S04.Q02` -**ThreadPoolExecutor for concurrent scanning / ThreadPoolExecutor pentru scanare concurentă** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the Week 13 port scanner, which Python class from concurrent.futures enables parallel port scanning with a thread pool? [În scanerul de porturi din Săptămâna 13, ce clasă Python din concurrent.futures permite scanarea paralelă a porturilor cu un pool de fire de execuție?] +The supplied S13 simple scanner iterates sequentially. Which concurrent.futures class could a student use for an optional extension that overlaps I/O waits using a thread pool? [Scannerul simplu S13 distribuit iterează secvențial. Ce clasă concurrent.futures ar putea folosi studentul pentru o extensie opțională care suprapune așteptările I/O cu un pool de fire?] -- **a)** AsyncioExecutor [AsyncioExecutor] -- **b)** ProcessPoolExecutor [ProcessPoolExecutor] -- **c)** ThreadPoolExecutor [ThreadPoolExecutor] -- **d)** MultiThreadQueue [MultiThreadQueue] +- **a)** ThreadPoolExecutor +- **b)** AsyncioExecutor +- **c)** MultiThreadQueue
    💡 Feedback -ThreadPoolExecutor manages a pool of threads, submitting scan tasks concurrently. ProcessPoolExecutor would use processes, which is less efficient for I/O-bound socket operations. [ThreadPoolExecutor gestionează un pool de fire de execuție, trimițând sarcini de scanare concurent. ProcessPoolExecutor ar folosi procese, ceea ce este mai puțin eficient pentru operațiuni de socket limitate de I/O.] +**Correct answer / Răspuns corect: a.** ThreadPoolExecutor manages worker threads. This is an extension proposal; the baseline scanner does not currently use it. Bound concurrency and retain the authorised target scope. [ThreadPoolExecutor gestionează fire worker. Aceasta este o propunere de extensie; scannerul de bază nu o folosește în prezent. Limitați concurența și păstrați domeniul țintelor autorizate.]
    @@ -1101,20 +1087,18 @@ The subscription sensors/# matches sensors/temp and sensors/humidity but NOT wea --- ### Q56. `N13.S04.Q06` -**Protocol detection for TLS traffic on port 8883 / Detectarea protocolului pentru trafic TLS pe portul 8883** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the code tracing exercise T4, when detect_protocol receives a packet with dst_port=8883 and payload starting with byte 0x16, what protocol does it return? [În exercițiul de trasare a codului T4, când detect_protocol primește un pachet cu dst_port=8883 și payload-ul începând cu octetul 0x16, ce protocol returnează?] +A packet is addressed to TCP 8883 and its payload begins with 0x16. What can a simple port-and-byte heuristic reasonably report? [Un pachet este adresat TCP 8883 și payloadul începe cu 0x16. Ce poate raporta rezonabil o euristică simplă bazată pe port și octet?] -- **a)** MQTT-like [MQTT-like] -- **b)** HTTPS [HTTPS] -- **c)** MQTT-TLS [MQTT-TLS] -- **d)** MQTT [MQTT] +- **a)** A candidate TLS record on a conventional MQTT-over-TLS port; further decoding is needed. [Un candidat de înregistrare TLS pe portul convențional MQTT-over-TLS; este necesară decodare suplimentară.] +- **b)** Proved MQTT application content and verified encryption. [Conținut de aplicație MQTT dovedit și criptare verificată.] +- **c)** The sensor password and topic are known. [Parola senzorului și topicul sunt cunoscute.]
    💡 Feedback -Port 8883 matches MQTT_PORTS, and byte 0x16 is the TLS handshake record type. The function returns MQTT-TLS for TLS traffic on MQTT ports. [Portul 8883 se potrivește cu MQTT_PORTS, iar octetul 0x16 este tipul de înregistrare handshake TLS. Funcția returnează MQTT-TLS pentru traficul TLS pe porturile MQTT.] +**Correct answer / Răspuns corect: a.** 0x16 is a TLS handshake record content-type value, but one byte and a port do not validate a record or identify the encrypted application. No absent detect_protocol/T4 implementation is required to answer this conceptual item. [0x16 este valoarea tipului de conținut pentru o înregistrare TLS handshake, dar un octet și un port nu validează înregistrarea și nu identifică aplicația criptată. Itemul conceptual nu necesită o implementare detect_protocol/T4 absentă.]
    @@ -1181,20 +1165,18 @@ The display filter mqtt.msgtype == 3 selects PUBLISH messages. MQTT message type --- ### Q60. `N13.S02.Q02` -**TLS handshake display filter / Filtru de afișare pentru handshake TLS** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Which Wireshark display filter captures TLS handshake packets? [Ce filtru de afișare Wireshark captează pachetele de handshake TLS?] +Which Wireshark display filter selects messages that Wireshark has actually decoded as TLS handshake messages? [Ce filtru de afișare Wireshark selectează mesajele pe care Wireshark le-a decodat efectiv drept handshake TLS?] -- **a)** tls.version >= 0x0303 [tls.version >= 0x0303] -- **b)** tls.handshake (captures all handshake messages) [tls.handshake (capturează toate mesajele de handshake)] -- **c)** ssl.record.content_type == 22 [ssl.record.content_type == 22] -- **d)** tcp.port == 8883 and tls [tcp.port == 8883 and tls] +- **a)** `tls.handshake` +- **b)** `udp.port == 8883` +- **c)** `tcp port 8883`
    💡 Feedback -The filter tls.handshake isolates handshake-phase packets including ClientHello, ServerHello, and certificate exchanges. This works regardless of port. [Filtrul tls.handshake izolează pachetele din faza de handshake, inclusiv ClientHello, ServerHello și schimbul de certificate. Funcționează indiferent de port.] +**Correct answer / Răspuns corect: a.** Use tls.handshake for decoded handshake fields. In TLS 1.3, handshake messages after ServerHello, including Certificate when sent, are encrypted; without suitable session secrets those messages are not exposed as decoded handshake fields. A display filter does not itself decrypt or capture traffic. [Folosiți tls.handshake pentru câmpuri handshake decodate. În TLS 1.3, mesajele după ServerHello, inclusiv Certificate când este trimis, sunt criptate; fără secrete de sesiune potrivite nu apar drept câmpuri handshake decodate. Filtrul de afișare nu decriptează și nu capturează singur traficul.]
    @@ -1221,20 +1203,18 @@ The BPF filter tcp port 1883 captures all TCP packets to/from port 1883. BPF cap --- ### Q62. `N13.S04.Q05` -**Python settimeout method / Metoda settimeout din Python** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In the port scanner code, which method configures the socket timeout for distinguishing between closed and filtered ports? [În codul scanerului de porturi, care metodă configurează timeout-ul socket-ului pentru a distinge între porturile închise și filtrate?] +Which call sets a 0.5-second timeout on an existing Python socket? [Ce apel setează un timeout de 0,5 secunde pe un socket Python existent?] -- **a)** socket.setdefaulttimeout(timeout) [socket.setdefaulttimeout(timeout)] -- **b)** sock.settimeout(timeout) [sock.settimeout(timeout)] -- **c)** sock.timeout = timeout [sock.timeout = timeout] -- **d)** sock.configure(timeout=timeout) [sock.configure(timeout=timeout)] +- **a)** `sock.settimeout(0.5)` +- **b)** `sock.timeout = 0.5` +- **c)** `sock.configure(timeout=0.5)`
    💡 Feedback -sock.settimeout(timeout) configures the socket's blocking timeout. When connect_ex() exceeds this duration, a socket.timeout exception is raised, classified as filtered. [sock.settimeout(timeout) configurează timeout-ul de blocare al socket-ului. Când connect_ex() depășește această durată, se ridică o excepție socket.timeout, clasificată ca filtrat.] +**Correct answer / Răspuns corect: a.** settimeout configures timeout-mode operations. connect_ex can return a timeout-related errno; handle return codes and possible exceptions. A timeout does not uniquely identify a filtered port. [settimeout configurează operațiile în mod timeout. connect_ex poate întoarce un errno legat de timeout; tratați codurile de retur și excepțiile posibile. Timeout-ul nu identifică unic un port filtrat.]
    @@ -1308,17 +1288,15 @@ QoS 2: PUBLISH + PUBREC + PUBREL + PUBCOMP = (...). [QoS 2: PUBLISH + PUBREC + P --- -### Q67. `N13.D03.Q05` -**Expected open ports in lab scan / Porturile deschise așteptate în scanare** - -*Numerical* +### Q67. `N13.D03.Q05` — Declared host mappings / Mapări declarate pe gazdă -> How many host ports report as OPEN when scanning the Week 13 Docker setups from the host? Enter the count. [Câte porturi de pe gazdă raportează ca DESCHISE la scanarea setup-urilor Docker din Săptămâna 13, de pe gazdă? Introduceți numărul.] +*Numerical / Numeric* +With no environment overrides, how many **host port mappings** are declared in the supplied S13 pentest compose file? Count mappings, not successful scan results. [Fără suprascrieri prin mediu, câte **mapări de porturi pe gazdă** sunt declarate în compose-ul de pentest S13 distribuit? Numărați mapările, nu rezultatele reușite ale scanării.]
    💡 Feedback -Consider the host port mappings for the Week 13 services: 1883, 2121, 6200, 8080, 8888. [Luați în calcul mapările de porturi pe gazdă pentru serviciile din Săptămâna 13: 1883, 2121, 6200, 8080, 8888.] +**4**: 8888→80, 8080→8080, 2121→21 and 6200→6200, each bound to 127.0.0.1. A mapping does not guarantee a listening service. [Fiecare mapare este legată la 127.0.0.1. O mapare nu garantează un serviciu care ascultă.]
    @@ -1381,13 +1359,13 @@ Ports 22, 188(...), and 8888 are open. Ports 80 and 9999 are closed. Total open: *Drag & Drop into Text* -> Arrange the mosquitto_sub command for TLS-encrypted subscription: [Aranjați comanda mosquitto_sub pentru abonare criptată cu TLS:] +> Independent scenario: a configured MQTT/TLS broker is reachable as localhost:8883 and its trusted CA file is ./ca.crt. Arrange the subscription command: [Scenariu independent: un broker MQTT/TLS configurat este accesibil la localhost:8883, iar fișierul CA de încredere este ./ca.crt. Aranjați comanda de abonare:] ``` [[1]] -h localhost -p [[2]] --cafile [[3]] -t "iot/#" -v ``` -📋 Available choices / Variante disponibile: mosquitto_sub | 8883 | docker/configs/certs/ca.crt | mosquitto_pub | 1883 | server.key +📋 Available choices / Variante disponibile: mosquitto_sub | 8883 | ./ca.crt | mosquitto_pub | 1883 | server.key
    💡 Feedback @@ -1416,7 +1394,7 @@ error = sock.[[3]]((host, port))
    💡 Feedback -SOCK_STREAM for TCP, settimeout for timeout, connect_ex for non-blocking connect. [SOCK_STREAM pentru TCP, settimeout pentru timeout, connect_ex pentru conectare neblocantă.] +SOCK_STREAM selects TCP, settimeout(0.5) selects timeout mode and connect_ex returns connection error codes. This call can wait up to the timeout; it is not automatically non-blocking. [SOCK_STREAM selectează TCP, settimeout(0.5) selectează modul timeout, iar connect_ex returnează coduri de eroare ale conectării. Apelul poate aștepta până la timeout; nu devine automat neblocant.]
    @@ -1466,41 +1444,38 @@ create_default_context creates the context, load_verify_locations loads the CA, --- ### Q75. `N13.D05.Q07` -**Build docker network inspect command / Construiți comanda docker network inspect** -*Drag & Drop into Text* +*Drag and Drop / Trageți și plasați* -> Complete the Docker command to inspect the Week 13 network: [Completați comanda Docker pentru a inspecta rețeaua Săptămânii 13:] +Assume the S13 compose stack was started with `docker compose -p s13pentest -f S13_Part02_Config_Docker_Compose_Pentest.yml up -d`. Complete the command for its generated network name. [Presupuneți pornirea stackului cu comanda dată. Completați comanda pentru numele generat al rețelei.] -``` +```bash [[1]] [[2]] [[3]] [[4]] ``` -📋 Available choices / Variante disponibile: docker | network | inspect | pentestnet | compose | ls | bridge | dockerd - +Choices / Variante: `docker`, `network`, `inspect`, `s13pentest_pentestnet`, `compose`, `ls`, `pentestnet`.
    💡 Feedback -docker network inspect pentestnet displays network configuration details. [docker network inspect pentestnet afișează detaliile configurării rețelei.] +`docker network inspect s13pentest_pentestnet`. Compose prefixes the logical network name with the chosen project name unless an explicit network name overrides it. For another project name, inspect the actual network with `docker network ls`. [Compose prefixează numele logic cu proiectul ales, dacă nu există un nume explicit suprascris. Pentru alt proiect inspectați rețeaua reală cu `docker network ls`.]
    --- -### Q76. `N13.D05.Q08` -**Complete Wireshark combined lab filter / Completați filtrul combinat de laborator Wireshark** - -*Drag & Drop into Text* +### Q76. `N13.D05.Q08` — S13 host-port filter / Filtrul porturilor S13 pe gazdă -> Build a Wireshark display filter for all Week 13 lab traffic: [Construiți un filtru de afișare Wireshark pentru tot traficul laboratorului Săptămâna 13:] -> tcp.port in {[[1]], [[2]], [[3]], [[4]], [[5]]} +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -📋 Available choices / Variante disponibile: 1883 | 2121 | 6200 | 8080 | 8888 | 9000 | 443 | 80 | 8443 | 8883 +With the default S13 host mappings, which Wireshark display filter selects candidate TCP traffic on their host ports? [Cu mapările implicite S13 pe gazdă, ce filtru de afișare Wireshark selectează traficul TCP candidat pe porturile gazdei?] +- **a)** `tcp.port == 8888 || tcp.port == 8080 || tcp.port == 2121 || tcp.port == 6200` +- **b)** `tcp.port == 1883` +- **c)** `udp.port == 8888 || udp.port == 6200`
    💡 Feedback -The five relevant host ports in Week 13 are 1883, 2121, 6200, 8080, 8888 (MQTT broker + pentest services). [Cele cinci porturi relevante pe gazdă în Săptămâna 13 sunt 1883, 2121, 6200, 8080, 8888 (broker MQTT + servicii de pentest).] +**Correct answer / Răspuns corect: a.** These are four mapped host ports, not a claim of four active listeners. A capture inside the container network instead uses container ports 80, 8080, 21 and conditionally 6200. Adapt to environment overrides and the chosen capture point. [Acestea sunt patru porturi mapate pe gazdă, nu afirmația existenței a patru listenere active. O captură în rețeaua containerelor folosește porturile 80, 8080, 21 și condițional 6200. Adaptați la suprascrierile de mediu și la punctul capturii.]
    @@ -1644,19 +1619,19 @@ PUBLISH, PUBREC, PUBREL, PUBCOMP. [PUBLISH, PUBREC, PUBREL, PUBCOMP.] --- -### Q84. `N13.D10.Q07` -**Security priority ordering / Ordinea de prioritate a securității** - -*Gap Select* +### Q84. `N13.D10.Q07` — Risk-based priorities / Priorități bazate pe risc -> IoT security priorities: first implement [[1]], then [[2]], then [[3]], and finally monitoring. [Prioritățile securității IoT: mai întâi implementați ___, apoi ___, apoi ___ și în final monitorizarea.] +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -📋 Available choices / Variante disponibile: authentication | encryption | authorisation | monitoring | encryption | authentication +Which statement gives a defensible IoT security priority principle? [Ce afirmație oferă un principiu justificat de prioritizare a securității IoT?] +- **a)** Prioritise by demonstrated risk and dependencies, while planning authentication, authorisation, encryption, updates and monitoring together. [Prioritizați după riscul demonstrat și dependențe, planificând împreună autentificarea, autorizarea, criptarea, actualizările și monitorizarea.] +- **b)** Always finish authentication, then authorisation, then encryption, and only then consider monitoring. [Finalizați mereu autentificarea, apoi autorizarea, apoi criptarea și abia apoi luați în calcul monitorizarea.] +- **c)** The numeric OWASP category is the only input required. [Categoria numerică OWASP este singura informație necesară.]
    💡 Feedback -authentication, authorisation (ACLs), encryption (TLS). [autentificarea, autorizarea (ACL-uri), criptarea (TLS).] +**Correct answer / Răspuns corect: a.** A category catalogue supports coverage, not a universal implementation sequence. Controls are complementary, and urgent containment can precede a permanent fix. [Catalogul de categorii susține acoperirea, nu o secvență universală de implementare. Controalele sunt complementare, iar limitarea urgentă poate preceda remedierea permanentă.]
    diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W14_Questions.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W14_Questions.md index e2b207c..278b0c2 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W14_Questions.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W14_Questions.md @@ -168,20 +168,18 @@ TCP is connection-oriented with reliability through ACKs and retransmissions. UD --- ### Q9. `N14.C02.Q03` -**TCP Four-Way Termination Count / Numărul de pachete la terminarea TCP** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> How many packets are exchanged during a graceful TCP connection termination? [Câte pachete se schimbă în timpul terminării grațioase a unei conexiuni TCP?] +Assume an ordinary graceful TCP close with separate FIN and ACK segments in each direction, no combined FIN+ACK response, no retransmissions and no application data. How many segments does this stated sequence contain? [Presupuneți o închidere TCP grațioasă obișnuită cu segmente FIN și ACK separate în fiecare sens, fără răspuns combinat FIN+ACK, fără retransmisii și fără date de aplicație. Câte segmente conține secvența dată?] -- **a)** 4 (FIN, ACK, FIN, ACK) [4 (FIN, ACK, FIN, ACK)] -- **b)** 2 (FIN, ACK) [2 (FIN, ACK)] -- **c)** 3 — FIN, ACK, FIN-ACK exchange in total [3 — schimb FIN, ACK, FIN-ACK în total] -- **d)** 1 (RST) [1 (RST)] +- **a)** 4 +- **b)** 2 +- **c)** 1
    💡 Feedback -Graceful termination uses four packets: FIN from initiator, ACK from receiver, FIN from receiver, ACK from initiator. Each side independently closes its half of the connection. [Terminarea grațioasă folosește patru pachete: FIN de la inițiator, ACK de la receptor, FIN de la receptor, ACK de la inițiator. Fiecare parte își închide independent jumătatea de conexiune.] +**Correct answer / Răspuns corect: a.** The stated sequence is FIN, ACK, FIN, ACK. This is not a universal packet count: ACK and FIN can be combined and retransmissions can add packets. Each direction closes independently. [Secvența dată este FIN, ACK, FIN, ACK. Numărul nu este universal: ACK și FIN pot fi combinate, iar retransmisiile pot adăuga pachete. Fiecare sens se închide independent.]
    @@ -342,20 +340,18 @@ Health checks run periodically. During the detection interval, the LB may still --- ### Q18. `N14.C04.Q03` -**Reverse Proxy Forwarding Headers / Antetele de redirecționare ale proxy-ului invers** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> The Week 14 load balancer adds X-Forwarded-For and X-Real-IP headers. Why are these necessary? [Echilibratorul de sarcină din săptămâna 14 adaugă antetele X-Forwarded-For și X-Real-IP. De ce sunt acestea necesare?] +A trusted reverse proxy sets X-Forwarded-For and X-Real-IP before forwarding HTTP requests. What purpose can these headers serve? [Un reverse proxy de încredere setează X-Forwarded-For și X-Real-IP înaintea redirecționării cererilor HTTP. Ce rol pot avea antetele?] -- **a)** To preserve the original client IP address, which would otherwise be replaced by the proxy's address [Pentru a păstra adresa IP originală a clientului, care altfel ar fi înlocuită cu adresa proxy-ului] -- **b)** X-Forwarded-For and X-Real-IP headers preserve the original client IP address, allowing backend servers to identify the true source of each proxied request [Antetele X-Forwarded-For și X-Real-IP păstrează adresa IP originală a clientului, permițând serverelor backend să identifice sursa reală a fiecărei cereri proximate] -- **c)** To authenticate the load balancer identity to the backend application servers [Pentru a autentifica identitatea echilibratorului de sarcină la serverele backend] -- **d)** To specify which load balancing algorithm should be applied to the request [Pentru a specifica ce algoritm de echilibrare a sarcinii ar trebui aplicat cererii] +- **a)** Carry client-address information to the backend, which sees the proxy as its connection peer. [Transmit informația despre adresa clientului către backend, care vede proxy-ul drept corespondent al conexiunii.] +- **b)** Cryptographically authenticate every original client. [Autentifică criptografic fiecare client original.] +- **c)** Select the load-balancing algorithm automatically. [Selectează automat algoritmul de echilibrare.]
    💡 Feedback -When a reverse proxy forwards a request, the backend sees the proxy's IP as the source. X-Forwarded-For preserves the original client IP through the forwarding chain. [Când un proxy invers redirecționează o cerere, backend-ul vede IP-ul proxy-ului ca sursă. X-Forwarded-For păstrează IP-ul original al clientului prin lanțul de redirecționare.] +**Correct answer / Răspuns corect: a.** These headers convey application metadata, not cryptographic proof. Trust them only from controlled proxy paths with a defined overwrite/append policy; arbitrary client-supplied values can be forged. [Antetele transmit metadate ale aplicației, nu dovezi criptografice. Acordați încredere numai căilor proxy controlate cu politică definită de suprascriere/adăugare; valorile furnizate arbitrar de client pot fi falsificate.]
    @@ -542,20 +538,18 @@ Comprehensive monitoring requires multiple data sources: /lb-status for traffic --- ### Q28. `N14.C02.Q06` -**Connection Refused vs Timeout / Connection Refused vs Timeout** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> A student runs nc -zv localhost 9999 and receives 'Connection refused'. What can they definitively conclude? [Un student execută nc -zv localhost 9999 și primește 'Connection refused'. Ce poate concluziona cu certitudine?] +A TCP connection attempt receives an active reset/refusal. Which conclusion is supported? [O tentativă de conectare TCP primește un reset/refuz activ. Ce concluzie este susținută?] -- **a)** The host is reachable but no service listens on port 9999 [Gazda este accesibilă, dar niciun serviciu nu ascultă pe portul 9999] -- **b)** A firewall rule is actively blocking TCP traffic to port 9999 [O regulă de firewall blochează activ traficul TCP către portul 9999] -- **c)** The network path between client and server is completely broken [Calea de rețea între client și server este complet întreruptă] -- **d)** The DNS resolution failed and the hostname could not be resolved [Rezoluția DNS a eșuat și numele gazdei nu a putut fi rezolvat] +- **a)** The attempted connection was refused; an absent listener or an explicit firewall rejection can both cause this. [Conexiunea încercată a fost refuzată; lipsa listenerului sau respingerea firewall explicită pot produce ambele rezultatul.] +- **b)** There is certainly no firewall on the path. [Sigur nu există firewall pe cale.] +- **c)** The connection was gracefully closed after successful application processing. [Conexiunea a fost închisă grațios după procesarea reușită a aplicației.]
    💡 Feedback -'Connection refused' means a TCP RST was received, confirming network reachability. Firewall blocking would cause timeout, not refusal. DNS failure produces a different error message. ['Connection refused' înseamnă că s-a primit un TCP RST, confirmând accesibilitatea rețelei. Blocarea de firewall ar cauza timeout, nu refuz. Eșecul DNS produce un mesaj de eroare diferit.] +**Correct answer / Răspuns corect: a.** RST in response to SYN is active refusal, not a successful handshake. A firewall configured with tcp-reset can produce the same observation as an endpoint without a listener. Further evidence identifies the cause. [RST ca răspuns la SYN este refuz activ, nu handshake reușit. Un firewall configurat cu tcp-reset poate produce aceeași observație ca un endpoint fără listener. Dovezi suplimentare identifică cauza.]
    @@ -602,40 +596,36 @@ localhost resolution depends on /etc/hosts and system config. If it resolves to --- ### Q31. `N14.C02.Q04` -**RST Flag After SYN Meaning / Semnificația RST după SYN** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In a Wireshark capture you observe a TCP RST packet sent from a server immediately after a client's SYN. What does this indicate? [Într-o captură Wireshark observați un pachet TCP RST trimis de server imediat după SYN-ul clientului. Ce indică acest lucru?] +A TCP connection attempt receives an active reset/refusal. Which conclusion is supported? [O tentativă de conectare TCP primește un reset/refuz activ. Ce concluzie este susținută?] -- **a)** No service is listening on the destination port; the connection is refused [Niciun serviciu nu ascultă pe portul destinație; conexiunea este refuzată] -- **b)** The connection was established and then immediately terminated by the server application due to resource exhaustion [Conexiunea a fost stabilită și apoi terminată imediat de aplicația server din cauza epuizării resurselor] -- **c)** The connection was established and is now being gracefully terminated [Conexiunea a fost stabilită și este acum terminată grațios] -- **d)** The server acknowledges the SYN and requests a data retransmission [Serverul confirmă SYN-ul și solicită o retransmisie de date] +- **a)** The attempted connection was refused; an absent listener or an explicit firewall rejection can both cause this. [Conexiunea încercată a fost refuzată; lipsa listenerului sau respingerea firewall explicită pot produce ambele rezultatul.] +- **b)** There is certainly no firewall on the path. [Sigur nu există firewall pe cale.] +- **c)** The connection was gracefully closed after successful application processing. [Conexiunea a fost închisă grațios după procesarea reușită a aplicației.]
    💡 Feedback -TCP RST in response to SYN means no service listens on that port, producing 'Connection refused'. Firewall blocking causes timeout (no response at all). Receiving RST confirms the host is reachable. [TCP RST ca răspuns la SYN înseamnă că niciun serviciu nu ascultă pe acel port, producând eroarea 'Connection refused'. Blocarea de firewall cauzează timeout (niciun răspuns). Primirea RST confirmă că gazda este accesibilă.] +**Correct answer / Răspuns corect: a.** RST in response to SYN is active refusal, not a successful handshake. A firewall configured with tcp-reset can produce the same observation as an endpoint without a listener. Further evidence identifies the cause. [RST ca răspuns la SYN este refuz activ, nu handshake reușit. Un firewall configurat cu tcp-reset poate produce aceeași observație ca un endpoint fără listener. Dovezi suplimentare identifică cauza.]
    --- ### Q32. `N14.T00.Q02` -**Scenario: Wireshark Packet Analysis / Scenariu: Analiza pachetelor Wireshark** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> You capture 30 seconds of traffic and apply tcp.flags.syn == 1 && tcp.flags.ack == 0. You see 10 packets. What can you conclude? [Capturați 30 de secunde de trafic și aplicați tcp.flags.syn == 1 && tcp.flags.ack == 0. Vedeți 10 pachete. Ce puteți concluziona?] +The display filter `tcp.flags.syn == 1 && tcp.flags.ack == 0` matches ten captured packets. What can be concluded from that count alone? [Filtrul de afișare `tcp.flags.syn == 1 && tcp.flags.ack == 0` potrivește zece pachete capturate. Ce se poate concluziona doar din acest număr?] -- **a)** 10 new TCP connections were initiated during the capture period [10 conexiuni TCP noi au fost inițiate în perioada de captură] -- **b)** 10 HTTP requests were completed successfully through the load balancer [10 cereri HTTP au fost completate cu succes prin echilibratorul de sarcină] -- **c)** 10 packets were dropped by the firewall before reaching any destination [10 pachete au fost eliminate de firewall înainte de a ajunge la orice destinație] -- **d)** The network experienced 10 connection errors and all were retransmitted [Rețeaua a experimentat 10 erori de conexiune și toate au fost retransmise] +- **a)** Ten observed segments have SYN set and ACK clear; some may be retransmissions of the same attempt. [Zece segmente observate au SYN setat și ACK nesetat; unele pot fi retransmisii ale aceleiași tentative.] +- **b)** Exactly ten distinct connections were successfully established. [Exact zece conexiuni distincte au fost stabilite cu succes.] +- **c)** Exactly ten HTTP requests completed. [Exact zece cereri HTTP s-au finalizat.]
    💡 Feedback -SYN-only packets (SYN=1, ACK=0) represent the first packet of each new TCP connection. 10 such packets = 10 connection attempts. Each may carry multiple HTTP requests via keep-alive. [Pachetele doar SYN (SYN=1, ACK=0) reprezintă primul pachet al fiecărei conexiuni TCP noi. 10 astfel de pachete = 10 încercări de conexiune. Fiecare poate transporta mai multe cereri HTTP prin keep-alive.] +**Correct answer / Răspuns corect: a.** Count attempts or established connections only after considering retransmissions, endpoint tuples, sequence numbers and completion of handshakes. A SYN count alone is not a count of successful sessions. [Numărați tentative sau conexiuni stabilite numai după examinarea retransmisiilor, tuplelor de endpoint, numerelor de secvență și finalizării handshake-urilor. Numărul SYN singur nu reprezintă numărul sesiunilor reușite.]
    @@ -686,20 +676,19 @@ Docker networks provide isolation. The client reaches app1 only through the load --- ### Q35. `N14.S01.Q03` -**Listing Running Containers / Listarea containerelor active** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> Which command shows only the Week 14 running containers with their status and ports? [Ce comandă afișează doar containerele active din săptămâna 14 cu starea și porturile lor?] +For an example deployment started with Compose project name week14, which command lists only its running containers, including status and published ports? [Pentru o implementare exemplu pornită cu numele de proiect Compose week14, ce comandă listează numai containerele sale active, inclusiv starea și porturile publicate?] -- **a)** docker ps — lists all currently running containers with their names, status, port mappings and image information in a formatted table [listează toate containerele active cu numele, starea, mapările de porturi și informațiile despre imagine într-un tabel formatat] -- **b)** docker ps -a — shows all containers including stopped ones, not filtered [docker ps -a — afișează toate containerele inclusiv cele oprite, nefiltrat] -- **c)** docker images | grep week14 — lists images, not running containers [docker images | grep week14 — listează imaginile, nu containerele active] -- **d)** docker network inspect week14_backend_net — shows network details only [docker network inspect week14_backend_net — afișează doar detaliile rețelei] +- **a)** `docker ps --filter label=com.docker.compose.project=week14` +- **b)** `docker ps -a` +- **c)** `docker images` +- **d)** `docker network ls`
    💡 Feedback -The --filter flag narrows docker ps output. Using name=week14 shows only containers whose names match the prefix, with their status and port mappings. [Fanionul --filter restrânge rezultatul docker ps. Folosind name=week14 se afișează doar containerele ale căror nume corespund prefixului, cu starea și mapările de porturi.] +**Correct answer / Răspuns corect: a.** Compose applies the project label. Filtering by its exact value identifies the project without relying on a partial name match. This item supplies an example project name; it does not imply that S14 includes a deployable compose stack. [Compose aplică eticheta proiectului. Filtrarea după valoarea exactă identifică proiectul fără a depinde de potrivirea parțială a numelui. Itemul furnizează un nume exemplu; nu implică existența unui stack compose executabil în S14.]
    @@ -804,60 +793,54 @@ Systematic troubleshooting starts with identifying which component is failing. S --- ### Q41. `N14.S03.Q02` -**Docker Logs for Debugging / Logurile Docker pentru depanare** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> To view the last 50 log lines from the load balancer container in real-time, which command is correct? [Pentru a vizualiza ultimele 50 de linii de log de la containerul echilibratorului de sarcină în timp real, care comandă este corectă?] +A running example container is named week14_lb and logs to stdout/stderr. Which command prints up to its last 50 log lines and then follows new output? [Un container exemplu activ se numește week14_lb și scrie loguri la stdout/stderr. Ce comandă afișează până la ultimele 50 de linii și apoi urmărește ieșirea nouă?] -- **a)** docker logs week14_lb — displays the load balancer container output showing proxy routing decisions, backend selections and error messages [afișează ieșirea containerului echilibratorului arătând deciziile de rutare proxy, selecțiile backend și mesajele de eroare] -- **b)** docker logs week14_lb > lb.log — redirects to file, no real-time following [docker logs week14_lb > lb.log — redirecționează în fișier, fără urmărire în timp real] -- **c)** docker inspect week14_lb — shows container config, not application logs [docker inspect week14_lb — afișează configurația containerului, nu logurile aplicației] -- **d)** docker exec week14_lb cat /var/log/syslog — checks system log, not app output [docker exec week14_lb cat /var/log/syslog — verifică logul de sistem, nu output-ul aplicației] +- **a)** `docker logs --tail 50 -f week14_lb` +- **b)** `docker logs week14_lb` +- **c)** `docker inspect week14_lb`
    💡 Feedback -The -f flag follows the log output in real time (like tail -f). The --tail N flag limits initial output to the last N lines. Both combined provide real-time monitoring with reasonable context. [Fanionul -f urmărește output-ul logului în timp real (precum tail -f). Fanionul --tail N limitează output-ul inițial la ultimele N linii. Ambele combinate asigură monitorizare în timp real cu context rezonabil.] +**Correct answer / Răspuns corect: a.** --tail 50 bounds the initial history; -f follows subsequent output. The command shows what the application actually emits, not guaranteed backend-selection or security events. [--tail 50 limitează istoricul inițial; -f urmărește ieșirea ulterioară. Comanda arată ce emite efectiv aplicația, nu evenimente garantate de selecție backend sau securitate.]
    --- ### Q42. `N14.S03.Q03` -**Testing Backend Health Directly / Testarea directă a sănătății backend-ului** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> To verify that backend app1 is responding correctly, bypassing the load balancer, which curl command is appropriate? [Pentru a verifica că backend-ul app1 răspunde corect, ocolind echilibratorul de sarcină, care comandă curl este adecvată?] +An example backend listens on container port 8001 and is published as `127.0.0.1:8001:8001`. The load balancer is published on 8080. From that Docker host, which command explicitly uses the backend’s published endpoint? [Un backend exemplu ascultă pe portul 8001 în container și este publicat ca `127.0.0.1:8001:8001`. Load balancerul este publicat pe 8080. De pe gazda Docker, ce comandă folosește explicit endpointul publicat al backendului?] -- **a)** curl http://localhost:8001/health — sends a direct GET request to Backend 1 bypassing the load balancer, confirming backend availability independently [trimite o cerere GET directă către Backend 1 ocolind echilibratorul, confirmând disponibilitatea backend-ului independent] -- **b)** curl http://localhost:8080/health — goes through the load balancer, not direct [curl http://localhost:8080/health — trece prin echilibratorul de sarcină, nu direct] -- **c)** curl http://172.20.0.2:8001/health — container IP unreachable from host directly [curl http://172.20.0.2:8001/health — IP-ul containerului inaccesibil direct de la gazdă] -- **d)** curl http://localhost:9090/health — connects to the TCP echo server instead [curl http://localhost:9090/health — se conectează la serverul TCP echo în schimb] +- **a)** `curl http://127.0.0.1:8001/health` +- **b)** `curl http://127.0.0.1:8080/health` +- **c)** `curl http://127.0.0.1:9090/health`
    💡 Feedback -Port 8001 is mapped directly to app1 (8001:8001). Port 8002 maps to app2 (8002:8001). Using these host ports bypasses the load balancer for direct testing. [Portul 8001 este mapat direct la app1 (8001:8001). Portul 8002 se mapează la app2 (8002:8001). Folosirea acestor porturi gazdă ocolește echilibratorul de sarcină pentru testare directă.] +**Correct answer / Răspuns corect: a.** The supplied host mapping bypasses the load balancer. Whether a container IP is directly reachable depends on platform and routing: a native Linux daemon host often can reach its bridge subnet, while a Docker Desktop physical host has a different path. EXPOSE alone does not publish a port. [Maparea dată pe gazdă ocolește load balancerul. Accesibilitatea directă a IP-ului containerului depinde de platformă și rutare: gazda daemonului Linux nativ poate adesea ajunge la subrețeaua bridge, în timp ce gazda fizică Docker Desktop are altă cale. EXPOSE singur nu publică porturi.]
    --- ### Q43. `N14.S03.Q04` -**Port Conflict Resolution / Rezolvarea conflictelor de porturi** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> A container fails to start with 'address already in use' on port 8080. What diagnostic command identifies the conflicting process? [Un container nu reușește să pornească cu 'address already in use' pe portul 8080. Ce comandă de diagnosticare identifică procesul conflictual?] +On the Linux host reporting a TCP bind conflict on port 8080, which command queries listening sockets and their process information for that exact port? [Pe gazda Linux care raportează un conflict bind TCP pe 8080, ce comandă interoghează socketurile de ascultare și informațiile proceselor pentru portul exact?] -- **a)** netstat -tlnp | grep or ss -tlnp | grep — identifies the process occupying a specific port, showing PID and program name for resolution [identifică procesul care ocupă un port specific, afișând PID-ul și numele programului pentru rezolvare] -- **b)** docker ps | grep 8080 — shows Docker containers but not non-Docker processes [docker ps | grep 8080 — afișează containerele Docker, dar nu procesele non-Docker] -- **c)** ping localhost — tests network connectivity, irrelevant to port conflicts [ping localhost — testează conectivitatea rețelei, irelevant pentru conflictele de porturi] -- **d)** docker network ls — lists Docker networks, unrelated to port binding issues [docker network ls — listează rețelele Docker, fără legătură cu problemele de legare a porturilor] +- **a)** `sudo ss -ltnp 'sport = :8080'` +- **b)** `ping localhost` +- **c)** `docker network ls`
    💡 Feedback -ss -tlnp shows all TCP listening sockets with process names. Grep for the specific port reveals which process (Docker or otherwise) is already bound to it. [ss -tlnp afișează toate socket-urile TCP care ascultă cu numele proceselor. Grep pentru portul specific dezvăluie ce proces (Docker sau altul) este deja legat de acesta.] +**Correct answer / Răspuns corect: a.** The ss filter avoids an empty grep pattern or a substring match such as 18080. Process information requires sufficient permission. Docker publication may also be implemented through forwarding rules, so inspect Docker port mappings if the socket query does not explain the conflict. [Filtrul ss evită un pattern grep gol sau o potrivire parțială precum 18080. Informațiile procesului necesită permisiuni suficiente. Publicarea Docker poate folosi și reguli de redirecționare, deci inspectați mapările Docker dacă interogarea socketurilor nu explică conflictul.]
    @@ -982,60 +965,71 @@ The parser splits each header line on ": " (colon-space). For "X-Backend: app1", --- ### Q50. `N14.S05.Q03` -**Socket Connection to Unreachable Host / Conexiune socket către gazdă inaccesibilă** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In code tracing exercise T1, calling connect_to_server("10.255.255.1", 80) where the IP is unreachable results in: [În exercițiul de trasare T1, apelul connect_to_server("10.255.255.1", 80) unde IP-ul este inaccesibil rezultă în:] +A TCP socket with a five-second timeout attempts an address that is unreachable in the current environment. What outcome is guaranteed by the word unreachable alone? [Un socket TCP cu timeout de cinci secunde încearcă o adresă inaccesibilă în mediul curent. Ce rezultat este garantat numai de termenul inaccesibil?] -- **a)** "timeout" — the socket.timeout exception is caught after 5 seconds ["timeout" — excepția socket.timeout este capturată după 5 secunde] -- **b)** "connected" — the connection succeeds despite the unreachable IP address ["connected" — conexiunea reușește în ciuda adresei IP inaccesibile] -- **c)** "refused" — a ConnectionRefusedError is raised by the operating system ["refused" — o excepție ConnectionRefusedError este ridicată de sistemul de operare] -- **d)** "error: Network is unreachable" — an OSError exception occurs immediately ["error: Network is unreachable" — o excepție OSError apare imediat] +- **a)** No unique error: the call may fail immediately with a routing error or wait until a timeout, depending on the path. [Nicio eroare unică: apelul poate eșua imediat cu o eroare de rutare sau poate aștepta până la timeout, în funcție de cale.] +- **b)** It always waits exactly five seconds and raises socket.timeout. [Așteaptă întotdeauna exact cinci secunde și ridică socket.timeout.] +- **c)** It always succeeds because private addresses are reachable. [Reușește întotdeauna deoarece adresele private sunt accesibile.]
    💡 Feedback -An unreachable IP causes no response. With sock.settimeout(5), a socket.timeout exception fires after 5 seconds. The except clause catches it and returns 'timeout'. [Un IP inaccesibil nu cauzează niciun răspuns. Cu sock.settimeout(5), excepția socket.timeout se declanșează după 5 secunde. Clauza except o capturează și returnează 'timeout'.] +**Correct answer / Răspuns corect: a.** The address literal does not specify routing, neighbour reachability or firewall responses. A deterministic code-tracing question must supply the returned errno or exception rather than assume it from an IP address. [Literalul adresei nu specifică rutarea, accesibilitatea vecinilor sau răspunsurile firewall. Un item determinist de trasare trebuie să furnizeze errno-ul sau excepția, nu să le presupună dintr-o adresă IP.]
    --- ### Q51. `N14.S05.Q04` -**Packet Counter analyse_traffic Output / Rezultatul contorului de pachete analyse_traffic** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* + +For the self-contained code below, what is `result["http"]`? [Pentru codul autonom de mai jos, care este `result["http"]`?] -> Given the T5 code tracing with 5 packets (3 HTTP on port 80, 1 HTTPS on port 443, 1 UDP/DNS on port 53), what is result["http"]? [Dat fiind trasarea codului T5 cu 5 pachete (3 HTTP pe portul 80, 1 HTTPS pe portul 443, 1 UDP/DNS pe portul 53), care este result["http"]?] +```python +packets = [{"http": True}, {"http": True}, {"http": True}, + {"http": False}, {"udp": True}] +result = {"http": sum(bool(pkt.get("http")) for pkt in packets)} +``` -- **a)** result["by_port"][80] equals 3, since three packets in the input list have dst_port=80 and the counter accumulates each occurrence in the dictionary [result["by_port"][80] este egal cu 3, deoarece trei pachete din lista de intrare au dst_port=80 și contorul acumulează fiecare apariție în dicționar] -- **b)** 5 — all packets regardless of protocol type are counted in the HTTP field [5 — toate pachetele indiferent de tipul protocolului sunt numărate în câmpul HTTP] -- **c)** 4 — both HTTP and HTTPS packets are counted together as HTTP traffic [4 — atât pachetele HTTP, cât și HTTPS sunt numărate împreună ca trafic HTTP] -- **d)** 0 — the function only counts TCP and UDP protocols, not application-layer HTTP [0 — funcția numără doar protocoalele TCP și UDP, nu HTTP de la stratul aplicație] + +- **a)** 3 +- **b)** 5 +- **c)** 4 +- **d)** 0
    💡 Feedback -The analyse_traffic function checks pkt.get("http") for each packet. Only packets where this key is truthy increment stats["http"]. The HTTPS packet has http=False. [Funcția analyse_traffic verifică pkt.get("http") pentru fiecare pachet. Doar pachetele unde această cheie este adevărată incrementează stats["http"]. Pachetul HTTPS are http=False.] +**Correct answer / Răspuns corect: a.** Exactly three values are truthy. This counts the supplied semantic flag; port 80 alone would not prove HTTP traffic. [Exact trei valori sunt adevărate. Codul numără indicatorul semantic dat; portul 80 singur nu ar demonstra trafic HTTP.]
    --- ### Q52. `N14.S05.Q05` -**Container Health Check Logic / Logica verificării de sănătate a containerului** -*Multiple Choice* +*Multiple Choice — one correct answer / Alegere multiplă — un singur răspuns corect* -> In code tracing T4, what does check_container("app99") return for a non-existent container? [În trasarea codului T4, ce returnează check_container("app99") pentru un container inexistent?] +The following self-contained trace receives empty stdout from a successful container query. What is result? [Următoarea trasare autonomă primește stdout gol de la o interogare de container reușită. Care este result?] -- **a)** result1["running"] is True and result1["ip"] is "172.20.0.2" because the container is active and has a network IP assigned by Docker [result1["running"] este True și result1["ip"] este "172.20.0.2" deoarece containerul este activ și are un IP de rețea atribuit de Docker] -- **b)** {"name": "app99", "running": True, "ip": "0.0.0.0"} [{"name": "app99", "running": True, "ip": "0.0.0.0"}] -- **c)** An empty dictionary {} because the function returns early on error [Un dicționar gol {} deoarece funcția returnează devreme la eroare] -- **d)** A subprocess.CalledProcessError exception is raised and not caught [O excepție subprocess.CalledProcessError este ridicată și nu este capturată] +```python +name = "app99" +stdout = "" +result = {"name": name, "running": False, "ip": None} +if stdout.strip(): + result["running"] = True +``` + + +- **a)** `{"name": "app99", "running": False, "ip": None}` +- **b)** `{"name": "app99", "running": True, "ip": "0.0.0.0"}` +- **c)** `{}`
    💡 Feedback -docker ps -q -f name=app99 returns empty stdout (no matching container). The if ps_result.stdout.strip() check is False, so running stays False and ip stays None. [docker ps -q -f name=app99 returnează stdout gol (niciun container corespunzător). Verificarea if ps_result.stdout.strip() este False, deci running rămâne False și ip rămâne None.] +**Correct answer / Răspuns corect: a.** The condition is false, so neither initial value changes. Query failure is a different case and must be handled separately; a name substring filter also does not prove exact identity. [Condiția este falsă, deci valorile inițiale nu se schimbă. Eșecul interogării reprezintă alt caz și trebuie tratat separat; filtrarea prin subșir de nume nu demonstrează identitatea exactă.]
    @@ -1214,16 +1208,14 @@ Backend.mark_failure() sets healthy=False when consecutive_failures >= (...). [B --- ### Q63. `N14.D03.Q08` -**Total Distinct Networks in Week 14 / Total rețele distincte în săptămâna 14** - -*Numerical* -> How many distinct Docker networks are defined in the Week 14 docker-compose.yml (not counting the default)? [Câte rețele Docker distincte sunt definite în docker-compose.yml din săptămâna 14 (fără cea implicită)?] +*Numerical / Numeric* +An independent example Compose configuration explicitly declares `backend_net` with subnet `172.20.0.0/24` and `frontend_net` with subnet `172.21.0.0/24`, and no other networks. How many named networks are declared? [O configurație Compose exemplu independentă declară explicit `backend_net` cu subrețeaua `172.20.0.0/24` și `frontend_net` cu `172.21.0.0/24`, fără alte rețele. Câte rețele denumite sunt declarate?]
    💡 Feedback -Two networks: backend_net (17(...).(...)0.0.0/(...)4) and frontend_net (17(...).(...)1.0.0/(...)4). [Două rețele: backend_net (17(...).(...)0.0.0/(...)4) și frontend_net (17(...).(...)1.0.0/(...)4).] +**2**. The two literal subnet strings are complete and distinct. This question supplies its configuration assumptions and does not refer to an absent Week 14 compose file. [Cele două șiruri literale de subrețea sunt complete și distincte. Itemul furnizează ipotezele de configurație și nu trimite la un fișier compose Week 14 absent.]
    diff --git a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/README.md b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/README.md index de02e54..c9aa87e 100644 --- a/00_APPENDIX/c)studentsQUIZes(multichoice_only)/README.md +++ b/00_APPENDIX/c)studentsQUIZes(multichoice_only)/README.md @@ -7,20 +7,20 @@ Student-facing revision bank organised by teaching week. Each Markdown file cont | Name | Description | Metric | |---|---|---| | [`README.md`](README.md) | Orientation for the weekly question bank | — | -| [`COMPnet_W01_Questions.md`](COMPnet_W01_Questions.md) | Week 01 questions (network basics) | 271 lines, 16 questions | -| [`COMPnet_W02_Questions.md`](COMPnet_W02_Questions.md) | Week 02 questions (models, sockets and transport basics) | 602 lines, 35 questions | -| [`COMPnet_W03_Questions.md`](COMPnet_W03_Questions.md) | Week 03 questions (network programming, TCP/UDP patterns) | 823 lines, 49 questions | -| [`COMPnet_W04_Questions.md`](COMPnet_W04_Questions.md) | Week 04 questions (framing, bytes and protocol parsing) | 1,170 lines, 75 questions | -| [`COMPnet_W05_Questions.md`](COMPnet_W05_Questions.md) | Week 05 questions (IP addressing and subnetting) | 801 lines, 47 questions | -| [`COMPnet_W06_Questions.md`](COMPnet_W06_Questions.md) | Week 06 questions (NAT, ARP, DHCP, ICMP and neighbour discovery) | 1,126 lines, 77 questions | -| [`COMPnet_W07_Questions.md`](COMPnet_W07_Questions.md) | Week 07 questions (routing concepts and tools) | 730 lines, 46 questions | -| [`COMPnet_W08_Questions.md`](COMPnet_W08_Questions.md) | Week 08 questions (transport protocols and socket behaviour) | 787 lines, 55 questions | -| [`COMPnet_W09_Questions.md`](COMPnet_W09_Questions.md) | Week 09 questions (session and presentation concepts) | 723 lines, 53 questions | -| [`COMPnet_W10_Questions.md`](COMPnet_W10_Questions.md) | Week 10 questions (application protocols and HTTP concepts) | 728 lines, 52 questions | -| [`COMPnet_W11_Questions.md`](COMPnet_W11_Questions.md) | Week 11 questions (FTP, DNS and SSH) | 1,218 lines, 60 questions | -| [`COMPnet_W12_Questions.md`](COMPnet_W12_Questions.md) | Week 12 questions (email protocols and mail security basics) | 1,237 lines, 61 questions | -| [`COMPnet_W13_Questions.md`](COMPnet_W13_Questions.md) | Week 13 questions (IoT and network security topics) | 1,699 lines, 86 questions | -| [`COMPnet_W14_Questions.md`](COMPnet_W14_Questions.md) | Week 14 questions (integrated recap and exam revision) | 1,549 lines, 79 questions | +| [`COMPnet_W01_Questions.md`](COMPnet_W01_Questions.md) | Week 01 questions (network basics) | 16 questions | +| [`COMPnet_W02_Questions.md`](COMPnet_W02_Questions.md) | Week 02 questions (models, sockets and transport basics) | 35 questions | +| [`COMPnet_W03_Questions.md`](COMPnet_W03_Questions.md) | Week 03 questions (network programming, TCP/UDP patterns) | 49 questions | +| [`COMPnet_W04_Questions.md`](COMPnet_W04_Questions.md) | Week 04 questions (framing, bytes and protocol parsing) | 75 questions | +| [`COMPnet_W05_Questions.md`](COMPnet_W05_Questions.md) | Week 05 questions (IP addressing and subnetting) | 47 questions | +| [`COMPnet_W06_Questions.md`](COMPnet_W06_Questions.md) | Week 06 questions (NAT, ARP, DHCP, ICMP and neighbour discovery) | 77 questions | +| [`COMPnet_W07_Questions.md`](COMPnet_W07_Questions.md) | Week 07 questions (routing concepts and tools) | 46 questions | +| [`COMPnet_W08_Questions.md`](COMPnet_W08_Questions.md) | Week 08 questions (transport protocols and socket behaviour) | 55 questions | +| [`COMPnet_W09_Questions.md`](COMPnet_W09_Questions.md) | Week 09 questions (session and presentation concepts) | 53 questions | +| [`COMPnet_W10_Questions.md`](COMPnet_W10_Questions.md) | Week 10 questions (application protocols and HTTP concepts) | 52 questions | +| [`COMPnet_W11_Questions.md`](COMPnet_W11_Questions.md) | Week 11 questions (FTP, DNS and SSH) | 60 questions | +| [`COMPnet_W12_Questions.md`](COMPnet_W12_Questions.md) | Week 12 questions (email protocols and mail security basics) | 61 questions | +| [`COMPnet_W13_Questions.md`](COMPnet_W13_Questions.md) | Week 13 questions (IoT and network security topics) | 86 questions | +| [`COMPnet_W14_Questions.md`](COMPnet_W14_Questions.md) | Week 14 questions (integrated recap and exam revision) | 79 questions | Total size: 791 questions across 14 weeks. @@ -43,7 +43,9 @@ apply again"] - Students: work through the week’s lecture and lab, then attempt the corresponding `COMPnet_WNN_Questions.md` file without looking at the answers. - Instructors: extract questions into an LMS question bank or use them as in-class checks. -The files are Markdown sources. They are not automatically imported by the repository tooling. +The files are Markdown sources. They are not automatically imported by the repository tooling. Question numbers and historical source identifiers are retained for traceability. A self-contained hypothetical design exercise defines its own contract; it must not be treated as an executable description of the supplied laboratory files. In particular, S04 uses LF-independent total-length text framing, a one-byte binary length prefix and its documented UDP message model. Validate the supplied scripts using the seminar instructions. + +For LMS use, configure the question type, the correct choice or formula, tolerance and random-value ranges explicitly. Preview the resulting question in the target LMS before assigning it; the Markdown feedback is not a verified Moodle import package. ## Design Notes diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3.md index 12d76a8..acab32b 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3.md @@ -136,7 +136,7 @@ netstat -tulnp Explică flag-urile: `-t` TCP, `-u` UDP, `-l` listening, `-n` numeric (fără DNS invers), `-p` procesul proprietar. -Arată output-ul: un port în LISTEN (ex. sshd pe :22), eventual ESTABLISHED (sesiunea SSH curentă). +Arată un port în LISTEN (ex. sshd pe :22). Pentru ESTABLISHED (sesiunea SSH curentă), rulează separat `netstat -tnp` sau `ss -tnp`; `-l` selectează listeners. > *▸ Alternativă modernă: `ss -tulnp` — aceleași flag-uri, disponibil pe distribuțiile recente. Vom folosi `netstat` și `ss` alternativ pe tot semestrul.* @@ -241,9 +241,9 @@ Client tastează `salut` → apare în SERVER. Server tastează `răspuns` → a ### Pregătire logistică — acum ai 3 terminale -Pe lângă cele două sesiuni SSH de la Bloc C (SERVER și CLIENT), deschide un **al treilea terminal SSH** dedicat capturii. Alternativ, Wireshark pe Windows. +Pe lângă cele două sesiuni SSH de la Bloc C (SERVER și CLIENT), deschide un **al treilea terminal SSH** dedicat capturii. Wireshark pe Windows poate analiza ulterior fişierul salvat în VM; traficul de pe `lo` al VM nu apare pe adaptorul Windows. -> *▸ Dacă configurația NAT face capturile dificile în Wireshark pe host, fă toată demonstrația cu `tshark` din VM. Pedagogic e identic; doar interfața e text în loc de grafic.* +> *▸ Pentru traficul localhost al VM, capturează cu `tshark -i lo` în VM, apoi transferă PCAP-ul pentru analiza în Wireshark pe Windows. Pedagogic e identic; doar interfața e text în loc de grafic.* ### Narativ de tranziție @@ -258,7 +258,7 @@ Pe lângă cele două sesiuni SSH de la Bloc C (SERVER și CLIENT), deschide un | 🟠 TERMINAL CAPTURĂ (SSH #3) | |:----| | `$ sudo tshark -i lo -f "tcp port 9200"` | -| *(sau Wireshark pe host: Capture Filter → `tcp port 9200` → Start)* | +| *(sau Wireshark în VM, interfaţa lo: Capture Filter → `tcp port 9200` → Start)* | > *▸ „Asta e un capture filter — filtrare la nivel libpcap/BPF, înainte de captură. Doar traficul care se potrivește se înregistrează."* @@ -397,7 +397,7 @@ Postel, J. (Ed.). (1981). Transmission Control Protocol. RFC 793. Internet Engin Postel, J. (1980). User Datagram Protocol. RFC 768. Internet Engineering Task Force. https://doi.org/10.17487/RFC0768 -McCanne, S. & Jacobson, V. (1993). The BSD packet filter: A new architecture for user-level packet capture. In *Proceedings of the USENIX Winter 1993 Conference* (pp. 259–270). USENIX Association. https://doi.org/10.5555/1267303.1267305 +McCanne, S. & Jacobson, V. (1993). The BSD packet filter: A new architecture for user-level packet capture. In *Proceedings of the USENIX Winter 1993 Conference* (pp. 259–270). USENIX Association. https://www.usenix.org/conference/usenix-winter-1993-conference/bsd-packet-filter-new-architecture-user-level-packet Matthews, J. N. (2005). Hands-on approach to teaching computer networking using packet traces. In *Proceedings of the 6th Conference on Information Technology Education* (pp. 361–367). ACM. https://doi.org/10.1145/1095714.1095777 diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3__noMININET-SDN_.md index 42be3c1..dddc4da 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3__noMININET-SDN_.md @@ -494,13 +494,13 @@ Postel, J. (Ed.). (1981). Transmission Control Protocol. RFC 793. Internet Engin Postel, J. (1980). User Datagram Protocol. RFC 768. Internet Engineering Task Force. https://doi.org/10.17487/RFC0768 -McCanne, S. & Jacobson, V. (1993). The BSD packet filter: A new architecture for user-level packet capture. In *Proceedings of the USENIX Winter 1993 Conference* (pp. 259–270). USENIX Association. https://doi.org/10.5555/1267303.1267305 +McCanne, S. & Jacobson, V. (1993). The BSD packet filter: A new architecture for user-level packet capture. In *Proceedings of the USENIX Winter 1993 Conference* (pp. 259–270). USENIX Association. https://www.usenix.org/conference/usenix-winter-1993-conference/bsd-packet-filter-new-architecture-user-level-packet Matthews, J. N. (2005). Hands-on approach to teaching computer networking using packet traces. In *Proceedings of the 6th Conference on Information Technology Education* (pp. 361–367). ACM. https://doi.org/10.1145/1095714.1095777 Driver, R., Asoko, H., Leach, J., Mortimer, E. & Scott, P. (1994). Constructing scientific knowledge in the classroom. *Educational Researcher, 23*(7), 5–12. https://doi.org/10.3102/0013189X023007005 -Merkel, D. (2014). Docker: Lightweight Linux containers for consistent development and deployment. *Linux Journal, 2014*(239). https://doi.org/10.5555/2600239.2600241 +Merkel, D. (2014). Docker: Lightweight Linux containers for consistent development and deployment. *Linux Journal, 2014*(239). https://www.linuxjournal.com/content/docker-lightweight-linux-containers-consistent-development-and-deployment --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-outline-vi1.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-outline-vi1.md index cf586ab..9940677 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-outline-vi1.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-outline-vi1.md @@ -82,7 +82,7 @@ netstat -tulnp Explică fiecare flag: `-t` TCP, `-u` UDP, `-l` listening, `-n` numeric (fără DNS invers), `-p` procesul proprietar. -Arată output-ul: un port în LISTEN (ex. sshd pe :22), eventual ESTABLISHED (sesiunea SSH curentă). +Arată un port în LISTEN (ex. sshd pe :22). Pentru ESTABLISHED (sesiunea SSH curentă), rulează separat `netstat -tnp` sau `ss -tnp`; `-l` selectează listeners. > *▸ Alternativă modernă: `ss -tulnp` — exact aceleași flag-uri, disponibil pe distribuțiile mai noi.* diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2.md index cccae22..778fabf 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2.md @@ -180,7 +180,7 @@ tshark -r /tmp/tcp_demo.pcapng ### C4. Epifanie: TCP livrează un stream, nu „mesaje" (vizează misconception #12) -**Ce faci:** Rulezi clientul de două ori rapid: +**Ce faci:** Reporneşte captura în terminalul 🟠 înainte de cele două rulări; opreşte-o după ce ambele conexiuni s-au închis. Rulezi clientul de două ori: ```bash python3 S02_Part04_Example_TCP_Client.py python3 S02_Part04_Example_TCP_Client.py @@ -207,12 +207,12 @@ nano S02_Part02_Template_TCP_Server.py **Arată cu cursorul** (pe proiector) zona `>>> STUDENT CODE STARTS HERE`: -> *▸ „Trei lucruri de implementat: (1) log complet — IP, port, mesaj, lungime în bytes; (2) construiți răspunsul `b"OK: " + mesaj.upper()`; (3) trimiteți cu `sendall()`."* +> *▸ „Trei lucruri de implementat: (1) log complet — IP, port, mesaj, lungime în bytes; (2) construiți răspunsul `b"OK: " + mesaj.upper()`; (3) trimiteți cu `sendall()`, incluzând LF (`b"\n"`) la final. Scaffold-ul citeşte repetat linii complete, nu fragmente arbitrare de recv()."* **Subliniază:** - `self.client_address` → `(ip, port)` — tuplu, nu string - `self.data` → bytes, trebuie decodat cu `.decode(errors='replace')` (misconception #10) -- `sendall()` vs `send()` — `sendall` garantează trimiterea integrală +- `sendall()` vs `send()` — `sendall` trimite până ce toate datele sunt acceptate de stiva locală sau apare o eroare; nu confirmă procesarea la aplicaţia peer > *▸ „Scenariul complet e descris pas cu pas în `S02_Part03_Scenario_TCP_Server_Netcat_Wireshark.md`. Citiți-l — conține secvența exactă de testare și ce fișiere încărcați."* diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2__noMININET-SDN_.md index cd3d12d..a2ef72e 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2__noMININET-SDN_.md @@ -234,12 +234,12 @@ Reîmprospătează Wireshark (F5 sau re-open). Două handshake-uri cu porturi ef Arată zona `>>> STUDENT CODE STARTS HERE`: -> *▸ „Trei lucruri de implementat: (1) log complet — IP, port, mesaj, lungime în bytes; (2) construiți răspunsul `b"OK: " + mesaj.upper()`; (3) trimiteți cu `sendall()`."* +> *▸ „Trei lucruri de implementat: (1) log complet — IP, port, mesaj, lungime în bytes; (2) construiți răspunsul `b"OK: " + mesaj.upper()`; (3) trimiteți cu `sendall()`, incluzând LF (`b"\n"`) la final. Scaffold-ul citeşte repetat linii complete, nu fragmente arbitrare de recv()."* **Subliniază:** - `self.client_address` → `(ip, port)` — tuplu - `self.data` → bytes, decodați cu `.decode(errors='replace')` (misconception #10) -- `sendall()` vs `send()` — `sendall` garantează trimiterea integrală +- `sendall()` vs `send()` — `sendall` trimite până ce toate datele sunt acceptate de stiva locală sau apare o eroare; nu confirmă procesarea la aplicaţia peer > *▸ „Scenariul complet, pas cu pas: `S02_Part03_Scenario_TCP_Server_Netcat_Wireshark.md`. Citiți-l înainte de a începe — conține secvența exactă de testare și fișierele de încărcat."* @@ -470,7 +470,7 @@ docker rm -f s02lab | Toll, W. E. (1995). Socket programming in the data communications laboratory. In *Proceedings of the 26th SIGCSE Technical Symposium on Computer Science Education* (pp. 39–43). ACM. | https://doi.org/10.1145/199688.199711 | | Postel, J. (1981). Transmission Control Protocol (RFC 793). Internet Engineering Task Force. | https://doi.org/10.17487/RFC0793 | | Postel, J. (1980). User Datagram Protocol (RFC 768). Internet Engineering Task Force. | https://doi.org/10.17487/RFC0768 | -| Merkel, D. (2014). Docker: Lightweight Linux containers for consistent development and deployment. *Linux Journal, 2014*(239). | https://doi.org/10.5555/2600239.2600241 | +| Merkel, D. (2014). Docker: Lightweight Linux containers for consistent development and deployment. *Linux Journal, 2014*(239). | https://www.linuxjournal.com/content/docker-lightweight-linux-containers-consistent-development-and-deployment | --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2.md index d1b7409..aa2507f 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2.md @@ -17,7 +17,7 @@ La finalul seminarului, studenții pot: 1. Rula și explica un server TCP (Transmission Control Protocol) multi-client cu câte un thread per conexiune și să identifice stream-urile distincte în tshark/Wireshark. 2. Completa un template de mini-chat în care serverul forward-ează mesajul unui client către toți ceilalți (fan-out la nivel de aplicație). 3. Captura traficul TCP și filtra pe `tcp.stream` pentru a demonstra că fan-out-ul generează segmente separate. -4. Rula exemplele UDP (User Datagram Protocol) broadcast și multicast și distinge în captură adresa destinație: `255.255.255.255` vs `224.0.0.1`. +4. Rula exemplele UDP (User Datagram Protocol) broadcast și multicast și distinge în captură adresa destinație: `255.255.255.255` vs `239.255.0.1`. 5. Formula conceptual diferența unicast / broadcast / multicast / anycast pe baza adresei destinație și a mecanismului de replicare. --- @@ -304,7 +304,7 @@ Oprești captura după 1–2 mesaje. **Contrast direct (diagramă progresivă — mental):** -> *▸ „Acum filtrăm: `ip.dst == 224.0.0.1 && udp.port == 5001`. Diferența față de broadcast: adresa destinație e un grup multicast (clasă D, 224.x.x.x). Primește doar cine s-a abonat cu `IP_ADD_MEMBERSHIP`. Broadcast trimite la toți indiferent; multicast trimite doar la abonați."* +> *▸ „Acum filtrăm: `ip.dst == 239.255.0.1 && udp.port == 5001`. Diferența față de broadcast: adresa destinație e un grup multicast (clasă D, 224.x.x.x). Apartenenţa grupului la nivel de host şi livrarea către socket sunt distincte. Pentru Linux, IP_MULTICAST_ALL=0 limitează acest socket la abonamentele sale; altfel poate primi şi pentru grupuri înscrise global. Broadcast trimite la toți indiferent; multicast trimite doar la abonați."* ### Mini-sinteză tabelară (spusă verbal sau scrisă rapid pe tablă) @@ -386,7 +386,7 @@ python3 6_udp-anycast/S03_Part06B_Example_UDP_Anycast_Client.py | Tot traficul TCP pe portul 3333 | `tcp.port == 3333` | | Un singur stream TCP | `tcp.stream eq 0` | | Broadcast UDP pe 5007 | `ip.dst == 255.255.255.255 && udp.port == 5007` | -| Multicast UDP pe 5001 | `ip.dst == 224.0.0.1 && udp.port == 5001` | +| Multicast UDP pe 5001 | `ip.dst == 239.255.0.1 && udp.port == 5001` | ### Porturi din seminar diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2__noMININET-SDN_.md index d6f300c..ffecbb3 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2__noMININET-SDN_.md @@ -19,7 +19,7 @@ La finalul seminarului, studenții pot: 1. Rula și explica un server TCP (Transmission Control Protocol) multi-client cu câte un thread per conexiune și identifica stream-urile distincte în Wireshark. 2. Completa un template de mini-chat în care serverul forward-ează mesajul unui client către toți ceilalți (fan-out la nivel de aplicație). 3. Captura traficul TCP cu `tcpdump` și filtra pe `tcp.stream` în Wireshark pentru a demonstra că fan-out-ul generează segmente separate. -4. Rula exemplele UDP (User Datagram Protocol) broadcast și multicast și distinge în captură adresa destinație: `255.255.255.255` vs `224.0.0.1`. +4. Rula exemplele UDP (User Datagram Protocol) broadcast și multicast și distinge în captură adresa destinație: `255.255.255.255` vs `239.255.0.1`. 5. Formula conceptual diferența unicast / broadcast / multicast / anycast pe baza adresei destinație și a mecanismului de replicare. --- @@ -364,9 +364,9 @@ Oprești captura după 1–2 mesaje. Deschizi captura în Wireshark (Windows): - `udp.port == 5001` -- `ip.dst == 224.0.0.1 && udp.port == 5001` +- `ip.dst == 239.255.0.1 && udp.port == 5001` -> *▸ „Diferența față de broadcast: adresa destinație e un grup multicast (clasă D, 224.x.x.x). Primește doar cine s-a abonat cu `IP_ADD_MEMBERSHIP`. Broadcast trimite la toți indiferent; multicast trimite doar la abonați."* +> *▸ „Diferența față de broadcast: adresa destinație e un grup multicast (clasă D, 224.x.x.x). Apartenenţa grupului la nivel de host şi livrarea către socket sunt distincte. Pentru Linux, IP_MULTICAST_ALL=0 limitează acest socket la abonamentele sale; altfel poate primi şi pentru grupuri înscrise global. Broadcast trimite la toți indiferent; multicast trimite doar la abonați."* **Task-ul de temă (menționat verbal):** @@ -473,7 +473,7 @@ Altminteri, acumulează containere uitate pornite. | Tot traficul TCP pe portul 3333 | `tcp.port == 3333` | | Un singur stream TCP | `tcp.stream eq 0` | | Broadcast UDP pe 5007 | `ip.dst == 255.255.255.255 && udp.port == 5007` | -| Multicast UDP pe 5001 | `ip.dst == 224.0.0.1 && udp.port == 5001` | +| Multicast UDP pe 5001 | `ip.dst == 239.255.0.1 && udp.port == 5001` | ### Porturi din seminar diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2.md index b655627..192f549 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2.md @@ -365,7 +365,7 @@ Deschizi captura, faci Follow TCP Stream. Payload-ul e un blob binar. **Punchline:** -> *▸ „Vedeți bytes care sunt un obiect Python serializat cu `pickle`. Fără un dissector sau un decoder, traficul e opac. Asta e tipic pentru protocoale binare: compact și strict, dar necesită tooling dedicat."* +> *▸ „Vedeți bytes care sunt un obiect Python serializat cu `pickle`. Unele şiruri rămân lizibile în bytes. Pickle nu criptează şi nu garantează compactarea: antetul are un octet, dar serializarea adaugă metadate. Comparăm lungimea totală capturată, apoi decodificăm numai date de laborator de încredere."* **Notă de igienă (15 sec):** diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2__noMININET-SDN_.md index ca031ab..5122d08 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2__noMININET-SDN_.md @@ -420,7 +420,7 @@ Payload-ul e un blob binar. **Punchline:** -> *▸ „Vedeți bytes care sunt un obiect Python serializat cu `pickle`. Fără un dissector sau un decoder, traficul e opac. Asta e tipic pentru protocoale binare: compact și strict, dar necesită tooling dedicat."* +> *▸ „Vedeți bytes care sunt un obiect Python serializat cu `pickle`. Unele şiruri rămân lizibile în bytes. Pickle nu criptează şi nu garantează compactarea: antetul are un octet, dar serializarea adaugă metadate. Comparăm lungimea totală capturată, apoi decodificăm numai date de laborator de încredere."* **Notă de igienă (15 sec):** diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2.md index 1b5e5f6..d011e18 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2.md @@ -394,7 +394,7 @@ Trei idei de fixat: | Mogul, J., & Postel, J. (1985). *Internet Standard Subnetting Procedure* (RFC 950). RFC Editor. | https://doi.org/10.17487/RFC0950 | | Fuller, V., & Li, T. (2006). *Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan* (RFC 4632). RFC Editor. | https://doi.org/10.17487/RFC4632 | | Deering, S., & Hinden, R. (2017). *Internet Protocol, Version 6 (IPv6) Specification* (RFC 8200). RFC Editor. | https://doi.org/10.17487/RFC8200 | -| Deering, S., & Hinden, R. (2006). *IP Version 6 Addressing Architecture* (RFC 4291). RFC Editor. | https://doi.org/10.17487/RFC4291 | +| Hinden, R., & Deering, S. (2006). *IP Version 6 Addressing Architecture* (RFC 4291). RFC Editor. | https://doi.org/10.17487/RFC4291 | | Kawamura, S., & Kawashima, M. (2010). *A Recommendation for IPv6 Address Text Representation* (RFC 5952). RFC Editor. | https://doi.org/10.17487/RFC5952 | | Lantz, B., Heller, B., & McKeown, N. (2010). A network in a laptop: Rapid prototyping for software-defined networks. *Proceedings of the 9th ACM SIGCOMM Workshop on Hot Topics in Networks.* | https://doi.org/10.1145/1868447.1868466 | diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2__noMININET-SDN_.md index 58d42db..6c198c7 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2__noMININET-SDN_.md @@ -311,11 +311,18 @@ ping -c 2 10.0.2.10 ### Pas 5 — Repari: forwarding ON + ping + traceroute (2 min) -🟢 **În s05-r1:** -```bash -sysctl -w net.ipv4.ip_forward=1 +🔵 **În PowerShell, în directorul fişierului Compose:** schimbă valoarea +`net.ipv4.ip_forward` din `"0"` în `"1"` în `docker-compose.yml`, apoi: + +```powershell +docker compose -f docker-compose.yml up -d --force-recreate r1 +docker exec s05-r1 sysctl net.ipv4.ip_forward ``` +`/proc/sys` poate fi read-only într-un container. `NET_ADMIN` nu schimbă această +montare; setăm sysctl la creare, fără a acorda `privileged`. Redeschide terminalul +routerului şi reia captura după recreare, apoi repetă pingul din h1. + 🟢 **În s05-h1:** ```bash ping -c 3 10.0.2.10 @@ -506,7 +513,7 @@ docker compose up -d --build | Mogul, J., & Postel, J. (1985). *Internet Standard Subnetting Procedure* (RFC 950). RFC Editor. | https://doi.org/10.17487/RFC0950 | | Fuller, V., & Li, T. (2006). *Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan* (RFC 4632). RFC Editor. | https://doi.org/10.17487/RFC4632 | | Deering, S., & Hinden, R. (2017). *Internet Protocol, Version 6 (IPv6) Specification* (RFC 8200). RFC Editor. | https://doi.org/10.17487/RFC8200 | -| Deering, S., & Hinden, R. (2006). *IP Version 6 Addressing Architecture* (RFC 4291). RFC Editor. | https://doi.org/10.17487/RFC4291 | +| Hinden, R., & Deering, S. (2006). *IP Version 6 Addressing Architecture* (RFC 4291). RFC Editor. | https://doi.org/10.17487/RFC4291 | | Kawamura, S., & Kawashima, M. (2010). *A Recommendation for IPv6 Address Text Representation* (RFC 5952). RFC Editor. | https://doi.org/10.17487/RFC5952 | --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S06-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S06-instructor-outline-v2__noMININET-SDN_.md index c90fd08..f7c2ad6 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S06-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S06-instructor-outline-v2__noMININET-SDN_.md @@ -386,6 +386,7 @@ networks: ### D1. Pornire topologie (1 min) ```powershell +docker compose -f docker-compose.s06-triangle.yml down docker compose -f docker-compose.s06-policy.yml up -d docker ps --format "table {{.Names}}\t{{.Status}}" ``` @@ -407,7 +408,7 @@ docker exec -it s06p-gw iptables -L FORWARD -v -n --line-numbers | Ce cauți | Match | Target | Analog SDN | |---|---|---|---| -| Regula conntrack | stare ESTABLISHED,RELATED | ACCEPT | — (implicit în OF) | +| Regula conntrack | stare ESTABLISHED,RELATED | ACCEPT | Nu este implicit în OpenFlow; necesită extensie conntrack/reguli explicite | | Regula h1↔h2 | src=10.0.11.0/24, dst=10.0.12.0/24 | ACCEPT | flow: permit, OUTPUT:port | | Regula h1→h3 | src=10.0.11.0/24, dst=10.0.13.0/24 | DROP | flow: drop (acțiuni goale) | | Policy implicită | FORWARD | DROP | table-miss | @@ -418,7 +419,7 @@ docker exec -it s06p-gw iptables -L FORWARD -v -n --line-numbers **Tab PowerShell separat — captură pe gw:** ```powershell -docker exec -it s06p-gw tcpdump -i any -nn -w /work/s06_policy_demo.pcap "(host 10.0.12.10 or host 10.0.13.10)" & +docker exec -it s06p-gw tcpdump -i any -nn -w /work/s06_policy_demo.pcap "(host 10.0.12.10 or host 10.0.13.10)" ``` **În alt tab — generezi trafic:** @@ -570,7 +571,7 @@ docker compose -f docker-compose.s06-policy.yml down | 3 | Client UDP rămâne blocat așteptând reply | Oprești cu Ctrl+C; revii după ce ai permis UDP în politica gw. Dacă persistă: verifici regulile cu `iptables -L -v -n`. | | 4 | Wireshark nu e instalat la toți | Deschizi pcap‑ul pe un singur ecran; discuți în plen. Analiza individuală devine temă. | | 5 | Docker Desktop nu pornește sau e instabil | Restart Docker Desktop; dacă continuă: studentul folosește Docker pe WSL2 nativ (dacă are) sau urmărește demo‑ul. | -| 6 | Eroare la ștergerea regulii iptables (număr greșit de linie) | Relistezi cu `--line-numbers`. Dacă s‑a stricat totul: `docker compose -f docker-compose.s06-policy.yml down && up -d` repornește cu regulile inițiale. | +| 6 | Eroare la ștergerea regulii iptables (număr greșit de linie) | Relistezi cu `--line-numbers`. Dacă s‑a stricat totul: `docker compose -f docker-compose.s06-policy.yml down`, apoi, numai după succes, `docker compose -f docker-compose.s06-policy.yml up -d` repornește cu regulile inițiale. | | 7 | Eroare „Address already in use" la server TCP/UDP | `docker exec -it s06p-h2 ss -tlnp` → identifici procesul → `kill ` sau repornești containerul. | --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2.md index fe33c9c..2de4ccd 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2.md @@ -130,7 +130,7 @@ Output așteptat (aproximativ): Acum generezi trafic TCP — pornești server pe h2, trimiți din h1: ```text mininet> h2 python3 ../S06/3_sdn-app-traffic/S06_Part03_Script_TCP_Server.py 5000 & -mininet> h1 bash -c "echo 'hello_s07' | nc 10.0.10.2 5000" +mininet> h1 bash -c "echo 'hello_s07' | nc -N 10.0.10.2 5000" ``` **Micro-întrebare (10 sec):** „Sniffer-ul arată `proto=TCP` dar nu arată porturile. Ce ar trebui să decodăm în plus?" (Răspuns: header-ul TCP, primii 4 bytes — porturile sursă și destinație.) @@ -184,7 +184,7 @@ mininet> h2 python3 2_packet-filter/S07_Part02A_Script_Packet_Filter.py h2-eth0 Generezi trafic: ```text -mininet> h1 bash -c "echo 'again' | nc 10.0.10.2 5000" +mininet> h1 bash -c "echo 'again' | nc -N 10.0.10.2 5000" ``` **Ce apare:** linii de forma `10.0.10.1: -> 10.0.10.2:5000 proto=TCP` @@ -255,7 +255,7 @@ Re-scanezi portul 5001 din h1 și observi `FILTERED`. Apoi cureți: mininet> h2 iptables -D INPUT -p tcp --dport 5001 -j DROP ``` -> *▸ „DROP → timeout → FILTERED. Dacă ar fi fost REJECT, vedeai RST → CLOSED."* +> *▸ „DROP poate produce timeout, raportat FILTERED de această probă; tăcerea nu dovedeşte cauza. Pentru RST folosiţi explicit REJECT --reject-with tcp-reset; REJECT implicit poate trimite ICMP."* --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2__noMININET-SDN_.md index 7ae7391..0cc7536 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2__noMININET-SDN_.md @@ -237,10 +237,10 @@ python3 /seminars/S07/1_sniffing/S07_Part01B_Script_Packet_Sniffer.py eth0 **🟢 TERMINAL ATTACKER:** ```bash -echo "hello_s07" | nc 172.30.7.20 5000 +echo "hello_s07" | nc -N 172.30.7.20 5000 ``` -**Ce apare:** linii cu `proto=ICMP` (din ping-ul anterior, dacă nu s-a ajuns la MAX_PACKETS) și `proto=TCP`. +**Ce apare:** linii cu `proto=TCP` din traficul generat după pornirea capturii. Pentru ICMP, rulează un nou ping în timp ce snifferul este activ. **Micro-întrebare (10 sec):** „Sniffer-ul arată `proto=TCP` dar nu arată porturile. Ce ar trebui să decodăm în plus?" (Răspuns: header-ul TCP, primii 4 bytes — porturile sursă și destinație.) @@ -290,7 +290,7 @@ python3 /seminars/S07/2_packet-filter/S07_Part02A_Script_Packet_Filter.py eth0 **🟢 TERMINAL ATTACKER:** ```bash -echo "again" | nc 172.30.7.20 5000 +echo "again" | nc -N 172.30.7.20 5000 ``` **Ce apare:** linii de forma `172.30.7.10: -> 172.30.7.20:5000 proto=TCP` @@ -367,7 +367,7 @@ Cureți regula: iptables -D INPUT -p tcp --dport 5001 -j DROP ``` -> *▸ „DROP → timeout → FILTERED. Dacă ar fi fost REJECT, vedeai RST → CLOSED."* +> *▸ „DROP poate produce timeout, raportat FILTERED de această probă; tăcerea nu dovedeşte cauza. Pentru RST folosiţi explicit REJECT --reject-with tcp-reset; REJECT implicit poate trimite ICMP."* --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2.md index 45b85f0..f237ec2 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2.md @@ -410,7 +410,7 @@ ss -tuln | grep -E ':8000|:8080' | 3 | Docker pull lent (nginx:alpine) | compose blochează la pull | Pre-pull: `docker pull nginx:alpine`. Alternativ: sari la Bloc F, tema include nginx | | 4 | `curl` returnează erori de conexiune | `Connection refused` | Verifică: serverul rulează? Portul e corect? Firewall? `ss -tuln` | | 5 | Serverul manual returnează 500 | Eroare Python în terminal 🔵 | Citește traceback-ul. Cele mai frecvente: fișier lipsă în `static/`, eroare de parsare request | -| 6 | nginx nu pornește | Eroare config în loguri | `docker compose logs nginx` — de obicei linia de eroare indică exact unde e problema în `.conf` | +| 6 | nginx nu pornește | Eroare config în loguri | `docker compose -f S08_Part04_Config_Docker_Compose.yml logs nginx` — de obicei linia de eroare indică exact unde e problema în `.conf` | | 7 | Serverul builtin nu răspunde la `/api/time` | Eroare 404 sau timeout | Verifică că rulezi `S08_Part02B_Example_Simple_HTTP_Builtin.py`, nu `python3 -m http.server` | **Regulă de sacrificare (dacă timpul se comprimă):** @@ -437,7 +437,7 @@ Mogul, J. C. (1995). The case for persistent-connection HTTP. *ACM SIGCOMM Compu Nielsen, H. F., Gettys, J., Baird-Smith, A., Prud'hommeaux, E., Lie, H. W., & Lilley, C. (1997). Network performance effects of HTTP/1.1, CSS1, and PNG. *ACM SIGCOMM Computer Communication Review, 27*(4), 155–166. https://doi.org/10.1145/263109.263157 -Reese, W. (2008). Nginx: The high-performance web server and reverse proxy. *Linux Journal, 2008*(173). https://doi.org/10.5555/1412202.1412204 +Reese, W. (2008). Nginx: The high-performance web server and reverse proxy. *Linux Journal, 2008*(173). https://www.linuxjournal.com/article/10108 --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2__noMININET-SDN_.md index 0a4d08b..92aa985 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2__noMININET-SDN_.md @@ -75,7 +75,7 @@ La finalul seminarului, studentul: ### Pregătire fișiere nginx Windows -Fișierele din kit (`S08_Part04_Config_Docker_Compose.yml` și `S08_Part04_Config_Nginx.conf`) folosesc `network_mode: host`, care funcționează doar pe Linux. Pentru Windows, **creezi înainte de seminar** două fișiere adaptate în `04_SEMINARS\S08\4_nginx\`: +Fișierele din kit (`S08_Part04_Config_Docker_Compose.yml` și `S08_Part04_Config_Nginx.conf`) folosesc `network_mode: host`. Pe Linux acesta foloseşte namespace-ul hostului. Docker Desktop 4.34+ oferă o opţiune de host networking care trebuie activată explicit şi are limite de nivel 4; nu o presupunem activă. https://docs.docker.com/engine/network/drivers/host/. Pentru Windows, **creezi înainte de seminar** două fișiere adaptate în `04_SEMINARS\S08\4_nginx\`: **Fișier 1: `S08_Part04_Config_Nginx.win.conf`** @@ -230,7 +230,7 @@ curl.exe -v http://localhost:8000/api/time > *▸ „Acum avem răspunsul la întrebarea de la început. La `/hello`, serverul NU a trimis Content-Length. Clientul se descurcă pentru că protocolul e HTTP/1.0 — serverul închide conexiunea, iar clientul citește până la EOF."* > -> *▸ „La `/api/time`, serverul a trimis explicit `Content-Length`. Clientul știe exact câți octeți să aștepte. Asta e mecanismul robust — și obligatoriu pentru HTTP/1.1 cu conexiuni persistente."* +> *▸ „La `/api/time`, serverul a trimis explicit `Content-Length`. Clientul știe exact câți octeți să aștepte. Acesta este mecanismul ales în laborator. HTTP/1.1 permite şi chunked transfer coding; mesajele pe conexiuni persistente au nevoie de delimitare neambiguă."* ### C.4. Temă @@ -295,7 +295,7 @@ cd 04_SEMINARS\S08\4_nginx docker compose -f S08_Part04_Config_Docker_Compose.win.yml up ``` -> *▸ „Pe Windows nu avem `network_mode: host`. Compose-ul pune backend-ul și nginx în aceeași rețea Docker. nginx accesează backend-ul prin numele serviciului: `http://backend:8000`."* +> *▸ „În această rută Windows nu presupunem activarea opţiunii host networking din Docker Desktop. Compose-ul pune backend-ul și nginx în aceeași rețea Docker. nginx accesează backend-ul prin numele serviciului: `http://backend:8000`."* ### E.3. Test comparativ: direct vs proxy @@ -445,7 +445,7 @@ Mogul, J. C. (1995). The case for persistent-connection HTTP. *ACM SIGCOMM Compu Nielsen, H. F., Gettys, J., Baird-Smith, A., Prud'hommeaux, E., Lie, H. W., & Lilley, C. (1997). Network performance effects of HTTP/1.1, CSS1, and PNG. *ACM SIGCOMM Computer Communication Review, 27*(4), 155–166. https://doi.org/10.1145/263109.263157 -Reese, W. (2008). Nginx: The high-performance web server and reverse proxy. *Linux Journal, 2008*(173). https://doi.org/10.5555/1412202.1412204 +Reese, W. (2008). Nginx: The high-performance web server and reverse proxy. *Linux Journal, 2008*(173). https://www.linuxjournal.com/article/10108 --- diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2.md index cdf6a8a..d9db401 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2.md @@ -180,7 +180,7 @@ PY > *▸ „Rezultatul e identic — aceleași fișiere. Dar mecanica e inversată: acum clientul a trimis comanda `PORT`, anunțând serverul pe ce port ascultă. Serverul s-a conectat **înapoi** la client pentru a trimite datele."* -> *▸ „Și asta răspunde la întrebarea de la început: colegul de acasă, prin NAT, era în active mode. Routerul lui bloca conexiunea inițiată de server. În passive mode, clientul inițiază toate conexiunile — trece de NAT fără probleme."* +> *▸ „Și asta răspunde la întrebarea de la început: colegul de acasă, prin NAT, era în active mode. Routerul lui bloca conexiunea inițiată de server. În passive mode, clientul inițiază toate conexiunile — poate traversa NAT-ul clientului; adresa şi porturile pasive ale serverului trebuie să fie accesibile."* **(← Hook reluat explicit)** @@ -326,7 +326,7 @@ docker compose -f S09_Part03_Config_Docker_Compose.yml down > > *Unu: FTP clasic = **două conexiuni TCP** — una pentru comenzi, una pentru date. Le-am numărat pe captură.* > -> *Doi: **active vs passive** = diferență de inițiator al conexiunii de date. Passive trece de NAT; active nu — și asta era problema colegului de acasă de la începutul orei.* +> *Doi: **active vs passive** = diferență de inițiator al conexiunii de date. Passive iniţiază datele de la client, iar active cere acces de la server spre client; rezultatul depinde de rutare, NAT şi filtrare — și asta era problema colegului de acasă de la începutul orei.* > > *(← Hook reluat)* > @@ -431,6 +431,6 @@ Bellovin, S. M. (1989). Security problems in the TCP/IP protocol suite. *ACM SIG **Tipar POE secundar (Bloc C.3):** „Cine face `listen()` în active mode?" — invers-intuitiv. Concepția greșită #11 (confuzie secvență server/client) se manifestă aici: studenții tind să creadă că serverul face `listen()` întotdeauna, dar în active mode clientul face `listen()` pe portul de date. -**Legătura cu concepția greșită #12 (recv() parțial):** Pseudo-FTP folosește un framing pe 1 byte + recv(1024) și presupune că totul ajunge într-un singur apel. Comentariul din cod (`[WARN] content_length vs data length mismatch`) evidențiază exact limita discutată la S04. Nu insista prea mult — 30 de secunde, fără deraiere. +**Legătura cu concepția greșită #12 (recv() parțial):** Pseudo-FTP folosește un octet pentru lungimea conținutului și `read_exact()` pentru a acumula exact octeții declarați, indiferent de fragmentarea TCP. Răspunsurile de control sunt și ele încadrate prin lungime; clientul consumă obligatoriu confirmarea finală `done!` sau eroarea înaintea comenzii următoare. Nu insista prea mult — 30 de secunde, fără deraiere. **Progresia temelor:** Stage 1–2 sunt auto-studiu + completare template (amintire/înțelegere/aplicare). Stage 3 cere analiză (active vs passive → cine face listen/connect). Stage 4 cere sinteză (scenariu multi-client, întrebări reflexive despre rolul serverului și extensibilitate FXP). diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2__noMININET-SDN_.md index 2b22600..d5faab5 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2__noMININET-SDN_.md @@ -272,7 +272,7 @@ Pauză 5 secunde. Majoritatea vor răspunde „serverul". Corect e **clientul**. > *▸ „Acum invers: serverul a ascultat pe un port temporar, clientul s-a conectat. Rezultatul e același — fișierul ajunge. Mecanica e diferită."* -> *▸ „Și asta răspunde complet la întrebarea de la început: colegul de acasă, prin NAT, era în active mode. Routerul lui bloca conexiunea inițiată de server. În passive mode, clientul inițiază totul — trece de NAT fără probleme."* +> *▸ „Și asta răspunde complet la întrebarea de la început: colegul de acasă, prin NAT, era în active mode. Routerul lui bloca conexiunea inițiată de server. În passive mode, clientul inițiază totul — poate traversa NAT-ul clientului; adresa şi porturile pasive ale serverului trebuie să fie accesibile."* **(← Hook reluat explicit)** @@ -292,7 +292,7 @@ La final: `exit` (containerul se oprește automat). > > *Unu: FTP clasic = **două conexiuni TCP** — una pentru comenzi, una pentru date. Le-am văzut pe captură.* > -> *Doi: **active vs passive** = diferență de inițiator al conexiunii de date. Passive trece de NAT; active nu — și asta era problema colegului de acasă de la începutul orei.* +> *Doi: **active vs passive** = diferență de inițiator al conexiunii de date. Passive iniţiază datele de la client, iar active cere acces de la server spre client; rezultatul depinde de rutare, NAT şi filtrare — și asta era problema colegului de acasă de la începutul orei.* > > *(← Hook reluat)* > @@ -303,11 +303,11 @@ La final: `exit` (containerul se oprește automat). | Stage | Fișier livrabil | Ce fac studenții | Script de referință | |---|---|---|---| | 1 | `intro_file_protocols_log.txt` | Răspunsuri scurte la 4 întrebări conceptuale | `S09_Part01A_Explanation_File_Protocols_Intro.md` | -| 2 | `pyftpd_log.txt` | LIST/RETR/STOR + observații (modifică TODO-urile din `S09_Part01D_Script_Pyftpd_Client.py`); pot rula serverul local sau în container (portul 2121 e mapat pe host) | `S09_Part01E_Tasks_Pyftpd.md` | +| 2 | `pyftpd_log.txt` | LIST/RETR/STOR + observații (modifică TODO-urile din `S09_Part01D_Script_Pyftpd_Client.py`); pot rula serverul local sau în container (portul 2121 şi intervalul pasiv 30000–30009 sunt mapate pe loopback-ul hostului) | `S09_Part01E_Tasks_Pyftpd.md` | | 3 | `pseudoftp_log.txt` + modificare `help` în server | Toate comenzile din `S09_Part02D_Tasks_Pseudo_FTP.md` + întrebări reflexive | `S09_Part02D_Tasks_Pseudo_FTP.md` | | 4 | `ftp_multi_client_log.txt` | Upload (client1) + download (client2) + întrebări reflexive | `S09_Part03B_Tasks_Multi_Client_Containers.md` | -> *▸ „Stage 1 și Stage 2 le faceți acasă. Citiți explicațiile din `S09_Part01A` și `S09_Part01B`, apoi modificați template-ul client (`S09_Part01D_Script_Pyftpd_Client.py`) — are trei TODO-uri: `LIST`, `RETR`, `STOR`. Serverul FTP rulează deja în container (portul 2121 e mapat pe host), deci puteți testa fără să instalați pyftpdlib local."* +> *▸ „Stage 1 și Stage 2 le faceți acasă. Citiți explicațiile din `S09_Part01A` și `S09_Part01B`, apoi modificați template-ul client (`S09_Part01D_Script_Pyftpd_Client.py`) — are trei TODO-uri: `LIST`, `RETR`, `STOR`. Serverul FTP rulează deja în container (portul 2121 şi intervalul pasiv 30000–30009 sunt mapate pe loopback-ul hostului), deci puteți testa fără să instalați pyftpdlib local."* > *▸ „Stage 3: porniți un container cu `python:3.12-slim` (exact ca în demo) și rulați pseudo-FTP-ul. Stage 4: scenariul multi-client l-ați văzut deja — refaceți-l și documentați."* @@ -371,7 +371,7 @@ La final: `exit` (containerul se oprește automat). | # | Problemă | Soluție | |---|---|---| -| 1 | Docker Desktop nu e pornit / Docker trage imagini lent | Pre-pull înainte de oră (`docker compose pull`). Dacă persistă, sari direct la Bloc D (pseudo-FTP într-un singur container, fără Compose). | +| 1 | Docker Desktop nu e pornit / Docker trage imagini lent | Pre-pull înainte de oră (`docker compose -f S09_Part03_Config_Docker_Compose.yml pull`). Dacă persistă, sari direct la Bloc D (pseudo-FTP într-un singur container, fără Compose). | | 2 | `apk add tcpdump` eșuează (container fără internet) | Renunți la captură live. Explici conceptual diferența control/data folosind diagrama de pe tablă. Studenții vor face captura acasă. | | 3 | Wireshark nu deschide `s09_ftp.pcap` | Verifică dacă fișierul e nenul: `dir s09_ftp.pcap`. Dacă e gol, repetă captura. Alternativ, folosește `tcpdump -r` direct în container. | | 4 | Portul 2121 ocupat pe host | Modifică mapping-ul în `S09_Part03_Config_Docker_Compose.yml`: schimbă `"2121:2121"` cu `"21210:2121"`. | @@ -399,7 +399,7 @@ Saltzer, J. H., Reed, D. P. și Clark, D. D. (1984). End-to-end arguments in sys **Ordonarea blocurilor — diferență față de varianta VM:** pe Windows nativ, pseudo-FTP fără Compose e mai simplu de pornit decât pe VM (nu necesită `pip install`), dar multi-client Docker e mai spectaculos ca punct de intrare. Ordinea B (Docker multi-client) → C (captură) → D (pseudo-FTP) asigură un demo vizual imediat și amână pseudo-FTP-ul (mai abstract) pentru după ce studenții au văzut traficul real. -**Stage 1 și Stage 2 ca teme:** spre deosebire de varianta VM (unde pyftpdlib rulează nativ), pe Windows fără VM nu avem Python cu pip într-un mediu controlat. Soluția: serverul FTP rulează deja în container (portul 2121 mapat pe host). Studenții pot rula `S09_Part01D_Script_Pyftpd_Client.py` de pe Windows dacă au Python instalat, sau dintr-un container temporar. Explicațiile din `S09_Part01A` și `S09_Part01B` se citesc ca auto-studiu. +**Stage 1 și Stage 2 ca teme:** spre deosebire de varianta VM (unde pyftpdlib rulează nativ), pe Windows fără VM nu avem Python cu pip într-un mediu controlat. Soluția: serverul FTP rulează deja în container (portul 2121 şi intervalul pasiv 30000–30009 mapate pe loopback-ul hostului). Studenții pot rula `S09_Part01D_Script_Pyftpd_Client.py` de pe Windows dacă au Python instalat, sau dintr-un container temporar. Explicațiile din `S09_Part01A` și `S09_Part01B` se citesc ca auto-studiu. **Tipar POE principal (Bloc C.5):** credențialele în clar pe captură. Studenții care au anticipat „sunt criptate" descoperă vizual pe ecran `USER test` / `PASS 12345`. diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S10-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S10-instructor-outline-v2.md index 78d3ded..818d241 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S10-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S10-instructor-outline-v2.md @@ -277,7 +277,7 @@ docker compose -f S10_Part04_Config_Docker_Compose.yml exec ssh-bastion \ **🔵 Terminal A (sesiunea rămâne activă):** ```bash -ssh -o StrictHostKeyChecking=no -p 2222 -L 9000:web:8000 labuser@localhost +ssh -N -p 2222 -L 127.0.0.1:9000:web:8000 labuser@localhost # parolă: labpass ``` @@ -297,7 +297,7 @@ Output așteptat: HTML cu „If you can see this page through an SSH tunnel, the sudo tshark -i lo -f "tcp port 9000" -a duration:8 -w /tmp/s10_http_9000.pcapng ``` -**🟢 Terminal A (generează trafic în timpul capturii):** +**🟢 Terminal C local în VM (generează trafic în timpul capturii; A rămâne ocupat de ssh -N):** ```bash curl http://localhost:9000/ > /dev/null ``` diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2.md index 8f4c413..42d0d05 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2.md @@ -129,7 +129,7 @@ Urmărești în loguri: containerele `nginx-proxy`, `web1`, `web2`, `web3`. **Predicție privind concepția greșită #5 (porturi auto-expuse):** > *▸ „Putem accesa direct web1 pe portul 8000 din browser? De ce nu?"* -Răspuns: nu — `expose` nu mapează pe host; doar Nginx, cu `ports: 8080:80`, e accesibil din exterior. +Răspuns: `localhost:8000` nu este publicat, iar numele `web1` este DNS intern Docker. Totuşi, hostul Linux al daemonului poate accesa IP-ul containerului dacă rutarea şi filtrarea permit. Docker Desktop şi hostul fizic pot avea alt traseu. `expose` este metadată, nu regulă firewall. ### C.2 Test round robin (4–5 min) @@ -343,7 +343,7 @@ mkdir -p captures docker run --rm --net=container:lb-custom \ -v "$(pwd)/captures:/captures" \ nicolaka/netshoot \ - tcpdump -i eth0 -w /captures/lb_upstream.pcap port 8000 + tcpdump -i eth0 -w /captures/lb_upstream.pcap "tcp port 8000 or tcp port 8080" ``` 🟢 **Terminal 2 (în paralel):** @@ -379,7 +379,7 @@ Sau, dacă ai Wireshark GUI: `wireshark captures/lb_upstream.pcap &` → filtru > *▸ „Trei lucruri de reținut:"* > 1. *„Reverse proxy = ascunde backend-urile; clientul vede o singură adresă."* -> 2. *„Diferența practică: Nginx e declarativ și are health checks; scriptul Python e procedural și orb — trimite și la backend-uri moarte."* +> 2. *„Diferența practică: Nginx e declarativ; în configuraţia livrată verificările sunt pasive; scriptul Python e procedural și orb — trimite și la backend-uri moarte."* > 3. *„LB-ul nu pasează conexiunea — o rupe în două. Asta ați văzut în pcap."* ### Reluare hook diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2__noMININET-SDN_.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2__noMININET-SDN_.md index 3b96d1e..5786290 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2__noMININET-SDN_.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2__noMININET-SDN_.md @@ -333,7 +333,7 @@ New-Item -ItemType Directory -Force captures | Out-Null docker run --rm --net=container:lb-custom ` -v "${PWD}\captures:/captures" ` nicolaka/netshoot ` - tcpdump -i eth0 -w /captures/lb_upstream.pcap port 8000 + tcpdump -i eth0 -w /captures/lb_upstream.pcap "tcp port 8000 or tcp port 8080" ``` 🟢 **Terminal 2 (în paralel):** @@ -362,7 +362,7 @@ Wireshark → *File → Open* → `captures\lb_upstream.pcap`. > *▸ „Trei lucruri de reținut:"* > 1. *„Reverse proxy = ascunde backend-urile; clientul vede o singură adresă."* -> 2. *„Nginx e declarativ și are health checks; scriptul Python e procedural și orb."* +> 2. *„Nginx e declarativ; în configuraţia livrată verificările sunt pasive; scriptul Python e procedural și orb."* > 3. *„LB-ul nu pasează conexiunea — o rupe în două. Ați văzut asta în pcap."* ### Reluare hook diff --git a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S12-instructor-outline-v2.md b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S12-instructor-outline-v2.md index 17b3488..1242e5a 100644 --- a/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S12-instructor-outline-v2.md +++ b/00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S12-instructor-outline-v2.md @@ -40,7 +40,7 @@ La finalul seminarului, studentul poate: ### Verificare mediu ```bash -cd ~/compnet-2025-redo-main # sau calea efectivă din VM +cd ~/COMPNET-EN # sau calea efectivă din VM source ~/venvs/compnet/bin/activate 2>/dev/null || true python3 -c "import requests, grpc; import grpc_tools; print('OK')" ``` @@ -54,74 +54,24 @@ python3 -m pip install requests grpcio grpcio-tools ### Pre-creare server JSON-RPC -Serverul JSON-RPC minimal nu există în kit — trebuie creat o singură dată. Recomandare: creează-l *înainte* de seminar, nu în fața studenților (evită 2 minute de lipire în `nano`). +Serverul local canonic este inclus în kit. Verifică-l înainte de seminar; nu crea o variantă separată. ```bash -cd 04_SEMINARS/S12/1_jsonrpc -cat > jsonrpc_server_minimal.py << 'PYEOF' -from http.server import BaseHTTPRequestHandler, HTTPServer -import json -import ast, operator - -BIN_OPS = { - ast.Add: operator.add, ast.Sub: operator.sub, - ast.Mult: operator.mul, ast.Div: operator.truediv, - ast.Pow: operator.pow, ast.Mod: operator.mod, - ast.FloorDiv: operator.floordiv, -} -UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg} - -def safe_eval(expr: str): - node = ast.parse(expr, mode="eval").body - def _eval(n): - if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): - return n.value - if isinstance(n, ast.BinOp) and type(n.op) in BIN_OPS: - return BIN_OPS[type(n.op)](_eval(n.left), _eval(n.right)) - if isinstance(n, ast.UnaryOp) and type(n.op) in UNARY_OPS: - return UNARY_OPS[type(n.op)](_eval(n.operand)) - raise ValueError("Unsupported expression.") - return _eval(node) - -class Handler(BaseHTTPRequestHandler): - def do_POST(self): - length = int(self.headers.get("Content-Length", "0")) - body = self.rfile.read(length).decode("utf-8", errors="replace") - try: - req = json.loads(body) - method, params = req.get("method"), req.get("params", []) - req_id = req.get("id") - if method != "evaluate": - raise ValueError(f"Unknown method: {method}") - expr = params[0] if params else "" - result = safe_eval(expr) - resp = {"jsonrpc": "2.0", "id": req_id, "result": result} - print(f"[JSONRPC-SERVER] evaluate({expr}) -> {result}") - except Exception as e: - resp = {"jsonrpc": "2.0", "id": None, - "error": {"code": -32602, "message": str(e)}} - print("[JSONRPC-SERVER] error:", e) - data = json.dumps(resp).encode("utf-8") - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(data))) - self.end_headers() - self.wfile.write(data) - -def main(): - host, port = "0.0.0.0", 8080 - print(f"[JSONRPC-SERVER] listening on http://{host}:{port}") - HTTPServer((host, port), Handler).serve_forever() - -if __name__ == "__main__": - main() -PYEOF +cd ~/COMPNET-EN/04_SEMINARS/S12/1_jsonrpc +python3 S12_Part01_Script_JSONRPC_Server.py ``` +Serverul canonic se află în `04_SEMINARS/S12/1_jsonrpc/`. Rulează-l din acest director +într-un terminal separat; nu este necesară crearea unui server temporar. Pentru ruta +Mininet, porneşte-l în h1 cu `--host 0.0.0.0 --port 8080`, iar clientul din h2 foloseşte +`JSONRPC_URL=http://10.0.0.1:8080/`. Verifică id-ul, codurile -32700/-32600/-32601/-32602 +şi lipsa corpului JSON pentru notificări (convenţia HTTP 204 a acestui exemplu). + + ### Repetiție codegen (opțional) ```bash -cd ../3_grpc +cd ~/COMPNET-EN/04_SEMINARS/S12/3_grpc python3 -m grpc_tools.protoc -I../2_protobuf \ --python_out=. --grpc_python_out=. \ ../2_protobuf/S12_Part02_Config_Calculator.proto @@ -132,7 +82,7 @@ python3 -c "import S12_Part02_Config_Calculator_pb2 as pb2; print('OK pb2')" Dacă nu vrei să editezi în fața studenților: -1. În `1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py`, schimbă `URL = "https://api.mathjs.org/v4/"` în `URL = "http://10.0.0.1:8080/"`. +1. În `1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py`, foloseşte variabila de mediu `JSONRPC_URL=http://10.0.0.1:8080/` la lansare. 2. În `3_grpc/S12_Part03_Script_g_RPC_Client.py`, schimbă `GRPC_TARGET = "localhost:50051"` în `GRPC_TARGET = "10.0.0.1:50051"`. --- @@ -186,8 +136,9 @@ result = server.Add(AddRequest(a=2, b=3)) **Fă (din directorul `04_SEMINARS/S12`):** ```bash -cd ~/compnet-2025-redo-main/04_SEMINARS/S12 -sudo mn --topo single,2 --mac --switch ovsk --controller none +cd ~/COMPNET-EN/04_SEMINARS/S12 +sudo mn --topo single,2 --mac --switch ovsbr --controller none +# În CLI Mininet: pingall; continuă numai după conectivitate h1 ↔ h2. ``` **Fă (verificare IP, 15 sec):** @@ -202,13 +153,13 @@ mininet> h2 ip -4 addr show h2-eth0 ### C.2 Pornești serverul JSON-RPC pe h1 🔵 ``` -mininet> h1 python3 1_jsonrpc/jsonrpc_server_minimal.py & +mininet> h1 python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Server.py --host 0.0.0.0 --port 8080 > /tmp/s12-jsonrpc.log 2>&1 & echo $! > /tmp/s12-jsonrpc.pid ``` Ar trebui să apară: ```text -[JSONRPC-SERVER] listening on http://0.0.0.0:8080 +JSON-RPC endpoint: http://0.0.0.0:8080/ ``` > *▸ „Serverul ascultă pe portul 8080. Evaluarea expresiei e deliberat restricționată — scopul e să vedem protocolul, nu să facem un calculator de producție."* @@ -222,10 +173,10 @@ Ar trebui să apară: **Fă:** ``` -mininet> h2 python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py +mininet> h2 env JSONRPC_URL=http://10.0.0.1:8080/ python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py ``` -**Observație:** clientul afișează payload-ul JSON (lizibil) și rezultatul `evaluate(2+3) = 5`. Serverul raportează `[JSONRPC-SERVER] evaluate(2+3) -> 5`. +**Observație:** clientul afișează payload-ul JSON (lizibil) și rezultatul `evaluate(2+3) = 5`. Serverul raportează `o linie de acces HTTP pentru POST, cu status 200; rezultatul se verifică în corpul răspunsului`. **Explicație:** @@ -238,12 +189,18 @@ mininet> h2 python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py ### C.4 Captură pcap JSON-RPC 🟠 ``` -mininet> h1 tcpdump -i h1-eth0 -w /tmp/jsonrpc.pcap tcp port 8080 -c 50 & -mininet> h2 python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py +mininet> h1 tcpdump -i h1-eth0 -w /tmp/jsonrpc.pcap tcp port 8080 > /tmp/s12-capture.log 2>&1 & echo $! > /tmp/s12-capture.pid +mininet> h2 env JSONRPC_URL=http://10.0.0.1:8080/ python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py ``` Apoi, în VM (alt terminal): +În Mininet, înainte de analiză, oprește exact procesul de captură pornit mai sus și așteaptă închiderea fișierului: + +```text +mininet> h1 kill -INT $(cat /tmp/s12-capture.pid); wait $(cat /tmp/s12-capture.pid) +``` + ```bash tshark -r /tmp/jsonrpc.pcap -q -z follow,tcp,ascii,0 | head -n 80 ``` @@ -263,7 +220,7 @@ tshark -r /tmp/jsonrpc.pcap -q -z follow,tcp,ascii,0 | head -n 80 **Fă (în alt terminal al VM, nu în Mininet):** ```bash -cd ~/compnet-2025-redo-main/04_SEMINARS/S12/2_protobuf +cd ~/COMPNET-EN/04_SEMINARS/S12/2_protobuf nano S12_Part02_Config_Calculator.proto ``` @@ -322,13 +279,13 @@ Dacă nu apar ambele fișiere, nu mergi mai departe. Oprește serverul JSON-RPC (dacă rulează încă): ``` -mininet> h1 kill %1 +mininet> h1 kill -TERM $(cat /tmp/s12-jsonrpc.pid) ``` Pornește serverul gRPC: ``` -mininet> h1 python3 3_grpc/S12_Part03_Script_g_RPC_Server.py & +mininet> h1 python3 3_grpc/S12_Part03_Script_g_RPC_Server.py > /tmp/s12-grpc.log 2>&1 & echo $! > /tmp/s12-grpc.pid ``` Ar trebui să apară: @@ -362,7 +319,7 @@ Dictează valori predictibile: > *▸ „Acum oprim serverul și rulăm clientul din nou."* ``` -mininet> h1 kill %1 +mininet> h1 kill -TERM $(cat /tmp/s12-grpc.pid) mininet> h2 python3 3_grpc/S12_Part03_Script_g_RPC_Client.py ``` @@ -387,7 +344,7 @@ mininet> h2 python3 3_grpc/S12_Part03_Script_g_RPC_Client.py Repornește serverul: ``` -mininet> h1 python3 3_grpc/S12_Part03_Script_g_RPC_Server.py & +mininet> h1 python3 3_grpc/S12_Part03_Script_g_RPC_Server.py > /tmp/s12-grpc.log 2>&1 & echo $! > /tmp/s12-grpc.pid ``` Captură: @@ -439,18 +396,19 @@ tshark -r /tmp/grpc.pcap -q -z follow,tcp,ascii,0 | head -n 80 | Ce | Comandă | |---|---| -| Pornire Mininet | `sudo mn --topo single,2 --mac --switch ovsk --controller none` | +| Pornire Mininet | `sudo mn --topo single,2 --mac --switch ovsbr --controller none +# În CLI Mininet: pingall; continuă numai după conectivitate h1 ↔ h2.` | | IP h1 | `10.0.0.1` (default Mininet `single,2`) | | IP h2 | `10.0.0.2` | -| Server JSON-RPC | `h1 python3 1_jsonrpc/jsonrpc_server_minimal.py &` | -| Client JSON-RPC | `h2 python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py` | +| Server JSON-RPC | `h1 python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Server.py --host 0.0.0.0 --port 8080 > /tmp/s12-jsonrpc.log 2>&1 & echo $! > /tmp/s12-jsonrpc.pid` | +| Client JSON-RPC | `h2 env JSONRPC_URL=http://10.0.0.1:8080/ python3 1_jsonrpc/S12_Part01_Script_JSONRPC_Client.py` | | Codegen protobuf | `python3 -m grpc_tools.protoc -I../2_protobuf --python_out=. --grpc_python_out=. ../2_protobuf/S12_Part02_Config_Calculator.proto` | -| Server gRPC | `h1 python3 3_grpc/S12_Part03_Script_g_RPC_Server.py &` | +| Server gRPC | `h1 python3 3_grpc/S12_Part03_Script_g_RPC_Server.py > /tmp/s12-grpc.log 2>&1 & echo $! > /tmp/s12-grpc.pid` | | Client gRPC | `h2 python3 3_grpc/S12_Part03_Script_g_RPC_Client.py` | -| Captură JSON-RPC | `h1 tcpdump -i h1-eth0 -w /tmp/jsonrpc.pcap tcp port 8080 -c 50 &` | +| Captură JSON-RPC | `h1 tcpdump -i h1-eth0 -w /tmp/jsonrpc.pcap tcp port 8080 > /tmp/s12-capture.log 2>&1 & echo $! > /tmp/s12-capture.pid` | | Captură gRPC | `h1 tcpdump -i h1-eth0 -w /tmp/grpc.pcap tcp port 50051 -c 80 &` | | Inspecție pcap | `tshark -r /tmp/.pcap -q -z follow,tcp,ascii,0 \| head -n 80` | -| Oprire proces background | `h1 kill %1` sau `pkill -f ', source, re.S | re.I) + fixtures.append({'path': str(path.relative_to(ROOT)), 'dom': parser.root, 'script': '\n'.join(scripts), 'toc': path.name.startswith('SETUP-')}) + fixture = tmp_path / 'html_logic.json' + fixture.write_text(json.dumps(fixtures), encoding='utf-8') + result = subprocess.run([node, str(Path(__file__).with_name('html_logic_probe.cjs')), str(fixture)], capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads(result.stdout) + assert report['decks'] == 10 and report['toc_passed'] + assert report['quiz_items'] == 21 and report['clipboard_buttons'] == 5 diff --git a/00_TOOLS/release/README.md b/00_TOOLS/release/README.md index 2448f73..4b2e899 100644 --- a/00_TOOLS/release/README.md +++ b/00_TOOLS/release/README.md @@ -1,67 +1,48 @@ -# release — Course Kit Packaging +# Course kit release packaging -Maintainer-only helper for producing a distributable ZIP archive of the repository. The script runs the repository QA checks first, then builds a ZIP using the inclusion and exclusion rules encoded in `create_release_zip.sh`. +This maintainer helper creates a ZIP from a **committed full Git checkout**. +It uses the same `00_TOOLS/qa/run_checks.py` entry point as CI. It neither +changes executable modes nor silently skips missing test dependencies. -## File and Folder Index +## Prepare and check -| Name | Type | Description | Metric | -|---|---|---|---| -| [`README.md`](README.md) | Markdown | Orientation for release packaging (this file) | — | -| [`create_release_zip.sh`](create_release_zip.sh) | Bash | Runs QA, then builds the release ZIP (path printed on success) | 60 lines | - -## Usage - -Run from the repository root: +Run these commands from the repository root, in a Python environment used for QA: ```bash -bash 00_TOOLS/release/create_release_zip.sh +python3 -m pip install -r 00_TOOLS/qa/requirements.txt +python3 00_TOOLS/qa/run_checks.py ``` -The script prints the output ZIP path and exits non-zero if a QA check fails. - -## Design Rationale - -Release creation is kept as a single script so that local packaging follows the same gates as CI. Packaging rules are kept next to the build logic to avoid divergence between documentation and what is actually shipped. - -## Cross-References and Contextual Connections - -### Prerequisites and Dependency Links - -| Prerequisite | Path | Why | -|---|---|---| -| QA checks pass | [`../qa/`](../qa/) | The release builder aborts on failing checks | -| `zip` available | — | The script uses `zip` to produce the archive | - -### Lecture, Seminar, Project and Quiz Mapping +The shared gates check Python syntax, executable permissions, relative Markdown +file targets, lexical integrity, lecture figure sources and pytest regressions. +The historical root `CHANGELOG.md` is explicitly excluded from the language +heuristic in both routes. This does not exclude it from the release archive. +The conservative `format-offline.js` helper is optional and is not a CI gate. -| This folder | Lecture foundation | Seminar usage | Project usage | Quiz | -|---|---|---|---|---| -| Release packaging | — | — | — | — | +## Build the archive -### Downstream Dependencies - -No course content depends on this directory at runtime. It is referenced by tool documentation and by the executable permission manifest. - -### Suggested Learning Sequence - -**Suggested sequence:** run QA locally (`00_TOOLS/qa/`) → run this script → distribute the resulting ZIP through the course channel - -## Selective Clone Instructions - -**Method A — Git sparse-checkout (requires Git 2.25+)** +Commit the reviewed changes first, then run: ```bash -git clone --filter=blob:none --sparse https://github.com/antonioclim/COMPNET-EN.git -cd COMPNET-EN -git sparse-checkout set 00_TOOLS/release +bash 00_TOOLS/release/create_release_zip.sh ../COMPNET-EN-v1.5.0.zip ``` -**Method B — Direct download (no Git required)** +The output must not already exist. The helper refuses tracked working-tree or +index changes, runs the shared gates, archives `HEAD` with Git's recorded modes +and checks the ZIP CRC before creating the final file. Untracked files and ignored +results are not packaged. The default filename uses the current short commit ID. +Set `COMP_NET_PYTHON` to the required interpreter if `python3` is not suitable. -``` -https://github.com/antonioclim/COMPNET-EN/tree/main/00_TOOLS/release -``` +A sparse checkout or a downloaded source ZIP is not the supported maintainer +input. Use a full clone for QA and packaging. Students may use the GitHub release +source archive directly; GitHub's automatic source archives are produced by GitHub, +not by this helper. + +## Scope of a successful result -## Version and Provenance +Passing these gates verifies source and component properties. Docker start-up, +Mininet/OpenFlow behaviour, Windows/VirtualBox, LMS import and browser/Excel use +require their own acceptance evidence. The OVA is a separately versioned Zenodo +asset and is never included or re-exported here. -The release builder is updated when the packaging exclusions change or when the QA checks gain new gates. +See [QA tools](../qa/) and the [main repository guide](../../README.md). diff --git a/00_TOOLS/release/create_release_zip.sh b/00_TOOLS/release/create_release_zip.sh index 2523735..2dbf9ae 100755 --- a/00_TOOLS/release/create_release_zip.sh +++ b/00_TOOLS/release/create_release_zip.sh @@ -1,60 +1,42 @@ #!/usr/bin/env bash -# create_release_zip.sh — build a distributable ZIP from a repository checkout -# -------------------------------------------------------------------------- -# Usage: -# bash 00_TOOLS/release/create_release_zip.sh -# bash 00_TOOLS/release/create_release_zip.sh +# Package a committed course checkout after the same source gates used by CI. set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" - -cd "$REPO_ROOT" - -OUT_NAME="${1:-compnet-course-kit_$(date +%Y-%m-%d).zip}" - -echo "[INFO] Repository root: $REPO_ROOT" -echo "[INFO] Output archive: $OUT_NAME" - -echo "[INFO] Applying executable permission bits (Phase 4)" -bash 00_TOOLS/qa/apply_permissions.sh - -if command -v node &>/dev/null; then - echo "[INFO] Formatting check (Prettier offline)" - node format-offline.js --check -else - echo "[WARN] Node.js not found, skipping format check" +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)" +cd -- "$REPO_ROOT" +PYTHON="${COMP_NET_PYTHON:-python3}" +OUT_NAME="${1:-$REPO_ROOT/../COMPNET-EN-$(git rev-parse --short HEAD).zip}" +if [[ -e "$OUT_NAME" ]]; then + echo "Refusing to replace an existing archive: $OUT_NAME" >&2 + exit 1 fi - -echo "[INFO] Markdown link check" -python 00_TOOLS/qa/check_markdown_links.py - -echo "[INFO] Language and lexical integrity check" -python 00_TOOLS/qa/check_integrity.py - -echo "[INFO] Lecture figure target check" -python 00_TOOLS/qa/check_fig_targets.py --puml-only - -if python -c "import pytest" &>/dev/null; then - echo "[INFO] Pytest" - python -m pytest -q -else - echo "[WARN] pytest not installed, skipping test run" +if ! git diff --quiet || ! git diff --cached --quiet; then + echo "Commit the intended source changes before packaging; the archive contains HEAD." >&2 + exit 1 fi - -echo "[INFO] Creating ZIP archive" - -rm -f "$OUT_NAME" - -zip -r "$OUT_NAME" . \ - -x "./.git/*" \ - -x "./node_modules/*" \ - -x "*/__pycache__/*" \ - -x "*.pyc" \ - -x "*/.pytest_cache/*" \ - -x "*/.mypy_cache/*" \ - -x "*/.ruff_cache/*" \ - -x "./.DS_Store" \ - -x "./00_TOOLS/plantuml.jar" - -echo "[OK] Archive created: $OUT_NAME" +"$PYTHON" 00_TOOLS/qa/run_checks.py +if ! git diff --quiet || ! git diff --cached --quiet; then + echo "A check changed tracked files. Review them before packaging." >&2 + exit 1 +fi +# git archive includes only committed paths and their recorded modes. +# It never adds personal captures, credentials, test results or an earlier ZIP. +TEMP_ARCHIVE="$(mktemp "${OUT_NAME}.tmp.XXXXXX")" +trap 'rm -f -- "$TEMP_ARCHIVE"' EXIT +git archive --format=zip --prefix=COMPNET-EN/ --output="$TEMP_ARCHIVE" HEAD +"$PYTHON" - "$TEMP_ARCHIVE" "$OUT_NAME" <<'PY' +import os +from pathlib import Path +import sys +import zipfile +source, target = map(Path, sys.argv[1:]) +with zipfile.ZipFile(source) as archive: + bad = archive.testzip() + if bad: + raise SystemExit('ZIP CRC failure: ' + bad) +# Exclusive output creation prevents replacement even if a file appeared meanwhile. +with target.open('xb') as output, source.open('rb') as data: + import shutil + shutil.copyfileobj(data, output) +print('Archive created:', target.resolve()) +PY diff --git a/00_TOOLS/subnetting/subnet_quiz_generator.py b/00_TOOLS/subnetting/subnet_quiz_generator.py old mode 100644 new mode 100755 index 6b22dfc..dad7368 --- a/00_TOOLS/subnetting/subnet_quiz_generator.py +++ b/00_TOOLS/subnetting/subnet_quiz_generator.py @@ -62,8 +62,9 @@ def _random_ipv4_network(rng: random.Random) -> ipaddress.IPv4Network: # Pick a random *subnet* of the chosen pool with the chosen prefix. # We do this by selecting a random subnet index. - subnets = list(pool.subnets(new_prefix=prefix)) - return rng.choice(subnets) + count = 1 << (prefix - pool.prefixlen) + address = int(pool.network_address) + rng.randrange(count) * (1 << (32 - prefix)) + return ipaddress.IPv4Network((address, prefix)) def _ipv4_netmask(prefix: int) -> str: @@ -152,6 +153,10 @@ def allocate_vlsm(base: ipaddress.IPv4Network, reqs: List[VlsmRequirement]) -> L """ if not base.is_private: raise ValueError("Base network must be private for this generator.") + if not reqs or len({r.name for r in reqs}) != len(reqs): + raise ValueError("Supply non-empty requirements with unique segment names.") + if any(not isinstance(r.hosts, int) or isinstance(r.hosts, bool) or r.hosts < 1 for r in reqs): + raise ValueError("Each segment must require a positive integer host count.") # Sort by decreasing hosts. reqs_sorted = sorted(reqs, key=lambda r: r.hosts, reverse=True) @@ -190,11 +195,10 @@ def allocate_vlsm(base: ipaddress.IPv4Network, reqs: List[VlsmRequirement]) -> L def generate_vlsm_scenario(rng: random.Random) -> Tuple[ipaddress.IPv4Network, List[VlsmRequirement], List[VlsmAllocation]]: """ - Generate a small VLSM scenario: base /24 or /23 and 3–4 subnets. + Generate 3–4 subnets and a private base large enough for every allocation. """ base_pool = rng.choice(PRIVATE_POOLS) base_prefix = rng.choice([23, 24, 25]) - base = rng.choice(list(base_pool.subnets(new_prefix=base_prefix))) # 3–4 requirements; keep within plausible lab sizes. names = ["LAN_A", "LAN_B", "LAN_C", "DMZ"] @@ -205,6 +209,12 @@ def generate_vlsm_scenario(rng: random.Random) -> Tuple[ipaddress.IPv4Network, L hosts = rng.choice([6, 10, 14, 20, 30, 50, 60, 100]) reqs.append(VlsmRequirement(name=names[i], hosts=hosts)) + needed = sum(1 << (32 - _smallest_prefix_for_hosts(r.hosts)) for r in reqs) + required_prefix = 32 - (needed - 1).bit_length() + base_prefix = min(base_prefix, required_prefix) + count = 1 << (base_prefix - base_pool.prefixlen) + address = int(base_pool.network_address) + rng.randrange(count) * (1 << (32 - base_prefix)) + base = ipaddress.IPv4Network((address, base_prefix)) allocs = allocate_vlsm(base, reqs) return base, reqs, allocs diff --git a/00_TOOLS/subnetting/tests/test_subnet_quiz_generator.py b/00_TOOLS/subnetting/tests/test_subnet_quiz_generator.py new file mode 100644 index 0000000..84a3910 --- /dev/null +++ b/00_TOOLS/subnetting/tests/test_subnet_quiz_generator.py @@ -0,0 +1,47 @@ +"""Feasibility and constant-space subnet selection regressions.""" +import importlib.util +import ipaddress +from pathlib import Path +import random +import sys + +import pytest + +SOURCE = Path(__file__).resolve().parents[1] / "subnet_quiz_generator.py" +SPEC = importlib.util.spec_from_file_location("course_subnet_quiz", SOURCE) +quiz = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = quiz +SPEC.loader.exec_module(quiz) + + +def test_seed20_and_deterministic_seed_sweep_are_feasible(): + for seed in range(1000): + first = quiz.generate_vlsm_scenario(random.Random(seed)) + assert first == quiz.generate_vlsm_scenario(random.Random(seed)) + base, requirements, allocations = first + assert [a.name for a in allocations] == [r.name for r in requirements] + for i, allocation in enumerate(allocations): + assert allocation.network.subnet_of(base) + assert allocation.usable_hosts >= allocation.hosts_required + assert all(not allocation.network.overlaps(other.network) for other in allocations[i + 1:]) + + +def test_largest_pool_selection_uses_an_index_not_subnet_enumeration(monkeypatch): + class FinalSubnet: + def choice(self, options): + return ipaddress.IPv4Network("10.0.0.0/8") + def randint(self, low, high): + return 30 + def randrange(self, count): + assert count == 4194304 + return count - 1 + def forbidden(*args, **kwargs): + raise AssertionError("Subnet enumeration must not occur") + monkeypatch.setattr(ipaddress.IPv4Network, "subnets", forbidden) + assert quiz._random_ipv4_network(FinalSubnet()) == ipaddress.IPv4Network("10.255.255.252/30") + + +@pytest.mark.parametrize("requirements", [[], [quiz.VlsmRequirement("A", 200), quiz.VlsmRequirement("B", 200)], [quiz.VlsmRequirement("A", 0)], [quiz.VlsmRequirement("A", 3), quiz.VlsmRequirement("A", 4)]]) +def test_impossible_or_ambiguous_requirements_still_fail(requirements): + with pytest.raises(ValueError): + quiz.allocate_vlsm(ipaddress.IPv4Network("192.168.1.0/24"), requirements) diff --git a/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html b/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html index 3259107..26d1394 100644 --- a/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html +++ b/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html @@ -801,6 +801,7 @@ .hero h1 { font-size: 1.7rem; } .substep { font-size: 1rem; } } +[hidden] { display:none !important; } @@ -810,7 +811,7 @@ -
    -
    + +
    @@ -464,7 +464,7 @@

    Client Lab Simulator RTT Analysis & Wireshark< async runExampleClient() { this.badge.innerText = "Step 2: Basic Connection"; - this.text.innerText = "Running 'python3 S02_Part04_Example_TCP_Client.py'. Watch Wireshark capture the 3-Way Handshake, one Data packet, and the Connection Teardown."; + this.text.innerText = "Running 'python3 S02_Part04_Example_TCP_Client.py'. Watch Wireshark capture the 3-Way Handshake, one LF-delimited request and reply, followed by an illustrative connection teardown. Actual packet boundaries and timing may differ."; await this.termClient.typeCommand("python3 S02_Part04_Example_TCP_Client.py"); @@ -482,19 +482,20 @@

    Client Lab Simulator RTT Analysis & Wireshark< // Data await wait(300); - this.wireshark.addPacket("54321", "12345", "54321 → 12345 [PSH, ACK] Seq=1 Ack=1 Len=12", 12, t0 + 0.3); // "Hello, world" + this.wireshark.addPacket("54321", "12345", "54321 → 12345 [PSH, ACK] Seq=1 Ack=1 Len=13", 13, t0 + 0.3); // "Hello, world" + LF - this.termServer.output("[CLIENT] Sent 12 bytes: b'Hello, world'"); + this.termServer.output("[CLIENT] Sent 13 bytes: b'Hello, world\\n'"); await wait(100); - this.wireshark.addPacket("12345", "54321", "12345 → 54321 [PSH, ACK] Seq=1 Ack=13 Len=16", 16, t0 + 0.4); // "OK: HELLO, WORLD" + this.wireshark.addPacket("12345", "54321", "12345 → 54321 [PSH, ACK] Seq=1 Ack=14 Len=17", 17, t0 + 0.4); // "OK: HELLO, WORLD" + LF - this.termClient.output("[INFO] Received b'OK: HELLO, WORLD' from server"); + this.termClient.output("[INFO] Received b'OK: HELLO, WORLD\\n' from server"); this.termClient.output("[INFO] Connection closed."); // Teardown - this.wireshark.addPacket("54321", "12345", "54321 → 12345 [FIN, ACK] Seq=13 Ack=17", 0); - this.wireshark.addPacket("12345", "54321", "12345 → 54321 [FIN, ACK] Seq=17 Ack=14", 0); + this.wireshark.addPacket("54321", "12345", "54321 → 12345 [FIN, ACK] Seq=14 Ack=18", 0); + this.wireshark.addPacket("12345", "54321", "12345 → 54321 [FIN, ACK] Seq=18 Ack=15", 0); + this.wireshark.addPacket("54321", "12345", "54321 → 12345 [ACK] Seq=15 Ack=19", 0); this.termClient.newPrompt(); @@ -533,21 +534,25 @@

    Client Lab Simulator RTT Analysis & Wireshark< const tSend = (Date.now() - this.wireshark.startTime) / 1000; + // TCP carries UTF-8 bytes, including the LF frame delimiter. + const requestLen = new TextEncoder().encode(msg + "\n").length; + const response = "OK: " + msg.toUpperCase() + "\n"; + // Request Packet - this.wireshark.addPacket("54322", "12345", `54322 → 12345 [PSH, ACK] Len=${msg.length}`, msg.length, tSend); + this.wireshark.addPacket("54322", "12345", `54322 → 12345 [PSH, ACK] Len=${requestLen}`, requestLen, tSend); - this.termServer.output(`[CLIENT] Sent ${msg.length} bytes: b'${msg}'`); + this.termServer.output(`[CLIENT] Sent ${requestLen} bytes: ${JSON.stringify(msg + '\n')}`); // Simulate delay await wait(rtt * 1000); // Visual wait // Response Packet - const respLen = msg.length + 4; // "OK: " + msg + const respLen = new TextEncoder().encode(response).length; this.wireshark.addPacket("12345", "54322", `12345 → 54322 [PSH, ACK] Len=${respLen}`, respLen, tSend + rtt); // Client Log this.termClient.output(`Sent: '${msg}'`); - this.termClient.output(`Received: b'OK: ${msg.toUpperCase()}'`); + this.termClient.output(`Received: ${JSON.stringify(response)}`); this.termClient.output(`[STATS] RTT: ${rttMs} ms`, 'log-rtt'); this.termClient.newPrompt("Message (or 'exit'): "); @@ -568,6 +573,7 @@

    Client Lab Simulator RTT Analysis & Wireshark< const tEnd = (Date.now() - this.wireshark.startTime) / 1000; this.wireshark.addPacket("54322", "12345", "54322 → 12345 [FIN, ACK]", 0, tEnd); this.wireshark.addPacket("12345", "54322", "12345 → 54322 [FIN, ACK]", 0, tEnd + 0.001); + this.wireshark.addPacket("54322", "12345", "54322 → 12345 [ACK] (acknowledges server FIN)", 0, tEnd + 0.002); this.badge.innerText = "Lab Complete"; this.badge.style.background = "#4ec9b0"; diff --git a/04_SEMINARS/_HTMLsupport/S03/5_udp-multicast/S03_Part05_Page_UDP_Multicast.html b/04_SEMINARS/_HTMLsupport/S03/5_udp-multicast/S03_Part05_Page_UDP_Multicast.html index 73f30e9..007623f 100644 --- a/04_SEMINARS/_HTMLsupport/S03/5_udp-multicast/S03_Part05_Page_UDP_Multicast.html +++ b/04_SEMINARS/_HTMLsupport/S03/5_udp-multicast/S03_Part05_Page_UDP_Multicast.html @@ -251,7 +251,7 @@
    -

    UDP Multicast 224.0.0.1

    +

    UDP Multicast 239.255.0.1

    @@ -266,7 +266,7 @@

    UDP Multicast 224.0.0.1

    🕸️
    Multicast Group
    -
    224.0.0.1
    +
    239.255.0.1
    @@ -317,7 +317,7 @@

    UDP Multicast 224.0.0.1

    # Implementing Subscription logic import socket, struct -MCAST_GRP = "224.0.0.1" +MCAST_GRP = "239.255.0.1" MCAST_PORT = 5001 sock = socket.socket(AF_INET, SOCK_DGRAM) @@ -379,7 +379,7 @@

    UDP Multicast 224.0.0.1

    node.classList.remove('left'); node.classList.add('joined'); btn.innerText = "Leave"; - logApp(`[SYSTEM] Recv ${id} joined 224.0.0.1`); + logApp(`[SYSTEM] Recv ${id} joined 239.255.0.1`); } else { node.classList.remove('joined'); node.classList.add('left'); @@ -396,7 +396,7 @@

    UDP Multicast 224.0.0.1

    document.getElementById('btnSend').disabled = true; // 1. Log Wireshark - logWireshark("192.168.1.100", "224.0.0.1", text); + logWireshark("192.168.1.100", "239.255.0.1", text); // 2. Animate: Sender -> Core await animatePacket('senderNode', null, 'pktMain', true); // true = to center diff --git a/04_SEMINARS/_HTMLsupport/S03/6_udp-anycast/S03_Part06_Page_UDP_Anycast.html b/04_SEMINARS/_HTMLsupport/S03/6_udp-anycast/S03_Part06_Page_UDP_Anycast.html index a1206b3..5fe9240 100644 --- a/04_SEMINARS/_HTMLsupport/S03/6_udp-anycast/S03_Part06_Page_UDP_Anycast.html +++ b/04_SEMINARS/_HTMLsupport/S03/6_udp-anycast/S03_Part06_Page_UDP_Anycast.html @@ -291,7 +291,7 @@

    UDP Anycast IPv6: 2001:db8::1

    2001:db8::1
    Latency: - + ms
    @@ -303,7 +303,7 @@

    UDP Anycast IPv6: 2001:db8::1

    2001:db8::1
    Latency: - + ms
    @@ -315,7 +315,7 @@

    UDP Anycast IPv6: 2001:db8::1

    2001:db8::1
    Latency: - + ms
    diff --git a/04_SEMINARS/_HTMLsupport/S04/1_text-proto_tcp/S04_Part01_Page_Text_Proto_TCP.html b/04_SEMINARS/_HTMLsupport/S04/1_text-proto_tcp/S04_Part01_Page_Text_Proto_TCP.html index 663601d..e247221 100644 --- a/04_SEMINARS/_HTMLsupport/S04/1_text-proto_tcp/S04_Part01_Page_Text_Proto_TCP.html +++ b/04_SEMINARS/_HTMLsupport/S04/1_text-proto_tcp/S04_Part01_Page_Text_Proto_TCP.html @@ -337,9 +337,10 @@

    Text Protocol Visualizer Framing: <LEN> <CMD> input.disabled = true; // 1. Client Framing Logic - // Formula: Total = len(cmd) + len(str(len(cmd))) + 1 - const contentLen = rawCmd.length; - const totalLen = contentLen + String(contentLen).length + 1; + // Formula: Total = UTF8_bytes(payload) + digits(Total) + 1 (fixed point) + const contentLen = new TextEncoder().encode(rawCmd).length; + let totalLen = contentLen + 2; + while (totalLen !== contentLen + String(totalLen).length + 1) totalLen = contentLen + String(totalLen).length + 1; const framedMsg = `${totalLen} ${rawCmd}`; log(`[CLIENT] Input: "${rawCmd}"`, "log-client"); @@ -355,8 +356,9 @@

    Text Protocol Visualizer Framing: <LEN> <CMD> // 4. Server Response Logic const responseText = executeCommand(rawCmd); - const respContentLen = responseText.length; - const respTotalLen = respContentLen + String(respContentLen).length + 1; + const respContentLen = new TextEncoder().encode(responseText).length; + let respTotalLen = respContentLen + 2; + while (respTotalLen !== respContentLen + String(respTotalLen).length + 1) respTotalLen = respContentLen + String(respTotalLen).length + 1; const framedResp = `${respTotalLen} ${responseText}`; log(`[SERVER] Sending Response: "${framedResp}"`, "log-server"); @@ -385,30 +387,16 @@

    Text Protocol Visualizer Framing: <LEN> <CMD> const header = fullMsg.substring(0, firstSpace); const body = fullMsg.substring(firstSpace + 1); - // Animate Header Bytes - for(let char of (header + " ")) { - addByte(char, 'header'); - await wait(50); + // One box is one actual UTF-8 byte, displayed in hexadecimal. + for (const byte of new TextEncoder().encode(header + ' ')) { + addByte(byte.toString(16).padStart(2, '0'), 'header'); await wait(50); } - - log(`[SERVER] Read Header: Length=${header}`, "log-server"); - - // Animate Body Bytes - const parts = body.split(' '); - const cmd = parts[0]; - - // Cmd - for(let char of (cmd + " ")) { - addByte(char, 'cmd'); - await wait(30); + log(`[SERVER] Read Header: Total bytes=${header}`, 'log-server'); + const commandBytes = new TextEncoder().encode(body.split(' ')[0]).length; + let index = 0; + for (const byte of new TextEncoder().encode(body)) { + addByte(byte.toString(16).padStart(2, '0'), index++ < commandBytes ? 'cmd' : 'arg'); await wait(20); } - - // Rest - for(let char of body.substring(cmd.length + 1)) { - addByte(char, 'arg'); - await wait(20); - } - log(`[SERVER] Parsed Payload: "${body}"`, "log-server"); } @@ -499,7 +487,9 @@

    Text Protocol Visualizer Framing: <LEN> <CMD> if (!exists) { const tr = document.createElement('tr'); tr.className = 'row-new'; - tr.innerHTML = `

    `; + const keyCell = document.createElement("td"), valueCell = document.createElement("td"); + keyCell.textContent = key; valueCell.textContent = serverState[key]; + tr.append(keyCell, valueCell); tbody.appendChild(tr); } } diff --git a/04_SEMINARS/_HTMLsupport/S05/1_ipv4-subnetting/S05_Part01A_Explanation_I_Pv4_Subnetting.html b/04_SEMINARS/_HTMLsupport/S05/1_ipv4-subnetting/S05_Part01A_Explanation_I_Pv4_Subnetting.html index 883ec44..95e74c5 100644 --- a/04_SEMINARS/_HTMLsupport/S05/1_ipv4-subnetting/S05_Part01A_Explanation_I_Pv4_Subnetting.html +++ b/04_SEMINARS/_HTMLsupport/S05/1_ipv4-subnetting/S05_Part01A_Explanation_I_Pv4_Subnetting.html @@ -307,6 +307,7 @@

    1. Address Analysis

    - - - - - - Packet Sniffer: Interactive Debugger - - - - - - -
    -
    -
    - - - -
    -
    -

    Packet Sniffer Debugger

    -

    STEP-BY-STEP PYTHON EXECUTION

    -
    -
    - - -
    -
    NETWORK
    -
    BUFFER
    -
    - -
    -
    - -
    - - -
    -
    - - -
    - - -
    -
    - - - packet_sniffer.py - -
    - -
    -
    - -
    - -
    - 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18 -
    - - -
    -
    # Function to parse IPv4 Header
    -
    def parse_ipv4_header(data):
    - -
    - # 1. Extract Version & IHL from first byte -
    -
    - version_ihl = data[0] -
    -
    - version = version_ihl >> 4 -
    -
    - ihl = (version_ihl & 0x0F) * 4 -
    - -
    - # 2. Unpack Header Fields -
    -
    - # Format: ! 8x B B 2x 4s 4s -
    -
    - ttl, proto, src, dst = struct.unpack( -
    -
    - '! 8x B B 2x 4s 4s', data[:20] -
    -
    - ) -
    - -
    - # 3. Format IP Addresses -
    -
    - src_ip = ipv4_addr(src) -
    -
    - dst_ip = ipv4_addr(dst) -
    - -
    - return src_ip, dst_ip, proto -
    -
    -
    -
    - - -
    - - -
    -

    - - System Status -

    -

    Waiting for traffic... Click "Generate Ping" to start.

    -
    - - -
    -
    -

    Raw Memory (Packet Buffer)

    -
    - Ethernet Header (14 bytes) - IP Header (20 bytes) -
    -
    - -
    - -
    -

    Buffer Empty

    -
    - -
    - -
    -
    -
    -
    - - -
    -
    - Variables Watch -
    - -
    - -
    - Local variables will appear here as you step through the code. -
    -
    -
    -
    - - - diff --git a/04_SEMINARS/_HTMLsupport/S07/2_packet-filter/S07_Part02_Page_Packet_Filter_V2.html b/04_SEMINARS/_HTMLsupport/S07/2_packet-filter/S07_Part02_Page_Packet_Filter_V2.html index 110f099..95b6918 100644 --- a/04_SEMINARS/_HTMLsupport/S07/2_packet-filter/S07_Part02_Page_Packet_Filter_V2.html +++ b/04_SEMINARS/_HTMLsupport/S07/2_packet-filter/S07_Part02_Page_Packet_Filter_V2.html @@ -288,44 +288,34 @@

    S07_Part02A_Script_Packet }, createPacketData: function(type) { - // Mock Byte array generation - let bytes = []; - // Ethernet (0-13) - for(let i=0; i<12; i++) bytes.push(Math.floor(Math.random()*255).toString(16).padStart(2,'0')); - bytes.push('08', '00'); // Proto IPv4 - - // IP (14-33) - bytes.push('45'); // Ver 4, IHL 5 - for(let i=0; i<8; i++) bytes.push(Math.floor(Math.random()*255).toString(16).padStart(2,'0')); - - let proto = (type === 'DNS') ? 17 : 6; - bytes.push(proto.toString(16).padStart(2,'0')); // Proto - bytes.push('00', '00'); // Checksum placeholder - - // Src IP / Dst IP mock logic - let srcIP = "192.168.1.5"; - let validNetwork = Math.random() > 0.3; // 70% chance to be 10.x - if (validNetwork) srcIP = "10.0.5." + Math.floor(Math.random()*255); - - let dstIP = "8.8.8.8"; - - // Push IP bytes (simplified visuals) - bytes.push('c0','a8','01','05'); // Fake src - bytes.push('08','08','08','08'); // Fake dst - - // Transport - let srcPort = Math.floor(Math.random() * 50000) + 1024; - let dstPort = (type === 'DNS') ? 53 : (type === 'HTTP' ? 80 : 22); - - return { - raw: bytes, - type: type, - srcIP: srcIP, - dstIP: dstIP, - proto: proto, - srcPort: srcPort, - dstPort: dstPort + const srcIP = Math.random() > 0.3 ? `10.0.5.${1 + Math.floor(Math.random() * 254)}` : '192.168.1.5'; + const dstIP = '8.8.8.8'; + const srcPort = 1024 + Math.floor(Math.random() * 50000); + const dstPort = type === 'DNS' ? 53 : (type === 'HTTP' ? 80 : 22); + const proto = type === 'DNS' ? 17 : 6; + const ipBytes = ip => ip.split('.').map(Number); + const word = n => [(n >>> 8) & 255, n & 255]; + const checksum = data => { + let sum = 0; + for(let i=0;i>> 16) sum = (sum & 65535) + (sum >>> 16); + return (~sum) & 65535; }; + const transport = proto === 17 + ? [...word(srcPort), ...word(dstPort), 0, 8, 0, 0] + : [...word(srcPort), ...word(dstPort), 0,0,0,1, 0,0,0,1, 0x50,0x10, 0x10,0, 0,0, 0,0]; + if (proto === 6) { + const check = checksum([...ipBytes(srcIP), ...ipBytes(dstIP), 0, proto, ...word(transport.length), ...transport]); + transport[16] = check >>> 8; transport[17] = check & 255; + } + const ip = [0x45,0,...word(20 + transport.length), 0,1,0,0, 64,proto,0,0, ...ipBytes(srcIP),...ipBytes(dstIP)]; + const check = checksum(ip); ip[10] = check >>> 8; ip[11] = check & 255; + const dmac = [0,12,41,0,0,1], smac = [0,80,86,0,0,2]; + const bytes = [...dmac,...smac,8,0,...ip,...transport]; + while(bytes.length < 60) bytes.push(0); // Ethernet padding, FCS excluded. + const hex = n => n.toString(16).padStart(2,'0'); + return {raw:bytes.map(hex), type, srcIP, dstIP, proto, srcPort, dstPort, + dmac:dmac.map(hex).join(':'), smac:smac.map(hex).join(':')}; }, renderBytes: function(packet) { @@ -357,8 +347,8 @@

    S07_Part02A_Script_Packet // Populate Data await this.wait(300); - document.getElementById('val-dmac').innerText = "00:0c:29:.."; - document.getElementById('val-smac').innerText = "00:50:56:.."; + document.getElementById('val-dmac').innerText = packet.dmac; + document.getElementById('val-smac').innerText = packet.smac; document.getElementById('val-ethproto').innerText = "0x0800"; await this.wait(this.delay); diff --git a/04_SEMINARS/_HTMLsupport/S08/2_simple-http/S08_Part02_Page_Simple_HTTP.html b/04_SEMINARS/_HTMLsupport/S08/2_simple-http/S08_Part02_Page_Simple_HTTP.html index a44e687..e14ccb9 100644 --- a/04_SEMINARS/_HTMLsupport/S08/2_simple-http/S08_Part02_Page_Simple_HTTP.html +++ b/04_SEMINARS/_HTMLsupport/S08/2_simple-http/S08_Part02_Page_Simple_HTTP.html @@ -89,7 +89,7 @@
    Py
    -

    Python http.server Lab

    +

    Python http.server Lab

    This page simulates requests. Its code checklist detects text patterns only; run the Python server and test /student with curl to verify behaviour.

    @@ -347,7 +347,7 @@

    Semin { id: 5, desc: 'Test /student using curl', done: false } ]); - // Smart Detection of Code Changes + // Lexical checklist only: this browser does not execute Python. const codeContainsStudentEndpoint = computed(() => { // Check for key elements of the solution in the code string const hasPath = codeContent.value.includes('if self.path == "/student"') || codeContent.value.includes('elif self.path == "/student"'); diff --git a/04_SEMINARS/_HTMLsupport/S08/3_socket-http/S08_Part03_Page_Socket_HTTP.html b/04_SEMINARS/_HTMLsupport/S08/3_socket-http/S08_Part03_Page_Socket_HTTP.html index a8f5c41..7b4217c 100644 --- a/04_SEMINARS/_HTMLsupport/S08/3_socket-http/S08_Part03_Page_Socket_HTTP.html +++ b/04_SEMINARS/_HTMLsupport/S08/3_socket-http/S08_Part03_Page_Socket_HTTP.html @@ -189,10 +189,10 @@

      if os.path.exists(filepath):
        status = '200 OK'
    -     content = open(filepath).read()
    +     content = open(filepath, "rb").read()
      else:
        status = '404 Not Found'
    -     content = '<h1>404 Not Found</h1>' +     content = b'<h1>404 Not Found</h1>'
    diff --git a/04_SEMINARS/_HTMLsupport/S10/4_ssh-port-forwarding/S10_Part04_Page_SSH_Port_Forwarding.html b/04_SEMINARS/_HTMLsupport/S10/4_ssh-port-forwarding/S10_Part04_Page_SSH_Port_Forwarding.html index 11cfeb7..c4b35ec 100644 --- a/04_SEMINARS/_HTMLsupport/S10/4_ssh-port-forwarding/S10_Part04_Page_SSH_Port_Forwarding.html +++ b/04_SEMINARS/_HTMLsupport/S10/4_ssh-port-forwarding/S10_Part04_Page_SSH_Port_Forwarding.html @@ -427,7 +427,7 @@

    this.addLog("Creating container web ... done", false, "text-green-400"); this.addLog("Creating container ssh-bastion ... done", false, "text-green-400"); - this.description = "Infrastructure is ready. The 'web' container is hidden. We need SSH to access it."; + this.description = "No host port is published for web:8000. This exercise reaches it through SSH; direct container-IP access depends on the daemon host and platform."; }, async establishTunnel() { diff --git a/04_SEMINARS/_HTMLsupport/S12/1_jsonrpc/S12_Part01_Page_JSONRPC.html b/04_SEMINARS/_HTMLsupport/S12/1_jsonrpc/S12_Part01_Page_JSONRPC.html index 63e73ab..98a31d1 100644 --- a/04_SEMINARS/_HTMLsupport/S12/1_jsonrpc/S12_Part01_Page_JSONRPC.html +++ b/04_SEMINARS/_HTMLsupport/S12/1_jsonrpc/S12_Part01_Page_JSONRPC.html @@ -338,7 +338,7 @@

    - Server (api.mathjs.org) + Server (local teaching server)
    diff --git a/04_SEMINARS/_HTMLsupport/S12/2_protobuf/S12_Part02_Page_Protobuf.html b/04_SEMINARS/_HTMLsupport/S12/2_protobuf/S12_Part02_Page_Protobuf.html index 8aea8c7..6e217f0 100644 --- a/04_SEMINARS/_HTMLsupport/S12/2_protobuf/S12_Part02_Page_Protobuf.html +++ b/04_SEMINARS/_HTMLsupport/S12/2_protobuf/S12_Part02_Page_Protobuf.html @@ -424,7 +424,7 @@

    -
    # Environment initialised. Protobuf compiler (protoc) ready.
    +
    # Interactive preview ready. Run protoc in your terminal for real validation.
    # Edit 'S12_Part02_Config_Calculator.proto' and click 'Generate Code' to compile.
    @@ -699,10 +699,10 @@

    setTimeout(r, 600)); - appendLog("[OK] Syntax check passed.", "text-green-500"); - appendLog("Generating Python data structures...", "text-gray-400"); + appendLog("[HINT] Expected text patterns found; syntax has not been compiled.", "text-green-500"); + appendLog("Previewing the expected generated Python filenames...", "text-gray-400"); await new Promise(r => setTimeout(r, 400)); - appendLog("Generating gRPC client/server stubs...", "text-gray-400"); + appendLog("No compiler is running in this page.", "text-gray-400"); // Show Files Animation const fileArea = document.getElementById('generated-files-area'); @@ -715,20 +715,20 @@

    setTimeout(r, 500)); - appendLog("Syntax Error: Compilation failed.", "text-red-500 font-bold"); + appendLog("CHECKLIST: Expected patterns are missing; this is not a compiler result.", "text-red-500 font-bold"); if (!checks.hasPowerReq) appendLog(" > Missing 'PowerRequest' message definition.", "text-red-400 ml-2"); else if (!checks.hasPowerRes) appendLog(" > Missing 'PowerResponse' message definition.", "text-red-400 ml-2"); else if (!checks.hasRpc) appendLog(" > Service 'Calculator' missing 'Power' method.", "text-red-400 ml-2"); - appendLog("Please fix the errors marked in the checklist.", "text-gray-400 mt-2"); + appendLog("Complete the requested extension, then run protoc for syntax and schema validation.", "text-gray-400 mt-2"); } // Restore prompt diff --git a/04_SEMINARS/_HTMLsupport/S12/3_grpc/S12_Part03_Page_g_RPC.html b/04_SEMINARS/_HTMLsupport/S12/3_grpc/S12_Part03_Page_g_RPC.html index d8a628b..dff9156 100644 --- a/04_SEMINARS/_HTMLsupport/S12/3_grpc/S12_Part03_Page_g_RPC.html +++ b/04_SEMINARS/_HTMLsupport/S12/3_grpc/S12_Part03_Page_g_RPC.html @@ -298,7 +298,7 @@

    {{ infoPanel.title }}

    - HTTP/2 DATA FRAME + PROTOBUF BODY (framing omitted) {{ packet.binaryPreview }}

    @@ -309,7 +309,7 @@

    {{ infoPanel.title }}

    :method: POST
    :scheme: http
    -
    :path: /Calculator/{{ packet.method }}
    +
    :path: /seminar12.Calculator/{{ packet.method }}
    content-type: application/grpc
    @@ -520,6 +520,11 @@

    } // 2. Client Log + const values = [...Object.values(requestData), result]; + if (values.some(value => !Number.isInteger(value) || value < -2147483648 || value > 2147483647)) { + this.logClient('int32 values and result must be integers in -2147483648..2147483647', 'text-red-400'); + this.isAnimating = false; return; + } this.logClient(`Calling stub.${method}(${JSON.stringify(requestData)})`, "text-slate-300"); // 3. Info Panel Update: Serialization @@ -535,7 +540,7 @@

    this.packet.type = 'req'; this.packet.method = method; this.packet.progress = 15; - this.packet.binaryPreview = this.mockHex(method, requestData); // Fake binary look + this.packet.binaryPreview = this.mockHex(method, requestData); // Actual Protobuf int32 body bytes // Animate Movement let interval = setInterval(() => { @@ -546,7 +551,7 @@

    this.infoPanel = { category: 'Transport', title: 'HTTP/2 POST', - content: `The binary payload is wrapped in an HTTP/2 frame and sent to /Calculator/${method}. Notice the header compression efficiency.` + content: `The Protobuf body receives a 5-byte gRPC message prefix and is carried by HTTP/2 DATA frames to /seminar12.Calculator/${method}. Notice the header compression efficiency.` }; this.currentStepText = 'Transmitting (HTTP/2)'; } @@ -612,7 +617,7 @@

    this.packet.active = true; this.packet.type = 'res'; this.packet.progress = 85; - this.packet.binaryPreview = "08 " + result.toString(16).padStart(2, '0').toUpperCase(); // Mock hex result + this.packet.binaryPreview = this.encodeInt32Fields([result]); // Animate Back let interval = setInterval(() => { @@ -634,11 +639,21 @@

    } }, 20); }, + encodeInt32Fields(values) { + const bytes = []; + values.forEach((value, index) => { + if (value === 0) return; // proto3 omits scalar defaults. + bytes.push((index + 1) << 3); + let number = value < 0 ? BigInt.asUintN(64, BigInt(value)) : BigInt(value); + do { + let part = Number(number & 127n); number >>= 7n; + bytes.push(part | (number ? 128 : 0)); + } while (number); + }); + return bytes.length ? bytes.map(b => b.toString(16).padStart(2, '0').toUpperCase()).join(' ') : '(empty proto3 body)'; + }, mockHex(method, data) { - // Just creates a techy-looking hex string for visuals - const v1 = Object.values(data)[0] % 255; - const v2 = Object.values(data)[1] % 255; - return `0A ${v1.toString(16).toUpperCase()} 12 ${v2.toString(16).toUpperCase()}`; + return this.encodeInt32Fields(Object.values(data)); }, logClient(text, color) { this.clientLogs.push({ text, color, time: this.getCurrentTime() }); diff --git a/04_SEMINARS/_tutorial-solve/s2/S02_Part02_Solution_TCP_Server_Template.py b/04_SEMINARS/_tutorial-solve/s2/S02_Part02_Solution_TCP_Server_Template.py index ab34d63..5e51507 100755 --- a/04_SEMINARS/_tutorial-solve/s2/S02_Part02_Solution_TCP_Server_Template.py +++ b/04_SEMINARS/_tutorial-solve/s2/S02_Part02_Solution_TCP_Server_Template.py @@ -1,7 +1,7 @@ import socketserver -class MyTCPHandler(socketserver.BaseRequestHandler): +class MyTCPHandler(socketserver.StreamRequestHandler): """ Request handler for our TCP server. @@ -20,38 +20,46 @@ def handle(self): - self.client_address is a tuple (ip, port) - len(self.data) gives the message length (in bytes) """ - # Read data from the client (at most 1024 bytes). - self.data = self.request.recv(1024).strip() + # TCP is a stream: read one bounded LF-terminated message at a time. + while True: + line = self.rfile.readline(1025) + if not line: + break + if len(line) > 1024 or not line.endswith(b"\n"): + self.request.sendall(b"ERR invalid line\n") + break + self.data = line[:-1].removesuffix(b"\r") - # >>> STUDENT CODE STARTS HERE + # >>> STUDENT CODE STARTS HERE - # 1. Display the client's IP and port in the format: - # [CLIENT] : connected - # Use self.client_address. + # 1. Display the client's IP and port in the format: + # [CLIENT] : connected + # Use self.client_address. - # 2. Display the message content and its length: - # [CLIENT] Sent bytes: + # 2. Display the message content and its length: + # [CLIENT] Sent bytes: - # 3. Build a response that starts with b"OK: " - # followed by the original message converted to upper case. + # 3. Build a response that starts with b"OK: " + # followed by the original message converted to upper case. - # Example: for "hello", the response should be: - # b"OK: HELLO" + # Example: for "hello", the response should be: + # b"OK: HELLO" - # 4. Send the response back to the client with sendall(). + # 4. Send the response back to the client with sendall(), including the terminating LF. - print('[CLIENT] ', self.client_address[0], ':', self.client_address[1], ' connected') - print('[CLIENT] Sent ', len(self.data), ' bytes: ', self.data.decode()) + print('[CLIENT] ', self.client_address[0], ':', self.client_address[1], ' connected') + print('[CLIENT] Sent ', len(self.data), ' bytes: ', self.data.decode()) - response = b"OK: " + self.data.upper() - self.request.sendall(response) + response = b"OK: " + self.data.upper() + self.request.sendall(response + b"\n") - # <<< STUDENT CODE ENDS HERE + # <<< STUDENT CODE ENDS HERE class MyTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): # Ensure we can restart the server immediately on the same port. allow_reuse_address = True + daemon_threads = True if __name__ == "__main__": diff --git a/04_SEMINARS/tests/README.md b/04_SEMINARS/tests/README.md new file mode 100644 index 0000000..73691a1 --- /dev/null +++ b/04_SEMINARS/tests/README.md @@ -0,0 +1,25 @@ +# Seminar regression checks + +Run these from the repository root: + +```bash +python3 -m venv .venv-seminar-tests +. .venv-seminar-tests/bin/activate +python -m pip install pytest +python -m pytest -q 04_SEMINARS/tests/test_protocol_regressions.py +node 04_SEMINARS/tests/test_html_models.cjs +``` + +The Python suite exercises the actual supplied handlers over local IPv4 sockets, +plus framing, serialisation, JSON-RPC and port/configuration boundary cases. It does +not send traffic to third-party systems. Tests use ephemeral local ports. + +The Node checks execute the actual helper functions and routing/SDN state models +extracted from the HTML sources. Animation and DOM elements are replaced by explicit +stubs. They verify arithmetic, filtering, packet fields, gateways, return paths and +flow reuse; they are not native browser or accessibility acceptance. + +These checks do not start Docker, Mininet, Open vSwitch or VirtualBox. The corresponding +laboratory walkthroughs, captures, platform-specific commands and rendered browser +interactions still require the documented native environments. Student TODOs remain +exercises, not promised completed implementations. diff --git a/04_SEMINARS/tests/test_html_models.cjs b/04_SEMINARS/tests/test_html_models.cjs new file mode 100644 index 0000000..83bdf4f --- /dev/null +++ b/04_SEMINARS/tests/test_html_models.cjs @@ -0,0 +1,59 @@ +const fs=require('fs'),path=require('path'),vm=require('vm'),assert=require('assert'); +const root=path.resolve(__dirname, '../_HTMLsupport'); +const read=p=>fs.readFileSync(path.join(root,p),'utf8'); +const results=[]; +function test(name,fn){try{fn();results.push({name,status:'PASS'})}catch(e){results.push({name,status:'FAIL',error:String(e)})}} +// Execute actual extracted helpers under Node; this is not a browser execution. +let s=read('S05/1_ipv4-subnetting/S05_Part01A_Explanation_I_Pv4_Subnetting.html'); +let c={};vm.createContext(c);vm.runInContext(s.slice(s.indexOf(' function ipToInt'),s.indexOf(' // --- Analysis Logic')),c); +test('IPv4 /0 and /32 masks',()=>{assert.equal(c.getMask(0),0);assert.equal(c.getMask(32),4294967295);assert.equal(c.getMask(24),4294967040)}); +test('IPv4 unsigned /8 arithmetic',()=>{assert.equal(c.intToIp((c.ipToInt('10.7.8.9')&c.getMask(8))>>>0),'10.0.0.0')}); +vm.runInContext(s.slice(s.indexOf(' function validateIP'),s.indexOf(' // --- VLSM Logic')),c); +test('IPv4 rejects malformed octets',()=>{for(const ip of ['1.2.3.999','1.2.3.4x','1..3.4','1.2.3.4.5'])assert.equal(c.validateIP(ip),false);assert.equal(c.validateIP('192.168.1.1'),true)}); +s=read('S05/1_ipv4-subnetting/S05_Part01B_Exercises_I_Pv4_Subnetting.html');c={};vm.createContext(c);let x=s.slice(s.indexOf(' const ipToInt'),s.indexOf(' const calculateSubnet')); +let start=s.indexOf(' const calculateSubnet');let end=s.indexOf('\n };',start)+12;x+=s.slice(start,end);vm.runInContext(x+'\nthis.calculateSubnet=calculateSubnet;',c); +test('IPv4 calculator /0, /31, /32',()=>{assert.equal(c.calculateSubnet('1.2.3.4',0).network,'0.0.0.0');assert.equal(c.calculateSubnet('1.2.3.4',0).broadcast,'255.255.255.255');assert.equal(c.calculateSubnet('10.0.0.0',31).numHosts,2);assert.equal(c.calculateSubnet('10.0.0.1',32).numHosts,1)}); +test('IPv4 calculator rejects bad input',()=>assert.throws(()=>c.calculateSubnet('1.2.3.999',24))); +s=read('S12/3_grpc/S12_Part03_Page_g_RPC.html');let m=s.match(/encodeInt32Fields\(values\) \{([\s\S]*?)\n \},/);let encode=new Function('values',m[1]); +test('Protobuf int32 ordinary and multibyte varints',()=>{assert.equal(encode([2,3]),'08 02 10 03');assert.equal(encode([256,128]),'08 80 02 10 80 01');assert.equal(encode([128]),'08 80 01')}); +test('Protobuf negative int32 and omitted defaults',()=>{assert.equal(encode([-1]),'08 FF FF FF FF FF FF FF FF FF 01');assert.equal(encode([0,1]),'10 01');assert.equal(encode([0]),'(empty proto3 body)')}); +s=read('S07/2_packet-filter/S07_Part02_Page_Packet_Filter_V2.html');m=s.match(/createPacketData: function\(type\) \{([\s\S]*?)\n \},/);const packet=new Function('type',m[1]); +test('Synthetic packet hex matches displayed IPv4 and ports',()=>{for(const typ of ['DNS','HTTP','SSH']){for(let k=0;k<5;k++){const p=packet(typ),a=p.raw.map(h=>parseInt(h,16));assert.equal(a.slice(26,30).join('.'),p.srcIP);assert.equal(a.slice(30,34).join('.'),p.dstIP);assert.equal((a[34]<<8)+a[35],p.srcPort);assert.equal((a[36]<<8)+a[37],p.dstPort);assert.equal(a[23],p.proto);assert.equal(a.length,60)}}}); +s=read('S01/S01_CLI_NetcatTCP-UDP_Wireshark_sim.html');c={wsCF:'',wsDF:'',wsAll:[],wsVis:[],wsRP(){},$:()=>({setCustomValidity(){},reportValidity(){}})};vm.createContext(c);vm.runInContext(s.slice(s.indexOf('function wsPC('),s.indexOf('function wsAP('))+s.slice(s.indexOf('function wsDF2('),s.indexOf('function wsRP(')),c); +c.wsAll=[{protocol:'TCP',port:9300,sourcePort:56230,destPort:9300,streamId:0},{protocol:'TCP',port:80,streamId:1},{protocol:'UDP',port:9301,streamId:0}]; +test('Display filter conjunctive port and stream matching',()=>{c.wsDF2('tcp.port == 80');assert.equal(c.wsVis.length,1);assert.equal(c.wsVis[0].port,80);c.wsDF2('tcp.stream eq 1');assert.equal(c.wsVis.length,1);assert.equal(c.wsVis[0].streamId,1);c.wsDF2('tcp.port == 1');assert.equal(c.wsVis.length,0)}); +test('Unsupported filter and capture port',()=>{c.wsDF2('tcp contains anything');assert.equal(c.wsVis.length,0);c.wsCF='tcp port 9300';assert.equal(c.wsPC(c.wsAll[0]),true);assert.equal(c.wsPC(c.wsAll[1]),false);assert.equal(c.wsPC(c.wsAll[2]),false)}); +// Actual page functions executed with minimal model stubs; this is not browser acceptance. +function model(page, marker) { + const html=read(page), source=html.slice(html.indexOf(marker),html.lastIndexOf('')); + const env={window:{},setTimeout:fn=>fn(),console};vm.createContext(env);vm.runInContext(source+'\nthis.modelApp=app;',env);return env.modelApp; +} +function noUI(app){for(const name of ['printToTerminal','updateUI','updateTaskUI','renderRoutingTables','animateDrop'])app[name]=()=>{};return app;} +function fakeDom(){ + const elements={};function node(){return {value:'',children:[],style:{},classList:{add(){},remove(){}},appendChild(c){this.children.push(c)},append(...cs){this.children.push(...cs)},set innerHTML(v){this.html=v;this.children=[]},get innerHTML(){return this.html||this.textContent||''}};} + return {elements,document:{getElementById(id){return elements[id]||(elements[id]=node())},createElement(){return node()}}}; +} +let dom=fakeDom(), alerts=[];s=read('S05/1_ipv4-subnetting/S05_Part01A_Explanation_I_Pv4_Subnetting.html'); +let v={document:dom.document,alert:x=>alerts.push(x)};vm.createContext(v);vm.runInContext(s.slice(s.indexOf(' function escapeText'),s.indexOf(' // Init')),v); +function vlsm(ip,cidr,requirements){alerts.length=0;dom.document.getElementById('ipInput').value=ip;dom.document.getElementById('cidrInput').value=String(cidr);v.inputRequirements=requirements.map(needed=>({name:'subnet '+needed,needed}));vm.runInContext('requirements=inputRequirements;calculateVLSM();',v);return dom.document.getElementById('vlsmTable').children.map(c=>c.innerHTML).join('');} +test('VLSM canonical base, sorted non-overlapping allocations and capacity',()=>{const out=vlsm('192.168.1.129',24,[10,100,50,2]);assert.equal(alerts.length,0);for(const net of ['192.168.1.0/25','192.168.1.128/26','192.168.1.192/28','192.168.1.208/30'])assert(out.includes(net));vlsm('192.168.1.0',24,[200,100]);assert(alerts.some(x=>x.includes('exceed')))}); +test('VLSM /0 finite arithmetic and invalid values',()=>{const out=vlsm('203.0.113.1',0,[4294967294]);assert(out.includes('0.0.0.0/0'));assert.equal(alerts.length,0);for(const cidr of [-1,33,24.5,'24oops']){vlsm('10.0.0.0',cidr,[10]);assert.equal(alerts.length,1)}vlsm('10.0.0.0',8,[65535]);assert.equal(alerts.length,0);vlsm('1.2.3.999',24,[10]);assert.equal(alerts.length,1)}); +let route=noUI(model('S05/3_network-simulation/S05_Part03_Page_Network_Simulation.html',' class NetworkNode')); +let legs=[],capture=[];route.animatePacket=(a,b,success,cb,variant)=>{legs.push([a,b,variant]);cb()};route.logTcpdump=(...args)=>capture.push(args);const ping=(a,d)=>{let result;legs=[];capture=[];route.simulatePacket(a,d,r=>result=r);return result}; +test('S05 routing respects missing gateway, disabled forwarding and partial request capture',()=>{route.resetSimulation();assert.equal(ping('h1','10.0.2.10'),false);assert.equal(legs.length,0);route.nodes.h1.routes=[{dest:'0.0.0.0/0',gw:'10.0.1.1'}];assert.equal(ping('h1','10.0.2.10'),false);assert.equal(capture.length,1);assert.equal(capture[0][3],'request');assert.equal(legs.length,1)}); +test('S05 routing requires return route and captures both directions',()=>{route.nodes.r1.forwarding=true;assert.equal(ping('h1','10.0.2.10'),false);assert.equal(capture.length,1);route.nodes.h2.routes=[{dest:'0.0.0.0/0',gw:'10.0.2.1'}];assert.equal(ping('h1','10.0.2.10'),true);assert.equal(capture.length,2);assert.equal(capture[1][3],'reply');route.nodes.h1.routes[0].gw='10.0.2.1';assert.equal(ping('h1','10.0.2.10'),false);route.nodes.h2.routes=[];assert.equal(ping('r1','10.0.2.10'),true)}); +let triangle=noUI(model('S06/1_routing/S06_Part01_Page_Routing_Triangle.html',' class Node')); +triangle.animatePacket=(a,b,cb)=>cb();function triPing(ttl=64){let result;triangle.simulatePacket('h1','10.0.3.2',ttl,(ok,trace,reached)=>result={ok,trace,reached});return result} +test('S06 triangle requires return route and reachable gateway',()=>{triangle.setupNetwork(true);assert.equal(triPing().ok,true);triangle.nodes.r3.routes=[];assert.equal(triPing().ok,false);triangle.nodes.r3.addRoute('10.0.1.0/30','10.0.13.1');triangle.nodes.r1.routes=[{dest:'10.0.3.0/30',gw:'10.0.23.2'}];assert.equal(triPing().ok,false);triangle.setupNetwork(true);assert.equal(triPing(1).ok,false);assert.equal(triPing(1).reached,false)}); +test('S06 ping summary follows completed replies and honours -c',()=>{triangle.setupNetwork(true);let logs=[];triangle.printToTerminal=s=>logs.push(s);triangle.handlePing('h1',['ping','-c','2','10.0.3.2']);assert(logs.at(-1).includes('2 packets transmitted, 2 received'));assert.equal(logs.filter(x=>x.startsWith('Simulated reply')).length,2)}); +test('Routing command models distinguish add from replace',()=>{route.resetSimulation();let logs=[];route.printToTerminal=x=>logs.push(x);route.handleIpRoute('h1',['route','add','default','via','10.0.1.1']);route.handleIpRoute('h1',['route','add','default','via','10.0.1.1']);assert(logs.at(-1).includes('File exists'));route.handleIpRoute('h1',['route','replace','default','via','10.0.1.1']);assert.equal(route.nodes.h1.routes.length,1);triangle.setupNetwork(true);triangle.checkTaskProgress=()=>{};logs=[];triangle.printToTerminal=x=>logs.push(x);triangle.handleAddRoute(triangle.nodes.r1,['ip','route','add','10.0.3.0/30','via','10.0.12.2']);assert(logs.at(-1).includes('File exists'));triangle.handleAddRoute(triangle.nodes.r1,['ip','route','replace','10.0.3.0/30','via','10.0.12.2']);assert.equal(triangle.nodes.r1.routes[0].gw,'10.0.12.2')}); +s=read('S05/2_ipv6-subnetting/S05_Part02_Page_I_Pv6_Subnetting.html');const ipv6start=s.indexOf(' const validate = (input) =>'),ipv6end=s.indexOf('\n };',ipv6start)+15;let ipv6={server:'2001:db8:1234:1::/64',lan:'2001:db8:1234:01::/64',iot:'2001:db8:1234:2::/64',router:'2001:db8:1234:3::/64'};vm.createContext(ipv6);vm.runInContext(s.slice(ipv6start,ipv6end)+'\nthis.check=validate;',ipv6); +test('IPv6 subnet uniqueness compares numeric hextets',()=>{assert.equal(ipv6.check(ipv6.server),false);ipv6.lan='2001:db8:1234:4::/64';assert.equal(ipv6.check(ipv6.server),true);assert.equal(ipv6.check('2001:db8:1234:10000::/64'),false);assert(s.includes('[0, 0x4000, 0x8000, 0xc000]'))}); +(async()=>{ + for (const file of ['S06_Part02_Page_2_ab_SDN_Topo_Switch.html','S06_Part02_Page_2_cd_SDNOS_Ken_Controller.html']) { + const html=read('S06/2_sdn/'+file);const env={flows:[],isAnimating:false,document:fakeDom().document,setTimeout:fn=>fn(),log(){},explain(){},renderFlows(){},sleep:async()=>{},movePacket:async()=>{}};vm.createContext(env); + vm.runInContext(html.slice(html.indexOf(' function addFlow('),html.indexOf(' function renderFlows('))+html.slice(html.indexOf(' function resetSim('),html.indexOf(' // Start')),env); + try{env.resetSim();let controllerTrips=0;env.movePacket=async(a,b)=>{if(b==='controller')controllerTrips++};await env.runSimulation('h2');assert.equal(controllerTrips,1);await env.runSimulation('h2');assert.equal(controllerTrips,1);await env.runSimulation('h3');assert.equal(controllerTrips,2);await env.runSimulation('h3');assert.equal(controllerTrips,2);env.resetSim();assert.equal(env.flows.length,1);await env.runSimulation('h2');assert.equal(controllerTrips,3);results.push({name:file+' learnt allow/drop flows are reused until reset',status:'PASS'});}catch(e){results.push({name:file+' learnt allow/drop flows are reused until reset',status:'FAIL',error:String(e)})} + } + if (process.env.SEMINAR_MODEL_REPORT) fs.writeFileSync(process.env.SEMINAR_MODEL_REPORT,JSON.stringify({method:'Actual extracted JavaScript functions and state models executed under Node with explicit stubs; not native browser or DOM acceptance',results},null,2)+'\n');console.log(JSON.stringify(results,null,2));process.exit(results.some(r=>r.status==='FAIL')?1:0); +})(); diff --git a/04_SEMINARS/tests/test_protocol_regressions.py b/04_SEMINARS/tests/test_protocol_regressions.py new file mode 100644 index 0000000..c80c1a2 --- /dev/null +++ b/04_SEMINARS/tests/test_protocol_regressions.py @@ -0,0 +1,242 @@ +"""Native loopback and boundary regressions for the supplied seminar implementations. + +These tests do not accept a VM, Docker stack, browser or Mininet topology. +Run from the repository root with: python3 -m pytest -q 04_SEMINARS/tests +""" +import contextlib +import importlib.util +import json +from pathlib import Path +import socket +import sys +import threading +from urllib.request import Request, urlopen + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def load(relative, name): + path = ROOT / relative + sys.path.insert(0, str(path.parent)) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +@contextlib.contextmanager +def connected(handler): + """Use an actual IPv4 connection and run the real handler in a thread.""" + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(('127.0.0.1', 0)) + listener.listen(1) + client = socket.create_connection(listener.getsockname(), timeout=2) + peer, _ = listener.accept() + listener.close() + errors = [] + def serve(): + try: + handler(peer) + except Exception as exc: + errors.append(exc) + finally: + peer.close() + thread = threading.Thread(target=serve, daemon=True) + thread.start() + try: + yield client + finally: + client.close() + thread.join(3) + assert not thread.is_alive(), 'Handler did not stop after peer closure' + assert not errors, repr(errors) + + +@pytest.mark.parametrize('size', [0, 7, 8, 9, 10, 96, 97, 98, 99, 100, 999]) +def test_text_frame_total_byte_length(size): + framing = load('S04/1_text-proto_tcp/text_framing.py', 'text_framing') + frame = framing.encode_frame('\u0103' + 'x' * size) + assert int(frame.split(b' ', 1)[0]) == len(frame) + + +def test_text_fragmentation_coalescence_and_incomplete_eof(): + module = load('S04/1_text-proto_tcp/S04_Part01A_Example_Text_Proto_TCP_Server.py', 'text_server') + framing = sys.modules['text_framing'] + with connected(module.handle_client) as client: + frame = framing.encode_frame('add key \u0103lice') + for byte in frame: + client.sendall(bytes([byte])) + assert framing.read_frame(client).split(b' ', 1)[1] == b'key added' + client.sendall(framing.encode_frame('get key') + framing.encode_frame('remove key')) + assert framing.read_frame(client).split(b' ', 1)[1].decode() == '\u0103lice' + assert framing.read_frame(client).split(b' ', 1)[1] == b'key removed' + client.sendall(b'20 incomplete') + client.shutdown(socket.SHUT_WR) + assert client.recv(1) == b'' + + +def test_binary_coalescence_and_keys_argument(): + client_module = load('S04/2_binary-proto_tcp/S04_Part02B_Example_Binary_Proto_TCP_Client.py', 'binary_client') + server = load('S04/2_binary-proto_tcp/S04_Part02A_Example_Binary_Proto_TCP_Server.py', 'binary_server') + import pickle + framing = sys.modules['binary_framing'] + assert client_module.get_command('keys')[0] >= 2 + with pytest.raises(ValueError): + client_module.get_command('add huge ' + 'x' * 1000) + with connected(server.handle_client) as client: + client.sendall(client_module.get_command('add k value') + client_module.get_command('get k')) + assert pickle.loads(framing.read_frame(client)[1:]).payload == 'k added' + assert pickle.loads(framing.read_frame(client)[1:]).payload == 'value' + + +def test_s02_repeated_lines_and_split_utf8(): + module = load('S02/S02_Part01_Example_TCP_Server.py', 's02_server') + with module.ThreadedTCPServer(('127.0.0.1', 0), module.TCPRequestHandler) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with socket.create_connection(server.server_address, timeout=2) as client: + with client.makefile('rb') as reader: + for message in ['hello', 'two', 'three', 'four', '\u0103lice']: + for byte in (message + '\n').encode(): + client.sendall(bytes([byte])) + assert reader.readline() == (message.upper() + '\n').encode() + finally: + server.shutdown() + thread.join(2) + + +def test_s03_reset_removes_registered_client(): + module = load('S03/S03_Part01_Example_TCP_Multi_client_Server.py', 's03_server') + import struct + with connected(lambda peer: (module.clients.append(peer), module.handle_client(peer, ('127.0.0.1', 1)))) as client: + client.sendall(b'hello') + assert client.recv(5) == b'Hello' + client.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) + assert module.clients == [] + + +def test_udp_serialisation_larger_than_old_buffer_and_limit(): + module = load('S04/3_proto_udp/S04_Part03_Script_Serialization.py', 'udp_serialisation') + payload = '\u0103' * 1000 + encoded = module.serialize(payload) + assert len(encoded) > 1024 + assert module.deserialize(encoded) == payload + with pytest.raises(ValueError): + module.serialize('x' * 65508) + + +def test_http_fragmented_headers_paths_and_byte_length(tmp_path): + module = load('S08/3_socket-http/S08_Part03B_Example_Socket_HTTP_Server.py', 'http_manual') + static = tmp_path / 'static' + static.mkdir() + (static / 'S08_Part03_Page_Index.html').write_text('\u0103lice', encoding='utf-8') + secret = tmp_path / 'secret.txt' + secret.write_text('not public') + (static / 'escape.txt').symlink_to(secret) + module.STATIC_DIR = str(static) + for target, expected in [('/', 200), ('../secret.txt', 400), ('/../secret.txt', 403), ('/%2e%2e/secret.txt', 403), ('/escape.txt', 403), ('/missing', 404)]: + with connected(module.handle_client) as client: + for byte in f'GET {target} HTTP/1.1\r\nHost: localhost\r\n\r\n'.encode(): + client.sendall(bytes([byte])) + response = bytearray() + while chunk := client.recv(4096): + response.extend(chunk) + header, body = bytes(response).split(b'\r\n\r\n', 1) + assert header.startswith(f'HTTP/1.1 {expected} '.encode()) + assert f'Content-Length: {len(body)}'.encode() in header + assert b'not public' not in body + + +def test_pseudo_ftp_four_transfers_and_control_ack(tmp_path): + server = load('S09/2_custom-pseudo-ftp/S09_Part02B_Script_Pseudo_FTP_Server.py', 'ftp_server') + client_module = load('S09/2_custom-pseudo-ftp/S09_Part02C_Script_Pseudo_FTP_Client.py', 'ftp_client') + server.FILE_ROOT = str(tmp_path / 'server') + client_module.LOCAL_STORAGE = str(tmp_path / 'client') + Path(server.FILE_ROOT).mkdir() + Path(client_module.LOCAL_STORAGE).mkdir() + (Path(server.FILE_ROOT) / 'a.txt').write_bytes('test \u0103'.encode()) + (Path(client_module.LOCAL_STORAGE) / 'b.txt').write_bytes(bytes(range(255))) + with connected(server.handle_client_commands) as client: + for command in ['active_get a.txt', 'passive_get a.txt', 'active_put b.txt', 'passive_put b.txt']: + client_module.process_command(client, command) + assert (Path(client_module.LOCAL_STORAGE) / 'a.txt').read_bytes() == 'test \u0103'.encode() + assert (Path(server.FILE_ROOT) / 'b.txt').read_bytes() == bytes(range(255)) + client.sendall(b'list\n') + assert 'b.txt' in sys.modules['pseudo_ftp_io'].read_reply(client) + + +def test_rpc_contract_over_http(): + module = load('S12/1_jsonrpc/S12_Part01_Script_JSONRPC_Server.py', 'rpc_server') + with module.ThreadingHTTPServer(('127.0.0.1', 0), module.Handler) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + cases = [ + (b'{', 200, -32700), + (b'[]', 200, -32600), + (b'{"jsonrpc":"2.0","method":"missing","id":7}', 200, -32601), + (b'{"jsonrpc":"2.0","method":"evaluate","params":["__import__(1)"],"id":7}', 200, -32602), + (b'{"jsonrpc":"2.0","method":"evaluate","params":["2+3"],"id":7}', 200, None), + (b'{"jsonrpc":"2.0","method":"evaluate","params":["2+3"]}', 204, None), + ] + try: + for body, status, code in cases: + req = Request(f'http://127.0.0.1:{server.server_port}/', data=body, headers={'Content-Type':'application/json'}) + with urlopen(req, timeout=2) as response: + assert response.status == status + raw = response.read() + if status == 204: + assert raw == b'' + else: + result = json.loads(raw) + if code: + assert result['error']['code'] == code + if code in {-32601, -32602}: + assert result['id'] == 7 + else: + assert result == {'jsonrpc':'2.0','id':7,'result':5} + finally: + server.shutdown() + thread.join(2) + + +def test_s13_port_exhaustion_and_env_comments(tmp_path): + ports = load('S13/generate_env_ports.py', 'ports_generator') + with socket.socket() as held: + held.bind(('127.0.0.1', 0)) + with pytest.raises(ValueError, match='No free'): + ports.pick_port(held.getsockname()[1], window=0) + with pytest.raises(ValueError): + ports.pick_port(65535, window=1) + env = load('S13/s13_env.py', 's13_env') + path = tmp_path / '.env' + path.write_text('A_HOST_PORT=19102 # local\nB_HOST_PORT="19103" # local\nC_HOST_PORT=\'19104\'\n') + assert env.load_env_file(path) == {'A_HOST_PORT':'19102','B_HOST_PORT':'19103','C_HOST_PORT':'19104'} + path.write_text('A_HOST_PORT=not-a-port\n') + with pytest.raises(ValueError): + env.load_env_file(path) + + +def test_rpc_batch_notifications_and_nonfinite_ids(): + rpc = load('S12/1_jsonrpc/S12_Part01_Script_JSONRPC_Server.py', 'rpc_batch') + batch = [ + {'jsonrpc': '2.0', 'method': 'add', 'params': [1, 2], 'id': 'item'}, + {'jsonrpc': '2.0', 'method': 'unknown'}, + 17, + ] + result = rpc.process_body(json.dumps(batch).encode()) + assert result[0] == {'jsonrpc': '2.0', 'id': 'item', 'result': 3} + assert len(result) == 2 and result[1]['error']['code'] == -32600 + assert result[1]['id'] is None + assert rpc.process_body(b'[{"jsonrpc":"2.0","method":"add","params":[1,2]}]') is None + assert rpc.process_body(b'[]')['error']['code'] == -32600 + assert rpc.process_body(b'{"jsonrpc":"2.0","method":"add","params":[1,2],"id":1e400}')['error']['code'] == -32600 + nested = rpc.process_body(b'[' * 2000 + b']' * 2000) + # Decoders may accept this valid JSON nesting or report their nesting limit. + if isinstance(nested, list): + assert nested[0]['error']['code'] == -32600 + else: + assert nested['error']['code'] == -32700 diff --git a/CHANGELOG.md b/CHANGELOG.md index d4fa68a..fffc5ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # CHANGELOG — Backbone comparison and downstream evolution (compnet-2025-redo-main → COMPNET-EN-main → COMPNET-EN-main_PHASEC_plus_more_labs_QAfix) +## Unreleased — v1.5.0 candidate, 17 November 2026 + +The candidate starts from the preserved v1.4.0 commit +`8b10df86bdd9dae33a7aa82beb580fa449c530ea`. It does not replace that tag or +re-export the independently versioned MININET-SDN 1.0.0 appliance. + +- Reconcile canonical examples, student quizzes, lecture/seminar diagrams, + project evidence and installation routes across the course kit. +- Correct confirmed protocol, connection ownership, framing, error propagation, + grading, export and interactive presentation defects; add targeted regressions. +- Rebuild the project verification workbook against the canonical requirements, + preserving requirement identifiers, assessment stages and original provenance. +- Use a common non-mutating source gate for local QA, CI and release packaging; + commit executable modes and reject uncommitted or failed packaging inputs. +- Correct verified reference metadata and qualify unsupported comparative claims. + Record the unresolved licence policy for the author's explicit decision. + +The detailed [remediation and acceptance record](00_TOOLS/qa/REMEDIATION_v1.5.0.md) +distinguishes native component tests, structural checks and model-based probes. +OVA/Windows/WSL, complete Docker/Mininet labs, native browser, LMS and desktop +spreadsheet acceptance remain separate release gates. This entry does not claim +that v1.5.0 has been published or that all cumulative findings are fully accepted. + ## 16 November 2026 — MININET-SDN distribution and student setup The update below uses the current GitHub snapshot as its base; the historical diff --git a/LICENCE.md b/LICENCE.md index 4032208..1b3ef25 100644 --- a/LICENCE.md +++ b/LICENCE.md @@ -1,304 +1,162 @@ # Open Educational Licence — Multi-Category -**Version 14.00.00 — February 2026** - ---- - -## Overview - -This repository uses a **multi-licence model**, similar to those adopted by -open educational projects such as UCLouvain CNP3 and SEED Labs. Different -categories of content carry different licences so that educational materials -can be shared and adapted while examination resources remain controlled and -authorship is protected. - -``` -┌──────────────────────────────────────────────────────────────────────┐ -│ Category A — Documentation and Educational Content │ -│ Licence: CC BY-NC-SA 4.0 │ -│ Scope: lectures, seminars, README files, guides, diagrams (puml), │ -│ HTML presentations, instructor notes, project briefs, │ -│ cheatsheets, troubleshooting docs, the Python self-study │ -│ guide, Portainer guides │ -├──────────────────────────────────────────────────────────────────────┤ -│ Category B — Source Code and Configuration │ -│ Licence: GPL-3.0-or-later │ -│ Scope: Python scripts (.py), shell scripts (.sh), Dockerfiles, │ -│ Docker Compose files (.yml/.yaml), nginx configs (.conf), │ -│ CI workflow files, QA scripts, Makefiles, PlantUML render │ -│ scripts, lab_runner, format-offline.js, package.json │ -├──────────────────────────────────────────────────────────────────────┤ -│ Category C — Examination and Assessment Materials │ -│ Licence: All Rights Reserved │ -│ Scope: quiz banks (00_APPENDIX/c)studentsQUIZes*), formative │ -│ quizzes (quiz.json, quiz.yaml, parsons_problems.json), │ -│ assessment rubrics, verification index (.xlsx), │ -│ PCAP validation rules (tools/pcap_rules/*.json), │ -│ solution templates (*Solution*), instructor outlines │ -│ (d)instructor_NOTES4sem/*) │ -└──────────────────────────────────────────────────────────────────────┘ -``` - -If a file does not clearly fall into one of the categories above, it -follows Category A by default. - ---- - -## Copyright Notice +**Policy revision prepared for v1.5.0 — 17 November 2026** + +## 1. Scope and order of precedence + +This policy distinguishes educational documentation, software and reserved +assessment material in the COMPNET-EN course kit. It applies only to rights that +the relevant rightsholder is entitled to license. Copyright, authorship and +component-specific notices must be preserved. + +Apply the following rules in order: + +1. A component-specific third-party licence or an existing licence grant remains + effective. This document does not relicense third-party material or withdraw + permissions already received under an earlier valid grant. +2. The exact repository-relative paths in `LICENCE_CATEGORY_C.txt` identify + Category C for this policy. This list takes precedence over the general + documentation and file-type descriptions below, subject to rule 1. +3. Source code and configuration outside that list belong to Category B. This + includes `.py`, `.sh`, `.ps1`, `.js`, `.cjs`, `.mjs`, `.c`, `.h`, `.cc`, `.cpp`, + `.hpp`, `.java`, `.kt`, `.kts`, `.php`, `.conf`, `.env`, `.zone`, `.proto`, + `.yml`, `.yaml` and `.toml` files; Docker build recipes with a `Dockerfile` + token in the filename, including prefixed names; Makefiles; package and + requirements manifests, including `requirements-optional.txt`; Git, editor + and Prettier configuration (`.gitattributes`, `.gitignore`, `.editorconfig`, + `.prettierignore` and `.prettierrc`). It also includes the operational + configurations `00_TOOLS/lab_runner/labs.json`, + `00_TOOLS/qa/executable_manifest.txt`, + `03_LECTURES/C11/assets/scenario-ssh-provision/controller/plan.json` and + `00_TOOLS/qa/evidence/kotlin/2026-11-17/PROTOCOL_FREEZE.json`. +4. Other repository materials belong to Category A. HTML teaching presentations, + PlantUML diagram sources and project briefs remain educational content under + this default. A separately identified third-party component keeps its terms. + +The reserved-path list includes the weekly question-bank directory, the named +formative datasets, the assessment workbook, PCAP assessment-rule JSON files, +identified solution templates and the S14 assessment rubric. Instructor outlines +under `00_APPENDIX/d)instructor_NOTES4sem/` are included in that explicit list; +other instructor-facing documentation follows the rules above. + +An embedded assessment example does not automatically change an entire +Category A presentation or project brief into Category C. New reserved files must +be identified explicitly when released; a filename resemblance alone does not +expand the reserved list. The policy and reserved-path list are documentation. + +## 2. Copyright and provenance **© 2017–2027 ing. dr. Antonio Clim.** -The Materials are protected under Romanian law (Law No. 8/1996 on Copyright -and Related Rights, as amended), European Union Directive 2001/29/EC, and -applicable international treaties including the Berne Convention for the -Protection of Literary and Artistic Works. +Retain the original copyright, contributor credits, academic provenance and +third-party notices. This policy does not assert that every component has a +single author or that the named author owns third-party material. ---- +## 3. Category A — Documentation and Educational Content -## Category A — Documentation and Educational Content +Category A material is offered under [Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International +(CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.en). +A complete, unmodified copy is included in `LICENSES/CC-BY-NC-SA-4.0.txt`. +The standard licence governs the permissions, attribution, non-commercial scope, +ShareAlike conditions, exceptions and limitations. This summary adds no further +restriction to that grant. -### Licence +Non-commercial sharing, adaptation and teaching are permitted under that licence. +Whether a particular use is non-commercial is determined by the licence, not by a +blanket assumption about an institution or the existence of tuition fees. Uses +outside its grant may be discussed with the relevant rightsholder. -This content is licensed under the -[Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International -(CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) -licence. +## 4. Category B — Source Code and Configuration -### What This Permits +Category B material is offered under the [GNU General Public License, version 3 +or any later version (GPL-3.0-or-later)](https://www.gnu.org/licenses/gpl-3.0.html). +The GPL version 3 text is included in `LICENSES/GPL-3.0-or-later.txt`; the +permission to use any later version is expressed by this policy and applicable +component notices. The applicable GPL text governs copying, modification, distribution and source +availability. Existing notices and applicable component-specific terms remain. -| Action | Permitted? | Condition | -|--------|:----------:|-----------| -| Read, download, study | ✓ | — | -| Share and redistribute | ✓ | Attribution required (see Section 5) | -| Adapt, translate, remix | ✓ | Same licence (ShareAlike), attribution, non-commercial | -| Use in teaching at any institution | ✓ | Non-commercial, with attribution (see Section 5) | -| Use in commercial training or paid courses | ✗ | Written permission required | -| Remove or obscure the original attribution | ✗ | — | +Commercial use and distribution are permitted when the GPL conditions are met. +This policy imposes no non-commercial condition, automatic co-authorship +obligation or additional research-citation condition on GPL-covered material. +Private use is not treated as a duty to publish modifications. Distribution and +combination with other works must be assessed under the applicable GPL terms. -### ShareAlike Obligation +## 5. Category C — Examination and Assessment Materials -If you remix, transform, or build upon the Category A materials, you must -distribute your contributions under the **same or a compatible licence** -(CC BY-NC-SA 4.0 or later). +For the exact paths in `LICENCE_CATEGORY_C.txt`, rights not already granted are +reserved. Personal study is permitted. Other uses requiring the rightsholder's +permission require prior written authorisation, unless an existing grant, +applicable exception or limitation already permits the use. ---- +This category covers the named controlled assessment resources. It does not +remove earlier permissions, override a third-party licence or limit uses that do +not require permission. Public visibility of a repository is distinct from this +category's reuse permissions; applicable platform terms also remain unaffected. -## Category B — Source Code and Configuration +Instructors may request permission through the repository issue tracker or +official ASE-CSIE academic channels, describing the materials, institution, +course and intended use. A separate agreement may define the authorised scope. -### Licence +## 6. Attribution, academic citation and authorship -This content is licensed under the -[GNU General Public License v3.0 or later -(GPL-3.0-or-later)](https://www.gnu.org/licenses/gpl-3.0.html). +Comply with the attribution and notice requirements of each applicable licence. +For Category A, use a reasonable attribution suited to the medium and context. +For Category B, preserve the copyright, licence and other notices required by the +GPL. Category C permissions may specify attribution in the relevant agreement. -### What This Permits +The following citation is a suggested academic format, preserving the existing +project citation. It is not an additional condition on a standard public licence: -| Action | Permitted? | Condition | -|--------|:----------:|-----------| -| Run, study, inspect | ✓ | — | -| Modify and distribute modifications | ✓ | Same licence (copyleft), attribution, source availability | -| Include in open-source projects | ✓ | GPL-3.0-compatible licence required | -| Include in proprietary/closed-source products | ✗ | GPL copyleft applies | -| Use code snippets for personal learning | ✓ | — | +> Clim, A. (2025). *Computer Networks — Course Kit (EN).* Bucharest University of +> Economic Studies (ASE), Faculty of Economic Cybernetics, Statistics and +> Informatics (CSIE). https://github.com/antonioclim/COMPNET-EN -### Copyleft Obligation +Where the author is identified in full, the preferred form is +**ing. dr. Antonio Clim**. Academic citation is requested when the materials +inform a publication. Collaboration and co-authorship should reflect substantive +scholarly contributions, the applicable publication criteria and the agreement +of the authors. Reuse above a numerical percentage does not automatically create +a co-authorship obligation. No licence permission depends on such an obligation. -If you distribute modified versions of the Category B code, you must make -your source code available under the GPL-3.0-or-later licence. +## 7. Teaching and commercial permission requests -### Linking and Aggregation +Teaching with Category A follows CC BY-NC-SA 4.0. Teaching with Category B follows +the GPL and is not restricted to non-commercial courses. Category C follows the +specific permission or existing grant applicable to the identified material. +Requests for uses beyond those permissions may be submitted through the channels +listed below. This section does not narrow any standard licence grant. -Mere aggregation of Category B code with independently developed software -in a distribution medium does not bring the other software under the scope -of the GPL-3.0. The full GPL-3.0 text governs boundary cases. +## 8. Contributions ---- +Contributors retain their copyright. Contributions intended for Category A or B +should identify and use the corresponding category licence, subject to retained +third-party terms and the contributor's authority to grant rights. Contributions +to reserved assessment material require a separately agreed scope. Submission +alone does not transfer copyright or permit relicensing of third-party content. +Contributor notices and acknowledgements must be retained as applicable. -## Category C — Examination and Assessment Materials +## 9. Warranty, other terms and interpretation -### Licence +The warranty exclusions, limitations of liability and other conditions of the +applicable standard licence govern Category A and B. No supplementary jurisdiction, +severability, permission or attribution term in this policy adds a restriction +to those standard licences. -**All rights reserved.** No part of the Category C materials may be -reproduced, distributed, adapted, translated, publicly displayed, or used -for any purpose beyond personal study without the prior express written -consent of the Author. +For reserved material, it is supplied as available without a separate warranty, +to the extent permitted by applicable law; any express written agreement governs +its own terms. Mandatory law and statutory exceptions remain unaffected. -### Rationale +This clarification preserves existing grants and original provenance. It is not +a representation that an earlier ambiguity removed the recipient's rights. -Examination materials, quiz banks, solution templates, PCAP validation -rules, and instructor outlines derive their pedagogical value from -controlled access. Public redistribution would compromise assessment -integrity for current and future cohorts. - -### How to Request Access - -Instructors at other institutions who wish to use Category C materials -in their own courses may request access by: - -1. Opening a formal request on the repository **Issue Tracker** or - contacting the Author through official ASE-CSIE academic channels. -2. Specifying the institution, course, expected enrolment, and intended - use. -3. Awaiting explicit written authorisation before any use. - -Category C materials may be shared under a separate bilateral agreement -at the Author's discretion. - ---- - -## 5. Attribution and Citation - -### 5.1 Mandatory Attribution (all uses) - -Any use of the Materials — whether under Category A, Category B, or an -authorised use of Category C — **must** include a clear and reasonably -prominent attribution in the following format: - -``` -Clim, A. (2025). Computer Networks — Course Kit (EN). - Bucharest University of Economic Studies (ASE), Faculty of Economic - Cybernetics, Statistics and Informatics (CSIE). - https://github.com/antonioclim/COMPNET-EN -``` - -Where author names appear in full form, the Author must be referenced as -**ing. dr. Antonio Clim**. - -For code files (Category B), attribution may alternatively take the form -of a comment header or a NOTICE file, consistent with GPL-3.0 practice. - -### 5.2 Co-authorship Requirement (use exceeding 20%) - -Any published work — including but not limited to journal articles, -conference papers, books, theses, technical reports, or course materials -intended for public distribution — in which materials from this repository -constitute **more than 20%** of the total content must include -**ing. dr. Antonio Clim** among the listed co-authors. - -The 20% threshold applies to any combination of verbatim reproduction, -paraphrased content, adapted code, redrawn diagrams, restructured -exercises, or conceptual frameworks traceable to the Materials. - -### 5.3 Determination of Proportion - -In the event of a dispute regarding the proportion of Materials used, the -assessment shall be conducted by an independent academic expert mutually -agreed upon by the parties, or — failing agreement — appointed by the -competent court. - ---- - -## 6. Teaching Permission — Detailed Terms - -### 6.1 Non-Commercial Teaching - -Any educational institution — university, school, or non-profit training -programme — may use Category A and Category B materials for classroom -instruction, seminar delivery, and laboratory exercises, **provided that**: - -1. The use is **non-commercial** (no tuition surcharge, course fee, or - other charge is levied specifically for access to these materials). -2. The attribution requirements of Section 5.1 are satisfied. -3. Any adapted or translated versions carry the CC BY-NC-SA 4.0 licence - (for Category A content) or the GPL-3.0-or-later licence (for - Category B content). - -### 6.2 Commercial and Paid Use - -Use of the Materials in any paid training programme, commercial bootcamp, -corporate workshop, or online platform that charges learners requires the -**prior express written consent** of the Author. Requests should be -submitted through the repository Issue Tracker or official ASE-CSIE -channels. - -### 6.3 Examination Materials in External Teaching - -Category C materials are **not included** in the general teaching -permission. Instructors at other institutions must request access -separately under Section 4 (Category C). - ---- - -## 7. Contributions - -### 7.1 Pull Requests and External Contributions - -By submitting a pull request or other contribution to this repository, -you agree that your contribution will be licensed under the applicable -category licence: - -- Documentation contributions: CC BY-NC-SA 4.0 -- Code contributions: GPL-3.0-or-later - -You retain copyright over your contribution but grant the Author a -perpetual, irrevocable, worldwide licence to use, modify, and distribute -it under the terms above. - -### 7.2 Attribution of Contributors - -Significant contributions will be acknowledged in the repository -CHANGELOG or README, at the Author's discretion. - ---- - -## 8. Disclaimer of Warranty - -THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL -THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE -MATERIALS. - ---- - -## 9. Governing Law and Jurisdiction - -This Licence shall be governed by and construed in accordance with the laws -of Romania. Any disputes arising under or in connection with this Licence -shall be subject to the exclusive jurisdiction of the courts of Bucharest, -Romania. - -EU Directive 2001/29/EC and the Berne Convention apply where Romanian law -is silent or where cross-border enforcement requires harmonised -interpretation. - ---- - -## 10. Severability - -If any provision of this Licence is held to be invalid or unenforceable, -the remaining provisions shall continue in full force and effect. The -invalid provision shall be replaced by a valid provision that most closely -achieves the original intent. - ---- - -## 11. Licence Compatibility Summary - -| If you want to… | Use Category A (CC BY-NC-SA) | Use Category B (GPL-3.0) | Use Category C (Reserved) | -|------------------|:----------------------------:|:------------------------:|:-------------------------:| -| Study personally | ✓ | ✓ | ✓ | -| Teach non-commercially | ✓ with attribution | ✓ with attribution | Request required | -| Adapt and reshare | ✓ same licence, non-commercial | ✓ same licence, source available | ✗ | -| Include in commercial product | ✗ (request needed) | ✗ (GPL copyleft) | ✗ (request needed) | -| Publish a paper using < 20% | ✓ with citation | ✓ with citation | ✓ with citation | -| Publish a paper using > 20% | ✓ with co-authorship | ✓ with co-authorship | ✓ with co-authorship | -| Fork the repository | ✓ A+B only, with attribution | ✓ code under GPL-3.0 | ✗ (Category C excluded) | -| Translate into another language | ✓ same licence, attribution | ✓ same licence | ✗ (request needed) | - ---- - -## Contact +## 10. Contact **ing. dr. Antonio Clim** -Bucharest University of Economic Studies (ASE) -Faculty of Economic Cybernetics, Statistics and Informatics (CSIE) -For permissions, questions, or institutional access requests: -use the repository **Issue Tracker** or official ASE-CSIE channels. +Bucharest University of Economic Studies (ASE) ---- +Faculty of Economic Cybernetics, Statistics and Informatics (CSIE) -*Last updated: February 2026* +For permissions, questions or institutional access requests, use the repository +issue tracker or official ASE-CSIE academic channels. diff --git a/LICENCE_CATEGORY_C.txt b/LICENCE_CATEGORY_C.txt new file mode 100644 index 0000000..a3dc746 --- /dev/null +++ b/LICENCE_CATEGORY_C.txt @@ -0,0 +1,87 @@ +# Category C paths for the v1.5.0 policy +# Prior grants, statutory exceptions and component-specific notices remain effective. +# One repository-relative path per line; this is the complete reserved-path list. +00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_bytes.yaml +00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_socket.yaml +00_APPENDIX/a)PYTHON_self_study_guide/formative/quiz.yaml +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W01_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W02_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W03_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W04_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W05_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W06_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W07_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W08_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W09_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W10_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W11_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W12_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W13_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/COMPnet_W14_Questions.md +00_APPENDIX/c)studentsQUIZes(multichoice_only)/README.md +00_APPENDIX/d)instructor_NOTES4sem/README.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-instructor-outline-v3__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S01-outline-vi1.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S02-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S03-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S04-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S05-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S06-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S06-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S07-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S08-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S09-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S10-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S10-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S11-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S12-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S12-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S13-instructor-outline-v2.md +00_APPENDIX/d)instructor_NOTES4sem/roCOMPNETclass_S13-instructor-outline-v2__noMININET-SDN_.md +00_APPENDIX/formative/parsons_problems.json +00_APPENDIX/formative/quiz.json +00_APPENDIX/formative/quiz.yaml +02_PROJECTS/00_common/tools/pcap_rules/A01.json +02_PROJECTS/00_common/tools/pcap_rules/A02.json +02_PROJECTS/00_common/tools/pcap_rules/A03.json +02_PROJECTS/00_common/tools/pcap_rules/A04.json +02_PROJECTS/00_common/tools/pcap_rules/A05.json +02_PROJECTS/00_common/tools/pcap_rules/A06.json +02_PROJECTS/00_common/tools/pcap_rules/A07.json +02_PROJECTS/00_common/tools/pcap_rules/A08.json +02_PROJECTS/00_common/tools/pcap_rules/A09.json +02_PROJECTS/00_common/tools/pcap_rules/A10.json +02_PROJECTS/00_common/tools/pcap_rules/S01.json +02_PROJECTS/00_common/tools/pcap_rules/S02.json +02_PROJECTS/00_common/tools/pcap_rules/S03.json +02_PROJECTS/00_common/tools/pcap_rules/S04.json +02_PROJECTS/00_common/tools/pcap_rules/S05.json +02_PROJECTS/00_common/tools/pcap_rules/S06.json +02_PROJECTS/00_common/tools/pcap_rules/S07.json +02_PROJECTS/00_common/tools/pcap_rules/S08.json +02_PROJECTS/00_common/tools/pcap_rules/S09.json +02_PROJECTS/00_common/tools/pcap_rules/S10.json +02_PROJECTS/00_common/tools/pcap_rules/S11.json +02_PROJECTS/00_common/tools/pcap_rules/S12.json +02_PROJECTS/00_common/tools/pcap_rules/S13.json +02_PROJECTS/00_common/tools/pcap_rules/S14.json +02_PROJECTS/00_common/tools/pcap_rules/S15.json +02_PROJECTS/00_common/tools/pcap_rules/S16.json +02_PROJECTS/00_common/tools/pcap_rules/S17.json +02_PROJECTS/00_common/tools/pcap_rules/S18.json +02_PROJECTS/00_common/tools/pcap_rules/S19.json +02_PROJECTS/00_common/tools/pcap_rules/S20.json +02_PROJECTS/RC2026_VERIFICATION_INDEX.xlsx +04_SEMINARS/S05/1_ipv4-subnetting/S05_Part01C_Solutions_Template_I_Pv4_Subnetting.md +04_SEMINARS/S05/2_ipv6-subnetting/S05_Part02C_Solutions_Template_I_Pv6_Subnetting.md +04_SEMINARS/S14/S14_Part03_Template_Assessment_Rubric.md +04_SEMINARS/_tutorial-solve/s2/S02_Part02_Solution_TCP_Server_Template.py diff --git a/LICENSES/CC-BY-NC-SA-4.0.txt b/LICENSES/CC-BY-NC-SA-4.0.txt new file mode 100644 index 0000000..7cdbe0b --- /dev/null +++ b/LICENSES/CC-BY-NC-SA-4.0.txt @@ -0,0 +1,438 @@ +Attribution-NonCommercial-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International Public License +("Public License"). To the extent this Public License may be +interpreted as a contract, You are granted the Licensed Rights in +consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the +Licensor receives from making the Licensed Material available under +these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + l. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + diff --git a/LICENSES/GPL-3.0-or-later.txt b/LICENSES/GPL-3.0-or-later.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSES/GPL-3.0-or-later.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index d37b228..abd9a59 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Computer Networks — Course Kit (EN) -![Version](https://img.shields.io/badge/version-v13.05.00-informational) +![Version](https://img.shields.io/badge/version-v1.5.0_candidate-orange) ![Language](https://img.shields.io/badge/language-English%20(British)-blue) ![Diagrams](https://img.shields.io/badge/diagrams-PlantUML-success) ![Labs](https://img.shields.io/badge/labs-Python%20and%20Docker-orange) @@ -16,6 +16,10 @@ The pedagogical intent is to move from declarative claims to defensible explanat --- +## Version status + +This branch prepares **v1.5.0**. The preserved pre-remediation release is [v1.4.0](https://github.com/antonioclim/COMPNET-EN/releases/tag/v1.4.0). Historical v13.05.00 references remain historical, and the MININET-SDN OVA retains its independent version 1.0.0 and Zenodo DOI. Candidate checks are documented in [the remediation record](00_TOOLS/qa/REMEDIATION_v1.5.0.md); this branch is not a declaration of full VM or browser acceptance. + ## Start here ### If you are a student @@ -300,7 +304,7 @@ A pragmatic workflow is: - `.pcapng` packet captures - Docker logs 5. Clean up between attempts. - If a seminar uses Docker Compose, prefer `docker compose down -v`. + For a Compose seminar, use its documented `docker compose -f down` command. Add `-v` only when the exercise explicitly calls for deleting that project’s persisted data and you have saved the required evidence. --- @@ -323,6 +327,7 @@ This is both a navigation tool and a dependency map. | 11 | [C11 FTP, DNS and SSH](03_LECTURES/C11/) | [S11 load balancing](04_SEMINARS/S11/) | reverse proxies and failure modes | Docker | | 12 | [C12 SMTP, POP3 and IMAP](03_LECTURES/C12/) | [S12 JSON-RPC, Protobuf and gRPC](04_SEMINARS/S12/) | structured APIs | Python, Docker | | 13 | [C13 IoT and network security](03_LECTURES/C13/) | [S13 scanning and vulnerability reasoning](04_SEMINARS/S13/) | security literacy | Docker, Wireshark | +| 14 | [C14 revision and integration](03_LECTURES/C14/) | [S14 recap and assessment](04_SEMINARS/S14/) | integrate evidence, explain behaviour and prepare for assessment | Python, Docker, Wireshark |
    Course coverage: lecture and seminar indices @@ -330,8 +335,8 @@ This is both a navigation tool and a dependency map. Lecture index is maintained in `03_LECTURES/README.md`. Seminar index is maintained in `04_SEMINARS/README.md`. -- Lectures: `03_LECTURES/C01/` … `03_LECTURES/C13/` -- Seminars: `04_SEMINARS/S01/` … `04_SEMINARS/S13/` +- Lectures: `03_LECTURES/C01/` … `03_LECTURES/C14/` +- Seminars: `04_SEMINARS/S01/` … `04_SEMINARS/S14/`
    @@ -380,7 +385,7 @@ The value of Portainer is observability for beginners and rapid inspection durin | view logs | container logs panel | `docker logs -f ` | | inspect networks | Networks view | `docker network ls` and `docker network inspect ` | | bring up a stack | Stacks feature (if enabled) | `docker compose up -d` | -| stop and clean | container stop and remove | `docker compose down -v` | +| stop and clean | container stop and remove | `docker compose down` (add `-v` only for an intended data reset) | --- @@ -407,8 +412,10 @@ If you change the repository you should keep it deterministic. The following checks are safe to run locally from the repository root. ```bash -python 00_TOOLS/qa/check_markdown_links.py -python 00_TOOLS/qa/check_integrity.py +python3 -m venv .venv-qa +source .venv-qa/bin/activate +python -m pip install -r 00_TOOLS/qa/requirements.txt +python 00_TOOLS/qa/run_checks.py ``` If you edit Markdown or HTML, run formatting: @@ -417,8 +424,9 @@ If you edit Markdown or HTML, run formatting: npm install npm run format:check -# or offline -node format-offline.js --write +# or check line endings and final newlines without installing npm packages +node format-offline.js --check +# Use --write only when you intend to apply those limited formatting changes. ``` --- @@ -433,18 +441,17 @@ Do not point these exercises at public infrastructure. ## Licence and permitted use -This repository is distributed under a **Restrictive Educational Licence**. -You should read `LICENCE.md` before reuse. - -In practical terms: - -| Allowed without additional permission | Not allowed without explicit written permission | -| --- | --- | -| personal study, local execution and local modification | redistribution, mirroring and organised teaching outside ASE-CSIE | -| personal notes for private reference | commercial use and paid training | -| citation as required by the licence | publishing derivative works without meeting the licence conditions | - -### Citation format (required by the licence) +The author approved Option A for the v1.5.0 candidate on 17 November 2026. +[LICENCE.md](LICENCE.md) defines Category A educational content under CC BY-NC-SA +4.0, Category B source code and configuration under GPL-3.0-or-later and the +reserved Category C paths in [LICENCE_CATEGORY_C.txt](LICENCE_CATEGORY_C.txt). +Component-specific third-party terms and permissions already granted take +precedence. The applicable licence governs attribution and reuse; the policy +adds no commercial restriction, research-citation condition or automatic +co-authorship obligation to GPL-covered material. See the +[author decision and application record](00_TOOLS/qa/LICENCE_DECISION_PENDING.md). + +### Suggested academic citation ```text Clim, A. (2025). Computer Networks — Course Kit (EN). Bucharest University of Economic Studies (ASE), Faculty of Economic Cybernetics, Statistics and Informatics (CSIE). https://github.com/antonioclim/COMPNET-EN diff --git a/SPECIAL_REPORT.md b/SPECIAL_REPORT.md index e6dc7ba..9e07d00 100644 --- a/SPECIAL_REPORT.md +++ b/SPECIAL_REPORT.md @@ -1,4 +1,12 @@ -# Computer Networks Teaching Materials at Top Universities +> **Dated public-material comparison — 17 November 2026.** +> The [new descriptive report](00_APPENDIX/docs/comparison/2026-11-17/README.md) +> supplies a separate 18-unit, 180-cell evidence corpus. The historical text +> and scores below are preserved; their original derivation remains unverified. +> Use the new report for its explicitly dated claims and evidence limits. +> Current candidate-branch integration is recorded separately in the +> [integration note](00_TOOLS/qa/F3_R15_INTEGRATION.md). + +# Computer Networks Teaching Materials at Selected Universities ## A Comparative Analysis — Second Edition --- @@ -6,7 +14,7 @@
    **Comparative Study: Computer Networks Curricula** -*Top 50 QS/THE/ARWU Faculties vs. the COMPNET-EN / ASE-CSIE Course Kit* +*Exploratory comparison of selected public materials with the COMPNET-EN / ASE-CSIE course kit* --- @@ -17,9 +25,31 @@ --- +## Audit correction and interpretation — 17 November 2026 + +This is an exploratory author assessment, not a validated ranking or a systematic +review. Its February 2026 opinions, scores and adverse findings are retained as a +historical record. The unchanged original is available in the +[v1.4.0 baseline](https://github.com/antonioclim/COMPNET-EN/blob/v1.4.0/SPECIAL_REPORT.md). + +The source table names 13 entries, while the original narrative claimed 17 courses. +It does not supply the ranking edition, an operational inclusion rule, immutable +source snapshots or a search log sufficient to reproduce that selection. Dates +in that table are historical author-reported dates, not access dates established +by the v1.5.0 audit. The 1–10 scores lack an independently applied scoring rubric +and should be read as opinions. Absence from the listed public material does not +establish absence from a course, institution or the wider literature. + +The sections below correct identified bibliographic errors, distinguish current +CI from historical audit checks and qualify unsupported exclusivity/absence +claims. They do not manufacture a missing comparative dataset. Rebuilding the +external-source corpus with dated evidence is still required before this report +can support comparative research claims. Licence interpretation also remains +subject to the [author's pending decision](00_TOOLS/qa/LICENCE_DECISION_PENDING.md). + ## Disclaimer and Conflict of Interest -This report was written by one of the authors of the COMPNET-EN materials. The conflict of interest is therefore structural, not incidental, and no amount of careful phrasing eliminates it. What can be done — and what this second edition attempts more rigorously than the first — is to ground every claim in publicly verifiable artefacts: URLs, file counts, commit histories, and published papers. Where a claim cannot be independently verified, it is marked as such. +This report was written by one of the authors of the COMPNET-EN materials. The conflict of interest is therefore structural, not incidental, and no amount of careful phrasing eliminates it. What can be done — and what this second edition attempts more rigorously than the first — is to ground every claim in publicly verifiable artefacts: URLs, file counts, commit histories, and published papers. The audit correction above identifies important gaps in that aim; the historical comparison is not fully independently reproducible. The reader who wants to check the data should start at `https://github.com/antonioclim/COMPNET-EN` (the kit under evaluation), then visit the repositories and course pages listed in Section 2. Every factual assertion in this document is intended to be falsifiable against those sources. @@ -39,9 +69,9 @@ This second edition also attempts to correct a methodological weakness of the fi ### 1.2. Scope and Methodology -We examined **17 networking courses** from institutions ranked in the QS World University Rankings, Times Higher Education, and ARWU top 50 for Computer Science. The analysis is restricted to materials that are **publicly accessible** as of February 2026 — GitHub repositories, course websites, open educational platforms, and published papers. No materials behind login walls (Canvas, Moodle, Courseworks) were included. +The original narrative described **17 networking courses**, but only 13 entries are identified in the final source table and some links are too general to reproduce a course-level inspection. The intended scope was public GitHub repositories, course websites, open educational platforms and papers available in February 2026. The claimed Top 50 selection cannot be reconstructed without a ranking edition and inclusion rule. Authenticated course material was outside the stated scope. -**Reproducibility note:** Every URL cited in this report was accessed between 25 and 28 February 2026. The reader can verify all claims by visiting the cited sources. Where a repository has a commit history, the relevant commit date is noted. Where a course website may have changed since our access, the limitation is acknowledged. +**Historical access claim:** the original author reported access between 25 and 28 February 2026. This repository does not contain the corresponding access log and source snapshots; the present audit does not certify that retrospective claim. A live URL permits a new inspection, not exact reproduction of its historical contents. **Evaluation criteria (unchanged from v1.0, extended with C8–C10):** @@ -120,7 +150,7 @@ The following table documents what we could and could not access: | 🇭🇰 CUHK | CSCI 4430 | `henryhxu/CSCI4430` (54 ⭐, 863 commits) | ✅ Full | Fall 2025 | | 🇷🇴 ASE-CSIE | COMPNET-EN | `antonioclim/COMPNET-EN` | ✅ Full | Feb 2026 | -**Observation.** Of the 17 external courses examined, only roughly half (9–10) offer substantial publicly inspectable materials. MIT 6.5820 — often cited as a benchmark — has no current public materials beyond OCW archives from over two decades ago. Imperial College London has no publicly accessible networking course materials whatsoever. TU München distributes via SSH-authenticated Git and Moodle. These are not lesser courses; they are simply courses whose quality we cannot independently evaluate. +**Historical observation, limited to the recorded sources.** The original inspection reported substantial public material for roughly half of its intended sample. The listed sources do not establish the absence of current MIT or Imperial networking material across the web. Restricted-access examples illustrate a visibility limitation; they do not support a judgement that those courses lack the corresponding resources. This means the comparison that follows is inherently biased towards courses that *choose transparency*. The reader should weight conclusions accordingly. @@ -181,7 +211,7 @@ Topic coverage reveals a more interesting picture than raw week counts. The foll | Email Protocols | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | | FTP | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | -**Observation.** COMPNET-EN covers the broadest range of application-layer protocols among the courses examined. IoT/MQTT and gRPC appear in none of the other 17 courses. Email protocols (SMTP/POP3/IMAP) appear only in UCLouvain's textbook. This breadth comes at a cost: where Stanford allocates 3–4 weeks to incrementally building a TCP implementation, COMPNET-EN necessarily treats each topic at lesser depth. The trade-off is real, and whether breadth or depth is preferable depends on the programme's objectives. +**Observation.** COMPNET-EN includes IoT/MQTT, gRPC and email protocols. The original comparison did not identify equivalent coverage in several of its listed public sources, but its incomplete corpus cannot support an exhaustive breadth ranking or a claim that other courses omit these topics. This breadth comes at a cost: where Stanford allocates 3–4 weeks to incrementally building a TCP implementation, COMPNET-EN necessarily treats each topic at lesser depth. The trade-off is real, and whether breadth or depth is preferable depends on the programme's objectives. ### 3.2. Dimension C2: Code Quality @@ -290,7 +320,7 @@ GA Tech ────┼─────────┼────⚫──── **NPS Labtainers** is the closest structural parallel to COMPNET-EN's Docker philosophy: every lab is containerised, distributed via Docker Hub, and operated through a unified CLI. It offers over 50 labs covering networking and security. However, Labtainers is a *lab framework*, not a complete course kit with integrated lectures, quizzes, projects, and instructor notes. -**COMPNET-EN's 18 Docker Compose labs spanning the full 14-week semester, with a unified `lab_runner` and Portainer integration, is — to the best of our knowledge and based on publicly verifiable evidence — unmatched among semester-long undergraduate networking courses.** The external frameworks that come closest — Kathará (Roma Tre / Télécom Paris, used at KTH, UCLouvain) and Containerlab — are standalone tools, not integrated course kits. +**COMPNET-EN combines semester materials, registered Compose labs, `lab_runner` and Portainer guidance. The available comparison does not establish that this combination is unmatched.** The external frameworks that come closest — Kathará (Roma Tre / Télécom Paris, used at KTH, UCLouvain) and Containerlab — are standalone tools, not integrated course kits. ### 3.5. Dimension C5: Documentation @@ -371,42 +401,33 @@ CMU 15-441 ▓▓▓▓▓▓ 3 large multi- ### 3.7. Dimension C7: Interactive Elements -The first edition identified interactive HTML presentations as a differentiator. This remains true in the second edition: COMPNET-EN provides 101 HTML files across `04_SEMINARS/_HTMLsupport/` and `00_APPENDIX/b)optional_LECTURES/`, plus 10 HTML slide decks in the Python self-study guide. +The first edition identified interactive HTML presentations as a differentiator. This remains true in the second edition: The audited v1.4.0 repository contains 101 HTML files in total, including the ten Python slide decks, fourteen optional lecture decks and the Mininet setup guide. These are file counts, not evidence that every interactive behaviour has passed native-browser acceptance. -Among the 17 external courses examined, **UCLouvain's Sphinx-based ebook** is the closest parallel — it renders as an interactive web document with embedded exercises. Berkeley CS168's textbook (`textbook.cs168.io`) is web-based but read-only, without embedded quizzes or interactive elements. All other courses distribute materials as PDFs, PPTs, Google Slides, or pre-recorded video. +Among the 17 external courses examined, **UCLouvain's Sphinx-based ebook** is the closest parallel — it renders as an interactive web document with embedded exercises. Berkeley CS168's textbook (`textbook.cs168.io`) is web-based but read-only, without embedded quizzes or interactive elements. The other formats recorded in the original comparison include PDFs, presentations and video; this list does not establish that those courses lack interactive material elsewhere. -The claim from the first edition — that interactive HTML presentations with embedded quizzes and keyboard navigation remain a largely unexploited niche — still holds. +Interactive presentations remain a design choice of this kit. Establishing how widely that choice is used requires a reproducible external-source survey. ### 3.8. Dimension C8: Quality Assurance and CI/CD This dimension is new to the second edition and reflects what is arguably COMPNET-EN's most distinctive infrastructure investment. -**COMPNET-EN's CI/CD pipeline** (`.github/workflows/ci.yml`) runs on every push and pull request: +**Current v1.5.0 candidate CI** (`.github/workflows/ci.yml`) and local release +packaging use the same entry point: `python 00_TOOLS/qa/run_checks.py`. +The gate parses Python, checks executable permissions without first repairing +them, checks local Markdown links, runs the lexical integrity and PlantUML target +checks and executes the repository's collected Python regression tests. +Dependencies are installed from `00_TOOLS/qa/requirements.txt`. -1. Executable permissions normalisation from manifest (`apply_permissions.sh`) -2. Executable permissions verification (`check_executability.sh`) -3. Markdown relative link checking across 391 files, 2 231 targets (`check_markdown_links.py`) -4. Language and lexical integrity check — UTF-8 token validation, Romanian leakage control (`check_integrity.py`) -5. PlantUML figure target validation (`check_fig_targets.py --puml-only`) +The existing `QA_AUDIT_REPORT.md` is a historical audit document. Its Compose, +dependency and inventory observations are not automatically recurring CI checks. +The current gate does not start Docker, Mininet, VirtualBox or a native browser +and cannot establish acceptance in those environments. In particular, it does +not prove Compose service readiness merely by passing Python tests. -The **QA Audit Report** (`QA_AUDIT_REPORT.md`) additionally documents: -- Docker Compose YAML parse validation for all 28 config files -- `depends_on: service_healthy` sanity checks for all registered labs -- Python-image dependency risk scanning (detecting runtime failures from missing packages) -- Archive hygiene: no `__pycache__` or `.pyc` artefacts shipped - -Among all courses examined, the closest parallel is **KAIST CS341**, which has 4 GitHub Actions workflows testing builds on Linux, WSL, and macOS. **UCLouvain's ebook** uses Travis CI for automated builds. **No other networking course** in the sample shows evidence of CI/CD in its public repository. Stanford, CMU, Princeton, Georgia Tech, Michigan, Johns Hopkins, Berkeley, and CUHK have no visible CI/CD. - -| QA Feature | COMPNET-EN | KAIST | UCLouvain | NPS | All Others | -|:-----------|:----------:|:-----:|:---------:|:---:|:----------:| -| CI pipeline on push/PR | ✅ | ✅ | ✅ | regression | ❌ | -| Markdown link validation | ✅ (2 231 targets) | ❌ | ❌ | ❌ | ❌ | -| Docker Compose coherence | ✅ | ❌ | ❌ | ❌ | ❌ | -| Executable permission control | ✅ (96 manifest entries) | ❌ | ❌ | ❌ | ❌ | -| Lexical integrity / leakage | ✅ | ❌ | ❌ | ❌ | ❌ | -| Figure target validation | ✅ | ❌ | ❌ | ❌ | ❌ | - -This level of QA automation for *teaching materials* (as distinct from code) is, to our knowledge, without precedent in the courses examined. +The previous cross-institution CI comparison is an author observation with an +incomplete source corpus. No claim of unprecedented QA or universal absence of +CI in other courses is supported here. See [CI setup](00_APPENDIX/docs/ci_setup.md) +for the executable workflow and its limits. ### 3.9. Dimension C9: Academic Validation (Where COMPNET-EN Loses) @@ -416,43 +437,33 @@ This is the dimension that the first edition ignored and that the second edition | Course | Publication | Venue | Year | |:-------|:-----------|:------|:----:| -| ETH Zürich mini-Internet | "An Open Platform to Teach How the Internet Practically Works" | ACM SIGCOMM Education Workshop | 2020 | -| KAIST KENSv3 | "Teaching Networking by Building Protocol Stacks" | ACM SIGCSE (predecessor work) | 2015 | +| ETH Zürich mini-Internet | "An Open Platform to Teach How the Internet Practically Works" | ACM SIGCOMM Computer Communication Review, 50(2); also presented as Best of CCR at SIGCOMM | 2020 | +| KAIST KENSv2 (predecessor to KENSv3) | "An Educational Networking Framework for Full Layer Implementation and Testing" | ACM SIGCSE, pp. 663–668 | 2015 | | NPS Labtainers | "Individualizing Cybersecurity Lab Exercises with Labtainers" | IEEE Security & Privacy | 2018 | | NPS Labtainers | Conference demonstration | ACM SIGCSE | 2021 | | UCLouvain IPMininet | Multiple publications on INGInious and IPMininet | Various | 2014–2024 | -| SEED Labs (Du, Syracuse) | "SEED: A Suite of Instructional Laboratories" | ACM Journal on Educational Resources | 2011+ | +| SEED Labs (Du & Wang) | "SEED: A Suite of Instructional Laboratories for Computer Security Education" | ACM Journal on Educational Resources in Computing, 8(1), Article 3 | 2008 | -**COMPNET-EN has zero peer-reviewed publications, zero documented adoption beyond ASE-CSIE Bucharest, and limited external community engagement.** No GitHub stars/forks data suggests significant external usage. No conference presentation has described its approach. No measurable learning outcomes have been published. +**The source corpus attached to this report does not document peer-reviewed evaluation of COMPNET-EN, adoption beyond ASE-CSIE or measured learning outcomes.** No reproducible literature/adoption search log or dated repository-metrics dataset is supplied, so this is an evidence gap, not a demonstrated universal absence of publications, presentations or use. -This matters because, without external validation, the pedagogical claims made in this report — and in the kit's own documentation — rest entirely on the authors' assertions. The recently adopted multi-licence model (CC BY-NC-SA 4.0 for documentation, GPL-3.0 for code — see Section 3.10) removes the licensing barrier to external replication that existed in the first edition, but replication itself has not yet occurred. +This matters because, without external validation, the pedagogical claims made in this report — and in the kit's own documentation — rest entirely on the authors' assertions. The declared multi-licence model is discussed in Section 3.10, but its internal conflicts remain unresolved. Neither licensing clarity nor external replication can be inferred from the existing text alone. > *Self-criticism:* This is the single largest weakness of the COMPNET-EN project. Infrastructure without validation is engineering; validated infrastructure is scholarship. The transition from the first to the second requires work that has not yet been done. ### 3.10. Dimension C10: Licensing, Ecosystem, and Adoption -The value of a course kit is a function not only of its contents but of who can use it, adapt it, and build upon it. As of February 2026, COMPNET-EN has adopted a **multi-licence model** structurally aligned with UCLouvain CNP3: - -- **Category A (documentation, lectures, seminars, guides, diagrams, HTML presentations):** CC BY-NC-SA 4.0 — any institution may use, adapt, and translate for non-commercial teaching, provided attribution and ShareAlike conditions are met. -- **Category B (Python scripts, shell scripts, Dockerfiles, Compose configs, CI workflows, QA tools, lab_runner):** GPL-3.0-or-later — standard open-source copyleft; modifications must be published under the same licence. -- **Category C (quiz banks, formative quizzes, solution templates, PCAP validation rules, instructor outlines):** All Rights Reserved — access by bilateral agreement, protecting assessment integrity. +`LICENCE.md` declares CC BY-NC-SA 4.0 for educational content, +GPL-3.0-or-later for code and reserved rights for assessment material. It also +contains overlapping instructor-material categories and additional commercial-use +and co-authorship provisions. The v1.5.0 audit therefore does not treat the reuse +policy as resolved or rank its openness against other projects. -An additional clause requires co-authorship when materials constitute more than 20% of a derived published work. - -| Course/Framework | Licence Model | Non-Commercial Teaching | Adaptation Permitted | Institutional Adoption (documented) | -|:-----------------|:-------------|:-----------------------:|:--------------------:|:-----------------------------------:| -| NPS Labtainers | Public domain | ✅ | ✅ | Military + civilian; NSF-funded | -| SEED Labs (Syracuse) | Open | ✅ | ✅ | 1 180+ institutions worldwide | -| UCLouvain CNP3 ecosystem | CC BY-SA (ebook), GPL (exercises) | ✅ | ✅ | Multiple European universities | -| Kathará | GPL-3.0 | ✅ | ✅ | Roma Tre, Télécom Paris, KTH, UCLouvain | -| ETH mini-Internet | Apache-2.0 | ✅ | ✅ | Workshops, NANOG presentations | -| Stanford CS144 | — (no explicit licence) | ⚠️ | ⚠️ | Global self-study community (PKUFlyingPig fork) | -| KAIST KENSv3 | MIT | ✅ | ✅ | 151 GitHub stars | -| **COMPNET-EN** | **CC BY-NC-SA / GPL-3.0 / Reserved** | **✅** | **✅ (A+B)** | **ASE-CSIE Bucharest (elsewhere not yet documented)** | - -**What changed and why.** The first edition of this report identified the then-restrictive CC BY-NC-ND 4.0 licence as a structural impediment to community growth. That licence has since been replaced. COMPNET-EN now uses a tri-category model comparable in openness to UCLouvain, Kathará, and SEED Labs — the three projects with the strongest documented adoption trajectories. The non-commercial clause (NC in CC BY-NC-SA) is more restrictive than UCLouvain's CC BY-SA or NPS's public domain, but it is the same constraint applied by many OER projects and does not prevent academic adoption. - -**What has not changed.** The licence is a structural prerequisite for community growth, not a guarantee of it. No documented adoption outside ASE-CSIE Bucharest exists yet. No GitHub fork or star data suggests significant external usage. The licence change removes a barrier; whether the materials prove useful enough for others to invest in adapting them is a question that only time and the quality of the kit itself can answer. +The [pending decision record](00_TOOLS/qa/LICENCE_DECISION_PENDING.md) preserves +the issue and provides concrete alternatives for the author. The original +comparison and its adoption figures remain available in v1.4.0; they are not +repeated as current verified measurements. External adoption remains +**undocumented in the evidence supplied with this report**, which is different +from proving that no adoption exists. --- @@ -462,15 +473,15 @@ An additional clause requires co-authorship when materials constitute more than **What they do brilliantly:** The 8-checkpoint TCP/IP stack build is the gold standard for networking project pedagogy. The narrative coherence — each lab extending the previous one — creates a sense of architectural accumulation that discrete weekly projects cannot replicate. Code quality enforcement (clang-format, clang-tidy, sanitisers) is exemplary. -**What they lack publicly:** No Docker infrastructure (VM image only). No explicit pedagogical methodology documentation. No formative assessment tools. No instructor guides. +**Not identified in the original source selection (not an exhaustive absence claim):** No Docker infrastructure (VM image only). No explicit pedagogical methodology documentation. No formative assessment tools. No instructor guides. **Lesson for COMPNET-EN:** A single deep, narratively coherent project can teach more about TCP than fifteen separate briefs. The roadmap should consider a "capstone track" option alongside the existing catalogue. ### 4.2. ETH Zürich: The Infrastructure and Validation Model -**What they do brilliantly:** The mini-Internet project is unique in requiring class-wide cooperation at Internet scale. Each group operates a real AS. And critically, they *published the approach* at SIGCOMM'20, providing academic validation that others can cite and replicate. +**What they do brilliantly:** The mini-Internet project is unique in requiring class-wide cooperation at Internet scale. Each group operates a real AS. And critically, they *published the approach* in ACM SIGCOMM Computer Communication Review in 2020 and presented it as a Best of CCR paper at SIGCOMM, providing academic validation that others can cite and replicate. -**What they lack publicly:** No explicit pedagogical scaffolding. No interactive presentations. No formative quizzes. Limited documentation beyond the project itself. +**Not identified in the original source selection (not an exhaustive absence claim):** No explicit pedagogical scaffolding. No interactive presentations. No formative quizzes. Limited documentation beyond the project itself. **Lesson for COMPNET-EN:** Publication matters. The mini-Internet project is influential not only because it is good but because it is *documented in a peer-reviewed venue*. @@ -478,7 +489,7 @@ An additional clause requires co-authorship when materials constitute more than **What they do brilliantly:** The complete ecosystem — open textbook (3rd edition, 4th in progress), INGInious auto-graded exercises with PCAP field validation, IPMininet for topology creation, C socket exercises, network trace problems, over 40 GitHub repositories in the `cnp3` organisation — demonstrates what long-term sustained investment in open educational resources can achieve. -**What they lack:** Docker-native weekly labs. Interactive HTML presentations. Weekly quiz banks. The ebook is comprehensive but static (Sphinx rendering, no embedded interactivity). +**Scope distinction:** the CNP3 ecosystem includes INGInious interactive, auto-graded exercises as well as Sphinx-rendered textbook content. The original report does not establish the absence of interactivity from that ecosystem. A like-for-like comparison should distinguish textbook, presentation and assessment functions. **Lesson for COMPNET-EN:** Building an ecosystem takes years of consistent effort across textbook, tooling, and grading infrastructure. COMPNET-EN has the *breadth* but not yet the *longevity* or *external validation*. @@ -494,7 +505,7 @@ An additional clause requires co-authorship when materials constitute more than **What they do brilliantly:** The three multi-week projects (Mixnet, TCP, HTTP+video) are technically ambitious and industry-relevant. The custom Wireshark dissector and AWS EC2 testing infrastructure demonstrate serious investment. Recent offerings (Fall 2024) added a privacy-preserving mix network project — a contemporary topic that no other course in the sample addresses. -**What they lack publicly:** No CI/CD. No Docker for most work (custom VMs). No formative assessment tools visible. No instructor guides. +**Not identified in the original source selection (not an exhaustive absence claim):** No CI/CD. No Docker for most work (custom VMs). No formative assessment tools visible. No instructor guides. **Lesson for COMPNET-EN:** The Wireshark dissector idea is excellent — building custom protocol decoders forces students to think at the wire level. COMPNET-EN's PCAP tools (`pcap_stats.py`, `pcap_tshark_summary.py`) could evolve in this direction. @@ -504,7 +515,7 @@ An additional clause requires co-authorship when materials constitute more than ### 5.1. Evaluation Matrix -Scoring 1–10 per dimension, evaluated by the author with acknowledged bias. Scores reflect only what is publicly verifiable. "N/V" = not verifiable from public sources. +Historical author scores on a 1–10 scale are retained below, including unfavourable scores. They are not recomputed or validated by the audit: the original evidence matrix, calibration rules and independent ratings are absent. "N/V" means not verified by the original author from the selected public sources. The total is not a research result or a current ranking. | Course | C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8 | C9 | C10 | TOTAL | |:-------|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:---:|:-----:| @@ -523,7 +534,7 @@ Scoring 1–10 per dimension, evaluated by the author with acknowledged bias. Sc ### 5.2. Findings that Changed from the First Edition -1. **C1 (Comprehensiveness) raised from 7 to 8.** The first edition evaluated a kit that covered standard networking topics across 14 weeks but lacked IoT/MQTT, gRPC/modern RPC, and the 39 runnable micro-scenarios now embedded in lecture directories. The current kit is the broadest in the sample — no other course covers both IoT/MQTT and gRPC. The score does not reach 9 or 10 because Berkeley CS168 (17 weeks) and ETH Zürich (15 weeks, deeper per-topic) remain ahead in either duration or depth. +1. **C1 (Comprehensiveness) raised from 7 to 8.** The first edition evaluated a kit that covered standard networking topics across 14 weeks but lacked IoT/MQTT, gRPC/modern RPC, and the 39 runnable micro-scenarios now embedded in lecture directories. The kit includes both IoT/MQTT and gRPC; an exclusive breadth claim is not established by the recorded corpus. The score does not reach 9 or 10 because Berkeley CS168 (17 weeks) and ETH Zürich (15 weeks, deeper per-topic) remain ahead in either duration or depth. 2. **C2 (Code Quality) lowered from 7 to 6.** The first edition was generous. Without strict Python linting in CI, the score cannot match Stanford (10) or CMU (9). The `ruff.toml` exists but is not enforced. @@ -535,23 +546,30 @@ Scoring 1–10 per dimension, evaluated by the author with acknowledged bias. Sc 6. **C6 (Projects) adjusted from 9 to 8.** The 25 project briefs with E1/E2/E3 gates and PCAP validation rules are substantial, but honest comparison with Stanford's TCP stack build and CMU's multi-week systems projects requires acknowledging the depth gap. -7. **C8 (Quality Assurance) is a new dimension — scored 10.** No other course in the sample maintains a CI/CD pipeline that validates Markdown links (2 231 targets), Docker Compose coherence, executable permissions from a manifest, lexical integrity, and PlantUML figure targets on every push. KAIST CS341 is the closest with 4 GitHub Actions workflows, but their scope is build verification, not content quality assurance. - -8. **C9 (Academic Validation) is a new dimension — scored 2.** COMPNET-EN has zero peer-reviewed publications, zero documented adoption beyond ASE-CSIE Bucharest, and no conference presentations describing its approach. Compare this to ETH Zürich (SIGCOMM'20), KAIST (SIGCSE'15), NPS Labtainers (IEEE S&P'18, SIGCSE'21), and UCLouvain (multiple venues, 2014–2024). The asymmetry between C8 (10) and C9 (2) is itself a finding: engineering excellence and scholarly validation are independent dimensions. +7. **C8 (Quality Assurance) was scored 10 by the original author.** This score is retained as historical opinion. Compose coherence was not an every-push check in the inspected workflow. Section 3.8 now describes the actual shared gate; the cross-course exclusivity claim is withdrawn pending a reproducible comparison. -9. **C10 (Licensing) raised from 3 to 7.** The adoption of a multi-licence model (CC BY-NC-SA / GPL-3.0 / Reserved) replaces the CC BY-NC-ND 4.0 licence that the first edition flagged as a growth constraint. The new structure is comparable to UCLouvain and Kathará. The score remains below NPS (public domain, 10) and UCLouvain (CC BY-SA, 9) because the NC clause and the co-authorship requirement introduce frictions that fully permissive licences do not, and because no external adoption has yet been documented under the new terms. +8. **C9 (Academic Validation) is a new dimension — scored 2.** The supplied corpus does not document peer-reviewed evaluation, external adoption or conference presentations describing COMPNET-EN; it does not demonstrate their universal absence. Compare this to ETH Zürich (SIGCOMM'20), KAIST (SIGCSE'15), NPS Labtainers (IEEE S&P'18, SIGCSE'21), and UCLouvain (multiple venues, 2014–2024). The asymmetry between C8 (10) and C9 (2) is itself a finding: engineering excellence and scholarly validation are independent dimensions. -### 5.3. Main Conclusions +9. **C10 (Licensing) was raised from 3 to 7 by the original author.** That +historical opinion is retained in the matrix. The current audit identified +conflicting terms and overlapping categories, so the score must not be used as +evidence that the licensing barrier has been resolved. -1. **COMPNET-EN occupies a distinctive niche.** It is arguably the most infrastructure-complete, pedagogically explicit, and operationally detailed single-repository networking course kit that is publicly accessible. This is a verifiable claim: the reader can check the file counts, the CI pipeline, the QA report, and the documentation against any other course in the sample. +### 5.3. Qualified conclusions -2. **No single course excels across all dimensions.** Stanford dominates project depth and code quality. ETH Zürich dominates infrastructure ambition and academic validation. UCLouvain dominates ecosystem breadth and formative assessment. NPS dominates lab variety and assessment integrity. Berkeley dominates textbook quality. COMPNET-EN dominates operational completeness, QA automation, and pedagogical documentation. The landscape is fragmented. - -3. **The validation gap is the critical weakness.** Without peer-reviewed publication, documented learning outcomes, and multi-institutional adoption, COMPNET-EN's claims rest on self-assessment. This report is itself an instance of the problem: a self-evaluation cannot substitute for external review. - -4. **The licence model is now structurally aligned with the field.** The adoption of a multi-licence model (CC BY-NC-SA for documentation, GPL-3.0 for code, all-rights-reserved for examination materials) removes the licensing barrier identified in the first edition. COMPNET-EN now uses a structure comparable to UCLouvain CNP3, Kathará, and SEED Labs — the three projects with the strongest documented adoption trajectories. Whether the materials attract external adoption remains an open question, but the licence is no longer the obstacle. - -5. **The breadth-versus-depth trade-off is real.** COMPNET-EN covers IoT/MQTT, gRPC, email protocols, SDN, load balancing, and security across 14 weeks. No other course in the sample matches this breadth. But no other course in the sample sacrifices as much depth per topic, either. The design philosophy prioritises survey completeness over implementation mastery. +1. COMPNET-EN combines lectures, practical examples, diagrams, project briefs, + quizzes and operational tools in one repository. Their presence is directly + inspectable; comparative superiority is not established by file counts. +2. The original case studies suggest useful design alternatives: sustained + systems projects, shared network infrastructure, integrated assessment and + companion textbooks. The historical scores express the author's priorities. +3. Evidence of learning effectiveness and independent evaluation remains a gap + in the supplied corpus. Self-assessment cannot substitute for those studies. +4. The licence policy requires an explicit author decision before its reuse + conditions can be described coherently. +5. The breadth-versus-depth trade-off remains a useful design question. The kit + covers IoT/MQTT, gRPC, email, SDN, load balancing and security in fourteen weeks; + comparisons of achieved student mastery require outcome data. ### 5.4. Limitations of This Analysis @@ -577,7 +595,9 @@ Scoring 1–10 per dimension, evaluated by the author with acknowledged bias. Sc | CMU 15-441 | Build custom Wireshark dissectors for student protocols | Low | | Berkeley CS168 | Develop a companion open textbook or integrate with existing open textbooks | Long-term | -### 6.2. Proposed Roadmap +### 6.2. Historical proposed roadmap + +The following dates were proposed in the original report. They are not a record of completed work, accepted publications, funded activity or approved institutional commitments. ``` 2026 Q1–Q2 ─────► Enforce Python linting in CI (ruff strict, mypy) @@ -608,7 +628,7 @@ Thanks are also owed to the open-source communities behind Docker, Wireshark, Pl ### Courses Analysed -| # | University | Course | Primary Public URL | Last Verified | +| # | University | Course | Primary Public URL | Historical date claimed | |:-:|:-----------|:-------|:-------------------|:-------------:| | 1 | Stanford | CS144 | `cs144.github.io` / `github.com/CS144` | Dec 2025 | | 2 | ETH Zürich | 227-0120-00L | `github.com/nsg-ethz/mini_internet_project` | Dec 2025 | @@ -626,11 +646,12 @@ Thanks are also owed to the open-source communities behind Docker, Wireshark, Pl ### Peer-Reviewed Publications Referenced -- Holterbach, T. et al. (2020). "An Open Platform to Teach How the Internet Practically Works." *ACM SIGCOMM Education Workshop*. -- Thompson, M. F. et al. (2018). "Individualizing Cybersecurity Lab Exercises with Labtainers." *IEEE Security & Privacy*, 16(2). -- Du, W. (2011+). "SEED: A Suite of Instructional Laboratories for Computer Security Education." *ACM Journal on Educational Resources in Computing*. -- Brown, N. C. C. & Wilson, G. (2018). "Ten Quick Tips for Teaching Programming." *PLOS Computational Biology*. -- Mazur, E. (1997). *Peer Instruction: A User's Manual*. Prentice Hall. +- Holterbach, T., Bühler, T., Rellstab, T., & Vanbever, L. (2020). An open platform to teach how the Internet practically works. *ACM SIGCOMM Computer Communication Review, 50*(2). https://doi.org/10.1145/3402413.3402420 +- Thompson, M. F., & Irvine, C. E. (2018). Individualizing cybersecurity lab exercises with Labtainers. *IEEE Security & Privacy, 16*(2), 91–95. https://doi.org/10.1109/MSP.2018.1870862 +- Du, W., & Wang, R. (2008). SEED: A suite of instructional laboratories for computer security education. *ACM Journal on Educational Resources in Computing, 8*(1), Article 3. https://doi.org/10.1145/1348713.1348716 +- Lee, K., Kim, J., & Moon, S. (2015). An educational networking framework for full layer implementation and testing. In *Proceedings of the 46th ACM Technical Symposium on Computer Science Education* (pp. 663–668). ACM. https://doi.org/10.1145/2676723.2677304 +- Brown, N. C. C., & Wilson, G. (2018). Ten quick tips for teaching programming. *PLOS Computational Biology, 14*(4), e1006023. https://doi.org/10.1371/journal.pcbi.1006023 +- Mazur, E. (1997). *Peer instruction: A user's manual*. Prentice Hall. https://mazur.harvard.edu/publications/peer-instruction-users-manual - Parsons, D. & Haden, P. (2006). "Parson's Programming Puzzles: A Fun and Effective Learning Tool for First Programming Courses." *Australasian Computing Education Conference*. ### Frameworks and Tools Referenced @@ -652,8 +673,8 @@ Thanks are also owed to the open-source communities behind Docker, Wireshark, Pl --- -*Last updated: 28 February 2026* -*Document version: 2.0* +*Historical report: 28 February 2026; audit corrections: 17 November 2026*
    +*Document version: 2.0 with v1.5.0 audit corrections*
    *Kit version: v13.05.00* *Repository: `github.com/antonioclim/COMPNET-EN`* diff --git a/format-offline.js b/format-offline.js index 008ef66..162dfeb 100755 --- a/format-offline.js +++ b/format-offline.js @@ -3,8 +3,8 @@ * format-offline.js * * Deterministic formatting pass for Markdown and HTML files. - * Replicates the subset of Prettier behaviour configured in .prettierrc - * (proseWrap: preserve, printWidth: 120, endOfLine: lf, tabWidth: 2). + * Preserves significant whitespace; only converts CRLF line endings and adds + * a missing final newline. Syntax-aware formatting remains a separate task. * * Usage: * node format-offline.js --check # exit 1 if any file would change @@ -57,47 +57,24 @@ function collectFiles(root) { } // ── Markdown formatter ──────────────────────────────────────────────── -function formatMarkdown(src) { - let out = src; - - // 1. Normalise line endings to LF - out = out.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); - - // 2. Trim trailing whitespace on every line - out = out.replace(/[ \t]+$/gm, ""); - - // 3. Collapse runs of 3+ blank lines into exactly 2 newlines (one blank line) - out = out.replace(/\n{3,}/g, "\n\n"); - - // 4. Ensure single trailing newline - out = out.trimEnd() + "\n"; - - return out; -} - -// ── HTML formatter ──────────────────────────────────────────────────── -function formatHTML(src) { - let out = src; - - // 1. Normalise line endings to LF - out = out.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); - - // 2. Trim trailing whitespace per line - out = out.replace(/[ \t]+$/gm, ""); - - // 3. Collapse runs of 3+ blank lines into 2 newlines - out = out.replace(/\n{3,}/g, "\n\n"); - - // 4. Ensure single trailing newline - out = out.trimEnd() + "\n"; - - return out; +// This conservative pass deliberately preserves whitespace inside Markdown code, +// hard line breaks and HTML pre/script/style content. It is not a Prettier clone. +function normaliseText(src) { + const out = src.replace(/\r\n/g, "\n"); + return out.endsWith("\n") || out.length === 0 ? out : out + "\n"; } +function formatMarkdown(src) { return normaliseText(src); } +function formatHTML(src) { return normaliseText(src); } // ── Main ────────────────────────────────────────────────────────────── function main() { const args = process.argv.slice(2); const mode = args[0] || "--check"; + if (!["--check", "--write", "--list"].includes(mode)) { + console.error("Usage: node format-offline.js --check|--write|--list"); + process.exitCode = 2; + return; + } const root = path.resolve(__dirname); const files = collectFiles(root); @@ -134,4 +111,5 @@ function main() { } } -main(); +module.exports = { formatMarkdown, formatHTML }; +if (require.main === module) main();

    ${key}${serverState[key]}