\appendix
\chapter{User Manual}
This manual provides simple instructions for installing, starting, and using the two developed tools.
Let's start with a step-by-step guide to deploying and running the Domain Analyzer CLI tool.

\section{Domain Analyzer Tool}
\begin{enumerate}
\item \textbf{Prerequisites} - before using the tool, ensure that your system has Python 3.8 or higher and \texttt{pip} installed;
	
\item \textbf{Installation and deployment} - once you downloaded the source code:
	\begin{enumerate}
	\item Create a virtual environment in your working folder to avoid dependency conflicts, run:
		\begin{Verbatim}
		python3 -m venv .venv
		source .venv/bin/activate
		\end{Verbatim}
		
	\item Install dependencies manually using \texttt{pip}:
	\begin{Verbatim}
	pip install dnspython tldextract idna python-Levenshtein requests
	\end{Verbatim}
	\end{enumerate}

\item \textbf{Running the tool} - the tool is executed via the \texttt{main.py}
	\begin{itemize}
	\item \textbf{Analyzing a Single Domain} - to analyze a specific domain, pass it as the default argument:
	\begin{Verbatim}
	python main.py example.com
	\end{Verbatim}
	
	\item \textbf{Analyzing Multiple Domains} - if you have a large list of domains, place them in a text file (one per line) and use the \texttt{-i} or \texttt{---input} flag:
	\begin{Verbatim}	
	python main.py -i domains_list.txt	
	\end{Verbatim}
	
	\item \textbf{Adding Brands for Typosquatting Detection} - to enable brand-spoofing and typosquatting detection heuristics, provide a text file containing the known legitimate brands using the \texttt{---brands} flag:
	\begin{Verbatim}	
	python main.py --brands brands.txt -i domains_list.txt	
	\end{Verbatim}
	
	% -- inserire screen esempio file brands.txt e domain_list.txt
	
	\begin{figure}[h]
    \centering
    \includegraphics[width=0.6\linewidth]{Figures/brand_domainlist.png}
    \caption{Brands and domain list files example}
    \label{fig:brandsdomainlist}
\end{figure}
	
	\item \textbf{Customizing DNS and Threading}
		\begin{itemize}
		\item Custom DNS Resolvers: by default, the system's DNS is used. To use custom resolvers (e.g., Cloudflare, Google), specify them with \texttt{---dns}:
		
		\begin{flushleft}
		\begin{Verbatim}
		python main.py example.com --dns 1.1.1.1 8.8.8.8
		\end{Verbatim}
		\end{flushleft}
		
		\item Timeout: it is possible to adjust the DNS query timeout (default is 2.5 seconds) using \texttt{---timeout}:
  		\begin{Verbatim}
  		python main.py example.com --timeout 5.0
		\end{Verbatim}

		\item Concurrency / Thread Pool: the tool uses parallel threads for rapid batch analysis, it also allows to maximize network throughput by increasing workers (default is 50):
		\begin{Verbatim}  
  		python main.py -i domains_list.txt --workers 100
		\end{Verbatim}
		\end{itemize}
		
	\item \textbf{Specific Probes} - DKIM Selector Probing allows probing for common DKIM selectors (such as \texttt{google}, \texttt{default}, \texttt{s1}, \texttt{mail}) using the \texttt{---dkim-probe} flag. This will issue additional DNS queries.
	\begin{Verbatim}
  	python main.py example.com --dkim-probe
	\end{Verbatim}
	\end{itemize}		
	
\item \textbf{Output formats and Reports} - tool supports three output formats, controlled by the \texttt{---format} flag:

\begin{itemize}

\item ASCII Table (Default) - prints a fixed-width table directly to standard output.
	\begin{Verbatim}
    python main.py example.com --format table
  	\end{Verbatim}
  	
  	\begin{table}[h]
	\begin{tabular}{|l|l|l|l|l|}
	\hline
	Input       & eTLD+1      & Score & Level & Reason                            \\ \hline
	example.com & example.com & 15    & LOW   & no\_dmarc\_reporting\_rua,no\_spf \\ \hline
	\end{tabular}
	\caption{Table output example}
	\end{table}
  	
