% !TeX root = ../Thesis.tex

%********************************************************************
% Some Proof (Appendix)
%*******************************************************
% -- TemplateKnob
% If problems with the headers: get headings in appendix etc. right
%\markboth{\spacedlowsmallcaps{Appendix}}{\spacedlowsmallcaps{Appendix}}
\chapter{Appendix}\label{ch:SomeProof}
\glsresetall % Resets all acronyms to not used

\section{Exception Handling}
\label{sec:exception-handling}

% Idea: have exception class which inherits from EuiccException base class -> class has mapping from error code to exception
% erorrs are reused by other functions -> have errors inherit from base class and function based errors raise these errors -> restructure inheritence before raising so that inheritence order is: ErrorException <- FunctionException <- common EuiccBaseException
% ErrorException can be like IccidOrAidNotFound Exception and function exception can be something like ProfileInteractionException
% Goal: Capture all exception that are possibly raised by a function but still have access to more granualar exception handling
% lising1 shows CodeBaseException from which the functionexceptions inherit: restructures exception inheritance from error_map to have all mapped exception inherit from the functionexception instead of the common base exception
% listing2 shows implemention of a function exception class with a fill error_map and some example error exception


Robust exception handling is critical in the context of \gls{euicc} interactions, especially when performing differential testing. The SGP.22 specification defines a comprehensive set of error codes, many of which are reused across different functions.\marginpar{Exceptions are categorized by function context and specific error type.} To allow both coarse-grained and fine-grained error handling, the exception hierarchy in our implementation is explicitly structured around two core ideas:

\begin{itemize}
  \item \textbf{Function-based exceptions} encapsulate the context in which the error occurred (e.g., Profile Management, \gls{isdr} interactions).
  \item \textbf{Error-based exceptions} represent the specific error raised (e.g., \gls{iccid} not found, \gls{aid} missing).
\end{itemize}

All exceptions inherit from a common \texttt{EuiccException} base class, ensuring they can be captured uniformly when needed.

\subsection*{Exception Hierarchy}
\marginpar{Hierarchy enables both broad and precise exception handling.}
The exception hierarchy is structured such that all specific error exceptions (e.g. \texttt{IccidNotFound}) inherit from a relevant function exception (e.g. \texttt{ProfileInteractionException}), which itself inherits from \texttt{EuiccException}. This enables both precise and broad exception matching, depending on the caller’s needs. For example:

\begin{center}
\texttt{EuiccException} $\rightarrow$ \texttt{ProfileInteractionException} $\rightarrow$ \texttt{IccidOrAidNotFound}
\end{center}

This structure is illustrated in \cref{lst:code-base-exception} and \cref{lst:function-exception}.

\begin{lstlisting}[language=python,label={lst:code-base-exception},caption={Class to raise exception based on the error code and restructure the inheritance.}]
class CodeBaseException(EuiccException):
    """Base class for all exceptions raised by the result handling."""

    message: str = "An unknown code error occurred"
    error_map: dict[int, Type['EuiccException']]

    def __init__(self, message: str | None = None):
        if message:
            self.message = message

        super().__init__(self.message)

    @classmethod
    def raise_from_code(cls, code: int):
        """Raises the appropriate exception subclass based on the error code."""
        exception_class = cls.error_map.get(code, UndefinedError)
        exception_class.__bases__ = (cls,)

        raise exception_class()
\end{lstlisting}

\begin{lstlisting}[language=python,label={lst:function-exception},caption={Implementation of the \lstinline{CodeBaseException} Class.}]
class ProfileInteractionException(CodeBaseException):
    """Base class for all exceptions raised by the profile handling."""

    message: str = "An unknown profile interaction error occurred"
    error_map = {
        1: IccidOrAidNotFound,
        2: ProfileNotInEnabledState,
        3: DisallowedByPolicy,
        4: WrongProfileReenabling,
        5: CatBusy,
        6: DisallowedByEnterpriseRule,
        7: CommandError,
        8: DisallowedForRpm,
        9: NoEsimPortAvailable,
        127: UndefinedError,
    }
    
class IccidOrAidNotFound(EuiccException):
    message = "ICCID or AID not found"
\end{lstlisting}

\subsection*{Benefits}

This exception model provides the following advantages:
\marginpar{Clean exception abstraction improves introspection during fuzzing and test execution.}
\begin{itemize}
  \item \textbf{Modular extensibility:} New error types can be added per function with minimal changes.
  \item \textbf{Granular diagnostics:} Developers can differentiate between general failure (\texttt{ProfileInteractionException}) and specific causes (\texttt{IccidNotFoundException}).
  \item \textbf{Cleaner call sites:} Exceptions can be caught using either the general or specific class, depending on context.
\end{itemize}

This exception system enables detailed introspection during fuzzing and testing while maintaining a clean abstraction between components.

% \todo{add section about inital testing of nonce randomness}

\section{CLI Structure}
\label{sec:cli_structure}
The CLI is organized around three core commands:
\begin{itemize}
    \item \textbf{tracing} — Interfaces with the \texttt{simtrace2} device and the \gls{lpa} to capture \gls{apdu} traffic in real time. This functionality is discussed in detail in \cref{sec:tracing}.\marginpar{CLI provides tracing, lpa, and fuzzing commands for core system interaction.}
    \item \textbf{lpa} — Exposes \gls{euicc} communication features such as profile management, notification handling, and remote procedure execution via the \gls{cli}.
    \item \textbf{fuzzing} — Wraps both \gls{apdu}-level and data-level fuzzing. Additionally, it provides a \texttt{compare} command to compare multiple trace recordings and highlight structural differences in JSON format.
