Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home / Kali security course / K02
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
WSL LABORATORIES / KALI LINUX / SECURITY & PRIVACY
IoT Security and Privacy

K02 · Local broker & service inventory

Ask Dr. Mohammad · K02 →

Practical IoT Security & Privacy · Kali WSL · 30 min

Design experiment & verify evidence →
K02 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK02 · Local broker & service inventory
V19.0 · Contextual AI workspace

Ask your engineering assistants

K02 · current context

Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
K02 · Local broker & service inventory

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Readiness checksRevision deckEngineering workspaceRecord evidence

Related course access: Networking and Communication — same laboratory, notebook and completion record.

K02 · Academic orientation

Scope and objectives

Scope of the experiment

Explain listener state, local binding and the difference between TCP connection and MQTT authentication.

The focus of this experiment is to distinguish local broker configuration from service availability. Students then interpret listener, port and service-inventory evidence, and verify the authorized loopback broker without external scanning. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Distinguish local broker configuration from service availability.
  • Interpret listener, port and service-inventory evidence.
  • Verify the authorized loopback broker without external scanning.
  • Identify the configured inputs (Plain broker running; TLS broker running; Bind address; Port 18885 already occupied) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can distinguish local broker configuration from service availability, interpret listener, port and service-inventory evidence, and verify the authorized loopback broker without external scanning.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify the authorized loopback broker without external scanning. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K03 · MQTT authentication & least privilege.

Environment and experimental methodology

The specified isolated laboratory environment, with local synthetic inputs and authorized services only. Use the experiment-specific setup and verification instructions.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Scientific architecture · Loopback broker and socket inventory

Loopback broker inventory — Local client; Loopback broker; Local subscriber; List local sockets / 0>0; CONNECT / 0>1; SUBSCRIBE / 2>1; PUBLISH test / 0>1; Route / 1>2
Scientific concept map: Local broker — Listening socket; Client connection — Loopback endpoint; Service inventory — Port and process; Publish / subscribe — Known test message; Verification — Expected service only.

Scientific foundations and analytical reasoning

A socket listener binds to an address and port. A loopback listener is reachable locally; an unspecified bind may expose it to additional interfaces.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · Service reachability and inventory

A listening socket is identified by transport protocol, local address and port. Binding to loopback limits access to the host; binding to a wildcard can expose additional interfaces depending on firewall and networking configuration. Inventory describes observed services, not their security posture.

Worked example and engineering interpretation

A local MQTT broker listening on 127.0.0.1:1883 can be reachable from a local client while inaccessible from another machine. Compare the listener configuration and a controlled connection outcome. Record the interface and time of observation.

Engineering principles · additional worked teaching example

A socket binds an address, port and transport. Two local TCP listeners cannot ordinarily bind the same address/port simultaneously. A loopback listener limits reachable interface scope; service inventory should distinguish active and configured services.

From theory to experiment

Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.

How to investigate K02 · Local broker & service inventory

An authorized service inventory identifies services in a controlled environment and verifies their response. This notebook starts a restricted local MQTT teaching peer, confirms its protocol handshake and tests an exact-topic exchange. No remote scanning is performed.

Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.

Experiment-specific guided practice

Objective: Inventory and initialize dedicated local teaching brokers.

  1. Enable both listeners at 127.0.0.1. Expect two rows on 18884 and 18885.
  2. Stop TLS; compare the socket inventory and the TLS connection status.
  3. Restore TLS and inject a pre-existing 18885 listener; distinguish the conflicting service from the lab broker.
  4. Change the bind address to 0.0.0.0 in the model only. Explain why it exceeds the approved loopback boundary.

Reference check:

Model boundary:

Independent task and submission evidence

Record the ephemeral local port, handshake and matching message. Explain why a port number alone does not establish the service identity or vulnerability; compare with the authorized WSL inventory.

Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Plain broker running = true; TLS broker running = true; Bind address = 127.0.0.1; Port 18885 already occupied = false. In the classroom model, Lab listeners = 2; Scope compliant = Yes; TLS bind conflict = No. Open indicates a TCP listener only. The TLS and MQTT checks belong to K04 and K03. No sockets are opened by this apparatus.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · topology and link dependencies

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

