diff --git a/00_TOOLS/Portainer/INIT_GUIDE/PORTAINER_SETUP.md b/00_TOOLS/Portainer/INIT_GUIDE/PORTAINER_SETUP.md index 12768b7..6ba823e 100644 --- a/00_TOOLS/Portainer/INIT_GUIDE/PORTAINER_SETUP.md +++ b/00_TOOLS/Portainer/INIT_GUIDE/PORTAINER_SETUP.md @@ -1,218 +1,153 @@ # Portainer CE — Installation and Configuration Guide -| | | -|---|---| -| **Course** | Computer Networks — COMPNET (ASE-CSIE) | -| **Port** | `9050` — verified conflict-free across the entire repository | -| **Credentials** | `stud` / `studstudstud` | -| **Image** | `portainer/portainer-ce:2.21-alpine` | - ---- - -## 1 Why port 9050 (not 9000) - -Port 9000 is taken by S10 Part 4, where the SSH tunnel command is `ssh -L 9000:web:8000`. That exercise is hardcoded across two dozen references in seminar materials, instructor outlines and task sheets — changing it would be disruptive. +Portainer provides a browser interface to the Docker daemon used by the exercises. It is optional for command-line Docker work. -Port 9090 is likewise occupied by the C08 TCP handshake scenario and several socket examples in the Python self-study guide. +| Setting | Course default | +|---|---| +| Host HTTP address | `127.0.0.1:9050` | +| Container HTTP port | `9000` | +| Initial lab account | `stud` / `studstudstud` | +| Image selected by this kit | `portainer/portainer-ce:2.21-alpine` | +| Data volume | `portainer_data` | -Port 9050 returned zero hits when searched against every `.md`, `.yml`, `.py`, `.conf` and `.html` file in the repository. It is safe to claim. +Port 9000 is used by the S10 SSH tunnel exercise. The external Portainer port is therefore 9050. The default image is a version-family tag rather than a digest; record the actual installed image when preparing a fixed teaching release. These instructions do not upgrade the image embedded in MININET-SDN. ---- +## 1. Choose the execution environment -## 2 Prerequisites +**MININET-SDN VirtualBox route:** connect to the VM and run Linux commands there. Docker Desktop and the PowerShell Portainer installer are not required on Windows. The working appliance already supplies its Docker environment; do not replace its packages as part of this optional installation. -You need Docker Engine 20.10 or later (Docker Desktop on Windows, or Docker Engine inside the VM), Docker Compose v2 (bundled with Docker Desktop) and a modern browser. Port 9050 must be free on the host — if something else is already bound there, the container will fail to start with a clear error message. +**WSL2 route:** run Linux commands in the Ubuntu distribution containing Docker Engine. Windows Python and a second Docker daemon on Windows are separate environments. ---- +**Docker Desktop route:** run the PowerShell script on Windows with Docker Desktop running in Linux-containers mode. This operates on the local Desktop engine, not the VirtualBox guest. -## 3 Installation — Recommended: Docker Compose +All routes require a responsive local Linux Docker daemon. The Bash installer also checks for `curl`, `python3`, `ss` and `mktemp`. The scripts reject remote Docker contexts because a remote daemon cannot be reached through the local loopback URL used by this setup. -The cleanest approach. Use the `docker-compose-portainer.yml` provided in this directory. +## 2. Automated setup -**Windows (PowerShell):** +Run from this directory in the intended environment. -```powershell -cd \00_TOOLS\Portainer\INIT_GUIDE - -docker compose -f docker-compose-portainer.yml up -d -``` - -**Linux / VM (Bash):** +### Linux, WSL or MININET-SDN guest ```bash -cd /00_TOOLS/Portainer/INIT_GUIDE - -docker compose -f docker-compose-portainer.yml up -d +bash portainer-init.sh ``` -The Compose file creates a container named `portainer`, a named volume `portainer_data` for persistence, maps `9050 → 9000` (host → container) and sets a restart policy of `unless-stopped` so Portainer survives reboots. - -**Quick verification:** +For an existing account with different credentials, supply its actual details without resetting the account: -```text -docker ps --filter name=portainer --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" - -NAMES STATUS PORTS -portainer Up 2 minutes 0.0.0.0:9050->9000/tcp, :::9050->9000/tcp +```bash +read -r -p 'Portainer username: ' PORTAINER_USER +read -r -s -p 'Portainer password: ' PORTAINER_PASSWORD +printf '\n' +export PORTAINER_USER PORTAINER_PASSWORD +bash portainer-init.sh +unset PORTAINER_USER PORTAINER_PASSWORD ``` ---- - -## 4 Installation — Alternative: single command +Optional environment variables are `PORTAINER_IMAGE`, `PORTAINER_NAME`, `PORTAINER_PORT`, `PORTAINER_VOLUME`, `PORTAINER_USER` and `PORTAINER_PASSWORD`. Set these only for a deliberate alternative instance. Changing the requested port or volume does not reconfigure an existing container automatically. -If you prefer not to use the Compose file, a one-liner does the same thing. - -**Windows (PowerShell):** +### Windows with Docker Desktop ```powershell -docker volume create portainer_data - -docker run -d -p 9050:9000 ` - --name portainer ` - --restart unless-stopped ` - -v /var/run/docker.sock:/var/run/docker.sock ` - -v portainer_data:/data ` - portainer/portainer-ce:2.21-alpine -``` - -**Linux / VM (Bash):** - -```bash -docker volume create portainer_data - -docker run -d -p 9050:9000 \ - --name portainer \ - --restart unless-stopped \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v portainer_data:/data \ - portainer/portainer-ce:2.21-alpine +powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\portainer-init.ps1 ``` ---- - -## 5 Installation — Automated scripts +This execution-policy choice applies to the new PowerShell process. The script requires no administrator elevation of its own, although Docker Desktop must already be installed and accessible. -For bulk provisioning (e.g. pre-configuring lab workstations), two scripts are included. They pull the image, create the volume, start the container, wait for the API to become available and create the admin user programmatically. - -**Windows:** +For an existing Portainer account: ```powershell -.\portainer-init.ps1 +$portainerCredential = Get-Credential -UserName stud -Message 'Existing Portainer account' +.\portainer-init.ps1 -User $portainerCredential.UserName -Password ($portainerCredential.GetNetworkCredential().Password) +Remove-Variable portainerCredential ``` -**Linux / VM:** +The script accepts `-Image`, `-Name`, `-Port`, `-Volume`, `-User` and `-Password`. -```bash -chmod +x portainer-init.sh -./portainer-init.sh -``` +### What the scripts verify -Both scripts are idempotent — running them a second time detects the existing container and recreates it cleanly. +The scripts check the Docker daemon, its Linux container mode and the requested local binding. They preserve existing containers and volumes, reuse a matching instance and download the image only when it is absent locally. They then require a responding Portainer API, successful authentication and `OK` from the local Docker endpoint through Portainer. ---- +A failed login, failed endpoint registration or HTTP 500 produces an error exit. An existing administrator is not treated as proof that the supplied password works. An existing service with a different binding or volume remains untouched and is reported for review. -## 6 First-time browser setup +A successful setup check verifies these management operations. It does not execute every networking seminar or validate a different Docker/Portainer version pair. -1. Open `http://localhost:9050`. +## 3. Open the interface -2. If this is the first launch (no admin user yet), you will see a registration form: - - **Username:** `stud` - - **Password:** `studstudstud` (exactly 12 characters — Portainer's minimum) - - Confirm the password, then click **Create user**. +### Docker Desktop or WSL2 -3. On the next screen, click **Get Started**. Portainer detects the local Docker socket automatically. +Open `http://localhost:9050` in the Windows browser. In WSL, if the Linux API responds but the Windows page does not, check WSL's localhost forwarding and the actual Docker context; do not replace the container to fix an unrelated host-access problem. -4. You should now see the **Home** dashboard with one environment ("local") showing container, image, volume and network counts. +### VirtualBox guest from Windows -**If you miss the 5-minute window:** Portainer enforces a timeout on admin creation after first boot. If the form disappears and you see a "timed out" message, recreate from scratch: +The guest's `127.0.0.1` is different from Windows' `127.0.0.1`. With the course SSH forwarding already configured (`127.0.0.1:2222` on Windows to guest port 22), open a Windows terminal and run: -```bash -docker stop portainer && docker rm portainer -docker volume rm portainer_data -# re-run the install command from Section 3 or 4 +```powershell +ssh -N -p 2222 -L 127.0.0.1:9050:127.0.0.1:9050 stud@127.0.0.1 ``` -The automated scripts (Section 5) avoid this problem entirely by creating the user through the API. - ---- +Use the guest's confirmed SSH login. Keep that terminal open, then browse to `http://127.0.0.1:9050` on Windows. Stop the tunnel with Ctrl+C when finished. -## 7 What the dashboard shows you +If Windows port 9050 is already used by another Docker environment, use a different **Windows** port without changing Portainer in the VM: -### Containers view - -The main table lists every container with its name, state (running / stopped / exited), image, creation timestamp, internal IP and published ports. From here you can start, stop, restart or remove containers, and jump straight to their logs or an interactive console. - -### Networks view +```powershell +ssh -N -p 2222 -L 127.0.0.1:19050:127.0.0.1:9050 stud@127.0.0.1 +``` -Lists all Docker networks with driver, subnet, gateway and connected containers. Click a network to see which containers are attached and what IPs they hold — this is the visual equivalent of `docker network inspect`, minus the JSON. +Then open `http://127.0.0.1:19050`. This tunnel requires the SSH service and the matching VirtualBox SSH rule; it does not require exposing the Docker API or Portainer to the LAN. -### Container detail — Logs +## 4. Compose alternative -Live tail with auto-scroll, timestamp toggle and in-log search. You can also download the full log as a text file. +For a new instance, the included Compose file starts the container: -### Container detail — Console +```bash +docker compose -f docker-compose-portainer.yml up -d +``` -Opens a browser-based terminal (`/bin/sh` or `/bin/bash`) inside the container. This is exactly `docker exec -it sh`, but without needing to remember the container name or switch to a terminal window. +The Compose file does **not** create the administrator or authenticate to Docker. Use the browser for initial setup, or run the matching installer afterwards to perform those steps and its checks. Do not run Compose over an existing unmanaged container of the same name expecting an automatic migration. ---- +The named volume retains the database across container restarts. Avoid `down -v` and volume deletion when preserving accounts and settings. -## 8 Day-to-day management +## 5. First browser setup -Starting Portainer (after a reboot or manual stop): +If the administrator has not been initialised, create the lab account shown above or the account selected for your deployment, then connect the local Docker socket through the environment wizard. Portainer may time out an uninitialised installation. Restart the container and complete setup promptly: ```bash -docker start portainer +docker restart portainer ``` -Stopping Portainer to free resources: - -```bash -docker stop portainer -``` +A message saying that Portainer is already initialised means an account already exists; use that account. Deleting the volume is not the remedy for an unknown password or a timed-out setup page. -Removing Portainer entirely: +## 6. Daily use ```bash -docker stop portainer && docker rm portainer -docker volume rm portainer_data -``` - -Updating the image: +# Status, binding and diagnostic logs +docker ps -a --filter name=portainer --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' +docker logs --tail 80 portainer -```bash -docker stop portainer && docker rm portainer -docker pull portainer/portainer-ce:2.21-alpine -# re-run the install command — the volume is preserved +# Stop or restart this management interface +docker stop portainer +docker start portainer ``` ---- - -## 9 Troubleshooting +Do not stop an unrelated service merely because it occupies port 9050. Select another intentional host port, or close the competing instance after identifying it. -| What you see | Likely cause | What to do | -|---|---|---| -| `localhost:9050` does not load | Container is not running | `docker start portainer` | -| Registration form is gone, no login prompt | Admin-creation timeout (5 min) | Remove container + volume, reinstall | -| "Port 9050 already in use" on start | Something else is bound to 9050 | Windows: `netstat -ano \| findstr :9050` — note the PID, then kill it. Linux: `ss -tlnp \| grep 9050` | -| "Permission denied" on Docker socket | Linux user not in `docker` group | Run with `sudo`, or `sudo usermod -aG docker $USER` then re-login | -| Portainer shows 0 containers | Wrong environment selected | Home → click the "local" environment tile | -| Compose containers not visible | Mismatched Docker context | `docker context ls` — the active context must be "default" | +## 7. Troubleshooting ---- - -## 10 A note on security - -Portainer mounts the Docker socket, which gives it full control over the Docker daemon. In a local lab environment this is perfectly fine — the workstation is not exposed to the internet, the VM is disposable and the credentials are shared lab credentials. +| Symptom | Action | +|---|---| +| Docker CLI missing or daemon unavailable | Start the intended engine and confirm `docker info`; the installer does not install Docker | +| Linux socket permission denied | Check membership of the Docker group and re-login if it was just changed; do not run the Windows installer against the guest | +| Existing container has another binding or volume | Inspect it and retain its data; the installer refuses automatic replacement | +| API works in VM but Windows page fails | Use the SSH tunnel in section 3 and confirm the guest SSH port forwarding | +| Administrator already exists, login fails | Use the existing credentials; no password reset occurs | +| API starts but local endpoint cannot communicate | Inspect `docker logs`, the socket mount and the selected engine/image compatibility | +| Image unavailable and no internet | Obtain the selected image beforehand; a failed pull does not delete the existing instance | +| HTTP 500 during environment registration | Treat as a server error, inspect the logs and do not label it “already configured” | -In a production setting, Portainer would sit behind TLS, enforce role-based access control and restrict network exposure. That distinction is worth a brief mention when you introduce the tool at S09 — it plants the seed for S13's discussion of attack surfaces. +## 8. Scope and upstream references ---- +Binding to loopback keeps the shared teaching login off the LAN. Portainer has administrative control over the selected Docker daemon through its socket. The course configuration is for the local teaching environment. -## 11 Files in this directory +The automation retains the existing image choice and does not promise compatibility with every newer Docker engine. The executable check must pass for the actual pair used. Consult [Portainer's API documentation](https://docs.portainer.io/api/docs) and [installation documentation](https://docs.portainer.io/start/install-ce/server/docker/linux) when selecting a different version. -| File | What it does | -|------|-------------| -| `PORTAINER_SETUP.md` | This guide | -| `docker-compose-portainer.yml` | Declarative Portainer deployment | -| `portainer-init.ps1` | Automated setup for Windows (PowerShell) | -| `portainer-init.sh` | Automated setup for Linux / VM (Bash) | +Scalar endpoint fields in the selected 2.21 API are read through [`Request.FormValue`](https://github.com/portainer/portainer/blob/2.21.5/pkg/libhttp/request/request.go). The Bash script uses multipart form fields; the Windows PowerShell 5.1 script uses URL-encoded scalar form fields for the local socket endpoint. diff --git a/00_TOOLS/Portainer/INIT_GUIDE/README.md b/00_TOOLS/Portainer/INIT_GUIDE/README.md index fae1a56..1a59b80 100644 --- a/00_TOOLS/Portainer/INIT_GUIDE/README.md +++ b/00_TOOLS/Portainer/INIT_GUIDE/README.md @@ -1,63 +1,41 @@ -# Portainer — Installation and Configuration Guide +# Portainer — Installation and Configuration -Pre-semester setup for Portainer Community Edition on port 9050. Students (or instructors) run this once; the container persists across all Docker-heavy seminars from week 8 onwards. +Portainer is optional: Docker commands can run without its web interface. The course uses host port **9050**, with the HTTP listener bound to **127.0.0.1**. Port 9000 is available for the S10 SSH tunnel exercise. -## File Index +## Choose the machine that runs Docker -| File | Description | Lines | +| Docker runs in | Use | Browser access | |---|---|---| -| [`PORTAINER_SETUP.md`](PORTAINER_SETUP.md) | Step-by-step installation guide covering Windows (PowerShell) and Linux/WSL (Bash) paths | 218 | -| [`docker-compose-portainer.yml`](docker-compose-portainer.yml) | Declarative Compose file — the recommended deployment method | 23 | -| [`portainer-init.ps1`](portainer-init.ps1) | PowerShell automation script for Windows hosts | 153 | -| [`portainer-init.sh`](portainer-init.sh) | Bash automation script for Linux/WSL hosts | 121 | +| MININET-SDN VirtualBox guest | `bash portainer-init.sh` inside the guest | SSH tunnel described in the [setup guide](PORTAINER_SETUP.md) | +| Ubuntu in WSL2 | `bash portainer-init.sh` inside that distribution | Windows `http://localhost:9050`, subject to WSL localhost forwarding | +| Docker Desktop on Windows, Linux containers | `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\portainer-init.ps1` | Windows `http://localhost:9050` | -## Usage +The Windows script does not install or manage Docker inside the VirtualBox guest. Do not install Docker Desktop merely to use Docker already running in MININET-SDN. -The fastest path is the Compose file: +## Files -```bash -docker compose -f docker-compose-portainer.yml up -d -``` - -Then open `http://localhost:9050` and log in with `stud` / `studstudstud`. - -For automated setup with health checks and credential pre-configuration, use the platform-appropriate script: - -```bash -# Linux / WSL -bash portainer-init.sh - -# Windows PowerShell -.\portainer-init.ps1 -``` - -## Design Rationale - -Port 9050 was chosen because port 9000 is reserved for the S10 SSH tunnel exercise and port 9090 is occupied by C08 TCP handshake scenarios. The Compose file pins the image to `portainer/portainer-ce:2.21-alpine` for reproducibility. +| File | Purpose | +|---|---| +| [PORTAINER_SETUP.md](PORTAINER_SETUP.md) | Import route, commands, access and troubleshooting | +| [docker-compose-portainer.yml](docker-compose-portainer.yml) | Declarative container setup; initial administrator setup is separate | +| [portainer-init.sh](portainer-init.sh) | Local Linux/WSL/VM setup with API, login and Docker connectivity checks | +| [portainer-init.ps1](portainer-init.ps1) | Local Windows Docker Desktop setup; PowerShell 5.1 syntax | -## Cross-References +The scripts preserve existing containers, accounts and volumes. They reuse a matching local instance or stop with a diagnostic if it differs. They do not reset existing passwords, delete data or update an existing image automatically. An uncached image requires internet access. A cached image can be used without pulling it again. -| Aspect | Link | -|---|---| -| Parent guide | [`../README.md`](../README.md) | -| Docker prerequisites | [`../../Prerequisites/Prerequisites.md`](../../Prerequisites/Prerequisites.md) | -| First use in class | [`../SEMINAR08/S08_PORTAINER_TEASER.md`](../SEMINAR08/S08_PORTAINER_TEASER.md) | -| First full introduction | [`../SEMINAR09/S09_PORTAINER_GUIDE.md`](../SEMINAR09/S09_PORTAINER_GUIDE.md) | +The default image remains the kit's `portainer/portainer-ce:2.21-alpine`. This tag identifies a version family, not an immutable image digest. A successful API and Docker check is required for the selected Docker/Portainer pair; the tag alone does not establish compatibility with every Docker release. -No other repository components reference this directory directly. The setup is a one-time operation with no downstream CI or build dependencies. +## Related materials -## Selective Clone Instructions +- [MININET-SDN setup](../../../01_GUIDE_MININET-SDN/) +- [Alternative WSL2 prerequisites](../../Prerequisites/Prerequisites.md) +- [Portainer in S08](../SEMINAR08/S08_PORTAINER_TEASER.md) +- [Portainer in S09](../SEMINAR09/S09_PORTAINER_GUIDE.md) -**Method A — Git sparse-checkout (Git 2.25+)** +## Selective checkout ```bash git clone --filter=blob:none --sparse https://github.com/antonioclim/COMPNET-EN.git cd COMPNET-EN git sparse-checkout set 00_TOOLS/Portainer/INIT_GUIDE ``` - -**Method B — Direct download (no Git required)** - -``` -https://github.com/antonioclim/COMPNET-EN/tree/main/00_TOOLS/Portainer/INIT_GUIDE -``` diff --git a/00_TOOLS/Portainer/INIT_GUIDE/docker-compose-portainer.yml b/00_TOOLS/Portainer/INIT_GUIDE/docker-compose-portainer.yml index 4230bad..4750591 100644 --- a/00_TOOLS/Portainer/INIT_GUIDE/docker-compose-portainer.yml +++ b/00_TOOLS/Portainer/INIT_GUIDE/docker-compose-portainer.yml @@ -4,7 +4,7 @@ # Port : 9050 → 9000 (9000 reserved by S10 SSH tunnel, # 9090 reserved by C08 TCP scenarios) # Access: http://localhost:9050 -# Login : stud / studstudstud +# Initial account is created separately; this Compose file does not set it. # ───────────────────────────────────────────────────── services: @@ -13,7 +13,7 @@ services: container_name: portainer restart: unless-stopped ports: - - "9050:9000" + - "127.0.0.1:9050:9000" volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - portainer_data:/data diff --git a/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.ps1 b/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.ps1 index b27f020..92d4028 100644 --- a/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.ps1 +++ b/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.ps1 @@ -1,153 +1,173 @@ -<# -.SYNOPSIS - Automated Portainer CE setup for the COMPNET lab environment. - -.DESCRIPTION - Pulls the Portainer image, creates a persistent volume, starts the - container on port 9050, waits for the API to respond and creates the - admin user (stud / studstudstud) without manual browser interaction. - -.NOTES - Port : 9050 (9000 is reserved by S10 SSH tunnel) - Credentials : stud / studstudstud - Requires : Docker Desktop running in Linux-containers mode +<# +Local Windows Docker Desktop setup. Requires Linux-containers mode. +For Docker inside MININET-SDN, run portainer-init.sh INSIDE that VM instead. +Existing containers, accounts and data volumes are never deleted or reset. +Windows PowerShell 5.1 compatible syntax; native Windows validation is separate. #> - +#requires -Version 5.1 +[CmdletBinding()] param( - [string] $Image = "portainer/portainer-ce:2.21-alpine", - [string] $Name = "portainer", - [int] $Port = 9050, - [string] $Volume = "portainer_data", - [string] $User = "stud", - [string] $Password = "studstudstud" + [string]$Image = 'portainer/portainer-ce:2.21-alpine', + [string]$Name = 'portainer', + [ValidateRange(1,65535)][int]$Port = 9050, + [string]$Volume = 'portainer_data', + [string]$User = 'stud', + [string]$Password = 'studstudstud' ) +Set-StrictMode -Version 2.0 +$ErrorActionPreference = 'Stop' -$ErrorActionPreference = "Stop" - -function Write-Step ([string] $Msg) { - Write-Host "`n>> $Msg" -ForegroundColor Cyan -} - -# ── 1 Check Docker ────────────────────────────────────────────── -Write-Step "Checking Docker availability" -try { - $dockerVer = docker version --format '{{.Server.Version}}' 2>&1 - Write-Host " Docker Engine $dockerVer detected." -} catch { - Write-Host "ERROR: Docker is not running. Start Docker Desktop first." -ForegroundColor Red - exit 1 -} - -# ── 2 Check port ──────────────────────────────────────────────── -Write-Step "Checking port $Port" -$portCheck = netstat -ano | Select-String ":$Port\s" -if ($portCheck) { - Write-Host " WARNING: port $Port may be in use (could be a previous instance)." -ForegroundColor Yellow -} - -# ── 3 Remove previous container (if any) ──────────────────────── -Write-Step "Removing previous Portainer instance (if present)" -$existing = docker ps -a --filter "name=^${Name}$" --format "{{.Names}}" 2>$null -if ($existing -eq $Name) { - docker stop $Name 2>$null | Out-Null - docker rm $Name 2>$null | Out-Null - Write-Host " Previous container removed." +function Invoke-Docker { + param([string[]]$DockerArguments, [switch]$AllowFailure) + # Native non-zero exit codes do not reliably throw in Windows PowerShell 5.1. + $savedPreference = $ErrorActionPreference + try { + $ErrorActionPreference = 'Continue' + $output = @(& docker @DockerArguments 2>&1) + $exitCode = $LASTEXITCODE + } finally { + $ErrorActionPreference = $savedPreference + } + if ($exitCode -ne 0 -and -not $AllowFailure) { + throw ('Docker command failed (exit {0}): {1}' -f $exitCode, ($output -join [Environment]::NewLine)) + } + [pscustomobject]@{ ExitCode = $exitCode; Text = ($output -join [Environment]::NewLine) } } -# ── 4 Pull image ──────────────────────────────────────────────── -Write-Step "Pulling $Image" -docker pull $Image - -# ── 5 Create volume ───────────────────────────────────────────── -Write-Step "Creating volume: $Volume" -docker volume create $Volume | Out-Null - -# ── 6 Start container ─────────────────────────────────────────── -Write-Step "Starting Portainer on port $Port" -docker run -d ` - -p "${Port}:9000" ` - --name $Name ` - --restart unless-stopped ` - -v /var/run/docker.sock:/var/run/docker.sock ` - -v "${Volume}:/data" ` - $Image | Out-Null - -# ── 7 Wait for API ────────────────────────────────────────────── -Write-Step "Waiting for Portainer API" -$baseUrl = "http://localhost:$Port" -$maxAttempts = 30 - -for ($i = 1; $i -le $maxAttempts; $i++) { +function Invoke-Portainer { + param([string]$Path, [string]$Method = 'GET', $Body = $null, + [string]$ContentType = 'application/json', [hashtable]$Headers = @{}) + $arguments = @{ + Uri = $script:BaseUrl + $Path + Method = $Method + Headers = $Headers + UseBasicParsing = $true + TimeoutSec = 15 + ErrorAction = 'Stop' + } + if ($null -ne $Body) { $arguments.Body = $Body; $arguments.ContentType = $ContentType } try { - $resp = Invoke-WebRequest -Uri "$baseUrl/api/status" ` - -UseBasicParsing -TimeoutSec 2 - if ($resp.StatusCode -eq 200) { - Write-Host " API ready (attempt $i/$maxAttempts)." - break - } + $response = Invoke-WebRequest @arguments + [pscustomobject]@{ Status = [int]$response.StatusCode; Content = [string]$response.Content } } catch { - if ($i -eq $maxAttempts) { - Write-Host "ERROR: API did not respond after $maxAttempts seconds." -ForegroundColor Red - exit 1 - } - Start-Sleep -Seconds 1 + $response = $_.Exception.Response + if ($null -eq $response) { throw } + [pscustomobject]@{ Status = [int]$response.StatusCode; Content = '' } } } -# ── 8 Create admin user ───────────────────────────────────────── -Write-Step "Creating admin user: $User" -$body = @{ Username = $User; Password = $Password } | ConvertTo-Json +function Assert-HttpSuccess { + param($Response, [string]$Operation) + if ($Response.Status -lt 200 -or $Response.Status -ge 300) { + throw ('{0} failed (HTTP {1}). Existing accounts and data were preserved.' -f $Operation, $Response.Status) + } +} try { - $resp = Invoke-WebRequest -Uri "$baseUrl/api/users/admin/init" ` - -Method POST ` - -ContentType "application/json" ` - -Body $body ` - -UseBasicParsing -TimeoutSec 10 - - if ($resp.StatusCode -eq 200) { - Write-Host " Admin user created." + if ($Name -notmatch '^[A-Za-z0-9][A-Za-z0-9_.-]*$') { throw 'Invalid container name.' } + if ($Volume -notmatch '^[A-Za-z0-9][A-Za-z0-9_.-]*$') { throw 'Invalid volume name.' } + if ([string]::IsNullOrWhiteSpace($User) -or $User -match '\s') { throw 'Invalid administrator username.' } + if ($Password.Length -lt 12) { throw 'Use a password of at least 12 characters.' } + if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { throw 'Docker CLI not found. Start Docker Desktop in Linux-containers mode.' } + $script:BaseUrl = 'http://127.0.0.1:' + $Port + Write-Host 'Checking the local Linux Docker daemon.' + $null = Invoke-Docker -DockerArguments @('info') + $os = (Invoke-Docker -DockerArguments @('info','--format','{{.OSType}}')).Text.Trim() + if ($os -ne 'linux') { throw 'Docker Desktop must use Linux containers.' } + if ($env:DOCKER_HOST -and -not $env:DOCKER_CONTEXT) { + $daemonAddress = $env:DOCKER_HOST + } else { + $daemonAddress = (Invoke-Docker -DockerArguments @('context','inspect','--format','{{.Endpoints.docker.Host}}')).Text.Trim() } -} catch { - $sc = $_.Exception.Response.StatusCode.Value__ - if ($sc -eq 409) { - Write-Host " Admin user already exists — reusing." -ForegroundColor Yellow + if ($daemonAddress -notmatch '^(npipe|unix)://') { throw 'Use a local Docker context. Remote SSH/TCP contexts are not supported by this installer.' } + + $existing = (Invoke-Docker -DockerArguments @('ps','-a','--filter',('name=^/' + $Name + '$'),'--format','{{.Names}}')).Text.Trim() + if ($existing -eq $Name) { + Write-Host 'Inspecting the existing container without replacing it.' + $objects = @((Invoke-Docker -DockerArguments @('container','inspect',$Name)).Text | ConvertFrom-Json) + $container = $objects[0] + if ($container.Config.Image -notmatch '^(docker.io/)?portainer/portainer-ce[:@]') { throw 'Existing container is not identified as Portainer CE; it has been preserved.' } + $portProperty = $container.HostConfig.PortBindings.PSObject.Properties['9000/tcp'] + if ($null -eq $portProperty) { throw 'Existing container has no HTTP mapping. Its configuration was preserved.' } + $bindings = @($portProperty.Value) + $matching = @($bindings | Where-Object { $_.HostPort -eq [string]$Port -and $_.HostIp -eq '127.0.0.1' }) + $allBindings = @($container.HostConfig.PortBindings.PSObject.Properties | ForEach-Object { $_.Value } | Where-Object { $null -ne $_ }) + $exposed = @($allBindings | Where-Object { $_.HostIp -notin @('127.0.0.1','::1') }) + if ($matching.Count -eq 0 -or $exposed.Count -gt 0) { throw 'Existing container does not use only the requested loopback binding. Review its configuration; no replacement was made.' } + $dataMounts = @($container.Mounts | Where-Object { $_.Destination -eq '/data' -and $_.Type -eq 'volume' -and $_.Name -eq $Volume }) + $socketMounts = @($container.Mounts | Where-Object { $_.Destination -eq '/var/run/docker.sock' }) + if ($dataMounts.Count -eq 0 -or $socketMounts.Count -eq 0) { throw 'Existing mounts differ from the requested local setup. Container and volumes were preserved.' } + Write-Host ('Existing image: ' + $container.Config.Image) + if (-not $container.State.Running) { $null = Invoke-Docker -DockerArguments @('start',$Name) } } else { - Write-Host " Could not create admin user (HTTP $sc). Create manually at $baseUrl" -ForegroundColor Yellow + $listeners = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners() + if (@($listeners | Where-Object { $_.Port -eq $Port }).Count -gt 0) { throw ('Port {0} is already listening. No existing service has been stopped.' -f $Port) } + $cached = Invoke-Docker -DockerArguments @('image','inspect',$Image) -AllowFailure + if ($cached.ExitCode -ne 0) { + Write-Host ('Downloading {0}; internet is required because it is not cached.' -f $Image) + $null = Invoke-Docker -DockerArguments @('pull',$Image) + } + $null = Invoke-Docker -DockerArguments @('volume','create',$Volume) + $null = Invoke-Docker -DockerArguments @('run','-d','-p',('127.0.0.1:' + $Port + ':9000'), + '--name',$Name,'--restart','unless-stopped','-v','/var/run/docker.sock:/var/run/docker.sock', + '-v',($Volume + ':/data'),$Image) } -} -# ── 9 Register local environment ──────────────────────────────── -Write-Step "Registering local Docker environment" -try { - $loginBody = @{ Username = $User; Password = $Password } | ConvertTo-Json - $loginResp = Invoke-WebRequest -Uri "$baseUrl/api/auth" ` - -Method POST -ContentType "application/json" ` - -Body $loginBody -UseBasicParsing -TimeoutSec 10 - $token = ($loginResp.Content | ConvertFrom-Json).jwt - $headers = @{ Authorization = "Bearer $token" } - - Invoke-WebRequest -Uri "$baseUrl/api/endpoints" ` - -Method POST -Headers $headers ` - -ContentType "application/x-www-form-urlencoded" ` - -Body "Name=local&EndpointCreationType=1" ` - -UseBasicParsing -TimeoutSec 10 | Out-Null - - Write-Host " Local environment registered." + Write-Host 'Waiting for the Portainer API.' + $ready = $false + for ($attempt = 1; $attempt -le 30; $attempt++) { + try { + $status = Invoke-Portainer -Path '/api/status' + if ($status.Status -eq 200) { + $statusJson = $status.Content | ConvertFrom-Json + if ($statusJson.PSObject.Properties['Version']) { $ready = $true; break } + } + } catch { } + Start-Sleep -Seconds 1 + } + if (-not $ready) { throw 'Portainer API did not become ready. Container and data preserved; inspect docker logs.' } + + $credentials = @{ Username = $User; Password = $Password } | ConvertTo-Json -Compress + $initialise = Invoke-Portainer -Path '/api/users/admin/init' -Method 'POST' -Body $credentials + if ($initialise.Status -in @(200,201)) { + Write-Host 'Administrator account initialised.' + } elseif ($initialise.Status -eq 409) { + Write-Host 'Administrator already exists; checking the supplied credentials without changing them.' + } else { + throw ('Administrator initialisation failed (HTTP {0}). No account or volume was reset.' -f $initialise.Status) + } + $login = Invoke-Portainer -Path '/api/auth' -Method 'POST' -Body $credentials + Assert-HttpSuccess $login 'Login (use the existing account credentials if already initialised)' + $loginJson = $login.Content | ConvertFrom-Json + if (-not $loginJson.PSObject.Properties['jwt'] -or [string]::IsNullOrWhiteSpace([string]$loginJson.jwt)) { throw 'Authentication returned no valid token.' } + $headers = @{ Authorization = 'Bearer ' + $loginJson.jwt } + + $listed = Invoke-Portainer -Path '/api/endpoints' -Headers $headers + Assert-HttpSuccess $listed 'Environment listing' + $endpoints = @($listed.Content | ConvertFrom-Json) + $local = @($endpoints | Where-Object { $_.Type -eq 1 -and $_.URL -eq 'unix:///var/run/docker.sock' }) + if ($local.Count -gt 0) { + $endpointId = [int]$local[0].Id + } else { + if (@($endpoints | Where-Object { $_.Name -eq 'local' }).Count -gt 0) { throw 'An environment named local uses a different connection. It has been preserved; review it in the browser.' } + # The 2.21 API reads these scalar fields through Go Request.FormValue. + $form = @{ Name = 'local'; EndpointCreationType = '1'; URL = 'unix:///var/run/docker.sock' } + $created = Invoke-Portainer -Path '/api/endpoints' -Method 'POST' -Headers $headers -Body $form -ContentType 'application/x-www-form-urlencoded' + Assert-HttpSuccess $created 'Local environment registration' + $createdJson = $created.Content | ConvertFrom-Json + if ($createdJson.Type -ne 1 -or $createdJson.URL -ne 'unix:///var/run/docker.sock') { throw 'Created environment does not identify the local Docker socket.' } + $endpointId = [int]$createdJson.Id + } + if ($endpointId -le 0) { throw 'No valid local environment ID was returned.' } + $ping = Invoke-Portainer -Path ('/api/endpoints/' + $endpointId + '/docker/_ping') -Headers $headers + Assert-HttpSuccess $ping 'Local Docker connectivity' + if ($ping.Content.Trim() -ne 'OK') { throw 'Portainer did not confirm access to the local Docker daemon.' } + + Write-Host 'Portainer setup verified: API ready, login accepted and local Docker ping returned OK.' -ForegroundColor Green + Write-Host ('URL on this Windows host: ' + $script:BaseUrl) + Write-Host ('Username: ' + $User) + Write-Host 'Existing accounts, containers and volumes were not deleted or reset.' } catch { - Write-Host " Auto-registration skipped — click 'Get Started' in the browser." -ForegroundColor Yellow + Write-Error $_.Exception.Message -ErrorAction Continue + exit 1 } - -# ── 10 Done ────────────────────────────────────────────────────── -Write-Host "" -Write-Host "================================================================" -ForegroundColor Green -Write-Host " Portainer is running." -ForegroundColor Green -Write-Host "================================================================" -ForegroundColor Green -Write-Host "" -Write-Host " URL : $baseUrl" -Write-Host " Username : $User" -Write-Host " Password : $Password" -Write-Host "" -Write-Host " Stop : docker stop portainer" -Write-Host " Start : docker start portainer" -Write-Host "" diff --git a/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.sh b/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.sh index 92cfbd5..b385ab8 100644 --- a/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.sh +++ b/00_TOOLS/Portainer/INIT_GUIDE/portainer-init.sh @@ -1,121 +1,155 @@ #!/usr/bin/env bash -# ───────────────────────────────────────────────────── -# Portainer CE — Automated setup for COMPNET labs -# -# Port : 9050 (9000 reserved by S10 SSH tunnel) -# Credentials : stud / studstudstud -# Requires : Docker Engine running -# ───────────────────────────────────────────────────── +# Local Linux/WSL/VM Portainer setup. Existing containers and volumes are preserved. +# Run against the Docker daemon on this machine, as a user with Docker access. set -euo pipefail -IMAGE="portainer/portainer-ce:2.21-alpine" -NAME="portainer" -PORT=9050 -VOLUME="portainer_data" -ADMIN="stud" -PASS="studstudstud" -BASE="http://localhost:${PORT}" +IMAGE="${PORTAINER_IMAGE:-portainer/portainer-ce:2.21-alpine}" +NAME="${PORTAINER_NAME:-portainer}" +PORT="${PORTAINER_PORT:-9050}" +VOLUME="${PORTAINER_VOLUME:-portainer_data}" +ADMIN="${PORTAINER_USER:-stud}" +PASS="${PORTAINER_PASSWORD:-studstudstud}" +BASE="http://127.0.0.1:${PORT}" -cyan() { printf '\033[1;36m>> %s\033[0m\n' "$1"; } -green() { printf '\033[1;32m%s\033[0m\n' "$1"; } -yellow() { printf '\033[1;33m %s\033[0m\n' "$1"; } -red() { printf '\033[1;31mERROR: %s\033[0m\n' "$1"; } +die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; } +step() { printf '\n>> %s\n' "$*"; } +for command_name in docker curl python3 ss mktemp; do + command -v "$command_name" >/dev/null 2>&1 || die "Required command missing: $command_name" +done +[[ "$PORT" =~ ^[0-9]+$ ]] && (( 10#$PORT > 0 && 10#$PORT < 65536 )) || die 'PORTAINER_PORT must be 1..65535.' +[[ "$NAME" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]*$ ]] || die 'Invalid container name.' +[[ "$VOLUME" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]*$ ]] || die 'Invalid volume name.' +[[ -n "$ADMIN" && ! "$ADMIN" =~ [[:space:]] ]] || die 'Invalid administrator username.' +(( ${#PASS} >= 12 )) || die 'Use a password of at least 12 characters.' -# ── 1 Check Docker ────────────────────────────────────────────── -cyan "Checking Docker availability" -if ! docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then - red "Docker is not running." - exit 1 +step 'Checking the local Linux Docker daemon' +docker info >/dev/null 2>&1 || die 'Docker is not responding or this user lacks Docker access.' +[[ "$(docker info --format '{{.OSType}}')" == linux ]] || die 'Linux containers are required.' +if [[ -n "${DOCKER_HOST:-}" && -z "${DOCKER_CONTEXT:-}" ]]; then + daemon_address="$DOCKER_HOST" +else + daemon_address="$(docker context inspect --format '{{.Endpoints.docker.Host}}')" fi -echo " Docker Engine $(docker version --format '{{.Server.Version}}') detected." +[[ "$daemon_address" == unix://* ]] || die "Use a local Unix-socket Docker context; remote contexts are not supported." -# ── 2 Check port ──────────────────────────────────────────────── -cyan "Checking port ${PORT}" -if ss -tlnp 2>/dev/null | grep -q ":${PORT} "; then - yellow "Port ${PORT} may be in use (could be a previous instance)." -fi +work_directory="$(mktemp -d)" +chmod 700 "$work_directory" +trap 'rm -rf -- "$work_directory"' EXIT -# ── 3 Remove previous container ───────────────────────────────── -cyan "Removing previous instance (if present)" -if docker ps -a --filter "name=^${NAME}$" --format '{{.Names}}' | grep -q "^${NAME}$"; then - docker stop "${NAME}" 2>/dev/null || true - docker rm "${NAME}" 2>/dev/null || true - echo " Previous container removed." +existing_names="$(docker ps -a --filter "name=^/${NAME}$" --format '{{.Names}}')" +if [[ "$existing_names" == "$NAME" ]]; then + step 'Inspecting the existing container without replacing it' + docker container inspect "$NAME" > "$work_directory/container.json" + python3 - "$work_directory/container.json" "$PORT" "$VOLUME" <<'PY_CHECK' +import json,sys +c=json.load(open(sys.argv[1],encoding='utf-8'))[0] +image=c.get('Config',{}).get('Image','') +if not image.startswith(('portainer/portainer-ce:', 'portainer/portainer-ce@', 'docker.io/portainer/portainer-ce:', 'docker.io/portainer/portainer-ce@')): + raise SystemExit('Existing container is not identified as Portainer CE; it has been preserved.') +bindings=c.get('HostConfig',{}).get('PortBindings',{}).get('9000/tcp') or [] +if not any(p.get('HostPort')==sys.argv[2] and p.get('HostIp') == '127.0.0.1' for p in bindings): + raise SystemExit('Existing container does not use the requested loopback port; it has been preserved. Review its configuration manually.') +all_bindings=[p for group in c.get('HostConfig',{}).get('PortBindings',{}).values() for p in (group or [])] +if any(p.get('HostIp') not in ('127.0.0.1','::1') for p in all_bindings): + raise SystemExit('Existing container also publishes a port beyond loopback; preserved. Review before using shared lab credentials.') +mounts=c.get('Mounts',[]) +if not any(m.get('Destination')=='/data' and m.get('Type')=='volume' and m.get('Name')==sys.argv[3] for m in mounts): + raise SystemExit('Existing Portainer data volume differs; container and data preserved. Select the intended PORTAINER_VOLUME.') +if not any(m.get('Destination')=='/var/run/docker.sock' for m in mounts): + raise SystemExit('Existing container lacks the local Docker socket mount; preserved.') +print('Existing image:',image) +PY_CHECK + running="$(docker inspect --format '{{.State.Running}}' "$NAME")" + if [[ "$running" != true ]]; then + docker start "$NAME" >/dev/null + fi +else + step "Preparing Portainer on loopback port ${PORT}" + if [[ -n "$(ss -H -ltn "sport = :${PORT}")" ]]; then + die "Port ${PORT} is already listening. No existing service has been stopped." + fi + if ! docker image inspect "$IMAGE" >/dev/null 2>&1; then + step "Downloading ${IMAGE} (internet required because the image is not cached)" + docker pull "$IMAGE" + fi + docker volume create "$VOLUME" >/dev/null + docker run -d -p "127.0.0.1:${PORT}:9000" --name "$NAME" \ + --restart unless-stopped \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -v "${VOLUME}:/data" "$IMAGE" >/dev/null fi -# ── 4 Pull image ──────────────────────────────────────────────── -cyan "Pulling ${IMAGE}" -docker pull "${IMAGE}" - -# ── 5 Create volume ───────────────────────────────────────────── -cyan "Creating volume: ${VOLUME}" -docker volume create "${VOLUME}" >/dev/null - -# ── 6 Start container ─────────────────────────────────────────── -cyan "Starting Portainer on port ${PORT}" -docker run -d \ - -p "${PORT}:9000" \ - --name "${NAME}" \ - --restart unless-stopped \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v "${VOLUME}:/data" \ - "${IMAGE}" >/dev/null - -# ── 7 Wait for API ────────────────────────────────────────────── -cyan "Waiting for Portainer API" -for i in $(seq 1 30); do - if curl -sf "${BASE}/api/status" >/dev/null 2>&1; then - echo " API ready (attempt ${i}/30)." +step 'Waiting for the Portainer API' +ready=false +for attempt in $(seq 1 30); do + if curl -fsS --connect-timeout 2 --max-time 3 "${BASE}/api/status" > "$work_directory/status.json" 2>/dev/null && + python3 - "$work_directory/status.json" <<'PY_STATUS' +import json,sys +s=json.load(open(sys.argv[1],encoding='utf-8')) +raise SystemExit(0 if isinstance(s,dict) and ('Version' in s or 'version' in s) else 1) +PY_STATUS + then + ready=true break fi - [ "$i" -eq 30 ] && { red "API did not respond after 30 seconds."; exit 1; } sleep 1 done +[[ "$ready" == true ]] || die 'Portainer API did not become ready. Container and data preserved; inspect docker logs.' -# ── 8 Create admin user ───────────────────────────────────────── -cyan "Creating admin user: ${ADMIN}" -HTTP=$(curl -s -o /dev/null -w "%{http_code}" \ - -X POST "${BASE}/api/users/admin/init" \ - -H "Content-Type: application/json" \ - -d "{\"Username\":\"${ADMIN}\",\"Password\":\"${PASS}\"}") - -case "${HTTP}" in - 200) echo " Admin user created." ;; - 409) yellow "Admin user already exists — reusing." ;; - *) yellow "Could not create admin (HTTP ${HTTP}). Create manually at ${BASE}" ;; +# Keep credentials and the session token in a private temporary directory. +printf '%s\0%s' "$ADMIN" "$PASS" | python3 -c 'import json,sys; u,p=sys.stdin.read().split("\0",1); json.dump({"Username":u,"Password":p},sys.stdout)' > "$work_directory/credentials.json" +init_status="$(curl -sS --connect-timeout 3 --max-time 15 -o "$work_directory/init.json" -w '%{http_code}' \ + -X POST -H 'Content-Type: application/json' --data-binary "@$work_directory/credentials.json" "${BASE}/api/users/admin/init")" +case "$init_status" in + 200|201) printf 'Administrator account initialised.\n' ;; + 409) printf 'Administrator already exists; checking the supplied credentials without changing them.\n' ;; + *) die "Administrator initialisation failed (HTTP ${init_status}). No account or volume was reset." ;; esac -# ── 9 Register local environment ──────────────────────────────── -cyan "Registering local Docker environment" -TOKEN=$(curl -sf -X POST "${BASE}/api/auth" \ - -H "Content-Type: application/json" \ - -d "{\"Username\":\"${ADMIN}\",\"Password\":\"${PASS}\"}" \ - | grep -o '"jwt":"[^"]*"' | cut -d'"' -f4) || true +curl -fsS --connect-timeout 3 --max-time 15 -X POST -H 'Content-Type: application/json' \ + --data-binary "@$work_directory/credentials.json" "${BASE}/api/auth" > "$work_directory/login.json" || + die 'Login failed. Use the credentials of the existing instance; its account and data have been preserved.' +python3 - "$work_directory/login.json" "$work_directory/auth-header" <<'PY_TOKEN' +import json,sys +s=json.load(open(sys.argv[1],encoding='utf-8')) +token=s.get('jwt') +if not isinstance(token,str) or not token or '\n' in token or '\r' in token: + raise SystemExit('Authentication response does not contain a valid token.') +open(sys.argv[2],'w',encoding='utf-8').write('Authorization: Bearer '+token+'\n') +PY_TOKEN -if [ -n "${TOKEN}" ]; then - EC=$(curl -s -o /dev/null -w "%{http_code}" \ - -X POST "${BASE}/api/endpoints" \ - -H "Authorization: Bearer ${TOKEN}" \ - -d "Name=local&EndpointCreationType=1") - case "${EC}" in - 200|201) echo " Local environment registered." ;; - 409|500) yellow "Environment already configured." ;; - *) yellow "Auto-registration skipped — click 'Get Started' in browser." ;; - esac -else - yellow "Could not obtain token — click 'Get Started' in browser." +step 'Checking the local Docker environment' +curl -fsS --connect-timeout 3 --max-time 15 -H "@$work_directory/auth-header" "${BASE}/api/endpoints" > "$work_directory/endpoints.json" +endpoint_id="$(python3 - "$work_directory/endpoints.json" <<'PY_ENDPOINT' +import json,sys +items=json.load(open(sys.argv[1],encoding='utf-8')) +if not isinstance(items,list): raise SystemExit('Unexpected environment-list response.') +for e in items: + if e.get('Type')==1 and e.get('URL')=='unix:///var/run/docker.sock': + print(int(e['Id'])); break +else: + if any(e.get('Name')=='local' for e in items): + raise SystemExit('An environment named local exists with a different connection; preserved. Review it in the browser.') +PY_ENDPOINT +)" +if [[ -z "$endpoint_id" ]]; then + curl -fsS --connect-timeout 3 --max-time 30 -X POST -H "@$work_directory/auth-header" \ + -F 'Name=local' -F 'EndpointCreationType=1' -F 'URL=unix:///var/run/docker.sock' \ + "${BASE}/api/endpoints" > "$work_directory/created-endpoint.json" || die 'Local environment registration failed.' + endpoint_id="$(python3 - "$work_directory/created-endpoint.json" <<'PY_CREATED' +import json,sys +s=json.load(open(sys.argv[1],encoding='utf-8')) +if s.get('Type')!=1 or s.get('URL')!='unix:///var/run/docker.sock': + raise SystemExit('Created environment does not identify the local Docker socket.') +print(int(s['Id'])) +PY_CREATED +)" fi +[[ "$endpoint_id" =~ ^[0-9]+$ ]] || die 'No valid local environment ID was returned.' +ping_result="$(curl -fsS --connect-timeout 3 --max-time 15 -H "@$work_directory/auth-header" "${BASE}/api/endpoints/${endpoint_id}/docker/_ping")" +[[ "$ping_result" == OK ]] || die 'Portainer cannot confirm access to the local Docker daemon.' -# ── 10 Done ────────────────────────────────────────────────────── -echo "" -green "================================================================" -green " Portainer is running." -green "================================================================" -echo "" -echo " URL : ${BASE}" -echo " Username : ${ADMIN}" -echo " Password : ${PASS}" -echo "" -echo " Stop : docker stop portainer" -echo " Start : docker start portainer" -echo "" +printf '\nPortainer setup verified: API ready, login accepted and local Docker ping returned OK.\n' +printf 'URL on this Linux machine: %s\nUsername: %s\n' "$BASE" "$ADMIN" +printf 'From Windows to a VirtualBox guest, use the SSH tunnel in PORTAINER_SETUP.md.\n' +printf 'Existing accounts, containers and volumes were not deleted or reset.\n' diff --git a/00_TOOLS/Prerequisites/Prerequisites.md b/00_TOOLS/Prerequisites/Prerequisites.md index 73263fc..f8003b4 100644 --- a/00_TOOLS/Prerequisites/Prerequisites.md +++ b/00_TOOLS/Prerequisites/Prerequisites.md @@ -1,6 +1,8 @@ # 🖧 Computer Networks Lab — Environment Setup Guide -> **Complete Documentation for Prerequisites** +> **Alternative WSL2 setup.** The ASE classroom route uses the [MININET-SDN VirtualBox appliance](../../01_GUIDE_MININET-SDN/). Use that guide for an imported OVA; do not run the WSL installation steps inside the appliance. +> +> This guide prepares a separate WSL environment for suitable container-based exercises. Mininet/OpenFlow work uses the dedicated VM route unless the exercise explicitly supplies a WSL alternative. > Bucharest University of Economic Studies — Faculty of Cybernetics, Statistics and Economic Informatics > *Economic Informatics & AI in Economics and Business Programmes* @@ -28,7 +30,7 @@ ### 1.1 Purpose of This Guide -This complete guide walks you through configuring a complete networking lab environment on Windows. By the end, you will have a fully functional containerised environment capable of: +This guide prepares Ubuntu in WSL2 for container-based networking exercises. Its checks establish prerequisite availability; each chosen exercise still requires its own functional test. The environment supports: - **Running isolated network experiments** using Docker containers - **Capturing and analysing network traffic** with Wireshark @@ -37,15 +39,7 @@ This complete guide walks you through configuring a complete networking lab envi ### 1.2 Why This Architecture? -We use **WSL2 + Docker in Ubuntu** instead of Docker Desktop for several compelling reasons: - -| Aspect | WSL2 + Docker | Docker Desktop | -|--------|---------------|----------------| -| **Performance** | Native Linux kernel, faster I/O | Virtualisation overhead | -| **Resource Usage** | Smaller memory footprint | Higher RAM consumption | -| **Network Access** | Complete Linux network stack | Abstracted networking | -| **Educational Value** | Real Linux environment | Windows abstraction | -| **Cost** | Completely free | Enterprise licensing | +This alternative places Docker Engine and the course Python environment inside Ubuntu on WSL2. Keep commands in that Linux environment so that the Docker socket, installed Python packages and exercise files refer to the same machine. Docker Desktop is a separate optional route; it is not needed for this one. ### 1.3 What You Will Install @@ -53,11 +47,11 @@ We use **WSL2 + Docker in Ubuntu** instead of Docker Desktop for several compell |-----------|---------|---------| | WSL2 | 2.x | Windows Subsystem for Linux | | Ubuntu | 22.04 LTS | Linux distribution | -| Docker | 28.2.2 | Container runtime | -| Docker Compose | 1.29.x | Multi-container orchestration | -| Portainer CE | 2.33.6 LTS | Web-based container management | +| Docker | Version installed from the selected Ubuntu repository | Container runtime | +| Docker Compose | v2 plugin (`docker compose`) | Multi-container orchestration | +| Portainer CE | Optional; selected in the [Portainer guide](../Portainer/INIT_GUIDE/) | Web-based container management | | Wireshark | 4.4.x | Network protocol analyser | -| Python Packages | Latest | docker, scapy, dpkt | +| Python | 3.10+ in a Linux virtual environment | Packages for the selected exercises | ### 1.4 Time Estimate @@ -105,22 +99,22 @@ We use **WSL2 + Docker in Ubuntu** instead of Docker Desktop for several compell 1. **Docker containers** communicate through Docker's internal bridge network 2. **Traffic exits** via the WSL2 virtual network interface -3. **Wireshark on Windows** captures traffic on `vEthernet (WSL)` -4. **Portainer** is accessible via `localhost:9000` from the Windows browser +3. **Wireshark on Windows** can capture traffic crossing the WSL virtual interface; internal container and loopback traffic may require capture inside Linux +4. **Portainer** is accessible via `localhost:9050` from the Windows browser ### 2.3 Port Mapping | Service | Container Port | Host Port | Access URL | |---------|----------------|-----------|------------| -| Portainer | 9000 | 9000 | http://localhost:9000 | -| Portainer HTTPS | 9443 | 9443 | https://localhost:9443 | -| Portainer Edge | 8000 | 8000 | (Agent Communication) | +| Portainer HTTP | 9000 | 127.0.0.1:9050 | http://localhost:9050 | + +The optional course setup does not publish ports 9443 or 8000. Port 9000 on the host remains available for the S10 SSH tunnel. --- ## 3. Standard Credentials -> ⚠️ **Important:** Use exactly these credentials for all lab exercises to ensure consistency. +> The following are teaching-account defaults. Preserve existing personal accounts and Portainer credentials. Shared lab credentials are used only with the local access configuration in this guide. ### 3.1 Ubuntu WSL User @@ -137,7 +131,7 @@ This user is created during Ubuntu installation and has `sudo` privileges. |-------|-------| | **Username** | `stud` | | **Password** | `studstudstud` | -| **Access URL** | http://localhost:9000 | +| **Access URL** | http://localhost:9050 | > 📝 **Note:** Portainer requires a minimum 12-character password, hence `studstudstud`. @@ -174,10 +168,12 @@ This user is created during Ubuntu installation and has `sudo` privileges. Execute the following command: ```powershell -wsl --install +wsl --install --no-distribution ``` -**What this command does:** +This prepares the WSL platform without also creating an unintended default Ubuntu distribution. System-feature installation can require elevation; distribution installation in section 5 is performed under the Windows account that will use the labs. If elevation requires a different administrator account, return to your normal account before section 5. + +**What these commands do:** - Enables the WSL optional feature - Enables the Virtual Machine Platform feature - Downloads and installs the Linux kernel @@ -198,19 +194,11 @@ Or restart manually through the Start menu. After restart, open PowerShell and verify: ```powershell +wsl --set-default-version 2 wsl --status ``` -**Expected output:** -``` -Default Distribution: Ubuntu -Default Version: 2 - -Windows Subsystem for Linux was last updated on [data] -WSL automatic updates are on. - -Kernel version: 5.15.x.x-microsoft-standard-WSL2 -``` +The default WSL version should be 2. There may be no installed distribution yet; section 5 installs the named course distribution. Existing distributions are preserved. ### 4.4 Checklist @@ -235,7 +223,7 @@ Kernel version: 5.15.x.x-microsoft-standard-WSL2 #### Step 1: Install Ubuntu from PowerShell -Open PowerShell as Administrator and execute: +Open a normal PowerShell window under the Windows account that will use the labs. Check `wsl --list --verbose` first. If `Ubuntu-22.04` already exists, use it and preserve its accounts and data. For a fresh named distribution, execute: ```powershell wsl --install -d Ubuntu-22.04 --web-download @@ -259,7 +247,7 @@ Enter new UNIX username: #### Step 3: Create the User Account -> ⚠️ **Critical:** Use the standard credentials! +> For a new disposable teaching account, the laboratory convention is shown below. Preserve any existing Linux user and password. ``` Enter new UNIX username: stud @@ -278,10 +266,12 @@ wsl -l -v **Expected output:** ``` NAME STATE VERSION -* Ubuntu-22.04 Running 2 + Ubuntu-22.04 Running 2 ``` -### 5.3 Aderstanding the Ubuntu Environment +Open this exact distribution with `wsl -d Ubuntu-22.04`; the default distribution can be different. Do not unregister an existing distribution to change the default. + +### 5.3 Understanding the Ubuntu Environment When you open Ubuntu, you are in a complete Linux environment: @@ -328,30 +318,32 @@ stud@HOSTNAME:~$ Either: - Click on "Ubuntu" in the Start menu, or -- Type `wsl` in PowerShell +- Type `wsl -d Ubuntu-22.04` in PowerShell -#### Step 2: Updata System Packages +#### Step 2: Refresh Package Metadata ```bash -sudo apt update && sudo apt upgrade -y +sudo apt update ``` **What this does:** - `sudo`: Execute as superuser (administrator) - `apt update`: Refresh package list -- `apt upgrade -y`: Install all available updates (`-y` = yes to all) +No blanket system upgrade is required by this setup step. **Expected duration:** 2-5 minutes depending on internet speed. #### Step 3: Install Docker and Docker Compose ```bash -sudo apt install -y docker.io docker-compose +sudo apt install -y docker.io docker-compose-v2 curl python3 iproute2 ``` **Packages installed:** - `docker.io`: The Docker container runtime -- `docker-compose`: Tool for defining multi-container applications +- `docker-compose-v2`: Compose plugin invoked as `docker compose` + +These Ubuntu packages apply to a fresh WSL distribution. If a working Docker installation already exists, verify it first and do not mix Ubuntu packages with packages from Docker's own repository. The [Ubuntu package index](https://packages.ubuntu.com/search?keywords=docker-compose-v2) lists the plugin for supported releases; `jammy-updates` and the `universe` component must be available for Ubuntu 22.04. If the package has no installation candidate, check those configured repositories or use the [official Docker installation route](https://docs.docker.com/engine/install/ubuntu/) without combining the two package sources. #### Step 4: Add User to Docker Group @@ -372,7 +364,7 @@ sudo usermod -aG docker $USER sudo service docker start ``` -**Note:** In WSL2, services do not start automatically by default. We will configure this later. +**Note:** Service startup depends on whether systemd is enabled in this WSL distribution. Section 10 distinguishes the two cases. #### Step 6: Apply Group Changes @@ -383,9 +375,10 @@ newgrp docker ``` Or log out and log back in: -```bash -exit -wsl +Exit the Linux shell, then in **PowerShell** reopen the named distribution: + +```powershell +wsl -d Ubuntu-22.04 ``` #### Step 7: Verify Installation @@ -395,13 +388,13 @@ wsl docker --version # Check Docker Compose version -docker-compose --version +docker compose version # Test Docker functionality docker run hello-world ``` -**Expected Docker version output:** +**Illustrative version output (your installed version can differ):** ``` Docker version 28.2.2, build e6534b4 ``` @@ -469,85 +462,19 @@ For educational purposes, Portainer provides: ### 7.3 Installation Steps -#### Step 1: Create Persistent Volume - -Docker volumes persist data beyond the container lifecycle: - -```bash -docker volume create portainer_data -``` - -**What this does:** Creates a volume named `portainer_data` that will store Portainer configuration, users and settings. - -#### Step 2: Deploy Portainer Container - -```bash -docker run -d \ - -p 9000:9000 \ - --name portainer \ - --restart=always \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v portainer_data:/data \ - portainer/portainer-ce:latest -``` - -**Command explanation:** - -| Flag | Purpose | -|------|---------| -| `-d` | Run in detached mode (background) | -| `-p 9000:9000` | Map container port 9000 to host | -| `--name portainer` | Name the container "portainer" | -| `--restart=always` | Restart container if it stops or on reboot | -| `-v /var/run/docker.sock:...` | Give Portainer access to Docker daemon | -| `-v portainer_data:/data` | Persist Portainer data | -| `portainer/portainer-ce:latest` | Use latest Portainer CE image | - -#### Step 3: Verify Deployment +Use the [Portainer setup guide](../Portainer/INIT_GUIDE/PORTAINER_SETUP.md) for the selected image and account. From the repository root **inside WSL**, run: ```bash -docker ps +bash 00_TOOLS/Portainer/INIT_GUIDE/portainer-init.sh ``` -**Expected output:** -``` -CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -44b61d00ab18 portainer/portainer-ce:latest "/portainer" 10 seconds ago Up 9 seconds 8000/tcp, 9443/tcp, 0.0.0.0:9000->9000/tcp portainer -``` +The script binds `127.0.0.1:9050` on this Linux machine to container port 9000. It preserves existing containers, data and accounts, checks authentication and confirms local Docker access through Portainer. An absent image requires internet access; a cached image is reused without a pull. Do not run the Windows installer to manage this WSL engine. ### 7.4 Initial Portainer Setup -> ⏱️ **Important:** You must complete initial setup within 5 minutes of deployment! - -#### Step 1: Access Portainer - -Open your Windows browser and navigate to: - -``` -http://localhost:9000 -``` - -#### Step 2: Create Administrator Account - -On the initial setup screen: - -| Field | Value | -|-------|-------| -| Username | `stud` | -| Password | `studstudstud` | -| Confirm password | `studstudstud` | - -Click **"Create user"** - -#### Step 3: Connect to Local Docker - -On the "Environment Wizard" screen: -1. Click **"Get Started"** to use the local environment -2. Or select **"Docker"** → **"Connect"** if displayed +After the installer succeeds, open `http://localhost:9050` in Windows and use the account confirmed by the installer. For a fresh lab account, the defaults are `stud` / `studstudstud`. A Compose-only start does not create those credentials automatically. -#### Step 4: Explore the Dashboard - -You should now see the Portainer dashboard with your local Docker environment connected. +If the interface works in WSL but not on Windows, check WSL localhost forwarding. If an administrator already exists, use that account rather than resetting the data volume. The [Portainer troubleshooting section](../Portainer/INIT_GUIDE/PORTAINER_SETUP.md#7-troubleshooting) describes diagnostic steps. ### 7.5 Portainer Interface Overview @@ -572,7 +499,7 @@ You should now see the Portainer dashboard with your local Docker environment co ### 7.6 Checklist - [ ] `docker ps` shows portainer container running -- [ ] http://localhost:9000 loads in Windows browser +- [ ] http://localhost:9050 loads in Windows browser - [ ] You can log in with stud/studstudstud - [ ] Dashboard shows "local" Docker environment @@ -596,7 +523,7 @@ We install Wireshark on Windows (not in WSL) because: 1. **GUI Performance:** Native Windows application with better graphics 2. **Interface Access:** Direct access to Windows network interfaces -3. **WSL Traffic:** The `vEthernet (WSL)` interface captures all WSL traffic +3. **WSL Traffic:** The `vEthernet (WSL)` interface captures traffic crossing that interface; use Linux capture tools for traffic that remains inside Linux or Docker 4. **Integration:** Easy saving and sharing of files on Windows ### 8.3 Installation Steps @@ -687,32 +614,47 @@ Python is widely used for network automation and analysis: ### 9.2 Prerequisites -Ensure Python 3.11+ is installed on Windows: +Install and use Python **inside Ubuntu in WSL**, where the Docker daemon runs. Packages installed in Windows Python are separate and cannot satisfy the Linux verifier. -```powershell -python --version +```bash +sudo apt install -y python3 python3-venv python3-pip git curl wget tcpdump netcat-openbsd iproute2 +python3 --version ``` -If not installed, download from: https://www.python.org/downloads/ +The supported baseline is Python 3.10 or later. If the selected exercise requires a newer interpreter, use its documented environment. Keep the existing MININET-SDN appliance environment unchanged. ### 9.3 Installation Steps -Open PowerShell or Command Prompt: +Create a separate Linux virtual environment and activate it before installation, verification and exercises: -```powershell -# Install Docker SDK -pip install docker +```bash +python3 -m venv ~/venvs/compnet-wsl +source ~/venvs/compnet-wsl/bin/activate +python3 -m pip install docker scapy dpkt requests flask PyYAML colorama +``` + +Exercise-dependent packages: + +```bash +python3 -m pip install paramiko pyftpdlib paho-mqtt dnspython grpcio protobuf +``` + +Downloads require internet. These commands prepare a fresh environment and do not constitute a frozen package lock. Keep package versions with your experiment records where exact replay is required. Do not install into the system Python with `--break-system-packages` as a routine remedy. + +Check the active interpreter and basic imports: + +```bash +which python3 +python3 -c "import docker, scapy.all, dpkt; print('Core imports: OK')" +``` -# Install network analysis packages -pip install scapy dpkt +After opening another WSL terminal, activate this same environment again: -# Verify installation -python -c "import docker; print('Docker SDK: OK')" -python -c "import scapy; print('Scapy: OK')" -python -c "import dpkt; print('dpkt: OK')" +```bash +source ~/venvs/compnet-wsl/bin/activate ``` -### 9.4 Package Overview +### 9.4 What the Packages Do #### docker (Python Docker SDK) @@ -763,69 +705,25 @@ with open('capture.pcap', 'rb') as f: ## 10. Step 7: Auto-start Configuration (Optional) -### 10.1 Why Auto-start? - -By default, WSL2 does not start services automatically. Every time you open Ubuntu, you would need to: +Check which init system is running **inside WSL**: ```bash -sudo service docker start +ps -p 1 -o comm= ``` -Configuring auto-start eliminates this manual step. - -### 10.2 Configuration Steps - -#### Step 1: Add Auto-start to Bash Profile - -Open Ubuntu terminal and execute: +If it reports `systemd`, enable and start the installed Docker service: ```bash -cat >> ~/.bashrc << 'EOF' - -# Auto-start Docker service -if ! pgrep -x "dockerd" > /dev/null; then - sudo service docker start > /dev/null 2>&1 -fi -EOF +sudo systemctl enable --now docker ``` -**What this does:** -- Adds code to `~/.bashrc` (executed on every terminal open) -- Checks if `dockerd` is running (`pgrep`) -- If not running, starts Docker service - -#### Step 2: Allow Passwordless Docker Start - -Create a sudoers exception: +Otherwise start Docker for the current WSL session: ```bash -echo 'stud ALL=(ALL) NOPASSWD: /usr/sbin/service docker start' | sudo tee /etc/sudoers.d/docker-start -sudo chmod 440 /etc/sudoers.d/docker-start -``` - -**What this does:** -- Creates file `/etc/sudoers.d/docker-start` -- Allows user `stud` to run `service docker start` without password -- Sets secure permissions (read-only for root and sudoers) - -#### Step 3: Test Auto-start - -```powershell -# In PowerShell, stop WSL completely -wsl --shutdown - -# Reopen Ubuntu -wsl - -# Docker should start automatically -docker ps +sudo service docker start ``` -### 10.3 Checklist - -- [ ] Docker starts automatically when you open Ubuntu -- [ ] No password prompt for Docker service -- [ ] `docker ps` works immediately after opening Ubuntu +A container restart policy takes effect after the Docker daemon starts; it does not itself start WSL when Windows boots. This guide does not append repeated shell startup commands or grant passwordless sudo. See [Microsoft's WSL systemd guidance](https://learn.microsoft.com/en-us/windows/wsl/systemd) if you deliberately choose to enable systemd. Preserve any existing `/etc/wsl.conf` settings. --- @@ -864,9 +762,9 @@ docker run --rm alpine ping -c 5 8.8.8.8 #### Test 3: Python Integration -```powershell -# In PowerShell -python -c "import docker; c = docker.from_env(); print(f'Containers: {len(c.containers.list())}')" +```bash +# Inside WSL, after activating ~/venvs/compnet-wsl +python3 -c "import docker; c = docker.from_env(); print(f'Containers: {len(c.containers.list())}')" ``` **Expected:** `Containers: 1` (or more) @@ -877,51 +775,31 @@ python -c "import docker; c = docker.from_env(); print(f'Containers: {len(c.cont |-----------|---------|--------------| | WSL2 | 2.x | `wsl --status` | | Ubuntu | 22.04 LTS | `lsb_release -a` | -| Docker | 28.2.2 | `docker --version` | -| Docker Compose | 1.29.x | `docker-compose --version` | -| Portainer | 2.33.6 LTS | http://localhost:9000 | +| Docker | Installed version | `docker --version` | +| Docker Compose | v2 | `docker compose version` | +| Portainer | Selected image; optional | http://localhost:9050 | | Wireshark | 4.4.x | Launch application | -| Python docker | 7.1.0 | `pip show docker` | -| Python scapy | 2.7.0 | `pip show scapy` | -| Python dpkt | 1.9.8 | `pip show dpkt` | +| Python docker | Installed version | `python3 -m pip show docker` | +| Python scapy | Installed version | `python3 -m pip show scapy` | +| Python dpkt | Installed version | `python3 -m pip show dpkt` | -### 11.3 Quick Verification Script +### 11.3 Prerequisite Verification -Create and run this verification script: +From the repository root, inside WSL: ```bash -#!/bin/bash -echo "=== WSL Status ===" -wsl.exe --status 2>/dev/null || echo "Run from Windows" - -echo "" -echo "=== Ubuntu Version ===" -lsb_release -d - -echo "" -echo "=== Docker Version ===" -docker --version - -echo "" -echo "=== Docker Compose Version ===" -docker-compose --version - -echo "" -echo "=== Active Containers ===" -docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" - -echo "" -echo "=== Portainer Status ===" -docker ps --filter name=portainer --format "{{.Status}}" +source ~/venvs/compnet-wsl/bin/activate +bash 00_TOOLS/Prerequisites/verify_lab_environment.sh +``` -echo "" -echo "=== Docker Networks ===" -docker network ls +The default checks are local and do not pull Docker images. To request additional bounded HTTPS connectivity probes: -echo "" -echo "✅ All checks complete!" +```bash +bash 00_TOOLS/Prerequisites/verify_lab_environment.sh --online ``` +Review warnings for the chosen exercise. Passing these checks is not a complete course acceptance test. For the VirtualBox appliance use [its own verifier](../../01_GUIDE_MININET-SDN/verify_mininet_vm.sh). + --- ## 12. Troubleshooting @@ -976,7 +854,7 @@ echo "✅ All checks complete!" # Run this sequence for fast diagnosis: echo "1. Docker daemon:" && docker info >/dev/null 2>&1 && echo " ✓ OK" || echo " ✗ Not running" echo "2. Portainer:" && docker ps --filter name=portainer --format " ✓ {{.Status}}" 2>/dev/null || echo " ✗ Container absent" -echo "3. Ports:" && ss -tlnp 2>/dev/null | grep -E ":(9000|8080)" | awk '{print " ✓ " $4}' || echo " ✓ Free" +echo "3. Ports:" && ss -tlnp 2>/dev/null | grep -E ":(9050|8080)" | awk '{print " ✓ " $4}' || echo " ✓ Free" ``` --- @@ -1037,7 +915,7 @@ wsl docker ps ### 12.3 Portainer Issues -#### Cannot access http://localhost:9000 +#### Cannot access http://localhost:9050 1. Check if container is running: ```bash @@ -1056,22 +934,14 @@ docker restart portainer #### "Portainer has already been initialised" -If you missed the 5-minutes window: +An administrator already exists. Use its actual credentials; this does not mean the volume is faulty. For an uninitialised setup that has timed out, restart the container and complete initialisation promptly: ```bash -# Delete Portainer and volume -docker stop portainer -docker rm portainer -docker volume rm portainer_data - -# Redeploy -docker volume create portainer_data -docker run -d -p 9000:9000 --name portainer --restart=always \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v portainer_data:/data \ - portainer/portainer-ce:latest +docker restart portainer ``` +Preserve `portainer_data`. Deleting it would remove users and settings and is not a routine setup repair. + ### 12.4 Wireshark Issues #### No interfaces visible @@ -1123,7 +993,7 @@ sudo service docker stop # Stop Docker | Service | URL | |---------|-----| -| Portainer | http://localhost:9000 | +| Portainer | http://localhost:9050 | | Docker Docs | https://docs.docker.com/ | | Wireshark Docs | https://www.wireshark.org/docs/ | | WSL Docs | https://learn.microsoft.com/en-us/windows/wsl/ | diff --git a/00_TOOLS/Prerequisites/Prerequisites_CHECKS.md b/00_TOOLS/Prerequisites/Prerequisites_CHECKS.md index 0807a67..4c96193 100644 --- a/00_TOOLS/Prerequisites/Prerequisites_CHECKS.md +++ b/00_TOOLS/Prerequisites/Prerequisites_CHECKS.md @@ -19,10 +19,10 @@ After completing each section of **Prerequisites.md**, return here and check if Can you answer these questions? -1. **Why do we use WSL2 + Docker instead of Docker Desktop?** +1. **What is the purpose of this WSL2 alternative?**
Answer - WSL2 + Docker offers: better performance (native Linux kernel), lower resource consumption, complete access to Linux network stack, greater educational value (real Linux environment) and is completely free. + This alternative keeps Docker, Python packages and exercise files in the same Linux environment. Portainer is an optional management interface. The MININET-SDN VirtualBox appliance remains the classroom route.
2. **What components will we install and in what order?** @@ -93,7 +93,7 @@ Can you answer these questions? 1. **What command enables WSL2?**
Answer - `wsl --install` in PowerShell as Administrator + `wsl --install --no-distribution` for platform preparation, then `wsl --install -d Ubuntu-22.04 --web-download` under the intended Windows user
2. **How do you verify that WSL2 is the default version?** @@ -179,7 +179,7 @@ docker run --rm alpine echo "Test" 2. **On which port do you access Portainer from the browser?**
Answer - http://localhost:9000 + http://localhost:9050
📌 **Practical verification:** @@ -197,16 +197,16 @@ docker ps | grep portainer ### ✓ Understanding Check -1. **Why doesn't Docker start automatically in WSL2 after Windows restart?** +1. **Does a container restart policy start Docker and WSL automatically after Windows restart?**
Answer - WSL2 does not have systemd enabled by default, so services do not initialise automatically at boot. + No. Docker must first be running inside the intended WSL distribution. Service startup depends on its init configuration; check whether PID 1 is systemd. A container restart policy does not launch WSL itself.
2. **What command manually starts Docker in WSL?**
Answer - `sudo service docker start` + `sudo systemctl start docker` when systemd is PID 1, otherwise `sudo service docker start`
📌 **Common confusion:** See [docs/misconceptions.md](../../00_APPENDIX/docs/misconceptions.md) — Misconception 7 (Docker auto-start). @@ -220,14 +220,14 @@ docker ps | grep portainer Can you tick all these points? -- [ ] `wsl --status` shows "Default Version: 2" -- [ ] `docker --version` displays a version (28.x.x) +- [ ] `wsl --list --verbose` shows VERSION 2 for the distribution actually used +- [ ] `docker --version` and `docker compose version` report the installed versions - [ ] `docker ps` works without sudo -- [ ] Portainer container appears in `docker ps` -- [ ] Can access http://localhost:9000 from browser -- [ ] Can login to Portainer with stud/studstudstud +- [ ] If using optional Portainer, its container appears in `docker ps` +- [ ] If using Portainer, can access http://localhost:9050 from the browser +- [ ] If using Portainer, can log in with the configured account - [ ] Wireshark sees the "vEthernet (WSL)" interface -- [ ] `python3 -c "import docker, scapy, dpkt"` gives no error +- [ ] After activating the Linux virtual environment, `python3 -c "import docker, scapy, dpkt"` gives no error ### 🏁 Final Verification with Script diff --git a/00_TOOLS/Prerequisites/README.md b/00_TOOLS/Prerequisites/README.md index 548cad9..50f0c0b 100644 --- a/00_TOOLS/Prerequisites/README.md +++ b/00_TOOLS/Prerequisites/README.md @@ -1,15 +1,17 @@ # Prerequisites — Environment Setup -Student-facing documentation for configuring the lab environment before the first seminar. The default stack is WSL2 + Ubuntu + Docker Engine + Portainer CE, with Wireshark and Python 3.10+ on the host. Students complete this guide during week 0; the automated verification script confirms readiness. +Student-facing documentation for the **alternative WSL2 route**. The ASE classroom route uses the [MININET-SDN VirtualBox appliance](../../01_GUIDE_MININET-SDN/). Follow that guide and its [VM verifier](../../01_GUIDE_MININET-SDN/verify_mininet_vm.sh) when using the OVA. + +For the WSL alternative, Docker Engine and the course Python environment run inside Ubuntu. Wireshark runs on Windows where required. Portainer is optional and uses loopback port 9050. Passing prerequisite checks does not certify every seminar. ## File Index -| File | Description | Lines | -|---|---|---| -| [`Prerequisites.md`](Prerequisites.md) | Full installation guide — WSL2, Ubuntu, Docker, Portainer, Wireshark, Python packages and auto-start configuration | 1158 | -| [`Prerequisites_CHECKS.md`](Prerequisites_CHECKS.md) | Self-assessment questions per section of the main guide — understanding checks with expandable answers | 264 | -| [`verify_lab_environment.sh`](verify_lab_environment.sh) | Automated Bash script that tests WSL2, Docker, Portainer, Python and network tools; exits with a pass/fail summary | 506 | -| `wireshark_capture_example.png` | Screenshot used within the prerequisites guide | — | +| File | Description | +|---|---| +| [`Prerequisites.md`](Prerequisites.md) | Full installation guide — WSL2, Ubuntu, Docker, Portainer, Wireshark, Python packages and auto-start configuration | +| [`Prerequisites_CHECKS.md`](Prerequisites_CHECKS.md) | Self-assessment questions per section of the main guide — understanding checks with expandable answers | +| [`verify_lab_environment.sh`](verify_lab_environment.sh) | Local prerequisite checks for WSL2, Docker, optional Portainer and Linux Python; no package installation or image pull | +| `wireshark_capture_example.png` | Screenshot used within the prerequisites guide | ## Usage @@ -19,7 +21,7 @@ After completing the manual setup steps in `Prerequisites.md`, run the verificat bash verify_lab_environment.sh ``` -The script checks: WSL2 presence, Ubuntu version, Docker Engine status, Portainer container health, Python version and key packages and network tool availability. A colour-coded summary is printed at the end. If any component reports a failure, consult the corresponding section of `Prerequisites.md` or the troubleshooting appendix therein. +The script checks the WSL kernel, Ubuntu metadata, Docker daemon and Compose plugin, optional Portainer API, active Linux Python imports and network tools. Use `--online` only when you also want bounded HTTPS probes. Run it after activating `~/venvs/compnet-wsl`; Windows Python packages are not checked. Errors return exit 1; a wrong execution environment or invalid option returns exit 2. Subprocess prerequisite probes have a 15-second limit and a 2-second forced-stop grace, using GNU `timeout` from Ubuntu coreutils. It does not run Mininet/OpenFlow or a complete seminar. ## Design Rationale diff --git a/00_TOOLS/Prerequisites/verify_lab_environment.sh b/00_TOOLS/Prerequisites/verify_lab_environment.sh index 005ed9c..0bd578c 100755 --- a/00_TOOLS/Prerequisites/verify_lab_environment.sh +++ b/00_TOOLS/Prerequisites/verify_lab_environment.sh @@ -1,506 +1,154 @@ -#!/bin/bash -#═══════════════════════════════════════════════════════════════════════════════ -# verify_lab_environment.sh -# Complete verification script for the Computer Networks lab environment -# -# Academia de Studii Economice din București — CSIE -# Programmes: Economic Informatics & AI in Economics and Business -# -# Version: 2.0 (January 2025) -# Author: Revolvix -# -# Checks: WSL2, Ubuntu, Docker, Portainer, Python, network tools -# Compatible with: netENwsl & netROwsl repositories -#═══════════════════════════════════════════════════════════════════════════════ +#!/usr/bin/env bash +# WSL alternative environment checks for COMPNET-EN. +# Based on the original v2.0 verifier credited to Revolvix (January 2025). +# This revision checks prerequisites only; it does not install or pull images. +# For the VirtualBox appliance use 01_GUIDE_MININET-SDN/verify_mininet_vm.sh. +set -u -# Colours for output -GREEN='\033[0;32m' -RED='\033[0;31m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -CYAN='\033[0;36m' -MAGENTA='\033[0;35m' -BOLD='\033[1m' -NC='\033[0m' # No colour - -# Result counters ERRORS=0 WARNINGS=0 PASSED=0 - -# Reserved port for Portainer -PORTAINER_PORT=9000 - -#─────────────────────────────────────────────────────────────────────────────── -# Verification functions -#─────────────────────────────────────────────────────────────────────────────── - -print_header() { - echo "" - echo "╔═══════════════════════════════════════════════════════════════════════════════╗" - echo "║ ║" - echo "║ 🖧 COMPUTER NETWORKS LAB — ENVIRONMENT VERIFICATION ║" - echo "║ ║" - echo "║ Academia de Studii Economice din București — CSIE ║" - echo "║ by Revolvix | Version 2.0 | January 2025 ║" - echo "║ ║" - echo "╚═══════════════════════════════════════════════════════════════════════════════╝" - echo "" -} - -print_section() { - echo "" - echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" - echo -e "${BLUE}▶ $1${NC}" - echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" -} - -check_required() { - local name="$1" - local command="$2" - - if eval "$command" &>/dev/null; then - echo -e " ${GREEN}✓${NC} $name" - ((PASSED++)) - return 0 - else - echo -e " ${RED}✗${NC} $name ${RED}[MISSING]${NC}" - ((ERRORS++)) - return 1 - fi -} - -check_optional() { - local name="$1" - local command="$2" - - if eval "$command" &>/dev/null; then - echo -e " ${GREEN}✓${NC} $name" - ((PASSED++)) - return 0 - else - echo -e " ${YELLOW}○${NC} $name ${YELLOW}(optional — recommended)${NC}" - ((WARNINGS++)) - return 1 - fi -} - -check_info() { - local name="$1" - local value="$2" - echo -e " ${CYAN}ℹ${NC} $name: ${BOLD}$value${NC}" -} - -check_port() { - local port="$1" - local service="$2" - - if ss -tlnp 2>/dev/null | grep -q ":$port "; then - echo -e " ${GREEN}✓${NC} Port $port ($service) — ${GREEN}ACTIVE${NC}" - return 0 +ONLINE=false +PORTAINER_PORT=9050 +for option in "$@"; do + case "$option" in + --online) ONLINE=true ;; + --help|-h) printf 'Usage: bash verify_lab_environment.sh [--online]\nDefault: local WSL checks only. --online adds bounded HTTPS probes; no downloads or image pulls.\n'; exit 0 ;; + *) printf 'Unknown option: %s\n' "$option" >&2; exit 2 ;; + esac +done +if ! command -v timeout >/dev/null 2>&1; then + printf 'GNU timeout is required (Ubuntu coreutils). No prerequisite commands were run.\n' >&2 + exit 2 +fi +# A stalled daemon, import or helper must not block the readiness report forever. +probe() { + if [[ "$1" == command && "${2:-}" == -v ]]; then + command -v "$3" else - echo -e " ${YELLOW}○${NC} Port $port ($service) — ${YELLOW}INACTIVE${NC}" - return 1 + timeout -k 2s 15s "$@" fi } - -#─────────────────────────────────────────────────────────────────────────────── -# Begin verification -#─────────────────────────────────────────────────────────────────────────────── - -print_header - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 1: System Information -#─────────────────────────────────────────────────────────────────────────────── - -print_section "SYSTEM INFORMATION" - -check_info "Hostname" "$(hostname 2>/dev/null || echo 'N/A')" -check_info "User" "$(whoami 2>/dev/null || echo 'N/A')" -check_info "Home" "$HOME" -check_info "Shell" "$SHELL" - -# Check whether we are running inside WSL -if grep -qi microsoft /proc/version 2>/dev/null || grep -qi WSL /proc/version 2>/dev/null; then - check_info "Environment" "${GREEN}WSL2 detected${NC}" - IS_WSL=true +pass() { printf 'PASS %s\n' "$*"; PASSED=$((PASSED+1)); } +warn() { printf 'WARN %s\n' "$*"; WARNINGS=$((WARNINGS+1)); } +fail() { printf 'FAIL %s\n' "$*"; ERRORS=$((ERRORS+1)); } +required() { local label="$1"; shift; if probe "$@" >/dev/null 2>&1; then pass "$label"; else fail "$label"; fi; } +optional() { local label="$1"; shift; if probe "$@" >/dev/null 2>&1; then pass "$label"; else warn "$label"; fi; } + +printf 'COMPNET-EN — WSL alternative: prerequisite verification\n' +kernel="$(probe uname -r)" +if [[ "$kernel" != *[Mm]icrosoft* && "$kernel" != *WSL* ]]; then + printf 'This script targets the WSL route. For MININET-SDN in VirtualBox, run:\n' + printf ' bash 01_GUIDE_MININET-SDN/verify_mininet_vm.sh\n' + printf 'No acceptance claim has been made for this native Linux/VirtualBox environment.\n' + exit 2 +fi +if [[ "$kernel" == *[Mm]icrosoft-standard* || "$kernel" == *WSL2* ]]; then + pass 'WSL2 kernel identified' else - check_info "Environment" "${YELLOW}Native Linux (not WSL)${NC}" - IS_WSL=false + fail 'WSL detected but WSL2 not established; confirm VERSION 2 with wsl --list --verbose on Windows' fi - -# Ubuntu version -if [ -f /etc/os-release ]; then +if [[ -r /etc/os-release ]]; then + # Standard distribution metadata; no user configuration is sourced. . /etc/os-release - check_info "Distribution" "$PRETTY_NAME" - - # Check for recommended Ubuntu version - if [[ "$VERSION_ID" == "22.04" ]]; then - echo -e " ${GREEN}✓${NC} Recommended Ubuntu version (22.04 LTS)" - ((PASSED++)) - elif [[ "$VERSION_ID" =~ ^2[2-4]\. ]]; then - echo -e " ${YELLOW}○${NC} Acceptable Ubuntu version ($VERSION_ID)" - ((WARNINGS++)) + printf 'Distribution: %s\n' "${PRETTY_NAME:-unknown}" + if [[ "${ID:-}" == ubuntu && "${VERSION_ID:-}" =~ ^(22\.04|24\.04)$ ]]; then + pass 'Ubuntu LTS release documented by this setup route' else - echo -e " ${RED}✗${NC} Unexpected Ubuntu version ($VERSION_ID) — 22.04 LTS recommended" - ((ERRORS++)) + warn 'This distribution is outside the documented Ubuntu 22.04/24.04 route' fi -fi - -check_info "Kernel" "$(uname -r 2>/dev/null || echo 'N/A')" -check_info "Architecture" "$(uname -m 2>/dev/null || echo 'N/A')" - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 2: Core Components -#─────────────────────────────────────────────────────────────────────────────── - -print_section "CORE COMPONENTS" - -# Python -check_required "Python 3.11+" "python3 --version 2>&1 | grep -E 'Python 3\.(1[1-9]|[2-9][0-9])'" -if python3 --version &>/dev/null; then - PYTHON_VERSION=$(python3 --version 2>&1 | cut -d' ' -f2) - check_info "Python version" "$PYTHON_VERSION" -fi - -check_required "pip3" "pip3 --version" -check_required "Git" "git --version" -check_required "curl" "curl --version" -check_required "wget" "wget --version" - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 3: Docker -#─────────────────────────────────────────────────────────────────────────────── - -print_section "DOCKER" - -check_required "Docker Engine" "docker --version" -if docker --version &>/dev/null; then - DOCKER_VERSION=$(docker --version 2>&1 | cut -d' ' -f3 | tr -d ',') - check_info "Docker version" "$DOCKER_VERSION" -fi - -check_required "Docker Compose (plugin)" "docker compose version" -if docker compose version &>/dev/null; then - COMPOSE_VERSION=$(docker compose version 2>&1 | cut -d' ' -f4) - check_info "Compose version" "$COMPOSE_VERSION" -fi - -# Verify Docker daemon -if docker info &>/dev/null; then - echo -e " ${GREEN}✓${NC} Docker daemon is active and responding" - ((PASSED++)) else - echo -e " ${RED}✗${NC} Docker daemon is not responding" - echo -e " ${YELLOW}→ Try: sudo service docker start${NC}" - ((ERRORS++)) -fi - -# Check whether Docker runs without sudo -if docker ps &>/dev/null; then - echo -e " ${GREEN}✓${NC} Docker can run without sudo" - ((PASSED++)) -else - echo -e " ${RED}✗${NC} Docker requires sudo" - echo -e " ${YELLOW}→ Run: sudo usermod -aG docker \$USER && newgrp docker${NC}" - ((ERRORS++)) -fi - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 4: Portainer (PORT 9000 RESERVED!) -#─────────────────────────────────────────────────────────────────────────────── - -print_section "PORTAINER CE (Port 9000 — RESERVED!)" - -echo -e " ${MAGENTA}⚠️ WARNING: Port 9000 is PERMANENTLY RESERVED for Portainer!${NC}" -echo -e " ${MAGENTA} No lab service should use this port.${NC}" -echo "" - -if docker ps 2>/dev/null | grep -q portainer; then - echo -e " ${GREEN}✓${NC} Portainer container is running" - ((PASSED++)) - - # Verify port 9000 - if check_port 9000 "Portainer HTTP"; then - ((PASSED++)) + warn 'Distribution metadata unavailable' +fi + +required 'Python 3.10 or later in this Linux environment' python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3,10) else 1)' +required 'pip for the same Python interpreter' python3 -m pip --version +required 'Git' git --version +required 'curl' curl --version +required 'Docker CLI' docker --version +required 'Docker Compose v2 plugin (docker compose)' docker compose version +if probe docker info >/dev/null 2>&1; then + pass 'Docker daemon responds to the current Linux user' + docker_type="$(probe docker info --format '{{.OSType}}' 2>/dev/null)" + if [[ "$docker_type" == linux ]]; then pass 'Docker daemon uses Linux containers'; else fail 'Docker daemon does not report Linux containers'; fi + if [[ -n "${DOCKER_HOST:-}" && -z "${DOCKER_CONTEXT:-}" ]]; then + daemon_address="$DOCKER_HOST" + else + daemon_address="$(probe docker context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null)" fi - - # Display access URL - echo -e " ${CYAN}ℹ${NC} Access URL: ${BOLD}http://localhost:9000${NC}" - echo -e " ${CYAN}ℹ${NC} Credentials: ${BOLD}stud / studstudstud${NC}" -else - echo -e " ${YELLOW}○${NC} Portainer is not running" - echo -e " ${YELLOW}→ Start with: docker start portainer${NC}" - echo -e " ${YELLOW}→ Or install using the command from the setup guide${NC}" - ((WARNINGS++)) -fi - -# Check whether another service occupies port 9000 -if ss -tlnp 2>/dev/null | grep -q ":9000 " && ! docker ps 2>/dev/null | grep -q portainer; then - echo -e " ${RED}✗${NC} WARNING: Port 9000 is occupied by ANOTHER service!" - echo -e " ${RED} This will cause conflicts with Portainer!${NC}" - ((ERRORS++)) -fi - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 5: Active Containers -#─────────────────────────────────────────────────────────────────────────────── - -print_section "ACTIVE DOCKER CONTAINERS" - -if docker ps &>/dev/null; then - CONTAINER_COUNT=$(docker ps --format "{{.Names}}" 2>/dev/null | wc -l) - - if [ "$CONTAINER_COUNT" -gt 0 ]; then - echo -e " ${GREEN}✓${NC} $CONTAINER_COUNT active container(s):" - echo "" - docker ps --format " │ {{.Names}}: {{.Status}} ({{.Ports}})" 2>/dev/null | head -10 - - if [ "$CONTAINER_COUNT" -gt 10 ]; then - echo " │ ... and $((CONTAINER_COUNT - 10)) more container(s)" - fi + if [[ "$daemon_address" == unix://* ]]; then + pass 'Docker context uses a local Unix socket' else - echo -e " ${CYAN}ℹ${NC} No active containers (apart from Portainer)" + fail 'Docker context is remote or unresolved; a remote daemon does not establish local WSL capability' fi else - echo -e " ${RED}✗${NC} Unable to list containers" -fi - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 6: Docker Networks -#─────────────────────────────────────────────────────────────────────────────── - -print_section "DOCKER NETWORKS" - -if docker network ls &>/dev/null; then - echo -e " ${CYAN}ℹ${NC} Available networks:" - docker network ls --format " │ {{.Name}}: {{.Driver}}" 2>/dev/null -else - echo -e " ${RED}✗${NC} Unable to list Docker networks" + fail 'Docker daemon unavailable to this user; check service, context and permissions before changing group membership' fi +required 'Docker container listing works' docker ps -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 7: Network Tools -#─────────────────────────────────────────────────────────────────────────────── - -print_section "NETWORK TOOLS" +printf '\nNetwork tools\n' +for name in tcpdump nc; do required "$name available" command -v "$name"; done +for name in tshark nmap iperf3 traceroute mtr dig ss; do optional "$name available (exercise dependent)" command -v "$name"; done -check_required "tcpdump" "which tcpdump" -check_optional "tshark (CLI Wireshark)" "which tshark" -check_required "netcat (nc)" "which nc" -check_optional "nmap" "which nmap" -check_optional "iperf3" "which iperf3" -check_optional "traceroute" "which traceroute" -check_optional "mtr" "which mtr" -check_optional "dig (DNS)" "which dig" -check_optional "ss (socket stat)" "which ss" - -# Check for Wireshark on Windows (only when running in WSL) -if [ "$IS_WSL" = true ]; then - echo "" - echo -e " ${CYAN}ℹ${NC} Checking for Wireshark on Windows..." - - if [ -d "/mnt/c/Program Files/Wireshark" ] || [ -d "/mnt/c/Program Files (x86)/Wireshark" ]; then - echo -e " ${GREEN}✓${NC} Wireshark detected on Windows" - ((PASSED++)) +printf '\nPython packages in the active Linux interpreter\n' +for module in docker scapy.all dpkt requests flask yaml colorama; do + required "Python import: $module" python3 -c "import $module" +done +for module in paramiko pyftpdlib paho.mqtt.client dns.resolver grpc google.protobuf; do + optional "Python import: $module (exercise dependent)" python3 -c "import $module" +done +printf 'These checks use Linux Python. Installing packages in Windows Python does not satisfy them.\n' + +printf '\nOptional Portainer\n' +if probe docker inspect --format '{{.State.Running}}' portainer 2>/dev/null | grep -qx true; then + pass 'Named Portainer container is running' + if probe curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:${PORTAINER_PORT}/api/status" 2>/dev/null | + probe python3 -c 'import json,sys; s=json.load(sys.stdin); raise SystemExit(0 if isinstance(s,dict) and "Version" in s else 1)' >/dev/null 2>&1; then + pass 'Portainer API responds on loopback port 9050' else - echo -e " ${YELLOW}○${NC} Wireshark does not appear to be installed on Windows" - echo -e " ${YELLOW}→ Download from: https://www.wireshark.org/download.html${NC}" - ((WARNINGS++)) + warn 'Portainer API not confirmed on 9050; inspect the actual mapping. No container was replaced.' fi -fi - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 8: Essential Python Libraries -#─────────────────────────────────────────────────────────────────────────────── - -print_section "ESSENTIAL PYTHON LIBRARIES (Required)" - -check_required "docker" "python3 -c 'import docker'" -check_required "scapy" "python3 -c 'import scapy.all'" -check_required "dpkt" "python3 -c 'import dpkt'" -check_required "requests" "python3 -c 'import requests'" -check_required "flask" "python3 -c 'import flask'" -check_required "PyYAML" "python3 -c 'import yaml'" -check_required "colorama" "python3 -c 'import colorama'" - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 9: Advanced Python Libraries -#─────────────────────────────────────────────────────────────────────────────── - -print_section "ADVANCED PYTHON LIBRARIES (Recommended for Weeks 9–14)" - -check_optional "paramiko (SSH)" "python3 -c 'import paramiko'" -check_optional "pyftpdlib (FTP)" "python3 -c 'import pyftpdlib'" -check_optional "paho-mqtt (MQTT/IoT)" "python3 -c 'import paho.mqtt.client'" -check_optional "dnspython (DNS)" "python3 -c 'import dns.resolver'" -check_optional "grpcio (gRPC)" "python3 -c 'import grpc'" -check_optional "protobuf" "python3 -c 'import google.protobuf'" - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 10: Lab Port Availability -#─────────────────────────────────────────────────────────────────────────────── - -print_section "LAB PORTS (Availability Check)" - -echo -e " ${CYAN}ℹ${NC} Port 9000: ${MAGENTA}RESERVED for Portainer${NC} (DO NOT use!)" -echo "" - -# Common ports used in lab sessions -declare -A LAB_PORTS=( - [8080]="HTTP / Load Balancer" - [8081]="Backend Server 1" - [8082]="Backend Server 2" - [8083]="Backend Server 3" - [9090]="Echo Server / TCP Test" - [1883]="MQTT plaintext (Week 13)" - [8883]="MQTT TLS (Week 13)" - [2525]="SMTP test (Week 12)" - [5000]="JSON-RPC / Flask (Week 12)" - [50051]="gRPC (Week 12)" - [2121]="FTP test (Week 13)" -) - -echo -e " ${CYAN}ℹ${NC} Ports currently in use:" - -PORTS_IN_USE=0 -for port in "${!LAB_PORTS[@]}"; do - if ss -tlnp 2>/dev/null | grep -q ":$port "; then - echo -e " │ ${YELLOW}:$port${NC} - ${LAB_PORTS[$port]} - ${YELLOW}IN USE${NC}" - ((PORTS_IN_USE++)) - fi -done - -if [ "$PORTS_IN_USE" -eq 0 ]; then - echo -e " │ ${GREEN}No lab ports currently in use${NC}" -fi - -echo "" -echo -e " ${CYAN}ℹ${NC} Ports ${GREEN}8080–8089${NC} and ${GREEN}9001–9099${NC} are available for lab work." - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 11: Internet Connectivity -#─────────────────────────────────────────────────────────────────────────────── - -print_section "CONNECTIVITY" - -# Ping test -if ping -c 1 -W 2 8.8.8.8 &>/dev/null; then - echo -e " ${GREEN}✓${NC} Internet access (ping 8.8.8.8)" - ((PASSED++)) else - echo -e " ${RED}✗${NC} No Internet access" - ((ERRORS++)) + warn 'Portainer is not running; it is optional for CLI-based exercises' fi +printf 'Portainer, when configured: http://localhost:9050. Port 9000 remains available for the S10 tunnel.\n' +printf 'Account authentication and endpoint access are checked by portainer-init.sh, not by this verifier.\n' -# DNS test -if host google.com &>/dev/null || dig google.com +short &>/dev/null; then - echo -e " ${GREEN}✓${NC} DNS resolution is working" - ((PASSED++)) -else - echo -e " ${YELLOW}○${NC} DNS resolution issues" - ((WARNINGS++)) -fi - -# Docker Hub test -if docker pull hello-world &>/dev/null 2>&1 || docker images hello-world --format "{{.Repository}}" 2>/dev/null | grep -q hello-world; then - echo -e " ${GREEN}✓${NC} Docker Hub access" - ((PASSED++)) -else - echo -e " ${YELLOW}○${NC} Docker Hub access issues" - ((WARNINGS++)) -fi - -#─────────────────────────────────────────────────────────────────────────────── -# SECTION 12: Disc Space -#─────────────────────────────────────────────────────────────────────────────── - -print_section "DISC SPACE" - -# Available space in home -DISK_AVAIL=$(df -h ~ 2>/dev/null | awk 'NR==2 {print $4}') -DISK_USED_PERCENT=$(df -h ~ 2>/dev/null | awk 'NR==2 {print $5}' | tr -d '%') - -check_info "Available space in ~" "$DISK_AVAIL" - -if [ -n "$DISK_USED_PERCENT" ]; then - if [ "$DISK_USED_PERCENT" -lt 80 ]; then - echo -e " ${GREEN}✓${NC} Sufficient disc space available ($DISK_USED_PERCENT% used)" - ((PASSED++)) - elif [ "$DISK_USED_PERCENT" -lt 90 ]; then - echo -e " ${YELLOW}○${NC} Limited disc space ($DISK_USED_PERCENT% used)" - ((WARNINGS++)) +printf '\nStorage\n' +if disk_kib="$(probe df -Pk "${HOME:-.}" 2>/dev/null | awk 'NR==2 {print $4}')" && [[ "$disk_kib" =~ ^[0-9]+$ ]]; then + if (( disk_kib >= 5 * 1024 * 1024 )); then + pass 'At least 5 GiB free on the Linux home filesystem' else - echo -e " ${RED}✗${NC} Insufficient disc space ($DISK_USED_PERCENT% used)" - ((ERRORS++)) + warn 'Less than 5 GiB free on the Linux home filesystem; image builds may require more' fi +else + warn 'Could not determine free filesystem space' fi +printf 'Also check free space on the Windows volume storing the WSL virtual disk.\n' -# Docker disc usage -if docker system df &>/dev/null; then - echo "" - echo -e " ${CYAN}ℹ${NC} Docker disc usage:" - docker system df --format " │ {{.Type}}: {{.Size}} ({{.Reclaimable}} reclaimable)" 2>/dev/null -fi - -#─────────────────────────────────────────────────────────────────────────────── -# FINAL SUMMARY -#─────────────────────────────────────────────────────────────────────────────── - -echo "" -echo "╔═══════════════════════════════════════════════════════════════════════════════╗" -echo "║ VERIFICATION SUMMARY ║" -echo "╚═══════════════════════════════════════════════════════════════════════════════╝" -echo "" - -TOTAL=$((PASSED + ERRORS + WARNINGS)) - -echo -e " ${GREEN}✓ Checks passed:${NC} $PASSED" -echo -e " ${RED}✗ Critical errors:${NC} $ERRORS" -echo -e " ${YELLOW}○ Warnings:${NC} $WARNINGS" -echo -e " ─────────────────────────" -echo -e " ${BOLD}Total checks:${NC} $TOTAL" -echo "" - -if [ $ERRORS -eq 0 ]; then - echo -e "╔═══════════════════════════════════════════════════════════════════════════════╗" - echo -e "║ ${GREEN}✅ LAB ENVIRONMENT IS CORRECTLY CONFIGURED!${NC} ║" - echo -e "╚═══════════════════════════════════════════════════════════════════════════════╝" - echo "" - - if [ $WARNINGS -gt 0 ]; then - echo -e " ${YELLOW}Note: $WARNINGS optional components are missing. These may be needed${NC}" - echo -e " ${YELLOW}for advanced lab sessions (Weeks 9–14).${NC}" - echo "" +if [[ "$ONLINE" == true ]]; then + printf '\nOptional HTTPS connectivity probes\n' + if curl -fsS -I --connect-timeout 3 --max-time 10 https://github.com >/dev/null 2>&1; then + pass 'HTTPS connection to GitHub succeeded' + else + warn 'HTTPS connection to GitHub failed; proxy, DNS, network or service availability may be responsible' fi - - echo -e " 📚 Available repositories:" - echo -e " 🇬🇧 https://github.com/antonioclim/netENwsl" - echo -e " 🇷🇴 https://github.com/antonioclim/netROwsl" - echo "" - echo -e " 🌐 Portainer: http://localhost:9000 (stud / studstudstud)" - echo "" + registry_status="$(probe curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 3 --max-time 10 https://registry-1.docker.io/v2/ 2>/dev/null || true)" + case "$registry_status" in + 200|401) pass 'Docker registry HTTPS endpoint responds (this does not verify image-pull authorisation)' ;; + *) warn 'Docker registry HTTPS endpoint not confirmed; cached images do not prove online access' ;; + esac else - echo -e "╔═══════════════════════════════════════════════════════════════════════════════╗" - echo -e "║ ${RED}❌ ERRORS DETECTED — ENVIRONMENT IS NOT FULLY CONFIGURED${NC} ║" - echo -e "╚═══════════════════════════════════════════════════════════════════════════════╝" - echo "" - echo -e " ${RED}Resolve the errors marked with ✗ before continuing.${NC}" - echo "" - echo -e " Common issues and solutions:" - echo -e " ─────────────────────────────" - echo -e " • Docker daemon not responding → ${CYAN}sudo service docker start${NC}" - echo -e " • Docker requires sudo → ${CYAN}sudo usermod -aG docker \$USER && newgrp docker${NC}" - echo -e " • Missing Python packages → ${CYAN}pip3 install --break-system-packages ${NC}" - echo -e " • Portainer not running → ${CYAN}docker start portainer${NC}" - echo "" + printf '\nInternet access was not tested. Use --online to request bounded HTTPS probes.\n' fi -echo -e "─────────────────────────────────────────────────────────────────────────────────" -echo -e " ${BOLD}Computer Networks Lab${NC} — ASE București, CSIE" -echo -e " Verification script v2.0 | January 2025 | by Revolvix" -echo -e "─────────────────────────────────────────────────────────────────────────────────" -echo "" - -exit $ERRORS +printf '\nSummary: %s passed, %s errors, %s warnings.\n' "$PASSED" "$ERRORS" "$WARNINGS" +printf 'Each subprocess prerequisite probe is limited to 15 seconds, with a 2-second forced-stop grace.\n' +printf 'Scope: prerequisite availability only. No Mininet/SDN exercise, packet capture or complete seminar was executed.\n' +printf 'Course: https://github.com/antonioclim/COMPNET-EN\n' +if (( ERRORS == 0 )); then + printf 'Required WSL prerequisites checked; review warnings for the selected exercise.\n' + exit 0 +fi +printf 'Resolve the reported prerequisite failures before the affected exercise.\n' +exit 1 diff --git a/00_TOOLS/mininet/README.md b/00_TOOLS/mininet/README.md index 9cdf857..5ff0f7e 100644 --- a/00_TOOLS/mininet/README.md +++ b/00_TOOLS/mininet/README.md @@ -1,5 +1,7 @@ # Mininet / Open vSwitch utilities +**ASE lab environment:** use the [MININET-SDN appliance and setup guide](../../01_GUIDE_MININET-SDN/README.md#download-the-lab-virtual-machine). The workstation provisioning script for ASE PCs is not a student prerequisite. + ## `ovs_reset.sh` A **lab-only** deep reset helper for Mininet + Open vSwitch. diff --git a/00_TOOLS/mininet/ovs_reset.sh b/00_TOOLS/mininet/ovs_reset.sh index e93551d..4cd2e1f 100644 --- a/00_TOOLS/mininet/ovs_reset.sh +++ b/00_TOOLS/mininet/ovs_reset.sh @@ -26,7 +26,7 @@ # # Notes # ----- -# - Verification mode (--verify) is non-destructive and does not require sudo. +# - Verification mode (--verify) is non-destructive; it needs permission to read OVSDB. # - Full reset requires sudo because it manipulates OVS and namespaces. set -euo pipefail @@ -86,7 +86,10 @@ delete_ovs_bridges() { require_cmd ovs-vsctl local bridges - bridges=$(ovs-vsctl list-br 2>/dev/null || true) + if ! bridges=$(ovs-vsctl --timeout=10 list-br); then + log_error "Cannot read OVSDB; a failed query does not prove that it is empty." + return 1 + fi if [[ -z "${bridges}" ]]; then log_success "No OVS bridges found" @@ -96,7 +99,7 @@ delete_ovs_bridges() { while IFS= read -r br; do [[ -z "$br" ]] && continue log_info " deleting bridge: $br" - ovs-vsctl --if-exists del-br "$br" 2>/dev/null || true + ovs-vsctl --timeout=10 --if-exists del-br "$br" || return 1 done <<<"${bridges}" log_success "OVS bridges removed" @@ -105,32 +108,33 @@ delete_ovs_bridges() { mininet_cleanup() { if command -v mn >/dev/null 2>&1; then log_info "Running standard Mininet cleanup: mn -c" - mn -c 2>/dev/null || true - log_success "Mininet cleanup complete" + if mn -c; then + log_success "Mininet cleanup complete" + else + log_warn "Mininet cleanup returned an error; inspect the output before continuing." + fi else log_warn "Mininet command 'mn' not found; skipped mn -c" fi } restart_ovs() { - log_info "Restarting Open vSwitch service (best effort)…" - - # Common service names on Ubuntu/Debian. - if command -v systemctl >/dev/null 2>&1; then - systemctl restart openvswitch-switch 2>/dev/null || true - fi - - if command -v service >/dev/null 2>&1; then - service openvswitch-switch restart 2>/dev/null || true + log_info "Restarting Open vSwitch service…" + local restarted=0 + if command -v systemctl >/dev/null 2>&1 && + systemctl restart openvswitch-switch; then + restarted=1 + elif command -v service >/dev/null 2>&1 && + service openvswitch-switch restart; then + restarted=1 fi - - # Last resort: ask ovs-vswitchd to exit cleanly (OVS may respawn via systemd) - if command -v ovs-appctl >/dev/null 2>&1; then - ovs-appctl exit --cleanup 2>/dev/null || true + if [[ $restarted -ne 1 ]]; then + log_error "Open vSwitch restart failed; the reset is incomplete." + return 1 fi - + # Do not ask ovs-vswitchd to exit after successfully starting the service. sleep 2 - log_success "OVS restart attempted" + log_success "Open vSwitch service restarted" } verify_clean() { @@ -138,7 +142,10 @@ verify_clean() { log_info "Verifying clean OVS state…" local bridges - bridges=$(ovs-vsctl list-br 2>/dev/null || true) + if ! bridges=$(ovs-vsctl --timeout=10 list-br); then + log_error "Cannot read OVSDB; a failed query does not prove that it is empty." + return 1 + fi if [[ -z "${bridges}" ]]; then log_success "OVS is clean (no bridges)" @@ -150,7 +157,7 @@ verify_clean() { if [[ $QUIET -eq 0 ]]; then echo "" log_info "Current OVS status:" - ovs-vsctl show || true + ovs-vsctl --timeout=10 show || return 1 echo "" fi @@ -230,7 +237,7 @@ main() { exit 0 else echo "================================================" - log_warn "Reset completed with warnings — leftover bridges detected." + log_warn "Reset incomplete — inspect the OVS query and bridge diagnostics above." echo "================================================" exit 1 fi diff --git a/00_TOOLS/qa/executable_manifest.txt b/00_TOOLS/qa/executable_manifest.txt index a7ee9b0..d838b0f 100644 --- a/00_TOOLS/qa/executable_manifest.txt +++ b/00_TOOLS/qa/executable_manifest.txt @@ -41,6 +41,9 @@ 00_TOOLS/release/create_release_zip.sh 00_TOOLS/subnetting/subnet_quiz_generator.py +# ── 01_GUIDE_MININET-SDN ──────────────────────────────────────── +01_GUIDE_MININET-SDN/verify_mininet_vm.sh + # ── 02_PROJECTS ────────────────────────────────────────────── 02_PROJECTS/00_common/assets/render.sh 02_PROJECTS/00_common/docker/tester_base/entrypoint.sh diff --git a/00_TOOLS/qa/test_mininet_setup_contracts.py b/00_TOOLS/qa/test_mininet_setup_contracts.py new file mode 100644 index 0000000..b8c0323 --- /dev/null +++ b/00_TOOLS/qa/test_mininet_setup_contracts.py @@ -0,0 +1,171 @@ +"""Regression checks for the VM setup fixes, without privileged networking. + +The controller is executed against a small in-memory OpenFlow message recorder. +These checks exercise policy precedence, persistence and event registration; +they do not emulate a switch or establish native OS-Ken/Mininet acceptance. +OVS verification tests use a fake ovs-vsctl executable and never reset OVS. +Run: python3 -m unittest discover -s 00_TOOLS/qa -p test_mininet_setup_contracts.py -v +""" + +from __future__ import annotations + +import importlib.util +import logging +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import types +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +CONTROLLER = ROOT / "04_SEMINARS/S06/2_sdn/S06_Part02C_Script_SDNOS_Ken_Controller_AdvancedPolicy.py" + + +def load_controller(allow_udp: bool): + names = [ + "os_ken", "os_ken.base", "os_ken.base.app_manager", "os_ken.controller", + "os_ken.controller.ofp_event", "os_ken.controller.handler", "os_ken.lib", + "os_ken.lib.packet", "os_ken.lib.packet.packet", "os_ken.lib.packet.ethernet", + "os_ken.lib.packet.arp", "os_ken.lib.packet.ipv4", "os_ken.lib.packet.ether_types", + "os_ken.ofproto", "os_ken.ofproto.ofproto_v1_3", + ] + modules = {name: types.ModuleType(name) for name in names} + for name, module in modules.items(): + if "." in name: + parent, leaf = name.rsplit(".", 1) + setattr(modules[parent], leaf, module) + + class OSKenApp: + def __init__(self, *args, **kwargs): + self.logger = logging.getLogger("controller-test") + + def register(event, dispatcher): + def decorate(function): + function.observed_event = event + function.observed_dispatcher = dispatcher + return function + return decorate + + modules["os_ken.base.app_manager"].OSKenApp = OSKenApp + handler = modules["os_ken.controller.handler"] + handler.CONFIG_DISPATCHER = "config" + handler.MAIN_DISPATCHER = "main" + handler.set_ev_cls = register + events = modules["os_ken.controller.ofp_event"] + events.EventOFPSwitchFeatures = type("EventOFPSwitchFeatures", (), {}) + events.EventOFPPacketIn = type("EventOFPPacketIn", (), {}) + modules["os_ken.ofproto.ofproto_v1_3"].OFP_VERSION = 4 + spec = importlib.util.spec_from_file_location("tested_sdn_controller", CONTROLLER) + module = importlib.util.module_from_spec(spec) + with patch.dict(sys.modules, modules), patch.dict(os.environ, {"ALLOW_UDP_TO_H3": str(int(allow_udp)), "FLOW_IDLE_TIMEOUT": "60", "FLOW_HARD_TIMEOUT": "300"}): + spec.loader.exec_module(module) + return module + + +class Parser: + @staticmethod + def OFPMatch(**fields): + return fields + + @staticmethod + def OFPActionOutput(port, max_len=None): + return types.SimpleNamespace(port=port, max_len=max_len) + + @staticmethod + def OFPInstructionActions(kind, actions): + return types.SimpleNamespace(kind=kind, actions=actions) + + @staticmethod + def OFPFlowMod(**fields): + return types.SimpleNamespace(**fields) + + +def initial_rules(allow_udp: bool): + module = load_controller(allow_udp) + messages = [] + datapath = types.SimpleNamespace( + id=1, ofproto_parser=Parser, + ofproto=types.SimpleNamespace(OFPP_CONTROLLER=0xFFFFFFFD, OFPCML_NO_BUFFER=0xFFFF, OFPIT_APPLY_ACTIONS=4), + send_msg=messages.append, + ) + app = module.AdvancedPolicyController() + app.switch_features_handler(types.SimpleNamespace(msg=types.SimpleNamespace(datapath=datapath))) + return module, messages + + +def selected_ports(rules, src, dst, protocol, elapsed=0): + packet = dict(eth_type=0x0800, ipv4_src=src, ipv4_dst=dst, ip_proto=protocol) + candidates = [ + rule for rule in rules + if all(packet.get(key) == value for key, value in rule.match.items()) + and (rule.hard_timeout == 0 or elapsed < rule.hard_timeout) + and (rule.idle_timeout == 0 or elapsed < rule.idle_timeout) + ] + rule = max(candidates, key=lambda entry: entry.priority) + return [action.port for instruction in rule.instructions for action in instruction.actions] + + +class ControllerPolicyTests(unittest.TestCase): + def test_features_are_observed_during_configuration(self): + module = load_controller(False) + self.assertEqual(module.AdvancedPolicyController.switch_features_handler.observed_dispatcher, "config") + self.assertEqual(module.AdvancedPolicyController.OFP_VERSIONS, [4]) + + def test_default_h1_h2_bidirectional_traffic_is_permitted(self): + module, rules = initial_rules(False) + for protocol in (1, 6, 17): + self.assertEqual(selected_ports(rules, module.H1_IP, module.H2_IP, protocol), [2]) + self.assertEqual(selected_ports(rules, module.H2_IP, module.H1_IP, protocol), [1]) + + def test_protected_host_is_blocked_without_exception(self): + module, rules = initial_rules(False) + for peer in (module.H1_IP, module.H2_IP): + for protocol in (1, 6, 17): + self.assertEqual(selected_ports(rules, peer, module.H3_IP, protocol), []) + self.assertEqual(selected_ports(rules, module.H3_IP, peer, protocol), []) + + def test_udp_exception_wins_in_both_directions(self): + module, rules = initial_rules(True) + for peer, peer_port in ((module.H1_IP, 1), (module.H2_IP, 2)): + self.assertEqual(selected_ports(rules, peer, module.H3_IP, 17), [3]) + self.assertEqual(selected_ports(rules, module.H3_IP, peer, 17), [peer_port]) + for protocol in (1, 6): + self.assertEqual(selected_ports(rules, peer, module.H3_IP, protocol), []) + self.assertEqual(selected_ports(rules, module.H3_IP, peer, protocol), []) + + def test_udp_policy_does_not_expire_into_permanent_drop(self): + module, rules = initial_rules(True) + for elapsed in (61, 301, 3600): + self.assertEqual(selected_ports(rules, module.H1_IP, module.H3_IP, 17, elapsed), [3]) + self.assertEqual(selected_ports(rules, module.H3_IP, module.H1_IP, 17, elapsed), [1]) + + +class OVSVerificationTests(unittest.TestCase): + def run_verifier(self, stdout, exit_code): + with tempfile.TemporaryDirectory() as directory: + command = Path(directory) / "ovs-vsctl" + command.write_text("#!/bin/sh\nprintf '%s' \"$FAKE_OVS_OUTPUT\"\nexit \"$FAKE_OVS_STATUS\"\n") + command.chmod(0o755) + environment = dict(os.environ, PATH=directory + os.pathsep + os.environ["PATH"], FAKE_OVS_OUTPUT=stdout, FAKE_OVS_STATUS=str(exit_code)) + return subprocess.run( + ["bash", str(ROOT / "00_TOOLS/mininet/ovs_reset.sh"), "--verify", "--quiet"], + env=environment, text=True, capture_output=True, timeout=5, + ) + + def test_database_failure_is_not_clean_state(self): + result = self.run_verifier("", 1) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Cannot read OVSDB", result.stderr) + + def test_successful_empty_database_is_clean(self): + self.assertEqual(self.run_verifier("", 0).returncode, 0) + + def test_remaining_bridge_is_not_clean(self): + self.assertNotEqual(self.run_verifier("s1\n", 0).returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/01_GUIDE_MININET-SDN/README.md b/01_GUIDE_MININET-SDN/README.md index 228aed9..704e420 100644 --- a/01_GUIDE_MININET-SDN/README.md +++ b/01_GUIDE_MININET-SDN/README.md @@ -1,145 +1,144 @@ -# Mininet-SDN — Setup Guide - -The VirtualBox-based lab environment for the Computer Networks course. This directory contains a complete, step-by-step installation and configuration guide that takes a student from a bare Windows 10/11 machine to a fully operational Ubuntu 24.04 virtual workstation equipped with Docker Engine, Mininet, Open vSwitch, Wireshark, Scapy, Python 3.12 and all ancillary tools required by the course seminars and projects. An alternative WSL2-based path exists in [`00_TOOLS/Prerequisites/`](../00_TOOLS/Prerequisites/); this guide covers the VirtualBox/OVA route. - -## File Index - -| File | Description | Size | -|---|---|---| -| [`SETUP-GUIDE-COMPNET-EN.md`](SETUP-GUIDE-COMPNET-EN.md) | Full guide in Markdown — 16 sections covering VirtualBox installation, OVA import, NAT port forwarding, SSH via PuTTY, Docker verification, Wireshark setup, shared folders, repository cloning, end-to-end testing, troubleshooting and a Linux host appendix | 965 lines | -| [`SETUP-GUIDE-COMPNET-EN.html`](SETUP-GUIDE-COMPNET-EN.html) | Styled HTML rendering of the same guide, using IBM Plex Sans / JetBrains Mono webfonts — suitable for offline reading or printing | 1 767 lines (79 KB) | - -## Working Architecture - -The guide produces the following environment. The ASCII diagram below is reproduced from the Markdown guide for quick orientation: - -``` -┌──────────────────────────────────────────────────────────────┐ -│ HOST (Windows 10/11) │ -│ │ -│ ┌─────────────┐ ┌────────────┐ ┌────────────────────┐ │ -│ │ PuTTY │ │ Wireshark │ │ Shared Folder │ │ -│ │ (SSH) │ │ (capture) │ │ C:\SHARED │ │ -│ └──────┬──────┘ └──────┬─────┘ └─────────┬──────────┘ │ -│ │ port 2222 │ │ vboxsf │ -│ ═══════╪════════════════╪═══════════════════╪═══════════ │ -│ │ VirtualBox NAT │ │ -│ ┌──────┴────────────────┴───────────────────┴──────────┐ │ -│ │ VM: MININET-SDN (Ubuntu 24.04) │ │ -│ │ │ │ -│ │ user: stud / pass: stud │ │ -│ │ enp0s3: 10.0.2.15 (NAT) docker0: 172.17.0.1 │ │ -│ │ │ │ -│ │ ┌────────────────────────────────────────────┐ │ │ -│ │ │ Docker Engine 28.x + Compose v2 │ │ │ -│ │ │ ┌──────┐ ┌──────┐ ┌──────┐ │ │ │ -│ │ │ │ web1 │ │ web2 │ │ dns │ ...scenarios │ │ │ -│ │ │ └──────┘ └──────┘ └──────┘ │ │ │ -│ │ └────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ Mininet 2.3 │ OVS 3.3 │ Python 3.12 (venv compnet) │ │ -│ └──────────────────────────────────────────────────────┘ │ -└──────────────────────────────────────────────────────────────┘ -``` - -## Guide Structure - -The Markdown guide follows a linear 10-step installation sequence, plus troubleshooting and a Linux appendix: - -```mermaid -flowchart LR - A["Step 1\nVirtualBox"] --> B["Step 2\nImport OVA"] - B --> C["Step 3\nNAT + Port\nForwarding"] - C --> D["Step 4\nFirst Boot\n+ Login"] - D --> E["Step 5\nPuTTY / SSH"] - E --> F["Step 6\nDocker\nVerification"] - F --> G["Step 7\nWireshark"] - G --> H["Step 8\nShared\nFolders"] - H --> I["Step 9\nClone Repo"] - I --> J["Step 10\nEnd-to-End\nTest"] - J --> K["Troubleshooting"] - - style A fill:#e1f5fe,stroke:#0288d1 - style J fill:#c8e6c9,stroke:#388e3c - style K fill:#fff3e0,stroke:#f57c00 -``` - -## VM Credentials and Port Forwarding - -| Field | Value | -|---|---| -| Username | `stud` | -| Password | `stud` | -| Hostname | `mininet-vm` | -| Guest IP (NAT) | `10.0.2.15` | -| SSH from host | `127.0.0.1:2222` → guest port `22` | -| HTTP test (optional) | `127.0.0.1:8080` → guest port `8080` | -| Docker API (optional) | `127.0.0.1:2375` → guest port `2375` | - -## Pedagogical Context - -The guide assumes zero prior virtualisation experience and deliberately leads students through every click and command so that the working environment itself becomes a first contact with networking concepts — NAT, port forwarding, SSH tunnelling, DNS resolution and Docker networking all appear before the first seminar session begins. The VirtualBox/OVA path was chosen to provide a controlled, reproducible image; the WSL2 alternative in `00_TOOLS/Prerequisites/` trades reproducibility for lighter resource usage and tighter Windows integration. - -## Cross-References - -### Prerequisites - -No prior course material is required. The guide is self-contained and targets a clean Windows installation. Students who prefer the WSL2 path should consult `00_TOOLS/Prerequisites/Prerequisites.md` instead. +# MININET-SDN — VirtualBox lab environment -### Relationship to the Rest of the Repository +MININET-SDN is the virtual workstation used for Networking and SDN in the +second semester of the third-year Economic Informatics undergraduate programme +at ASE CSIE. Antonio Clim built, configured and tested the appliance for the +teaching laboratories. Students can import the same appliance on a compatible +personal computer. -| Relationship | Path | Detail | -|---|---|---| -| Alternative setup path (WSL2) | [`../00_TOOLS/Prerequisites/`](../00_TOOLS/Prerequisites/) | Produces an equivalent Docker + Wireshark environment without VirtualBox | -| Portainer web UI | [`../00_TOOLS/Portainer/`](../00_TOOLS/Portainer/) | Portainer runs on top of the Docker Engine configured by this guide; shares the `stud`/`stud` credential convention | -| First seminar | [`../04_SEMINARS/S01/`](../04_SEMINARS/S01/) | S01 is the first session that exercises the installed tools (Wireshark, netcat, ping) | -| All Docker-based seminars | [`../04_SEMINARS/S03/`](../04_SEMINARS/S03/) through [`../04_SEMINARS/S12/`](../04_SEMINARS/S12/) | Every seminar from S03 onward runs `docker compose` scenarios inside the environment this guide creates | -| SDN firewall project | [`../02_PROJECTS/02_administration_security/`](../02_PROJECTS/02_administration_security/) | Project A01 (OpenFlow firewall) directly references the Mininet-SDN workstation | -| Instructor notes (VM variant) | [`../00_APPENDIX/d)instructor_NOTES4sem/`](../00_APPENDIX/d%29instructor_NOTES4sem/) | Seminar outlines that assume the VM environment; 13 companion `__noMININET-SDN_` variants exist for the WSL2 path | +## Download the lab virtual machine -### Downstream Dependencies +**Version 1.0.0:** [https://doi.org/10.5281/zenodo.24289763](https://doi.org/10.5281/zenodo.24289763) -The root [`README.md`](../README.md) and [`CHANGELOG.md`](../CHANGELOG.md) reference this directory (currently under the older name `01_GHID_MININET-SDN` — these links are stale and should be updated to `01_GUIDE_MININET-SDN`). No CI pipeline or Makefile target references files in this folder directly. +**Publication status:** Published on 16 November 2026. +Download `MININET-SDN.ova` and `SHA256SUMS.txt` from the +[Zenodo release record](https://zenodo.org/records/24289763). -### Suggested Learning Sequence +| Item | Value | +|---|---| +| Appliance | MININET-SDN.ova | +| File size | 1,182,349,312 bytes (1.182 GB / 1.101 GiB) | +| SHA-256 | e2e02971bc23546e9e46914e1fcd249411afdcba281b8c21a1dfba153844dff5 | +| Machine-readable identity | [appliance.json](appliance.json) | +| Checksum manifest | [SHA256SUMS.txt](SHA256SUMS.txt) | +| Installation | [Markdown guide](SETUP-GUIDE-COMPNET-EN.md) or [HTML guide](SETUP-GUIDE-COMPNET-EN.html) | -``` -01_GUIDE_MININET-SDN/ (this folder — Week 0) - → 00_TOOLS/Portainer/ (optional, same week) - → 04_SEMINARS/S01/ (Week 1 — first hands-on session) - → 03_LECTURES/C01/ (Week 1 — theoretical foundations) -``` +The DOI identifies the virtual appliance. The course materials remain in +[COMPNET-EN](https://github.com/antonioclim/COMPNET-EN). Use this specific appliance +version when following instructions for the corresponding teaching environment. -## Known Issues +The [concept DOI](https://doi.org/10.5281/zenodo.24289762) represents all versions +of the appliance. Use the version-specific DOI above with the matching checksum +to identify the exact classroom image; the concept DOI follows the latest release. -The root `README.md` (lines 63, 192, 473) and `CHANGELOG.md` (lines 34, 56, 344) still reference this folder under its former Romanian name `01_GHID_MININET-SDN`. These should be updated to `01_GUIDE_MININET-SDN` to match the current filesystem. +### Cite this appliance -## Selective Clone +Clim, A. (2026). *MININET-SDN: VirtualBox lab environment for computer networking +and software-defined networking* (Version 1.0.0) [Software]. Zenodo. +[https://doi.org/10.5281/zenodo.24289763](https://doi.org/10.5281/zenodo.24289763) -To download only this folder without cloning the full repository: +### Verify the download -**Method A — Git sparse-checkout (requires Git 2.25+)** +Download the OVA and SHA256SUMS.txt into the same directory. In Windows PowerShell: -```bash -git clone --filter=blob:none --sparse https://github.com/antonioclim/COMPNET-EN.git -cd COMPNET-EN -git sparse-checkout set 01_GUIDE_MININET-SDN -``` +~~~powershell +$expected = ((Get-Content -LiteralPath .\SHA256SUMS.txt -TotalCount 1) -split ' ', 2)[0] +$actual = (Get-FileHash -LiteralPath .\MININET-SDN.ova -Algorithm SHA256).Hash +if ($actual -ieq $expected) { 'SHA-256: MATCH' } else { throw 'SHA-256: MISMATCH' } +~~~ -**Method B — Direct download (no Git required)** +On GNU/Linux, from that directory: -Browse to the folder on GitHub: +~~~bash +sha256sum -c SHA256SUMS.txt +~~~ -``` -https://github.com/antonioclim/COMPNET-EN/tree/main/01_GUIDE_MININET-SDN -``` +## Choose the correct setup route -To download just this directory, use a tool such as [download-directory.github.io](https://download-directory.github.io) or [gitzip](https://kinolien.github.io/gitzip/). The GitHub "Download ZIP" button downloads the entire repository. +| Situation | Route | +|---|---| +| ASE classroom PC with MININET-SDN already installed | Start the existing VM and use the course repository inside it. | +| Student's compatible personal computer | Import the OVA in VirtualBox and follow this directory's setup guide. | +| WSL2 alternative for supported exercises | Use [00_TOOLS/Prerequisites](../00_TOOLS/Prerequisites/). That checker is separate from the VM checks. | +| Institutional PC provisioning | The ASE deployment script is an administrator's multi-subject setup tool; it is not required for student OVA import. | + +Docker Engine runs **inside the VM** on the appliance route. The Windows host +provides VirtualBox and, optionally, an SSH client and Wireshark. Installing +Docker Desktop or the institutional WSL stack is not part of importing this OVA. + +The course guide documents Ubuntu 24.04, x86-64, 2 vCPUs and at least 2048 MB +guest RAM. These are the guide's configuration baseline. Host requirements, +network settings and access instructions are in the setup guide; the compressed +OVA size is not the amount of disk space needed after import. + +## First use and prerequisite checks + +1. Import the OVA using VirtualBox's Import Appliance dialogue. +2. Use NAT. If SSH is required, forward host 127.0.0.1:2222 to guest port 22. +3. Start the guest and use the documented lab account, stud / stud. +4. Obtain the COMPNET-EN repository inside the guest. +5. From the repository root, run the guest prerequisite checker: + +~~~bash +bash 01_GUIDE_MININET-SDN/verify_mininet_vm.sh +~~~ + +The checker reads versions, tests imports and probes access to the Docker daemon +and the OVS service. It does not install packages, create containers, start a +Mininet topology or request sudo. It prefers the existing course Python at +~/venvs/compnet/bin/python3 when present. It returns 1 for required failures and 2 +for configuration warnings. + +A successful prerequisite check is followed by the functional exercises in the +[setup guide](SETUP-GUIDE-COMPNET-EN.md) and [S06](../04_SEMINARS/S06/). +The SDN route uses the course environment's osken-manager command. OS-Ken 4 removed +that command, so an unpinned upgrade is not a substitute for the prepared course +environment. The optional requirements file preserves the pre-4 CLI compatibility +range; it is not a lockfile of the appliance's installed packages. + +For the packet-capture exercises, capture inside the guest when inspecting +Mininet links or Docker networks. Host Wireshark does not directly expose every +interface inside the VM. + +## Files in this directory + +| File | Purpose | +|---|---| +| [SETUP-GUIDE-COMPNET-EN.md](SETUP-GUIDE-COMPNET-EN.md) | Student instructions, command contexts, examples and troubleshooting | +| [SETUP-GUIDE-COMPNET-EN.html](SETUP-GUIDE-COMPNET-EN.html) | Browser version of the installation guide | +| [verify_mininet_vm.sh](verify_mininet_vm.sh) | Read-only guest prerequisite probes | +| [SHA256SUMS.txt](SHA256SUMS.txt) | Integrity reference for the OVA | +| [appliance.json](appliance.json) | Version, DOI and exact file identity | -## Provenance +## Course connections -| Field | Value | +| Material | Role | |---|---| -| Author | ing. dr. Antonio Clim — ASE Bucharest, CSIE | -| Last updated | February 2026 | -| Generation | Manual authorship (guide content); README enriched by documentation pass v1.0 | +| [S01](../04_SEMINARS/S01/) | First practical session | +| [S05](../04_SEMINARS/S05/) | Addressing and Mininet simulation | +| [S06](../04_SEMINARS/S06/) | Routing, OpenFlow and application traffic | +| [C07](../03_LECTURES/C07/) | Routing theory and demonstrations | +| [Projects](../02_PROJECTS/) | Application and SDN project briefs | +| [Portainer setup](../00_TOOLS/Portainer/INIT_GUIDE/) | Optional container interface; use the guest's Docker daemon | +| [Instructor notes](../00_APPENDIX/d%29instructor_NOTES4sem/) | Teaching and delivery guidance | + +## Provenance and distribution + +- Appliance author and course maintainer: ing. dr. Antonio Clim, ASE CSIE. +- File identity: supplied by the author's PowerShell SHA-256 computation on + 16 November 2026 and checked for consistency with the published Zenodo export. +- The author confirmed that the appliance was built, configured and tested for + the ASE laboratories. +- Third-party software retains its own licences. Course materials keep the terms + in [LICENCE.md](../LICENCE.md); the OVA is not a blanket relicensing of its + operating system and installed packages. + +## Obtain the teaching repository + +~~~bash +git clone https://github.com/antonioclim/COMPNET-EN.git +cd COMPNET-EN +~~~ + +For a ZIP download, use GitHub's Code → Download ZIP and follow the setup guide's +ZIP instructions. Downloading the course repository does not download the OVA. diff --git a/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html b/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html index 3ece67e..3259107 100644 --- a/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html +++ b/01_GUIDE_MININET-SDN/SETUP-GUIDE-COMPNET-EN.html @@ -824,22 +824,23 @@
Contents — 15 steps
    -
  1. 00 What you will install and why
  2. -
  3. 01 Minimum requirements
  4. -
  5. 02 Installing VirtualBox
  6. -
  7. 03 Importing the MININET-SDN appliance
  8. -
  9. 04 Network configuration (Port Forwarding)
  10. -
  11. 05 First boot and login
  12. -
  13. 06 PuTTY — connecting via SSH
  14. -
  15. 07 Docker and docker compose
  16. -
  17. 08 Wireshark — capturing traffic
  18. -
  19. 09 Shared Folders
  20. -
  21. 10 Cloning the course repository
  22. -
  23. 11 Full end-to-end test
  24. -
  25. 12 Troubleshooting
  26. -
  27. 13 The cleanup script
  28. -
  29. 14 Appendix — Linux host
  30. -