\end{itemize}
\marginpar{Each CLI command resides in a dedicated subfolder.}
Each of these commands is implemented in its respective subfolder (e.g., \texttt{tracing/}, \texttt{lpa/}, \texttt{fuzz/}). The modular structure of the \gls{cli} is shown in \cref{fig:cli_structure}, which illustrates how the subcommands map to the file and folder hierarchy of the project.

\begin{figure}[h]
    \centering
    \begin{forest}
  for tree={
    font=\ttfamily,
    grow'=0,
    child anchor=west,
    parent anchor=south,
    anchor=west,
    calign=first,
    inner sep=1pt,
    l=1.5em,
    s sep=3pt,
    edge path={
      \noexpand\path [draw, \forestoption{edge}]
      (!u.south west) +(3.5pt,0) |- node[fill,inner sep=1.25pt] {} (.child anchor)\forestoption{edge label};
    },
    before typesetting nodes={
      if n=1
        {insert before={[,phantom]}}
        {}
    },
    fit=band,
    before computing xy={l=15pt},
  }
  [cli
    [\_\_init\_\_.py]
    [fuzzer
      [\_\_init\_\_.py]
      [apdu\_fuzzer.py]
      [compare.py]
      [data\_fuzzer.py]
    ]
    [trace
      [\_\_init\_\_.py]
      [record.py]
      [replay.py]
    ]
    [lpa
      [\_\_init\_\_.py]
      [euicc.py]
      [notification.py]
      [profile.py]
    ]
  ]
    \end{forest}
    \caption{\gls{cli} folder structure and modular separation of functionality}
    \label{fig:cli_structure}
\end{figure}

\paragraph{Dispatch and Argument Parsing}
Each submodule implements a \texttt{run()} function that parses the subcommand’s specific arguments and dispatches execution to the appropriate internal handler. At the top level, the root \texttt{\_\_init\_\_.py} file defines the global parser, registers the subcommands via subparsers, and handles any global options. This design pattern is shown in \cref{lst:cli_parser}.


\begin{lstlisting}[caption={Top-level CLI dispatch pattern}, label={lst:cli_parser}]
def add_subparser(parent_parser: argparse._SubParsersAction) -> None:
    trace_parser: argparse.ArgumentParser = parent_parser.add_parser(
        "trace",
        help="Trace-level operations (record, replay)",
        formatter_class=RichHelpFormatter,
    )
    trace_subparsers = trace_parser.add_subparsers(dest="trace_command", required=True)
    record.add_subparser(trace_subparsers)
    replay.add_subparser(trace_subparsers)


def run(args: argparse.Namespace) -> None:
    if args.trace_command == "record":
        record.run(args)
    elif args.trace_command == "replay":
        replay.run(args)
\end{lstlisting}


Each subcommand module (e.g., \texttt{fuzz/data\_fuzz.py}) provides its own parser configuration and encapsulated logic, adhering to a clearly defined interface.

\section{APDU Status Word Codes}
\label{sec:sw_codes}

In the context of \gls{apdu} communication with \glspl{euicc}, each Response-APDU (R-APDU) from the card ends with a two-byte Status Word (SW), which indicates the outcome of the command execution.\marginpar{Each R-APDU ends with a 16-bit Status Word indicating command execution outcome.} The SW is encoded as a 16-bit hexadecimal value and follows the ISO/IEC 7816-4 specification \cite{isoiec_isoiec_2006}.

Some SW codes contain fixed values, whereas others use placeholders (represented as \texttt{??} or \texttt{XX}) to indicate that specific bits may vary, often encoding additional information such as a retry count or the number of bytes remaining. \cref{tab:sw_codes} provides an overview of some of the most frequently observed status words.

\begin{table}[H]
\centering
\begin{tabular}{|c|p{10cm}|}
\hline
\textbf{SW Code} & \textbf{Description} \\
\hline
\texttt{9000} & Normal ending of the command. This indicates that the command was executed successfully and no further action is required. \\
\texttt{61XX} & Command executed successfully; \texttt{XX} bytes of data are available for retrieval using a subsequent \texttt{GET RESPONSE} command. \\
\texttt{91XX} & Command executed successfully; the card has sent a proactive command that the terminal must fetch. The \texttt{XX} indicates the length of the pending command. \\
\texttt{6A82} & File not found. This error typically occurs when the requested EF (Elementary File) or DF (Dedicated File) does not exist in the current context. \\
\texttt{6982} & Security status not satisfied. This usually implies that access conditions (e.g., PIN verification) were not met before executing the command. \\
\texttt{6D00} & Instruction code not supported or invalid. The \gls{euicc} does not recognize the INS byte of the command. \\
\texttt{6F00} & Technical problem with no precise diagnosis. Often a fallback or catch-all error code indicating an internal card error or undefined behavior. \\
\hline
\end{tabular}
\caption{Common \gls{apdu} Status Words}
\label{tab:sw_codes}
\end{table}