\item JSON - serializes the result structures to JSON format.
  \begin{Verbatim}
  python main.py example.com --format json
  \end{Verbatim}
	
	\captionof{listing}{JSON output example}
	\begin{minted}[frame=single, breaklines, linenos]{json}
	[
  	{
    		"domain_input": "example1.com",
    		"etld_plus_one": "example1.com",
    		"risk_score": 30,
    		"risk_level": "MEDIUM",
    		"reasons": [
      	"no_mx",
      	"no_dmarc",
      	"no_spf"
    		],
    		"syntax": {
     		"input_domain": "example1.com",
      "fqdn_provided": false,
      "registrable_domain": "example1.com",
      "subdomain": "",
      "idn": false,
      "mixed_scripts": false,
      "suspicious_tokens": [],
      "brand_in_subdomain": [],
      "typo_matches": []
    },
    "mx": {
      "present": false,
      "exchanges": []
    },
    "dmarc": {
      "present": false,
      "raw_records": [],
      "policy": null,
      "pct": null,
      "rua_present": null,
      "adkim": null,
      "aspf": null,
      "ambiguous": false,
      "parse_error": null
    },
    "spf": {
      "present": false,
      "raw_records": [],
      "spf_records_only": [],
      "multiple": false,
      "all_qualifier": null,
      "weak_all": false,
      "parse_error": null
    },
    "dkim": {
      "probed": false,
      "found_selectors": [],
      "notes": "DKIM probing disabled (no email context)."
    },
    "timestamp_utc": "2026-02-16T18:39:25Z"
  }
]
\end{minted}
  
  
\item CSV- flattens the parsed results into a single-row-per-domain CSV file.
  \begin{Verbatim}
  python main.py example.com --format csv
  \end{Verbatim}
\end{itemize}

\end{enumerate}








\section{DMARC container laboratory}

Now let's see how the virtual laboratory developed for the practical demonstration of SPF, DKIM, and DMARC protocols can be installed and run.

\begin{enumerate}
\item \textbf{Software prerequisites} - ensure the following tools are installed: Docker, Docker Compose, OpenSSL
\item \textbf{Open the terminal and navigate to the folder where the project is saved}: 
\begin{Verbatim}
cd /path/to/project
\end{Verbatim}

\item \textbf{Run the initial setup} - this operation needs to be done once before starting the lab, it creates DKIM cryptographic keys and files describing DNS zones. Run command:
\begin{Verbatim}
chmod +x setup.sh
./setup.sh
\end{Verbatim}

\item \textbf{Initializing the laboratory}
	\begin{itemize}
		\item Start the containers with: 
		\begin{Verbatim}
		docker compose up --build d
		\end{Verbatim}
		
		\item Wait for initialization with: 
		\begin{Verbatim}
		sleep 15
		\end{Verbatim} 
		recommended to wait for make virtual machines fully accessible
	\end{itemize}
	
	\item \textbf{Run the scenarios} - run the commands one at a time or only the desired ones:
	\begin{Verbatim}
	docker compose exec sender-mta bash /scripts/scenario-a.sh
	docker compose exec sender-mta bash /scripts/scenario-b.sh   
	docker compose exec sender-mta bash /scripts/scenario-c.sh   
	docker compose exec sender-mta bash /scripts/scenario-d.sh 
	\end{Verbatim}
	
	\item \textbf{Inspecting and Verifying the Results} - to understand the outcomes of the operations inspect the logs with:
	\begin{Verbatim}
	docker compose exec receiver-mta bash /scripts/check-logs.sh
	\end{Verbatim}
	
	\begin{figure}[h]
    \centering
    \includegraphics[width=0.8\linewidth]{Figures/scenariod-logs.png}
    \caption{Scenario D logs example}
    \label{fig:scenariodlogs2}
	\end{figure}

	Analyze headers saved in delivered mail running:
	\begin{Verbatim}
	docker compose exec receiver-mta bash /scripts/check-headers.sh
	\end{Verbatim}
	
	\begin{figure}[h]
    \centering
    \includegraphics[width=0.6\linewidth]{Figures/headers-scenarioa.png}
    \caption{Scenario A headers example}
    \label{fig:scenarioaheaders2}