K02 · Local broker & service inventory: topology and link dependenciesLocal client18884 · MQTT18885 · TLS

Step 1 of 2 · Connection 1

Connection 1

Link 1
client → plain · open

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
K02 · 01 / 08What is a listener?Reveal explanation
Engineering explanation

A service bound to an IP address and port.

K02 · 02 / 08Why loopback?Reveal explanation
Engineering explanation

It limits the training listener to local access; it is not a strong WSL isolation boundary.

K02 · 03 / 08What local listener and interface must be verified before testing reachability?Reveal explanation
Engineering explanation

Before starting, check both dedicated ports are free. If either is occupied, stop and identify the owner; do not kill unrelated processes. Initialize once in terminal A before starting its plain broker; start the TLS foreground broker in B separately, keep both running.

K02 · 04 / 08Why inspect listening addresses as well as port numbers?Reveal explanation
Engineering reasoning

A loopback listener is reachable locally; a wildcard listener may expose the service on other interfaces.

K02 · 05 / 08Why distinguish an open listener from an authorized MQTT exchange?Reveal explanation
Engineering reasoning

A listening port proves only a transport endpoint exists; authentication and topic permissions require separate application checks.

K02 · 06 / 08A dedicated teaching broker is inventoried. Select every technically valid statement. A. Verify the intended listener and configuration. B. Check service status before attempting a controlled exchange. C. A listener proves anonymous access is disabled. D. A port number alone identifies every security setting.Reveal explanation
Applied scenario

Correct: A. Verify the intended listener and configuration.; B. Check service status before attempting a controlled exchange.

K02 · 07 / 08In K02 · Local broker & service inventory, which command or code executes the final documented practical action?Reveal explanation
Implementation recall

ss -ltn | grep -E ":18884|:18885" nmap -sT -Pn -p 18884,18885 127.0.0.1

K02 · 08 / 08For K02 · Local broker & service inventory, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Use Kali, not Ubuntu. Before initialization, ss -ltn | grep -E ":18884|:18885" should print nothing if both free (grep exit 1 is expected). If initialized previously, reuse valid files; init refuses nonempty private setup. Start plain and TLS brokers as normal user in two separate foreground terminals. Check listeners and local Nmap only; expected both open. Keep brokers running for K03–K05; stop only your own instances after K05 or K11.

Loading experiment-specific apparatus…
K02 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Closed two-condition teaching fixture; actual security validation requires the practical procedure.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →

Experimental protocol

Before you run / verification gate

Before starting, check both dedicated ports are free. If either is occupied, stop and identify the owner; do not kill unrelated processes. Initialize once in terminal A before starting its plain broker; start the TLS foreground broker in B separately, keep both running.

Experimental protocol

Prerequisites
K01; three Kali terminals, toolkit initialized once
Procedure
Start the two foreground listeners; inspect only ports 18884/18885 on loopback.
Acceptance
Both listen at 127.0.0.1; any unexpected binding or occupied port is a stop condition.
Evidence
ss output and two-port Nmap result; do not scan other services.
Standards link
Interface access and configuration
Discussion
Why does open TCP not establish MQTT authorization?

Run & verify — acceptance checklist

Build verification: Configuration and generated certificate tests passed; actual Mosquitto/Nmap pending.

Use Kali, not Ubuntu. Before initialization, ss -ltn | grep -E ":18884|:18885" should print nothing if both free (grep exit 1 is expected). If initialized previously, reuse valid files; init refuses nonempty private setup. Start plain and TLS brokers as normal user in two separate foreground terminals. Check listeners and local Nmap only; expected both open. Keep brokers running for K03–K05; stop only your own instances after K05 or K11.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

Draw two local brokers on separate ports. Explain why a second listener on occupied 18885 generally fails.

02 · Compare or justify using evidence

Compare 127.0.0.1 and 0.0.0.0 bindings and design a local verification table for listener, protocol and reachability.

03 · Configuration reasoning

Configuration reasoning · Independent work