+
  • 01 What runs where
  • +
  • 02 Hardware and software requirements
  • +
  • 03 Installing VirtualBox
  • +
  • 04 Obtaining and importing MININET-SDN
  • +
  • 05 Configuring NAT and port forwarding
  • +
  • 06 First boot and component checks
  • +
  • 07 Connecting through SSH
  • +
  • 08 Using Docker inside the VM
  • +
  • 09 Capturing and inspecting traffic
  • +
  • 10 Transferring files
  • +
  • 11 Obtaining the course repository
  • +
  • 12 Testing the student workflow
  • +
  • 13 Troubleshooting
  • +
  • 14 Stopping your lab scenario
  • +
  • 15 References and useful links
  • +
  • 16 Linux hosts and the separate WSL route
  • + @@ -847,7 +848,7 @@
    -
    ASE-CSIE • Computer Networks • 2025–2026
    +
    ASE-CSIE • Networking and SDN • Year 3, Semester 2

    Installation & setup guide for the MININET-SDN workstation

    Everything you need to prepare your Windows host, import the virtual machine, run Docker Compose scenarios and capture traffic with Wireshark — step by step, with copy-ready commands.

    @@ -857,11 +858,11 @@

    Installation & setup guide for the MININET-SDN workstation

    - February 2026 + 16 November 2026 - ~30 min setup + Student workstation guide
    @@ -871,840 +872,347 @@

    Installation & setup guide for the MININET-SDN workstation

    -
    -
    -
    00
    -
    -

    What you will install and why

    -
    A bird's-eye view of the working environment
    -
    -
    -
    -

    Throughout the semester you will work inside a pre-built Ubuntu 24.04 LTS virtual machine that contains every tool you need for the networking labs. It ships with the Mininet network simulator and Open vSwitch software switches, Docker Engine with Compose, tshark for packet captures, Scapy for packet crafting, nmap for scanning and a Python virtual environment packed with dozens of libraries (Flask, paramiko, gRPC, dnspython and many more).

    -

    On your Windows machine you only need a handful of free programmes: VirtualBox (the hypervisor), PuTTY (an SSH client) and Wireshark (a graphical protocol analyser). Communication between Windows and the VM relies on port forwarding (NAT) and shared folders.

    -

    The end goal: open a PuTTY terminal, navigate to a lab scenario, run docker compose up, generate traffic, capture it and analyse it visually — all within five minutes.

    -
    +

    Course appliance: MININET-SDN was built, configured and tested by Antonio Clim for the ASE laboratories.

    On an ASE classroom PC: use the existing VM and begin at Section 6. The institutional PC deployment script is not a student prerequisite.

    On your own PC: follow the import route. Download version 1.0.0 from Zenodo; Section 4 provides the release link and checksum.

    -
    -
    -┌──────────────────────────────────────────────────────────────────┐
    -│  HOST (Windows 10/11)                                            │
    -│                                                                  │
    -│  ┌─────────────┐  ┌────────────┐  ┌────────────────────┐         │
    -│  │  PuTTY       │  │ Wireshark  │  │  Shared Folder     │         │
    -│  │  (SSH)       │  │ (capture)  │  │  C:\SHARED         │         │
    -│  └──────┬───── ┘  └──────┬─────┘  └─────────┬──────────┘         │
    -│         │ port 2222      │                   │ vboxsf             │
    -│  ═══════╪════════════════╪═══════════════════╪═════════════════   │
    -│         │       VirtualBox NAT               │                    │
    -│  ┌──────┴────────────────┴───────────────────┴──────────────┐     │
    -│  │  VM: MININET-SDN (Ubuntu 24.04)                          │     │
    -│  │                                                          │     │
    -│  │  user: stud / pass: stud                                │     │
    -│  │  enp0s3: 10.0.2.15 (NAT)     docker0: 172.17.0.1        │     │
    -│  │                                                          │     │
    -│  │  ┌────────────────────────────────────────────────┐      │     │
    -│  │  │  Docker Engine 28.x + Compose v2                │      │     │
    -│  │  │  ┌──────┐ ┌──────┐ ┌──────┐  ...scenarios     │      │     │
    -│  │  │  │ web1 │ │ web2 │ │ dns  │                    │      │     │
    -│  │  │  └──────┘ └──────┘ └──────┘                    │      │     │
    -│  │  └────────────────────────────────────────────────┘      │     │
    -│  │                                                          │     │
    -│  │  Mininet 2.3 │ OVS 3.3 │ Python 3.12 (venv compnet)  │     │
    -│  └──────────────────────────────────────────────────────────┘     │
    -└──────────────────────────────────────────────────────────────────┘
    -
    -
    +
    +
    01

    What runs where

    +
    +

    The supplied workstation provides the Ubuntu environment used for Mininet, Open vSwitch, Docker Engine, packet capture and the Python networking exercises. Keep the two operating systems distinct when copying commands:

    +
    LocationWhat you do there
    Windows hostStart VirtualBox, import the OVA on a personal PC, open PuTTY or PowerShell, inspect saved captures with Wireshark
    Ubuntu guest — VM console or an SSH terminalClone COMPNET-EN, run Python, Mininet, Docker Compose, curl and packet captures
    A Docker container inside the guestRun commands explicitly introduced with docker compose ... exec
    Mininet CLI (mininet>)Run commands prefixed with a Mininet host, such as h1 ping ...
    +

    In the Docker exercises, host means the Ubuntu VM that runs Docker Engine. It does not mean Windows. In S08, both the Python backend and the host-networked nginx container use the guest's network stack.

    +

    The main route requires VirtualBox, an SSH client and optionally the Wireshark desktop application on Windows. Docker Desktop is not required. Its separate Docker engine does not manage the containers running inside MININET-SDN.

    +
    -
    - -
    -
    -
    01
    -
    -

    Minimum requirements

    -
    Hardware, software and virtualisation check
    -
    -
    -
    -
    - - - - - - - - - -
    ComponentMinimumRecommended
    ProcessorIntel/AMD with VT-x / AMD-V supportAny CPU from the past 5 years
    RAM8 GB (2 GB allocated to the VM)16 GB
    Disc space10 GB free20 GB
    OSWindows 10 x64, build 1903+Windows 11
    VirtualisationEnabled in BIOS / UEFI
    -
    - -

    Checking hardware virtualisation

    -

    Open Task Manager (Ctrl + Shift + Esc) → Performance tab → CPU. In the bottom-right corner you should see:

    - -
    -
    Task Manager
    -
    Virtualization:  Enabled
    -
    - -

    If it reads Disabled, you must enter BIOS/UEFI (typically F2, F10, Del or Esc at startup) and enable the relevant option. On Intel look for Intel Virtualization Technology (VT-x); on AMD look for SVM Mode.

    - -
    -
    ⛔ No exceptions
    -

    Without hardware virtualisation enabled, VirtualBox will not be able to start the VM. Check this before everything else.

    -
    - -
    -
    ℹ Hyper-V and WSL2
    -

    If you already have Hyper-V or WSL2 enabled, VirtualBox 7.x can coexist with them. There is no need to disable anything — performance may be marginally lower than native but perfectly acceptable.

    -
    -
    +
    02

    Hardware and software requirements

    +
    +
    ComponentGuidance for a personal PC
    ProcessorIntel/AMD x86-64 with hardware virtualisation enabled
    RAM8 GB on the host; allocate at least 2 GB to the VM. 16 GB host RAM gives more room for other applications
    StorageCheck the virtual disk size shown during import. Allow additional free space for the 1.18 GB download, the imported disk, repository files and Docker images
    Operating systemA Windows installation supported by the VirtualBox release you install
    NetworkNeeded for the repository, container image pulls and any exercise that installs dependencies at startup
    +

    On Windows, open Task Manager → Performance → CPU and check that Virtualisation is enabled. If it is disabled on a personal PC, enable Intel VT-x or AMD-V/SVM in BIOS/UEFI. On a classroom PC, contact the instructor instead of changing the machine configuration.

    +

    If Hyper-V or WSL2 is already installed, consult the current VirtualBox host requirements if startup or performance problems occur. Follow the supplied VM route without altering unrelated working projects.

    +
    -
    - -
    -
    -
    02
    -
    -

    Installing VirtualBox

    -
    The hypervisor that runs the virtual workstation
    -
    -
    -
    -

    Download the installer

    -

    Head to the official downloads page and click Windows hosts (.exe file, roughly 105 MB):

    - -
    -
    URL
    -
    https://www.virtualbox.org/wiki/Downloads
    -
    - -

    Run the installer

    -

    Double-click the downloaded file. Click Next at every step — the default configuration is perfectly adequate. The installer will warn you that the network will disconnect briefly while it installs its drivers — confirm with Yes. Click Finish when done.

    - -

    Extension Pack (optional but recommended)

    -

    The Extension Pack adds USB 2.0/3.0 passthrough, PXE boot and RDP support. Download it from the same page (the All supported platforms link), then inside VirtualBox go to File → Tools → Extension Pack Manager, click Install and select the .vbox-extpack file.

    - -
    -
    ✓ Verification
    -

    Open VirtualBox. If you see the "Oracle VirtualBox Manager" window without error messages, the installation is complete.

    -
    -
    +
    03

    Installing VirtualBox

    +
    +

    Skip this section when VirtualBox and MININET-SDN are already available on the classroom PC.

    +
    1. Open the official VirtualBox download page.
    2. Download the installer for Windows hosts supported by your Windows version.
    3. Run the installer and retain the default components. Installation may require administrator approval and may briefly interrupt host networking.
    4. Open Oracle VirtualBox Manager after installation.
    +

    The networking examples in this guide use NAT, SSH and shared folders. They do not require the separately licensed Extension Pack. Guest Additions inside the VM provide shared-folder support; they are a different component.

    +
    -
    - -
    -
    -
    03
    -
    -

    Importing the MININET-SDN appliance

    -
    The OVA file that contains everything pre-configured
    -
    -
    -
    -

    Download the OVA file

    -

    The virtual workstation is distributed as an OVA (Open Virtualization Appliance) — essentially an archive containing the virtual disc, hardware settings and network configuration in a single package. Download it here:

    - -
    -
    Google Drive
    -
    https://drive.google.com/file/d/1LqnyD64gzePBjYEXpIGen41mNdjBKU3x/view?usp=drive_link
    -
    - -

    Save it somewhere easy to find, for example C:\Users\<YourName>\Downloads\.

    - -

    Import into VirtualBox

    -
      -
    1. Open VirtualBox
    2. -
    3. Go to File → Import Appliance… (or press Ctrl+I)
    4. -
    5. Click Browse and select the MININET-SDN.ova file
    6. -
    7. Click Next
    8. -
    - -

    On the settings screen, review and adjust if necessary:

    - -
    - - - - - - - - -
    SettingRecommended value
    NameMININET-SDN
    CPU2 (or more if you have 8+ cores)
    RAM2048 MB minimum (3072 MB ideal)
    NetworkNAT (the default)
    -
    - -

    Click Finish and wait one to three minutes. Once the process completes, the MININET-SDN machine will appear in the left-hand panel.

    -
    +
    04

    Obtaining and importing MININET-SDN

    +
    +

    4.1 Publication status and exact file identity

    +

    Published Zenodo release — version 1.0.0: https://doi.org/10.5281/zenodo.24289763.

    +

    The release was published on 16 November 2026. Open the DOI landing page and download MININET-SDN.ova and SHA256SUMS.txt into the same folder. Read the accompanying README and licence/provenance notice. Students on ASE classroom PCs can continue using the installed VM.

    +
    FieldValue
    OVA filenameMININET-SDN.ova
    Exact size of the deposited file1182349312 bytes — approximately 1.18 GB
    SHA-256e2e02971bc23546e9e46914e1fcd249411afdcba281b8c21a1dfba153844dff5
    +

    On Windows PowerShell, open the folder containing your downloaded OVA and run:

    +
    powershell
    $expected = 'e2e02971bc23546e9e46914e1fcd249411afdcba281b8c21a1dfba153844dff5'
    +$actual = (Get-FileHash -LiteralPath .\MININET-SDN.ova -Algorithm SHA256).Hash
    +if ($actual -ieq $expected) { 'SHA-256: MATCH' } else { throw 'SHA-256: MISMATCH' }
    +(Get-Item -LiteralPath .\MININET-SDN.ova).Length
    +

    A matching hash identifies the deposited file. Do not apply this expected hash to a later re-export: a new OVA requires its own checksum and version information.

    +

    4.2 Import on your personal PC

    +
    1. Open VirtualBox → File → Import Appliance (Ctrl+I).
    2. Select MININET-SDN.ova and click Next.
    3. Review the imported settings: name MININET-SDN, 2 virtual CPUs and at least 2048 MB RAM are suitable starting values. Retain the appliance's other working settings.
    4. Check the proposed disk location and available space.
    5. Click Import and wait until the VM appears in VirtualBox Manager.
    +

    Use an existing classroom VM directly; importing another copy is unnecessary. If a VM with the same name already exists on your personal PC, distinguish the new copy before import instead of overwriting your work.

    +
    -
    - -
    -
    -
    04
    -
    -

    Network configuration (Port Forwarding)

    -
    How PuTTY on Windows reaches SSH inside the VM
    -
    -
    -
    -

    The VM uses NAT (Network Address Translation): it can reach the internet through the host's connection, but Windows cannot initiate connections to the VM on its own. We therefore set up port forwarding rules that tell VirtualBox "redirect everything arriving on host port X to guest port Y".

    - -

    Port forwarding rules

    - -
    - - - - - - - -
    PurposeProtocolHost IPHost PortGuest IPGuest Port
    SSH (required)TCP127.0.0.1222210.0.2.1522
    HTTP test (optional)TCP127.0.0.1808010.0.2.158080
    Docker API (optional)TCP127.0.0.1237510.0.2.152375
    -
    - -

    Configuration steps

    -
      -
    1. Select the MININET-SDN machine in VirtualBox Manager
    2. -
    3. Click Settings (the cog icon) → Network
    4. -
    5. Under Adapter 1 (which should read "Attached to: NAT"), click Advanced (the small arrow)
    6. -
    7. Click the Port Forwarding button
    8. -
    9. Add the rules from the table above using the + (plus) button
    10. -
    11. Click OK → OK
    12. -
    - -
    -
    ℹ Why port 2222 rather than 22?
    -

    Port 22 on Windows might already be occupied (for instance if you have OpenSSH Server installed). We use 2222 on the host to avoid conflicts; inside the VM, the SSH daemon listens on the standard port 22. In practice, 127.0.0.1:2222 on Windows reaches 10.0.2.15:22 in the VM.

    -
    -
    +
    05

    Configuring NAT and port forwarding

    +
    +

    For a new personal-PC import, keep Adapter 1 attached to NAT. With the VM powered off, open Settings → Network → Adapter 1 → Advanced → Port Forwarding.

    +
    RuleProtocolHost IPHost portGuest IPGuest port
    sshTCP127.0.0.12222Leave blank for the NAT-assigned guest22
    http-test — optional Windows browser accessTCP127.0.0.18080Leave blank for the NAT-assigned guest8080
    +

    Add each missing rule with +, then save with OK. Inspect existing rules first; do not add duplicate rules to a working classroom VM. The usual NAT guest address is 10.0.2.15, but the connection from Windows uses 127.0.0.1 and the configured host port.

    +

    SSH forwarding is sufficient for the primary workflow. The HTTP rule is needed only if you want a Windows browser to reach nginx inside the guest. All curl tests below run inside the VM and do not require that HTTP rule.

    +

    No Docker TCP API forwarding is needed: Docker commands run in the SSH session inside the guest.

    +
    -
    - -
    -
    -
    05
    -
    -

    First boot and login

    -
    Verifying components inside the workstation
    -
    -
    -
    -

    Select MININET-SDN in VirtualBox and click Start. Wait roughly 30–60 seconds until the login prompt appears. Enter the credentials:

    - -
    -
    user stud
    -
    pass stud
    -
    hostname mininet-vm
    -
    - -
    -
    ✓ Normal: the password is invisible
    -

    When you type the password nothing appears on screen — no dots, no asterisks. This is standard Linux behaviour. Type stud and press Enter.

    -
    - -

    If you see a prompt like (compnet) stud@mininet-vm:~$, everything is working. Notice the (compnet) prefix — it means the Python virtual environment activates automatically at login.

    - -

    Quick component check

    - -
    -
    bash
    -
    # Docker Engine
    -docker --version
    -# → Docker version 28.2.2, …
    -
    -# Docker Compose
    -docker compose version
    -# → Docker Compose version 2.37.1+…
    -
    -# Mininet
    -sudo mn --version
    -# → 2.3.0
    -
    -# Open vSwitch
    -ovs-vsctl --version
    -# → ovs-vsctl (Open vSwitch) 3.3.4
    -
    -# Python (from the venv)
    -python3 --version
    -# → Python 3.12.3
    -
    -# A few key libraries
    -python3 -c "import scapy; print('scapy OK')"
    -python3 -c "import paramiko; print('paramiko OK')"
    -python3 -c "import flask; print('flask OK')"
    -
    -# Internet connectivity
    -ping -c 3 google.com
    -
    -
    +
    06

    First boot and component checks

    +
    +

    Start MININET-SDN and wait for the console login prompt. Use the course account:

    +
    text
    Username: stud
    +Password: stud
    +

    The password is not displayed while you type. Keep the standard classroom account unchanged unless instructed otherwise.

    +

    Run these checks inside the VM:

    +
    bash
    cat /etc/os-release
    +python3 --version
    +docker --version
    +docker compose version
    +mn --version
    +ovs-vsctl --version
    +command -v tshark
    +command -v osken-manager
    +

    A version command confirms that a client program is available; it does not by itself prove that its service or an exercise works. Section 12 tests actual course scenarios.

    +

    The course Python environment is normally activated at login. If the prompt does not show (compnet) and the environment exists, activate it:

    +
    bash
    test -f "$HOME/venvs/compnet/bin/activate" && source "$HOME/venvs/compnet/bin/activate"
    +python3 -c "import scapy, paramiko, flask; print('Course Python imports: OK')"
    +

    Preserve the working course environment. S06 uses the installed osken-manager entry point. OS-Ken 4.x removed that command, so upgrading the package blindly is not a repair for a missing command. The S06 instructions explain how to check the installed environment.

    +
    -
    - -
    -
    -
    06
    -
    -

    PuTTY — connecting via SSH

    -
    Work comfortably with copy-paste and a resizable window
    -
    -
    -
    -

    The VirtualBox console is rather limited: copy-paste is awkward, you cannot resize the window and the font is tiny. For day-to-day work we connect to the VM over SSH using PuTTY.

    - -

    Download and install

    -

    Grab the 64-bit MSI installer from the official site:

    - -
    -
    URL
    -
    https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html
    -
    - -

    Run the installer with default options.

    - -
    -
    ✓ Modern alternative
    -

    If you prefer something more up-to-date, you can use Windows Terminal (pre-installed on Windows 11) with the built-in SSH client: ssh -p 2222 stud@127.0.0.1. Works just as well.

    -
    - -

    Configuring the PuTTY session

    -
      -
    1. Open PuTTY
    2. -
    3. Host Name: 127.0.0.1
    4. -
    5. Port: 2222
    6. -
    7. Connection type: SSH
    8. -
    9. In the Saved Sessions field type MININET-SDN and click Save
    10. -
    11. Click Open
    12. -
    - -

    On first connection PuTTY shows a warning about the host key fingerprint — confirm with Accept (this is normal). Then enter stud / stud and you are in.

    - -

    Practical tips

    -
      -
    • Copy from PuTTY: select text with the mouse — it is copied to the clipboard automatically
    • -
    • Paste into PuTTY: right-click
    • -
    • Saved sessions: next time, simply double-click MININET-SDN in the session list
    • -
    • Larger window: Settings → Window → set 100 × 40 (far more comfortable than 80 × 24)
    • -
    • Keep-alive: Settings → Connection → "Seconds between keepalives" → 30 (prevents disconnection during inactivity)
    • -
    -
    +
    07

    Connecting through SSH

    +
    +

    7.1 Windows built-in SSH

    +

    Open PowerShell on Windows and run:

    +
    powershell
    ssh -p 2222 stud@127.0.0.1
    +

    Check that the host and port refer to your intended VM before accepting its first host-key prompt. Enter the course password. Once connected, Bash commands run inside Ubuntu even though the terminal window is on Windows.

    +

    7.2 PuTTY alternative

    +
    1. Install PuTTY from its official download page, if it is not already installed.
    2. Set Host Name to 127.0.0.1, Port to 2222 and Connection type to SSH.
    3. Save the session as MININET-SDN and click Open.
    4. Log in as stud with the course password.
    +

    Select text to copy in PuTTY; right-click to paste. Saved sessions make it easy to open the second terminal needed for capture exercises. In Connection, a keepalive interval of 30 seconds can help with idle sessions.

    +
    -
    - -
    -
    -
    07
    -
    -

    Docker and docker compose

    -
    Lab scenarios run inside containers
    -
    -
    -
    -

    Many labs (from lab 8 onwards) use Docker Compose to spin up complex infrastructure from a single YAML file: web servers, load balancers, DNS resolvers, FTP clients — all interconnected in a virtual Docker network.

    -

    Good news: Docker Engine is already installed inside the VM. You do not need to install anything extra on Windows for course work. Every docker compose up / down command is executed via your PuTTY SSH session.

    - -

    Quick test

    - -
    -
    bash — run in PuTTY
    -
    # Check that Docker Engine responds
    -docker info | head -5
    -
    -# Minimal test: download and run a test container
    -docker run --rm hello-world
    -
    - -

    If you see the "Hello from Docker!" message, everything is in order. Docker pulls the hello-world image from Docker Hub, runs it and removes it immediately (--rm).

    - -
    -
    ℹ Docker Desktop on Windows — is it needed?
    -

    Not for this course. Docker Desktop consumes substantial memory and adds a layer of complexity. If you need Docker on Windows for other projects, you can install it separately from docker.com/products/docker-desktop, but bear in mind that Docker Desktop and Docker Engine inside the VM are entirely separate instances — containers created on one do not appear on the other.

    -
    -
    +
    08

    Using Docker inside the VM

    +
    +

    Run all course Docker commands in the Ubuntu guest, through its console or SSH. Check the server as well as the client:

    +
    bash
    docker info --format '{{.ServerVersion}}'
    +docker compose version
    +docker run --rm hello-world
    +

    The first hello-world run may pull an image from the internet. A download or DNS failure is different from a stopped Docker service; retain the error message for troubleshooting.

    +

    Compose files in this repository often have descriptive filenames. Always supply their actual filename, for example:

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S08/4_nginx"
    +docker compose -f S08_Part04_Config_Docker_Compose.yml config --quiet
    +

    The same -f argument is required for up, ps, logs and down. A bare docker compose up does not automatically select S08_Part04_Config_Docker_Compose.yml.

    +

    If you already use Docker Desktop for another project, leave it separate. It is not needed to operate the Docker engine inside MININET-SDN.

    +
    -
    - -
    -
    -
    08
    -
    -

    Wireshark — capturing traffic

    -
    A graphical protocol analyser on Windows
    -
    -
    -
    -

    Download and install

    -

    Grab the Windows x64 Installer from the official site:

    - -
    -
    URL
    -
    https://www.wireshark.org/download.html
    -
    - -

    During installation leave all components ticked. When asked about Npcap, make sure you tick Install Npcap — without it Wireshark cannot capture packets.

    - -

    Capture strategy for VM scenarios

    -

    One important thing to understand: traffic internal to the VM (between Docker containers, between Mininet hosts) does not cross the physical network interface of your Windows host. Wireshark on Windows only sees traffic that passes through port forwarding (SSH, HTTP and so on).

    -

    The practical workflow for labs is therefore two-step:

    -
      -
    1. Capture traffic inside the VM with tshark or tcpdump, saving a .pcap file
    2. -
    3. Transfer the file to Windows (via Shared Folder) and open it in Wireshark for visual analysis
    4. -
    - -

    Full example — capturing from a Docker Compose scenario

    - -
    -
    bash — complete capture workflow
    -
    # 1. Start a scenario (e.g. lab 8 — nginx reverse proxy)
    -cd ~/compnet-2025-redo/assets/tutorial/s8/4_nginx/
    -docker compose up -d
    -
    -# 2. Start a tshark capture in the background
    -sudo tshark -i any -f "tcp port 8080" -w /tmp/s8_nginx.pcap &
    -
    -# 3. Generate test traffic
    -curl http://localhost:8080
    -
    -# 4. Stop the capture
    -kill %1
    -
    -# 5. Copy the pcap file to the Shared Folder
    -cp /tmp/s8_nginx.pcap /media/sf_SHARED/
    -
    -# 6. Tear down the scenario
    -docker compose down
    -
    - -

    On Windows, open C:\SHARED\s8_nginx.pcap with a double-click — Wireshark picks it up automatically.

    -
    +
    09

    Capturing and inspecting traffic

    +
    +

    9.1 Wireshark on Windows

    +

    Download the Windows installer from the official Wireshark site. Npcap is needed for live capture on Windows interfaces. Opening an existing capture file is a separate operation.

    +

    Windows loopback capture can show the SSH connection on host port 2222. It does not expose the decrypted commands or all traffic between Mininet hosts and guest containers. Capture that internal traffic inside the VM, then transfer the saved file.

    +

    9.2 A bounded capture using two SSH terminals

    +

    First start the S08 backend and nginx scenario in Terminal A, following Section 12.2. Keep that terminal open. Open a second SSH session, Terminal B, and run:

    +
    bash
    mkdir -p "$HOME/compnet-captures"
    +capture_file="$HOME/compnet-captures/s08-$(date -u +%Y%m%dT%H%M%SZ).pcapng"
    +sudo tshark -i lo -a duration:20 -f 'tcp port 8080 or tcp port 8000' -w "$capture_file"
    +sudo chown "$(id -u):$(id -g)" "$capture_file"
    +printf 'Capture saved: %s\n' "$capture_file"
    +

    While Terminal B displays Capturing on, run in Terminal A:

    +
    bash
    curl --fail --show-error --max-time 5 -I http://127.0.0.1:8080/
    +curl --fail --show-error --max-time 5 http://127.0.0.1:8080/
    +

    The capture ends after 20 seconds even if no packets arrive. Wait for completion before copying the file. The lo interface is appropriate here because S08 uses host networking and both test endpoints are inside the guest. For a bridge-network container exercise, select its actual bridge/interface or use -i any; docker0 is not automatically the interface for every Compose network.

    +

    Copy the file using Section 10 and open it with Wireshark. Look for the request to nginx on port 8080 and its separate backend request on port 8000. A capture with zero matching packets is a diagnostic result, not a successful traffic test.

    +
    -
    - -
    -
    -
    09
    -
    -

    Shared Folders

    -
    Transfer files between Windows and the VM without SCP
    -
    -
    -
    -

    Create the folder on Windows

    -

    Create a new folder on your drive, for example:

    -
    -
    Windows — File Explorer
    -
    C:\SHARED
    -
    - -

    Configure in VirtualBox

    -
      -
    1. With the VM powered off, go to Settings → Shared Folders
    2. -
    3. Click the + icon (Add Share)
    4. -
    5. Fill in: -
        -
      • Folder Path: C:\SHARED
      • -
      • Folder Name: SHARED
      • -
      • Read-only: unticked
      • -
      • Auto-mount: ticked
      • -
      • Mount point: leave blank
      • -
      -
    6. -
    7. Click OK → OK
    8. -
    - -

    Verification from the VM

    - -
    -
    bash
    -
    # Check the mount
    -ls -la /media/sf_SHARED/
    -
    -# Create a test file
    -echo "hello from the VM" > /media/sf_SHARED/test.txt
    -
    - -

    On Windows, open C:\SHARED — you should see test.txt.

    - -
    -
    ⚠ Permission denied?
    -

    The user stud is already a member of the vboxsf group. If you still get a permissions error, run sudo usermod -aG vboxsf stud then log out and back in.

    -
    -
    +
    10

    Transferring files

    +
    +

    10.1 VirtualBox Shared Folders

    +

    On Windows, create C:\SHARED. In VirtualBox → Settings → Shared Folders, add:

    +
    SettingValue
    Folder PathC:\SHARED
    Folder NameSHARED
    Read-onlyUnticked
    Auto-mountTicked
    Mount pointLeave blank
    +

    Start the VM or reopen the SSH session, then check inside the guest:

    +
    bash
    ls -ld /media/sf_SHARED
    +printf 'hello from the VM\n' > /media/sf_SHARED/compnet-transfer-check.txt
    +

    The test file should appear in C:\SHARED on Windows. After a completed capture in Terminal B, copy its exact file:

    +
    bash
    cp -- "$capture_file" /media/sf_SHARED/
    +

    If the mount exists but access is denied, check id and the vboxsf group. On your own VM, sudo usermod -aG vboxsf stud followed by logout/login can correct a missing membership. On classroom PCs, ask the instructor before changing configuration.

    +

    10.2 SCP alternative

    +

    Shared folders are convenient but not required. In Windows PowerShell, copy the completed captures through the existing SSH connection:

    +
    powershell
    scp -P 2222 'stud@127.0.0.1:compnet-captures/*.pcapng' .
    +

    This downloads the files into the current Windows directory. PuTTY installations can use pscp with the same uppercase -P port option.

    +
    -
    - -
    -
    -
    10
    -
    -

    Cloning the course repository

    -
    Materials for all 13 labs
    -
    -
    -
    -
    -
    bash — from PuTTY
    -
    cd ~
    -git clone https://github.com/hypothetical-andrei/compnet-2025-redo.git
    -cd compnet-2025-redo
    -ls -la
    -
    - -

    Repository structure:

    - -
    -
    directory layout
    -
    compnet-2025-redo/
    -├── assets/
    -│   ├── course/           ← lecture materials (c1–c13)
    -│   ├── tutorial/          ← lab materials (s1–s13)
    -│   │   ├── s1/               ping, netcat, wireshark
    -│   │   ├── s2/               TCP/UDP sockets
    -│   │   ├── s3/               broadcast, multicast, anycast
    -│   │   ├── s4/               text + binary protocols
    -│   │   ├── s5/               IPv4/IPv6 subnetting, Mininet
    -│   │   ├── s6/               routing, SDN, Open vSwitch
    -│   │   ├── s7/               sniffing, scanning, mini-IDS
    -│   │   ├── s8/               HTTP, nginx reverse proxy
    -│   │   ├── s9/               FTP, file transfer
    -│   │   ├── s10/              DNS, SSH in containers
    -│   │   ├── s11/              load balancing with nginx
    -│   │   ├── s12/              gRPC, protobuf, JSON-RPC
    -│   │   └── s13/              penetration testing
    -│   ├── tutorial-solve/    ← partial solutions
    -│   └── tools/             ← utilities (plantuml.jar etc.)
    -└── prompts/               ← content-generation prompts
    -
    - -

    Alternative: download as ZIP

    -

    If the VM has no internet access, download the archive on Windows, place it in C:\SHARED, then from the VM:

    - -
    -
    bash
    -
    cp /media/sf_SHARED/compnet-2025-redo-main.zip ~
    -cd ~
    -unzip compnet-2025-redo-main.zip
    -cd compnet-2025-redo-main
    -
    - -

    Compatibility script (recommended)

    -

    The VM includes a script that creates necessary symlinks, verifies Python dependencies and patches docker-compose.yml files where pip dependencies are missing:

    - -
    -
    bash
    -
    cd ~
    -chmod +x compnet_mininetvm_setup.sh
    -./compnet_mininetvm_setup.sh --kit-root ~/compnet-2025-redo --self-test
    -
    -
    +
    11

    Obtaining the course repository

    +
    +

    11.1 Git clone inside the VM

    +

    For a new student copy, run inside Ubuntu:

    +
    bash
    cd "$HOME"
    +git clone https://github.com/antonioclim/COMPNET-EN.git
    +cd COMPNET-EN
    +ls
    +

    If COMPNET-EN already exists, inspect that directory and your work instead of cloning over it. To update an existing Git clone, inspect git status and use git pull --ff-only only when the working copy is ready to update.

    +

    The current top-level directories include:

    +
    DirectoryContents
    00_TOOLS/Utilities and alternative environment instructions
    01_GUIDE_MININET-SDN/This guide and the VM verification helper
    02_PROJECTS/Project specifications and supporting assets
    03_LECTURES/Lecture materials
    04_SEMINARS/Seminar instructions, scripts and configurations
    00_APPENDIX/Supplementary learning and teaching materials
    +

    11.2 ZIP alternative

    +

    On Windows, download the current repository ZIP. Put COMPNET-EN-main.zip in C:\SHARED. In the VM:

    +
    bash
    cd "$HOME"
    +unzip /media/sf_SHARED/COMPNET-EN-main.zip
    +

    If ~/COMPNET-EN does not already exist, normalise the extracted directory name so the later commands work unchanged:

    +
    bash
    if [ -e "$HOME/COMPNET-EN" ]; then
    +    printf 'COMPNET-EN already exists; keep your existing work and select the intended copy.\n'
    +else
    +    mv -- "$HOME/COMPNET-EN-main" "$HOME/COMPNET-EN"
    +fi
    +

    A ZIP checkout has no Git history. Do not run git pull inside it.

    +

    11.3 Check the supplied environment

    +

    From the repository root:

    +
    bash
    cd "$HOME/COMPNET-EN"
    +bash 01_GUIDE_MININET-SDN/verify_mininet_vm.sh
    +

    The helper reads the available environment and reports missing requirements. It does not install packages or repair the VM. Keep its output if a required component is missing.

    +

    No separate compatibility script is needed to find the course files. The commands below use their real paths and explicit Compose filenames. The institutional classroom deployment script is not part of the student setup route.

    +
    -
    - -
    -
    -
    11
    -
    -

    Full end-to-end test

    -
    Everything together: SSH → Docker Compose → tshark → Wireshark
    -
    -
    -
    -

    The moment of truth. Connect via PuTTY and work through these two scenarios.

    - -

    Scenario A — Nginx Reverse Proxy (Lab 8)

    - -
    -
    bash — full test
    -
    # 1. Navigate to the scenario
    -cd ~/compnet-2025-redo/assets/tutorial/s8/4_nginx/
    -
    -# 2. Start a Python HTTP server on port 8000 (the backend)
    -python3 -m http.server 8000 &
    -
    -# 3. Start the nginx container (reverse proxy)
    -docker compose up -d
    -
    -# 4. Check container status
    -docker compose ps
    -
    -# 5. Test with curl
    -curl http://localhost:8080
    -
    -# 6. Tear everything down
    -docker compose down
    -kill %1
    -
    - -

    Scenario B — Multi-client FTP (Lab 9)

    - -
    -
    bash — docker compose with multiple containers
    -
    cd ~/compnet-2025-redo/assets/tutorial/s9/3_multi-client-containers/
    -
    -# Start everything (3 containers: ftp-server, client1, client2)
    -docker compose up -d
    -
    -# Check
    -docker compose ps
    -docker network ls
    -
    -# Tear down
    -docker compose down
    -
    - -
    -
    ✓ Success!
    -

    If both scenarios ran without errors — containers started, curl received a response, everything shut down cleanly — you are ready for the labs.

    -
    -
    +
    12

    Testing the student workflow

    +
    +

    These checks exercise specific paths. Successful results establish those paths on your machine; they do not replace the remaining seminar exercises.

    +

    12.1 Mininet check

    +

    Run in the VM, when no other Mininet exercise is active:

    +
    bash
    sudo mn --switch ovsbr --controller none --test pingall
    +

    This uses an OVS bridge without a remote controller and should report zero dropped pings. S06 separately tests the Os-Ken/OpenFlow controller path; follow the S06 instructions for that exercise.

    +

    12.2 S08: backend, nginx and HTTP

    +

    Run this sequence in SSH Terminal A inside the guest. Keep the terminal open so the backend process identifier remains available for cleanup.

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S08/4_nginx"
    +ss -ltn '( sport = :8000 or sport = :8080 )'
    +

    If either port is already in use, identify your previous exercise before continuing. Start the backend using a new log file:

    +
    bash
    backend_log=$(mktemp /tmp/compnet-s08-backend.XXXXXX)
    +python3 -m http.server 8000 --bind 127.0.0.1 --directory ../2_simple-http >"$backend_log" 2>&1 &
    +backend_pid=$!
    +printf 'Backend PID: %s; log: %s\n' "$backend_pid" "$backend_log"
    +curl --fail --show-error --retry 5 --retry-connrefused --retry-delay 1 --max-time 5 http://127.0.0.1:8000/
    +

    Then start nginx with the actual configuration file:

    +
    bash
    docker compose -f S08_Part04_Config_Docker_Compose.yml config --quiet
    +docker compose -f S08_Part04_Config_Docker_Compose.yml up -d
    +docker compose -f S08_Part04_Config_Docker_Compose.yml ps
    +curl --fail --show-error --retry 5 --retry-connrefused --retry-delay 1 --max-time 5 -I http://127.0.0.1:8080/
    +curl --fail --show-error --max-time 5 http://127.0.0.1:8080/
    +

    Expected evidence: HTTP 200, an X-Student-Lab: Seminar8 response header and the backend content. An Up container alone is insufficient. The supplied configuration uses network_mode: host, so nginx can reach the Python backend at the guest's 127.0.0.1:8000.

    +

    For the packet capture, keep this scenario running and follow Section 9 in Terminal B. If you configured the optional NAT HTTP rule, a Windows browser can also open http://127.0.0.1:8080/.

    +

    When finished, run in the same Terminal A:

    +
    bash
    docker compose -f S08_Part04_Config_Docker_Compose.yml down
    +kill "$backend_pid"
    +wait "$backend_pid" 2>/dev/null || true
    +

    Only the backend started by this sequence and this Compose project are stopped.

    +

    12.3 S09: one client uploads, another downloads

    +

    Run in the VM:

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S09/3_multi-client-containers"
    +mkdir -p server-data server-anon client1-data client2-data
    +printf 'Hello from client1\n' > client1-data/setup-check.txt
    +docker compose -f S09_Part03_Config_Docker_Compose.yml config --quiet
    +docker compose -f S09_Part03_Config_Docker_Compose.yml up -d
    +docker compose -f S09_Part03_Config_Docker_Compose.yml ps
    +

    Image downloads and the FTP server's initial dependency installation require internet access unless the required artefacts are already available. Wait for FTP readiness with this bounded check:

    +
    bash
    docker compose -f S09_Part03_Config_Docker_Compose.yml exec -T client1 python - <<'PYREADY'
    +import ftplib
    +import time
    +
    +deadline = time.monotonic() + 60
    +while True:
    +    try:
    +        with ftplib.FTP() as ftp:
    +            ftp.connect('ftp-server', 2121, timeout=2)
    +            ftp.login('test', '12345')
    +            print('FTP login: OK')
    +        break
    +    except (OSError, ftplib.Error) as exc:
    +        if time.monotonic() >= deadline:
    +            raise SystemExit(f'FTP not ready: {exc}')
    +        time.sleep(1)
    +PYREADY
    +

    Then exercise the supplied clients:

    +
    bash
    docker compose -f S09_Part03_Config_Docker_Compose.yml exec -T client1 python S09_Part03_Script_Pyftpd_Multi_Client.py upload setup-check.txt
    +docker compose -f S09_Part03_Config_Docker_Compose.yml exec -T client2 python S09_Part03_Script_Pyftpd_Multi_Client.py download setup-check.txt
    +cmp client1-data/setup-check.txt client2-data/setup-check.txt && printf 'Transferred file: MATCH\n'
    +docker compose -f S09_Part03_Config_Docker_Compose.yml down
    +

    The expected evidence is a successful upload, a successful download and Transferred file: MATCH. The test uses the shared container network, where both clients can resolve ftp-server. Publishing an FTP control port alone does not establish a working passive data path from Windows; that separate networking case is not required here.

    +
    -
    - -
    -
    -
    12
    -
    -

    Troubleshooting

    -
    Common problems and their solutions
    -
    -
    -

    Click on each problem to reveal the solution:

    - -
    -
    !VM will not start: "VT-x is disabled in BIOS"▸
    -

    Hardware virtualisation is not enabled. Restart your machine, enter BIOS (F2, F10, Del or Esc at startup), find Intel Virtualization Technology (or SVM Mode on AMD), enable it, save and exit.

    -
    - -
    -
    !PuTTY: "Connection refused" at 127.0.0.1:2222▸
    -

    Three possible causes: the VM is not running, port forwarding is misconfigured or the SSH service inside the VM is not active. Check in order: (1) make sure the VM has reached the login prompt; (2) verify the rules under Settings → Network → Port Forwarding; (3) in the VirtualBox console run sudo systemctl start ssh && sudo systemctl enable ssh.

    -
    - -
    -
    !docker compose up reports port conflicts▸
    -
    -

    Stale containers from a previous session are still running. Quick fix:

    -
    -
    bash
    -
    docker rm -f $(docker ps -aq) 2>/dev/null
    -docker network prune -f
    -
    -

    Or use the clean.sh script described in the next section.

    -
    -
    - -
    -
    !docker compose returns "permission denied"▸
    -

    The user stud is not in the docker group. Run sudo usermod -aG docker stud, then log out and back in (close PuTTY and reconnect).

    -
    - -
    -
    !Shared Folder does not appear in the VM▸
    -
    -

    Guest Additions are already included in the OVA (v7.0.16). Just make sure you ticked Auto-mount during configuration. As a manual workaround:

    -
    -
    bash
    -
    sudo mkdir -p /media/sf_SHARED
    -sudo mount -t vboxsf SHARED /media/sf_SHARED
    -
    -
    -
    - -
    -
    !Wireshark on Windows cannot see VM traffic▸
    -

    This is expected — internal traffic (Docker, Mininet) exists only inside the VM. Capture it with sudo tshark -i docker0 -w /tmp/capture.pcap, copy the file to /media/sf_SHARED/ and open it on Windows.

    -
    - -
    -
    !The VM is extremely slow▸
    -

    Allocate more RAM (Settings → System → 3072 MB), more CPUs (2–4) and start the VM in Headless mode (right-click the VM → Start → Headless Start) — you lose the graphical window and work exclusively through PuTTY, which saves a considerable amount of resources.

    -
    - -
    -
    !Python: "No module named …"▸
    -

    The compnet virtual environment is not activated. Activate it manually with source ~/venvs/compnet/bin/activate. The prompt must begin with (compnet). Verify with which python3 — it should return /home/stud/venvs/compnet/bin/python3.

    -
    - -
    -
    !Error at sudo mn --test pingall▸
    -

    Open vSwitch is probably not running. Start it with sudo systemctl start openvswitch-switch && sudo systemctl enable openvswitch-switch, then try again.

    -
    +
    13

    Troubleshooting

    +
    +

    VM startup or SSH connection fails

    +

    Check that the intended VM is running and that the NAT forwarding rule exists. From the VM console, inspect:

    +
    bash
    systemctl status ssh --no-pager
    +

    On your own VM, start the service if it is stopped:

    +
    bash
    sudo systemctl start ssh
    +

    Check host port conflicts before changing a working forwarding rule. On classroom PCs, retain the configuration provided by the instructor.

    +

    Docker reports permission denied or cannot connect

    +

    Run inside the VM:

    +
    bash
    id
    +systemctl status docker --no-pager
    +docker context show
    +

    Use the guest's local Docker engine. On your own VM, a missing docker group membership can be corrected with sudo usermod -aG docker stud, followed by logout/login. A stopped service is a separate issue. Do not redirect Docker to a different engine to hide the original error.

    +

    Compose reports no configuration file

    +

    Change to the scenario directory and include the actual filename with -f. For S08:

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S08/4_nginx"
    +docker compose -f S08_Part04_Config_Docker_Compose.yml config --quiet
    +

    Port conflict or nginx returns 502

    +

    Inspect the listeners and scenario logs:

    +
    bash
    ss -ltn '( sport = :8000 or sport = :8080 )'
    +docker compose -f S08_Part04_Config_Docker_Compose.yml logs --tail 30 nginx
    +curl --fail --show-error --max-time 5 http://127.0.0.1:8000/
    +

    A 502 response commonly means nginx cannot reach its backend. Confirm that the Python server runs in the same Ubuntu guest and inspect the backend log created in Section 12. Stop only your own conflicting exercise using Section 14.

    +

    FTP containers exist but login or transfer fails

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S09/3_multi-client-containers"
    +docker compose -f S09_Part03_Config_Docker_Compose.yml logs --tail 40 ftp-server
    +

    Look for a failed image/dependency download, a missing bind-mounted file or a server startup error. Retry the readiness check after resolving the cause. For the supplied scenario, run the clients inside client1 and client2.

    +

    Shared folder missing or capture unavailable

    +

    Confirm the VirtualBox share name SHARED, Auto-mount and the guest's vboxsf membership. Use SCP if shared folders are unavailable. Wait for the bounded capture to finish before transferring it. Select the interface where the exercise traffic actually flows; S08 loopback traffic does not use docker0.

    +

    Python import or osken-manager missing

    +

    Activate the existing course environment and inspect its installed package:

    +
    bash
    test -f "$HOME/venvs/compnet/bin/activate" && source "$HOME/venvs/compnet/bin/activate"
    +command -v python3
    +command -v osken-manager
    +python3 -c "from importlib.metadata import version; print(version('os-ken'))"
    +

    Do not replace the course environment with an unpinned upgrade. OS-Ken 4.x no longer supplies the legacy manager command. Keep the diagnostic output and use the course environment supplied with the appliance or ask the instructor to restore it.

    +

    Mininet fails

    +

    Read the exact error. Check the installed tools and Open vSwitch service:

    +
    bash
    command -v mn
    +command -v ovs-vsctl
    +systemctl status openvswitch-switch --no-pager
    +

    A missing executable is not the same as a stopped service. If no other Mininet exercise is active, sudo mn -c can clear remnants of your failed Mininet run. Repeat the Section 12.1 check after resolving the cause.

    +
    -
    - -
    -
    -
    13
    -
    -

    The cleanup script

    -
    When containers get stuck and ports stay occupied
    -
    -
    -
    -

    Sometimes, if you close PuTTY without running docker compose down, containers remain active and hold on to their ports. The following scripts sort that out.

    - -

    On Windows — clean.ps1 (PowerShell)

    -

    Useful if you have Docker Desktop on Windows. Save the file and run it:

    - -
    -
    powershell — clean.ps1
    -
    # clean.ps1 — Automated Docker cleanup script
    -Write-Host "[INFO] Starting Docker cleanup..." -ForegroundColor Cyan
    -
    -# 1. Tear down the current compose project
    -Write-Host " -> Docker Compose Down..." -NoNewline
    -docker compose down 2>$null
    -Write-Host " OK" -ForegroundColor Green
    -
    -# 2. Force-remove ALL containers
    -Write-Host " -> Force-removing containers..." -NoNewline
    -$containers = docker ps -aq
    -if ($containers) {
    -    docker rm -f $containers 2>$null
    -    Write-Host " OK (containers removed)" -ForegroundColor Green
    -} else {
    -    Write-Host " OK (none found)" -ForegroundColor Gray
    -}
    -
    -# 3. Prune unused networks
    -Write-Host " -> Pruning networks..." -NoNewline
    -docker network prune -f 2>$null
    -Write-Host " OK" -ForegroundColor Green
    -
    -Write-Host "[DONE] All clean!" -ForegroundColor Cyan
    -
    - -

    Running from PowerShell:

    -
    -
    powershell
    -
    Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
    -.\clean.ps1
    -
    - -

    Inside the VM — clean.sh (Bash)

    -

    The version for direct use over SSH:

    - -
    -
    bash — one-liner creation
    -
    cat > ~/clean.sh << 'EOF'
    -#!/bin/bash
    -echo "[INFO] Starting Docker cleanup..."
    -docker compose down 2>/dev/null
    -docker rm -f $(docker ps -aq) 2>/dev/null
    -docker network prune -f 2>/dev/null
    -echo "[DONE] All clean!"
    -EOF
    -chmod +x ~/clean.sh
    -
    - -

    Then, whenever you need it: ~/clean.sh

    -
    +
    14

    Stopping your lab scenario

    +
    +

    Run cleanup inside the VM with the same Compose file used to start that scenario:

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S08/4_nginx"
    +docker compose -f S08_Part04_Config_Docker_Compose.yml down
    +

    For S09:

    +
    bash
    cd "$HOME/COMPNET-EN/04_SEMINARS/S09/3_multi-client-containers"
    +docker compose -f S09_Part03_Config_Docker_Compose.yml down
    +

    These commands stop and remove the selected project's containers and networks. The bind-mounted exercise files remain in their directories. Stop the separately launched S08 Python backend with its recorded PID in the original terminal, as shown in Section 12.2.

    +

    For an interactive Mininet exercise, type exit at mininet> so its script can stop its topology. Stop the controller with Ctrl+C in the controller terminal. Use sudo mn -c only when no other Mininet session is active and a failed run left resources behind.

    +

    There is no need to run a Windows-wide or Docker-wide cleanup script. Keep other projects and their containers intact.

    +
    -
    - - -
    -
    -
    14
    -
    -

    Appendix — Linux host

    -
    Key differences if you are not on Windows
    -
    -
    -
    -

    If your host runs Linux (Ubuntu, Debian, Fedora), the steps are largely identical. Here is a summary of the differences:

    - -

    Installing VirtualBox

    -
    -
    bash — Ubuntu / Debian
    -
    sudo apt update
    -sudo apt install virtualbox
    -
    - -

    Importing the OVA and configuring port forwarding from the command line

    -
    -
    bash
    -
    VBoxManage import ~/Downloads/MININET-SDN.ova
    -VBoxManage modifyvm "MININET-SDN" --natpf1 "ssh,tcp,127.0.0.1,2222,,22"
    -VBoxManage modifyvm "MININET-SDN" --natpf1 "http,tcp,127.0.0.1,8080,,8080"
    -
    - -

    SSH (no PuTTY needed)

    -
    -
    bash
    -
    ssh -p 2222 stud@127.0.0.1
    -
    - -

    Wireshark

    -
    -
    bash
    -
    sudo apt install wireshark
    -# When asked about setuid: answer "Yes"
    -sudo usermod -aG wireshark $USER
    -# Log out and back in, then:
    -wireshark &
    -
    -
    +
    +
    15

    References and useful links

    +
    +
    ResourceLink
    MININET-SDN version 1.0.0 — published releaseZenodo DOI
    Course repositoryantonioclim/COMPNET-EN
    VirtualBox downloads and documentationvirtualbox.org
    PuTTYOfficial download page
    WiresharkDownloads
    Explicit Compose filesDocker Compose CLI documentation
    Docker network modesDocker Compose networking
    Mininet walkthroughmininet.org
    OS-Ken application APIOpenStack documentation
    OS-Ken manager removal in 4.xOS-Ken 2026.1 release notes
    +

    Use the version-specific appliance DOI together with the matching checksum when identifying the course image. Record the Git commit used for the exercises separately, because course materials can change independently of the archived OVA.

    +
    - -
    - -
    -
    -
    ★
    -

    References and useful links

    -
    -
    -
    - - - - - - - - - - - -
    ResourceURL
    VM MININET-SDN (.ova)Google Drive
    Course repository (GitHub)github.com/hypothetical-andrei/compnet-2025-redo
    VirtualBoxvirtualbox.org/wiki/Downloads
    PuTTYchiark.greenend.org.uk/~sgtatham/putty
    Wiresharkwireshark.org/download.html
    Docker Compose docsdocs.docker.com/compose
    Mininet walkthroughmininet.org/walkthrough
    -
    -
    +
    +
    16

    Linux hosts and the separate WSL route

    +
    +

    16.1 A Linux host running VirtualBox

    +

    Install a VirtualBox release supported by your Linux distribution using its documented package route or the official Linux download instructions. Import the same OVA through VirtualBox Manager. The guest-side commands remain the same.

    +

    With a new VM powered off, the equivalent NAT SSH rule can be added from the Linux host:

    +
    bash
    VBoxManage modifyvm "MININET-SDN" --natpf1 "ssh,tcp,127.0.0.1,2222,,22"
    +

    Inspect existing rules first to avoid duplicates. Connect from the Linux host:

    +
    bash
    ssh -p 2222 stud@127.0.0.1
    +

    Use SCP or a configured VirtualBox share for captures. A vboxsf group change, if needed, belongs inside the guest, where the share is mounted. Opening saved captures on the Linux host does not require a live-capture privilege change.

    +

    16.2 WSL is a separate environment

    +

    The WSL prerequisites describe another course setup route. Its account, virtual environment, service addresses and installation steps must be followed as a complete route. Do not combine institutional WSL deployment settings with the VirtualBox account, ports or paths in this guide.

    +

    For students using the supplied MININET-SDN appliance, continue with its existing guest environment and the seminar instructions.

    +
    @@ -1716,18 +1224,37 @@

    Wireshark