\end{figure}	
	
	\item \textbf{Generate and Export the Global Forensic Report} - report generation showing the DNS tree, passed emails, rejected ones, and raw logs. Run:
	\begin{Verbatim}
	docker compose exec receiver-mta bash /scripts/forensic-report.sh
	\end{Verbatim}
	
	\item \textbf{Suspension and Teardown} - at the end of the tests, shut down the containers and free network resources so as not to overload the computer by running:
	\begin{Verbatim}
	docker compose down -v
	\end{Verbatim}
		
	\item \textbf{Clear logs to perform another run} - to execute another scenario in a clean way, it is possible to clear the logs in order to have a more readable logs and headers output:
	\begin{Verbatim}
	./path_to_the_project/scripts/clear-logs.sh
	\end{Verbatim}
	
\end{enumerate}

\chapter{Programmer Manual}
This appendix details the architectural design and code structure of the two tools. It provides software engineers and researchers with the information necessary to understand the codebase and to implement future developments, heuristics, or data-collection models. Let's start with the Domain Analyzer CLI.

\section{Domain Analyzer Tool}

\begin{itemize}
\item \textbf{Architectural Overview} - the project relies on a modular architecture written in Python. It aggregates data from two loosely coupled pipelines (Syntax Analysis and DNS/Email Posture) and feeds the aggregated evidence into a static scoring engine.  The entire codebase is parallelized vertically per domain. A multi-threaded orchestrator pushes each input domain through the entire pipeline individually. This ensures high throughput without complex inter-process communication algorithms. General architecture is represented in Figure \ref{fig:domainanalysisarchitecture}.

\begin{figure}[h]
    \centering
    \includegraphics[width=0.9\linewidth]{Figures/architecture_diagram_domainanalysis.png}
    \caption{General Architecture}
    \label{fig:domainanalysisarchitecture}
\end{figure}


\item \textbf{Core modules description}
	\begin{itemize}
	\item \texttt{models.py} (Data Model Layer): Provides rigid structure utilizing Python's \texttt{@dataclass}. These classes (\texttt{SyntaxInfo}, \texttt{MxInfo}, \texttt{DmarcInfo}, \texttt{SpfInfo}, \texttt{DkimInfo}, and \texttt{Result}) define the contract between different modules, ensuring data immutability and precise JSON serialization.
	
	\item \texttt{domain\_utils.py} (Input normalizers): Pre-processes the user's input, stripping HTTP/HTTPS protocols, resolving paths, lowercasing tokens, grouping by \texttt{tldextract} (eTLD+1), and detecting/decoding Punycode (\texttt{xn--}) using \texttt{idna}.
	
	\item \texttt{dns\_client.py} (DNS Wrapper): Responsible for executing DNS network operations. It wraps \texttt{dnspython}, creating custom threaded \texttt{Resolver} instances, executing MX and TXT queries, concatenating extensive multi-string Resource Records, and silencing runtime failures (like timeouts or NXDOMAIN) to guarantee the workflow doesn't crash on network unreliability.
	
	\item \texttt{syntax\_analyzer.py} (syntactic engine): Encapsulates static evaluations of the strings, including Mixed-Script spoofing (via Unicode ranges), keyword-based tokenization (e.g. tracking "login" or "billing" substrings), and brand impersonation computing the Damerau-Levenshtein distance against protected brands.
	
	\item \texttt{email\_posture.py} (record parsers): Digests the exact syntax of the retrieved DNS text records, strictly defining if DMARC syntax is ambiguous or valid, extracting SPF mechanisms with regex, and detecting explicit RFC violations.
	
	\item \texttt{scoring.py} (risk algorithm): Applies a predefined set of static integer weights against flags reported by the Syntactic and Email Posture engines. Outputs a deterministic \texttt{[0, 100]} score alongside a risk tier string (\texttt{LOW}, \texttt{MEDIUM}, \texttt{HIGH}).

	\item \texttt{reporting.py}: Exports the array of Result structures to screen or disk.
	\end{itemize}