A local plain listener is on 127.0.0.1:18885 and TLS listener attempts the identical endpoint. What should the student inspect before changing configuration?

Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Intermediate · Explain a changed-input result

Independent theoretical exercise · K02-01

Use the reference configuration (Plain broker running = true; TLS broker running = true; Bind address = 127.0.0.1; Port 18885 already occupied = false), but change Plain broker running = false. The model reports Lab listeners = 1. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · K02-02

Two model observations of Lab listeners are 2 (reference) and 1 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · K02-03

For TLS broker running = false, the model supplies this excerpt from Modeled socket inventory: TCP port · Service · State · Bind 18884 · Plain MQTT · LISTEN · 127.0.0.1 18885 · TLS MQTT · CLOSED · — Count rows whose Service value is exactly “Plain MQTT”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K02-04

An observation is Lab listeners = 1. Candidate A uses Plain broker running = true; TLS broker running = true; Bind address = 127.0.0.1; Port 18885 already occupied = false. Candidate B changes the listed settings (TLS broker running = false) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · K02-05

A student configures Port 18885 already occupied = true while preserving all other reference settings, but copies the reference report of Lab listeners = 2. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K02-06

Design a controlled comparison for K02 · Local broker & service inventory using reference Plain broker running = true; TLS broker running = true; Bind address = 127.0.0.1; Port 18885 already occupied = false and test Plain broker running = false. Specify the changed setting(s), measured metric Lab listeners, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Explain listener state, local binding and the difference between TCP connection and MQTT authentication.

1 · Reference workbench configuration

Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

Plain broker runningYes
TLS broker runningYes
Bind address127.0.0.1
Port 18885 already occupiedNo

2 · Perform the investigation in order

  1. Enable both listeners at 127.0.0.1. Expect two rows on 18884 and 18885.
  2. Stop TLS; compare the socket inventory and the TLS connection status.
  3. Restore TLS and inject a pre-existing 18885 listener; distinguish the conflicting service from the lab broker.
  4. Change the bind address to 0.0.0.0 in the model only. Explain why it exceeds the approved loopback boundary.
  5. In the actual practical, verify empty ports before starting the foreground brokers; inspect ss output and the local inventory, then stop only your lab processes.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Both listenersUse reference inputs aboveLab listeners: 2Record actual result
Stop TLSTLS broker running = NoLab listeners: 1Record actual result
Bind conflictPort 18885 already occupied = YesLab listeners: 1Record actual result
Broad bindBind address = 0.0.0.0Scope compliant: NoRecord actual result

4 · Analyze and report

A listening port is not proof that a user is authenticated or authorized.

Required evidence: Two listener inventories and a scope justification.

Model boundary: No sockets are opened by this apparatus.

Controlled investigation · reproducible evidence

Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

TrialIndependent changeDependent observation
Both listenersUse reference inputs aboveRecord actual outcome and units
Stop TLSTLS broker running = NoRecord actual outcome and units
Bind conflictPort 18885 already occupied = YesRecord actual outcome and units
Broad bindBind address = 0.0.0.0Record actual outcome and units

Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Actual TCP MQTT 3.1.1 exchange with a restricted loopback peer and opt-in real HiveMQ TLS; actual SQLite readback, virtual telemetry. External broker not validated locally. Default profile executed in an isolated local Python kernel. Live services and physical hardware are separate acceptance tasks.

Download NotebookOpen Google ColabAll Python notebooks
K02 / Kali · Mosquitto / Nmap30 min

Local broker & service inventory

Kali terminal C · working directory
Kali (Bash)
cd ~/kali-labs
bash verify_kali.sh
✓ Expected: Toolkit directory is selected and all dependency checks pass. Do not proceed if any check fails.

Objective: Create two lab-only listeners and verify the exact exposed ports.

Distinguish a listening socket from an authenticated application.

ACTION 01 / 05
Kali · before starting either broker
ss -ltn | grep -E ":18884|:18885"
✓ Expected: No matching LISTEN rows before starting the brokers (grep exit 1 is normal). If a listener already exists, stop and identify it; do not terminate an unrelated service.
ACTION 02 / 05

Open Terminal A. If you have already completed initialization, skip this action and proceed to the plain broker action. Do not overwrite the private directory.

Kali terminal A · initialize only once
cd ~/kali-labs
python3 lab.py init
✓ Expected: On a first run, a private training directory and certificates are created. If the directory already exists, do not run init again. Inspect the file names (never contents of credentials or keys), confirm complete configuration and valid certificates; if partial or expired, follow the toolkit renewal instructions. Do not start a broker after an unexpected initialization failure.
ACTION 03 / 05

Keep this foreground broker running in terminal A. Open terminal B for the protected broker next.

Kali terminal A · plain broker
mosquitto -c "$HOME/.psut-kali-security-v14/plain.conf" -v
✓ Expected: Mosquitto opens port 18884 on 127.0.0.1. The shell does not return while the broker runs; keep this terminal open. Any bind/configuration error must be resolved first.
ACTION 04 / 05
Kali terminal B
mosquitto -c "$HOME/.psut-kali-security-v14/tls.conf" -v
✓ Expected: The foreground training broker starts and logs a listener on its configured loopback port. Keep this terminal open; Ctrl+C stops it.
ACTION 05 / 05
Terminal C — local inventory only
ss -ltn | grep -E ":18884|:18885"
nmap -sT -Pn -p 18884,18885 127.0.0.1
✓ Expected: The specified loopback ports are reported open if their respective training brokers are running. No external hosts are scanned.
Expected result for each action (2)
  1. ss -ltn | grep -E ":18884|:18885"The isolated Kali broker listeners appear on 127.0.0.1:18884 and/or 18885 after startup. No other bind address is expected for these targets.
  2. nmap -sT -Pn -p 18884,18885 127.0.0.1The specified loopback ports are reported open if their respective training brokers are running. No external hosts are scanned.

Terminal C: open a new Kali shell and run cd ~/kali-labs before every python3 lab.py command. Terminals A and B remain dedicated foreground brokers.

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

Method and implementation

Review the implementation after attempting the practical steps.

Configuration inspection · method and source

Compare listener binding, anonymous access, password file, ACL and TLS certificate paths. Do not display the credentials or keys. A test CA is trusted only by the lab client.

Inspect the actual implementation below. Full file: lab.py.

PYTHON · Source code
def init():
    if os.geteuid()==0: raise RuntimeError('Use a normal Kali user, not root.')
    if HOME.is_symlink(): raise RuntimeError('Refusing symbolic link for private directory.')
    if HOME.exists() and any(x.name != 'evidence' for x in HOME.iterdir()): raise RuntimeError(f'{HOME} already exists. Keep it; use the existing setup or archive it manually after stopping brokers.')
    for tool in ['openssl','mosquitto','mosquitto_passwd','mosquitto_pub','mosquitto_sub']:
        if not shutil.which(tool): raise RuntimeError('Missing '+tool+'; follow Kali package setup.')
    for port in PORTS:
        with socket.socket() as s:
            try: s.bind(('127.0.0.1',port))
            except OSError: raise RuntimeError(f'Port {port} occupied; do not stop unrelated services.')
    os.umask(0o077); HOME.mkdir(mode=0o700,exist_ok=True)
    # Credentials generated for this disposable lab only. Never export them as evidence.
    credentials={k:secrets.token_hex(16) for k in ['sensor','viewer']}
    (HOME/'credentials.json').write_text(json.dumps(credentials))
    checked(['mosquitto_passwd','-b','-c',str(HOME/'passwd'),'sensor',credentials['sensor']]);checked(['mosquitto_passwd','-b',str(HOME/'passwd'),'viewer',credentials['viewer']])
    (HOME/'passwd').chmod(0o600)
    (HOME/'acl').write_text('user sensor\ntopic write psut-kali/demo/telemetry\n\nuser viewer\ntopic read psut-kali/demo/telemetry\n')
    generate_certificates()
    (HOME/'plain.conf').write_text('listener 18884 127.0.0.1\nallow_anonymous true\npersistence false\nlog_type all\n')
    (HOME/'tls.conf').write_text(f'listener 18885 127.0.0.1\nallow_anonymous false\npassword_file {HOME}/passwd\nacl_file {HOME}/acl\ncertfile {HOME}/server.crt\nkeyfile {HOME}/server.key\ntls_version tlsv1.2\npersistence false\nlog_type all\n')
    print('Created private training directory:',HOME,'\nStart each broker in a separate Kali terminal as a normal user (not sudo).')