\item \textbf{Future Developments}: The modular logic guarantees that adding new features rarely requires refactoring the core pipeline. Below it is descripted how a programmer can approach to extend the analyzer.

	\begin{itemize}
		\item Adding a new DNS Analysis step (such as BIMI or DNSSEC):
		\begin{enumerate}
			\item Create the model: in \texttt{models.py}, it is possible to define a new dataclass such as \texttt{BimiInfo}. Be sure to nest this new class as an attribute inside the primary \texttt{Result} dataclass.
			\item Implement DNS resolution: utilize the wrappers in \texttt{dns\_client.py} to draft targeted lookup logic.
			
			\item Parse and Analyze Records: inside \texttt{email\_posture.py} (or a newly created file), write the regex or parsing logic needed to analyze the specific components of the pulled record. Return an instance of \texttt{BimiInfo}.
			
			\item Integrate into the entry point: edit the \texttt{analyze\_one} method inside \texttt{main.py} so that it spawns the new DNS lookup, parses it using your logic, and injects the \texttt{BimiInfo} into \texttt{Result}.
		\end{enumerate}
		
		\item Adding a new output formatter: if integration with a SIEM framework or dashboard requires a data export format (e.g., XML, YAML) it could be possible to implement a dedicated function in \texttt{reporting.py}(e.g., "\texttt{write\_xml(results, path)}). Under \texttt{main.py}, it is possible to parse the new extra command-line flag inside \texttt{argparse} expanding the choices for the \texttt{--format} argument and finally wire the dispatcher at the end of the main to call your new formatter when the given format is selected.
		\item Future research ideas - future academic or commercial improvements to this project could explore:
		\begin{itemize}
			\item Asynchronous I/O implementation: transitioning from the OS-thread dependent \texttt{ThreadPoolExecutor} context to strict \texttt{asyncio}, utilizing \texttt{aiohttp} for Common Crawl requests and \texttt{aiodns} for DNS lookup. This move would decrease memory footprint for massive multi-million-domain batch processing.
			\item Machine Learning integration: replacing the integer-based weighted summation mechanism located within \texttt{scoring.py} with an offline-trained predictive classification model, trained against datasets composed by aggregating confirmed phishing domains versus benign domains from the top lists.
		\end{itemize}
	\end{itemize}


\end{itemize}

\section{DMARC container laboratory}
Now let's analyze the technical architecture in which the DMARC laboratory is embedded and operates.
The tool's architecture is built on containerization principles, relying entirely on Docker and Docker Compose, which allow the testing environment to be abstracted from the user's host machine, protecting it from potentially polluting network or DNS interference.

The system runs into an isolated internal network, named \texttt{mailnet} mapped to the \texttt{10.0.0.0/24} subnet, containing three communicating entities:
\begin{enumerate}
\item \textbf{DNS Container} (IP: \texttt{10.0.0.2}): it is an authoritative DNS daemon implemented using \texttt{BIND9}. It constitutes the backbone of trust for the mail infrastructure and maintains both forward and inverse IP DNS zones. It hosts within its TXT records the SPF definitions, DMARC policies, and publishes the public RSA components used to test DKIM keys (e.g., \texttt{selector1}) in plain text.


\item \textbf{Sender-MTA Container} (IP: \texttt{10.0.0.10}): this element plays the role of the "sending actor", employing a Postfix mailer configured solely to generate outbound connections, acting as a textual client towards the target domain. In Signing mode, the OpenDKIM daemon systematically and in real time applies signatures to this instance. Regarding the injection of email payloads (and specific Envelope vs. Header configurations), the command-line tool \texttt{swaks} is used, allowing modular construction of the SMTP envelope without passing through standard mail channels.

\item \textbf{Receiver-MTA Container} (IP: \texttt{10.0.0.20}): it symbolizes the Email Service Provider of the potential victim, impacted by both legitimate transmissions and spoofed attack vectors. It is also based on Postfix, it integrates a strict SMTP check chain (Milter Chain pipeline) with:
	\begin{itemize}
		\item A policy daemon written in python (\texttt{policyd-spf}) executes recipient restrictions, cross-referencing the socket IP address with the \texttt{MAIL FROM}. It applies the first upstream decisions.
   		\item An OpenDKIM manager operating in Verify mode decodes any base64 to calculate email integrity and it will inject formal headers (\texttt{dkim=pass/fail}).
   		\item The OpenDMARC daemon, which is the last bastion responsible for extrapolating the frame evaluated by the first filters, it also queries domain alignment lookups to assess conceptual correctness based on RFCs, discards or accepts, and records forensic metadata.	
	\end{itemize}
\end{enumerate}

Analizying the system at low level, it is possible to notice that it is composed of:

\begin{itemize}
	\item \textbf{Security Management and lifecycle bootstrap} to avoid deprecated practices like hardcoding cryptographic keys, Private Keys are injected using a Run/Setup Time approach. The script interface \texttt{setup.sh} performs:
	\begin{enumerate}
		\item invokes the \texttt{openssl} suite (or related tools);
		\item dynamically produces and moves raw cryptographic keys and TXT versions;
		\item updates the \texttt{.zone.template} files, compiling them and placing them inside \texttt{dns/zones/}, ready for BIND9 engagement before container image creation.	
	\end{enumerate}
	
	\item \textbf{Filter Call Order} (Postfix Milter): the \texttt{main.cf} setup file at receiver side plays a decisive role in evaluating the experiment. Pipes to milters occur in a cascade:
\texttt{smtpd\_milters = inet:localhost:8891, inet:localhost:8893}.
OpenDKIM (port 8891) is read, evaluated and resolved with priority over OpenDMARC (port 8893), which structurally depends on the parameters injected by the DKIM daemon. SPF is not a native milter on this stack and is handled in \texttt{smtpd\_recipient\_restrictions} by calling an external service \texttt{check\_policy\_service}.
\end{itemize}

For future improvements to the project, some architectural ideas:

\begin{enumerate}
	\item \textbf{ARC Protocol Integration} (Authenticated Received Chain) - in real world systems, domains often face DMARC failures generated by "Forwarding" caused by mailing lists or aliases. This practice compromises the authorized IP origin and sometimes the base payload, rendering original DKIM signatures useless.
	\begin{itemize}
		\item Development: it could be an idea creating an intermediary virtual machine/container configured for mailing-list forwarding, inserting the OpenARC daemon into the stack.
		\item Effects: it will allow the next study to demonstrate how forwarded cryptographic "seals" can preserve and extend trust despite manipulating headers during inter-MTA hops.	
	\end{itemize}
	
	\item \textbf{Telemetry collection and automatic processing of RUA/RUF analyses}: at the moment, forensic reports on the Receiver are managed by textually interfacing with logs generated by bash checks. An evolution would involve introducing SIEM infrastructures by leveraging frameworks such as \texttt{parsedmarc} that transform XML RUF and RUA data into archivable documents. This infrastructure could be combined with siem tools such as Elasticsearch, Logstash, and Kibana, allowing a programmer to read and study advanced metric dashboards instead of standard raw logs, offering immediate graphical indication of attack attempts across various scenarios.
	
	\item \textbf{Evolution of tools with web-based interface}: since the current scenarios pass through native docker interaction, it could be an idea to replace this step by introducing a small app written in Express or Flask, receiving web input and injecting \texttt{POST} calls, as it would lower the test time-to-market while concurrently bringing the usability benefits of a web application (or remote API) to end-users less familiar with the command line.
	
	\item \textbf{TLS and perimeter security protocols} - a potential step forward involves marginal transport encryption (SMTP-in-transit): demand Strict Transport Security (MTA-STS) by defining additional TXT zone files; hook the \texttt{Nginx/Apache} daemon for \texttt{HTTPS} policy file distribution, enabling instruction of Receiver machines to reject the connection itself if the sending server cannot explicitly encrypt the TLS channel without validated downgrade, providing a ruse for man-in-the-middle interceptions.
\end{enumerate}
