def generate_certificates():
    checked(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','30','-subj','/CN=PSUT local training CA','-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-keyout',str(HOME/'ca.key'),'-out',str(HOME/'ca.crt')])
    checked(['openssl','req','-newkey','rsa:2048','-nodes','-subj','/CN=localhost','-keyout',str(HOME/'server.key'),'-out',str(HOME/'server.csr')])
    (HOME/'extensions.cnf').write_text('subjectAltName=DNS:localhost,IP:127.0.0.1\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n')
    checked(['openssl','x509','-req','-in',str(HOME/'server.csr'),'-CA',str(HOME/'ca.crt'),'-CAkey',str(HOME/'ca.key'),'-CAcreateserial','-days','7','-extfile',str(HOME/'extensions.cnf'),'-out',str(HOME/'server.crt')])

Verification and notebook

Expected observation / verification

Keep A and B running. In terminal C run the inventory command below. Both bind to 127.0.0.1; no change to 1884.

Engineering discussion

Why is a listening TCP port not proof of successful MQTT authorization?

Python / Google Colab laboratory

K02 · 7 notebook cells · 2 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# K02 · K02 · Local broker & service inventory **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Theory and purpose An authorized service inventory identifies services in a controlled environment and verifies their response. This notebook starts a restricted local MQTT teaching peer, confirms its protocol handshake and tests an exact-topic exchange. No remote scanning is performed. **Execution boundary:** local computational model or loopback as explicitly described; not physical measurements or external service certification. Run cells in order.
02Instructions · Markdown
## 1. Define the experiment mechanism and inputs
03Python · executable cell
PYTHON · Code cell
# =====================================================================
# K02 | Code cell 01 | K02 · Local broker & service inventory
# Purpose: 1. Define the experiment mechanism and inputs
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import contextlib, json, socket, socketserver, ssl, struct, threading, uuid

# Define the reusable operation check; keep its logic separate from the trial.
def check(condition, message):
    if not condition: raise RuntimeError(message)

# Define the reusable operation u16; keep its logic separate from the trial.
def u16(n): return struct.pack('!H', n)

# Define the reusable operation string; keep its logic separate from the trial.
def string(s):
    b=s.encode('utf-8');return u16(len(b))+b

# Define the reusable operation exact; keep its logic separate from the trial.
def exact(s,n):
    b=bytearray()
    while len(b)<n:
        c=s.recv(n-len(b))
        if not c: raise EOFError('peer closed')
        b.extend(c)
    return bytes(b)

# Define the reusable operation packet; keep its logic separate from the trial.
def packet(s,head,body=b''):
    n=len(body);out=bytearray([head])
    while True:
        digit=n%128;n//=128;out.append(digit|(128 if n else 0))
        if not n: break
    s.sendall(out+body)

# Define the reusable operation read packet; keep its logic separate from the trial.
def read_packet(s):
    h=exact(s,1)[0];n=0;mul=1
    for _ in range(4):
        b=exact(s,1)[0];n+=(b&127)*mul
        if not b&128:break
        mul*=128
    else:raise ValueError('invalid MQTT length')
    check(n<=65536,'packet too large for lab');return h,exact(s,n)

# Define the reusable operation split string; keep its logic separate from the trial.
def split_string(b):
    check(len(b)>=2,'truncated MQTT field');n=int.from_bytes(b[:2],'big');check(len(b)>=2+n,'truncated MQTT string');return b[2:2+n].decode(),b[2+n:]

# Small synchronous teaching client: clean session, exact-topic QoS 1.
class MQTT:
    """Small synchronous teaching client: clean session, exact-topic QoS 1.
    Separate publisher/subscriber sockets; no reconnect, keepalive or wildcard API.
    """
    def __init__(self,host,port,tls=False):
        s=socket.create_connection((host,port),timeout=8);s.settimeout(8)
        try:
            if tls:s=ssl.create_default_context().wrap_socket(s,server_hostname=host)
            self.s=s;self.pid=0
            packet(s,0x10,string('MQTT')+b'\x04\x02'+u16(60)+string('psut-'+uuid.uuid4().hex[:16]))
            h,b=read_packet(s);check(h==0x20 and b==b'\x00\x00','CONNACK failed')
        except BaseException:s.close();raise
    def next_id(self):self.pid=self.pid%65535+1;return u16(self.pid)
    def subscribe(self,topic):
        pid=self.next_id();packet(self.s,0x82,pid+string(topic)+b'\x01');h,b=read_packet(self.s);check(h==0x90 and b==pid+b'\x01','QoS 1 SUBACK not granted')
    def publish(self,topic,payload):
        pid=self.next_id();packet(self.s,0x32,string(topic)+pid+payload);h,b=read_packet(self.s);check(h==0x40 and b==pid,'PUBACK mismatch')
    def receive(self):
        h,b=read_packet(self.s);check(h>>4==3 and ((h>>1)&3)==1,'expected QoS 1 PUBLISH');topic,rest=split_string(b);check(len(rest)>=2,'missing packet ID');packet(self.s,0x40,rest[:2]);return topic,rest[2:]
    def close(self):
        try:packet(self.s,0xe0)
        except OSError:pass
        self.s.close()
    def __enter__(self):return self
    def __exit__(self,*args):self.close()

# Encapsulate state and operations for Peer; keep its logic separate from the trial.
class Peer(socketserver.BaseRequestHandler):
    def handle(self):
        s=self.request;s.settimeout(15);server=self.server
        try:
            h,b=read_packet(s);proto,b=split_string(b);check(h==0x10 and proto=='MQTT' and b[:2]==b'\x04\x02','unsupported CONNECT');packet(s,0x20,b'\x00\x00')
            while True:
                h,b=read_packet(s)
                if h==0x82:
                    topic,tail=split_string(b[2:]);check(tail==b'\x01' and '+' not in topic and '#' not in topic,'exact QoS1 only')
                    with server.lock:server.subs.setdefault(topic,set()).add(s)
                    packet(s,0x90,b[:2]+b'\x01')
                elif h==0x32:
                    topic,tail=split_string(b);check(len(tail)>=2,'missing packet ID')
                    with server.lock:
                        for target in list(server.subs.get(topic,())):
                            server.seq=server.seq%65535+1
                            try:packet(target,0x32,string(topic)+u16(server.seq)+tail[2:])
                            except OSError:server.subs[topic].discard(target)
                    packet(s,0x40,tail[:2])
                elif h==0x40:continue # no retransmission in this restricted fixture
                elif h==0xc0:packet(s,0xd0)
                elif h==0xe0:break
                else:raise ValueError('unsupported packet')
        except (EOFError,OSError,ValueError,RuntimeError):pass
        finally:
            with server.lock:
                for targets in server.subs.values():targets.discard(s)

# Encapsulate state and operations for LoopbackPeer; keep its logic separate from the trial.
class LoopbackPeer(socketserver.ThreadingTCPServer):
    daemon_threads=True
    def __init__(self):
        self.lock=threading.Lock();self.subs={};self.seq=0;super().__init__(('127.0.0.1',0),Peer)

# Define the reusable operation endpoint; keep its logic separate from the trial.
@contextlib.contextmanager
def endpoint(mode):
    if mode=='hivemq':
        yield 'broker.hivemq.com',8883,True
    elif mode=='local':
        with LoopbackPeer() as p:
            t=threading.Thread(target=p.serve_forever,daemon=True);t.start()
            try:yield '127.0.0.1',p.server_address[1],False
            finally:p.shutdown();t.join(3)
    else:raise ValueError('Choose local or hivemq explicitly')
Ask Dr. Mohammad about this cell
04Instructions · Markdown
## 2. Execute the reference and inspect observations
05Python · executable cell
PYTHON · Code cell
# =====================================================================
# K02 | Code cell 02 | K02 · Local broker & service inventory
# Purpose: 2. Execute the reference and inspect observations
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with endpoint('local') as addr:
    print('Local service:',addr[0],addr[1])
    with MQTT(*addr) as subscriber, MQTT(*addr) as publisher:
        subscriber.subscribe('psut/inventory')
        publisher.publish('psut/inventory',b'authorized fixture')
        actual=subscriber.receive()
        assert actual==('psut/inventory',b'authorized fixture')
        print('Local MQTT service verified:',actual)
Ask Dr. Mohammad about this cell
06Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash cd ~/kali-labs python3 lab.py init ``` ```python def init(): if os.geteuid()==0: raise RuntimeError('Use a normal Kali user, not root.') if HOME.is_symlink(): raise RuntimeError('Refusing symbolic link for private directory.') if HOME.exists() and any(x.name != 'evidence' for x in HOME.iterdir()): raise RuntimeError(f'{HOME} already exists. Keep it; use the existing setup or archive it manually after stopping brokers.') for tool in ['openssl','mosquitto','mosquitto_passwd','mosquitto_pub','mosquitto_sub']: if not shutil.which(tool): raise RuntimeError('Missing '+tool+'; follow Kali package setup.') for port in PORTS: with socket.socket() as s: try: s.bind(('127.0.0.1',port)) except OSError: raise RuntimeError(f'Port {port} occupied; do not stop unrelated services.') os.umask(0o077); HOME.mkdir(mode=0o700,exist_ok=True) # Credentials generated for this disposable lab only. Never export them as evidence. credentials={k:secrets.token_hex(16) for k in ['sensor','viewer']} (HOME/'credentials.json').write_text(json.dumps(credentials)) checked(['mosquitto_passwd','-b','-c',str(HOME/'passwd'),'sensor',credentials['sensor']]);checked(['mosquitto_passwd','-b',str(HOME/'passwd'),'viewer',credentials['viewer']]) (HOME/'passwd').chmod(0o600) (HOME/'acl').write_text('user sensor\ntopic write psut-kali/demo/telemetry\n\nuser viewer\ntopic read psut-kali/demo/telemetry\n') generate_certificates() (HOME/'plain.conf').write_text('listener 18884 127.0.0.1\nallow_anonymous true\npersistence false\nlog_type all\n') (HOME/'tls.conf').write_text(f'listener 18885 127.0.0.1\nallow_anonymous false\npassword_file {HOME}/passwd\nacl_file {HOME}/acl\ncertfile {HOME}/server.crt\nkeyfile {HOME}/server.key\ntls_version tlsv1.2\npersistence false\nlog_type all\n') print('Created private training directory:',HOME,'\nStart each broker in a separate Kali terminal as a normal user (not sudo).') def generate_certificates(): checked(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','30','-subj','/CN=PSUT local training CA','-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-keyout',str(HOME/'ca.key'),'-out',str(HOME/'ca.crt')]) checked(['openssl','req','-newkey','rsa:2048','-nodes','-subj','/CN=localhost','-keyout',str(HOME/'server.key'),'-out',str(HOME/'server.csr')]) (HOME/'extensions.cnf').write_text('subjectAltName=DNS:localhost,IP:127.0.0.1\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n') checked(['openssl','x509','-req','-in',str(HOME/'server.csr'),'-CA',str(HOME/'ca.crt'),'-CAkey',str(HOME/'ca.key'),'-CAcreateserial','-days','7','-extfile',str(HOME/'extensions.cnf'),'-out',str(HOME/'server.crt')]) ```
07Instructions · Markdown
## Independent investigation and submission Record the ephemeral local port, handshake and matching message. Explain why a port number alone does not establish the service identity or vulnerability; compare with the authorized WSL inventory. | Trial | Changed input | Fixed settings | Predicted output | Observed output | Explanation | |---|---|---|---|---|---| | A | baseline | | | | | | B | one change | | | | | | A repeat | baseline | | | | | Save outputs and state one limitation.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research