docs/diploma

view thesis/tex/5-Improvements.tex @ 391:16d8eacf60e1

created index (it is not finished)
author meillo@marmaro.de
date Fri, 06 Feb 2009 21:09:21 +0100
parents 2a2f51551081
children b4611d4e1484
line source
1 \chapter{Improvement plans}
3 The last chapter came to the result that further development is best done in a double-strategy: First the existing code base should be improved to satisfy the most important needs in order to make it usable for some more time. Then \masqmail\ should get redesigned from scratch and rebuilt to gain a secure and modern \MTA\ architecture for the future.
5 This chapter finally describes approaches and techniques for the work on the current code base, and it introduces ideas and plans for a new, modern \MTA\ design which will become the next generation of \masqmail.
7 The first part of the chapter covers the short-time goals that base on the current code. The second part deals with the long-time goal---the redesign.
12 \section{Based on current code}
14 The three most important work tasks are implementable by improving the current code or by adding wrappers or interposition filters. The following sections describe solution approaches to do that work.
18 \subsection{Encryption}
19 \index{enc}
21 Encryption (\TODO\,1) should be the first functionality to be added to the current code. The requirement was already discussed on page~\pageref{requirement-encryption}. As explained there, \NAME{STARTTLS} encryption---defined in \RFC\,2487---should be added to \masqmail.
22 \index{starttls}
24 This work requires changes mainly in three source files: \path{smtp_in.c}, \path{smtp_out.c}, and \path{conf.c}.
26 The first file includes the functionality for the \SMTP\ server. It needs to offer \NAME{STARTTLS} support to clients and needs to initiate the encryption when the client requests it. Additionally, the server should be able to insist on encryption before it accepts any message, if this is wished by the administrator. %fixme
27 \index{smtp}
29 The second file includes the functionality for the \SMTP\ client. It should start the encryption by issuing the \NAME{STARTTLS} keyword if the server supports it. It should be possible to send messages only over encrypted channels, if the administrator wants so. %fixme
31 The third file controls the configuration files. New configuration options need to be added. The encryption policy for incoming connections needs to be defined. Three choices seem necessary: no encryption, offer encryption, insist on encryption. The encryption policy for outgoing connections should be part of each route setup. The options are the same: never encrypt, encrypt if possible, insist on encryption.
33 \subsubsection*{Depencencies}
35 \NAME{STARTTLS} uses \NAME{TLS} encryption which is based on certificates. Thus the \MTA\ needs its own certificate. This should be generated during installation. A third party application like \name{openssl} should be taken for this job. The encryption itself should also be done using an available library. \name{openssl} or a substitute like \name{gnutls} does then become a dependency for \masqmail. \name{gnutls} seems to be the better choice because the \name{openssl} license is incompatible to the \NAME{GPL}, under which \masqmail\ and \name{gnutls} are covered.
36 \index{tls}
37 \index{certificates}
38 \index{openssl}
39 \index{gnutls}
40 \index{gpl}
42 User definable paths to \masqmail's secret key, \masqmail's certificate, and the public certificates of trusted \name{Certificate Authorities} (short: \NAME{CA}s) are also nice to have.
45 \subsubsection*{Existing code}
46 \index{existing code}
48 \person{Frederik Vermeulen} wrote an encryption patch for \qmail\ which adds \NAME{STARTTLS} support \citeweb{qmail:tls-patch}. This patch includes about 500 lines of code.
49 \index{qmail}
51 Adding this code in a similar form to \masqmail\ will be fairly easy. It will save a lot of work as it is not necessary to write the code completely from scratch.
58 \subsection{Authentication}
59 \index{auth}
61 Authentication (\TODO\,2) is the second function to be added. It is important to restrict the access to \masqmail, especially for mail relay. The requirements for authentication where identified on page~\pageref{requirement-authentication}.
63 Static access restriction, based on the \NAME{IP} address is already possible by using \NAME{TCP} \name{Wrappers}. This makes it easy to refuse all connections from outside the local network for example, which is a good prevention against being an open relay. More detailed static restrictions, like splitting between mail for users on the system and mail for relay, should \emph{not} be added to the current code. This is a concern for the new design.
64 \index{tcp wrappers}
66 \subsubsection*{One of the dynamic methods}
68 Of the three dynamic, secret based, authentication methods (\SMTP-after-\NAME{POP}, \SMTP\ authentication, and certificates) the first one drops out as it requires a \NAME{POP} server running on the same or a trusted host. \NAME{POP} servers are rare on workstations and home servers do also not regularly include them. Thus it is no option for \masqmail.
69 \index{auth!methods}
71 Authentication based on certificates does suffer from the certificate infrastructure that is required. Although certificates are already used for encryption, its management overhead prevented wide spread usage for authentication.
73 \SMTP\ authentication (also referred to as \NAME{SMTP-AUTH}) support is easiest attained by using a \name{Simple Authentication and Security Layer} (short: \NAME{SASL}) implementation. \person{Dent} sees in \NAME{SASL} the best solution for dynamic authentication of users:
74 \index{smtp-auth}
75 \index{sasl}
77 \begin{quote}
78 %None of these add-ons is an ideal solution. They require additional code compiled into your existing daemons that may then require special write accesss to system files. They also require additional work for busy system administrators. If you cannot use any of the nonauthenticating alternatives mentioned earlier, or your business requirements demand that all of your users' mail pass through your system no matter where they are on the Internet, SASL is probably the solution that offers the most reliable and scalable method to authenticate users.
79 None of these [authentication methods] is an ideal solution. They require additional code compiled into your existing daemons that may then require special write access to system files. They also require additional work for busy system administrators. If you cannot use any of the nonauthenticating alternatives mentioned earlier, or your business requirements demand that all of your users' mail pass through your system no matter where they are on the Internet, \NAME{SASL} is probably the solution that offers the most reliable and scalable method to authenticate users.
80 \hfill\cite[page~44]{dent04}
81 \end{quote}
83 These days \NAME{SMTP-AUTH}---defined in \RFC\,2554---is supported by most email clients. If encryption is used then even insecure authentication methods like \NAME{PLAIN} and \NAME{LOGIN} become secure.
86 \subsubsection*{Simple Authentication and Security Layer}
87 \index{sasl}
89 \masqmail\ best uses an available \NAME{SASL} library. \name{Cyrus} \NAME{SASL} is used by \postfix\ and \sendmail. It is a complete framework that makes use of existing authentication concepts like the \path{passwd} file or \NAME{PAM}. As advantage it can be included in existing user data bases. \name{gsasl} is an alternative. It comes as a library which helps with the decision for a method and with generating the appropriate dialog data; the actual transmission of the data and the authentication against some database is left open to the programmer. \name{gsasl} is used, for instance, by \name{msmtp}. It seems best to give both concepts a try and decide then which one to use.
90 \index{cyrus sasl}
91 \index{pam}
92 \index{gsasl}
94 Currently, outgoing connections already feature \SMTP-\NAME{AUTH} but only in a hand-coded way. It is to decide whether this should remains as it is or should get replaced by the \NAME{SASL} approach that will be used for incoming connections. The decision should be influenced by the estimated time until the new design is usable.
96 Authentication needs code changes in the same places as encryption. The relevant code files are \path{smtp_in.c}, \path{smtp_out.c}, and \path{conf.c}.
98 The server code, to authenticate clients, must be added to \path{smtp_in.c} and the configuration options to \path{conf.c}. Several configuration options should be provided: the authentication policy (no authentication, offer authentication, insist on authentication), the authentication backend (if several are supported), an option to refuse plain text methods (\NAME{PLAIN} and \NAME{LOGIN}), and one to require encryption before authentication.
100 If the authentication code for outgoing connects shall be changed too, it must be done in \path{smtp_out.c}. The configuration options are already present.
103 \subsubsection*{Authentication backend}
104 \index{auth!backend}
106 For a small \MTA\ like \masqmail, it seems preferable to store the login data in a text file under \masqmail's control. This is the most simple choice for many usage scenarios. But using a central authentication facility has advantages in larger setups, too. \name{Cyrus} \NAME{SASL} supports both, so there is no problem. If \name{gsasl} is chosen, it seems best to start with an authentication file under \masqmail's control.
109 %fixme: << how could this be covered by architecture (e.g. smtp submission). >>
115 \subsection{Security}
116 \label{sec:current-code-security}
117 \index{security}
119 Improvements to \masqmail's security (\TODO\,3) are an important requirement and are the third task to be worked on. Retrofitting security \emph{into} \masqmail\ is not or hardly possible as it was explained in section~\ref{sec:discussion-further-devel}. But adding wrappers and interposition filters can be a large step towards security.
120 \index{wrapper}
121 \index{interposition filter}
123 \subsubsection*{Mail security layers}
125 At first mail security layers like \name{smap} come to mind. The market share analysis in section~\ref{sec:market-share} identified such software. Mail security layers are interposition filters that are located between the untrusted network and the \MTA. They accept mail in replacement for the \MTA\ in order to separate the \MTA\ from the untrusted network. Thus they are \name{proxies}.
126 \index{mail security layer}
127 \index{smap}
129 The work \name{smap} does is described in \cite{cabral01}: \name{smap} accepts messages as proxy for the \MTA\ and puts it into a queue. \name{smapd} a brother program runs as daemon and watches for new messages in this queue which it submits into the \MTA\ then.
131 Because the \MTA\ does not listen for connections from outside now, it is not directly vulnerable. Unfortunately, the \MTA\ can not react on relaying and spam by itself anymore because it has no direct connection to the mail sender. This job needs to be covered by the proxy now. Similar is the situation for encryption and authentication. However, care must be taken that the proxy stays small and simple as its own security will suffer otherwise.
133 The advantage of mail security layers is that the \MTA\ itself needs not to bother much with untrusted environments. The proxy cares for this.
135 \name{smap} is non-free software and thus no general choice for \masqmail. A way to achieve a similar setup is to copy \masqmail\ and strip one copy to the bare minimum of what is needed for the proxy job. \name{setuid} could be removed, and root privilege too if \name{inetd} is used. This hardens the proxy instance.
136 \index{inetd}
137 \index{proxy}
139 Mail from outside would then come through the proxy into the system. Mail from the local host and from the local network could be directly accepted by the normal \masqmail, if those locations are considered trusted. But it seems better to have them use the proxy too, or maybe a second proxy instance with different policy.
140 \index{policy}
142 The here described setup comes close to the structure of the incoming channels in the new design which is described in section~\ref{sec:new-design}. This shows the capabilities of the here chosen approach.
145 \subsubsection*{A concrete setup}
147 A stripped down proxy needs to be created. It should only be able to receive mail via \SMTP, encrypt the communication, authenticate clients, and send mail out via \SMTP\ to an internal socket (named ``X'' in the figure). This is a straight forward task. The normal \masqmail\ instance runs on the system too. It takes input from \name{stdin} (when the \path{sendmail} command is invoked) and via \SMTP\ where it listens on an internal socket (named ``X'' in the figure). Outgoing mail is handled without difference to a regular setup. Figure~\ref{fig:proxy-setup} depicts the setup.
148 \index{auth}
149 \index{enc}
151 \begin{figure}
152 \begin{center}
153 \includegraphics[scale=0.75]{img/proxy-setup.eps}
154 \end{center}
155 \caption{A setup with a proxy}
156 \index{figure!A setup with a proxy}
157 \label{fig:proxy-setup}
158 \end{figure}
161 \subsubsection*{Spam and malware handling}
162 \index{spam!handling}
163 \index{malware!handling}
165 The presented setup is the same as the one with two \MTA\ instances and a scanner application in between, which was suggested to add spam and malware scanner afterwards to an \MTA. This is a fortunate coincidence, because a scanner like \name{amavis} can simply be put in replace for the internal socket ``X''.
183 \section{A new design}
184 \label{sec:new-design}
185 \index{masqmail!new design}
187 In chapter~\ref{chap:present-and-future} the requirements for a modern and secure \masqmail\ were identified. Now modules that implement the various jobs of an \MTA\ are defined and plugged together to create a new \masqmail. The architecture is inspired by existing \MTA{}s and driven by the identified requirements.
189 One wise experience was kept in mind during the design: ``Many times in life, getting off to the right start makes all the difference.'' \cite[page~32]{graff03}.
193 \subsection{Design decisions}
195 This section describes and discusses architectural decision that were made for the new design. The functional requirements are only referenced, as they were already discussed in chapter~\ref{chap:present-and-future}.
197 A number of major design ideas lead the development of the new architecture:
198 \begin{enumerate}
199 \item Throughout compartmentalization.
200 \item Free the internal system from the in and out channels. Provide interfaces to add arbitrary protocol handlers afterwards.
201 \item Have a single point for scanning where all mail goes through.
202 \item Concentrate on the mail transfer job. Use specialized external programs for other jobs.
203 \item Keep it simple, clear, and general.
204 \end{enumerate}
205 \index{compartmentalization}
207 %fixme: << conditional compilation >>
210 \subsubsection*{Incoming channels}
211 \index{incoming channels}
213 The functional requirements for incoming channels were already discussed as \RF\,1 on page~\pageref{rf1}. Two required incoming channels were identified: the \path{sendmail} command for local mail submission and the \SMTP\ daemon for remote connections.
214 \index{sendmail!command}
216 A bit different is the structure of \name{sendmail~X} at that point: Locally submitted messages go also to the \SMTP\ daemon, which is the only connection to the mail queue. %fixme: is it a smtp dialog? or a back door?
217 \person{Finch} proposes a similar approach \cite{finch-sendmail}: He wants the \path{sendmail} command to be a simple \SMTP\ client that contacts the \SMTP\ daemon of the \MTA, like it is done by connections from remote. The advantage here is to have one single module where all \SMTP\ dialog with submitters is done. Hence one single point to accept or refuse incoming mail. Additionally does the module which puts mail into the queue not need to be \name{setuid} or \name{setgid}, because it is only invoked from the \SMTP\ daemon. The \MTA's architecture would become simpler and common tasks are not duplicated in modules that do similar jobs.
218 \index{sendmailx}
219 \index{smtp}
220 \index{setuid}
222 But merging the input channels in the \SMTP\ daemon makes the \MTA\ heavily dependent on \SMTP. To \qmail\ and \postfix\ new protocol handlers may be added without change in other parts of the system. The \SMTP\ modules can even be removed if it is not needed. It is better to have a larger number of independent modules if each one is simpler then. The need to implement \SMTP\ clients in every module for internal communication makes them more complicated.
223 \index{qmail}
224 \index{postfix}
226 With the increasing need for new protocols in mind, it seems better to have single modules for each incoming channel, although this leads to duplicated acceptance checks. Independent checks in different modules, however, have the advantage to be able to simply apply different policies. Thus it is possible to run two \SMTP\ modules that listen on different ports: one accessible from the Internet which requires authentication, the other one only accessible from the local network without authentication.
228 The approach of simple independent modules, one for each incoming channel, should be taken.
230 A module which is a \NAME{POP} or \NAME{IMAP} client to import contents of other mailboxes into the system may be added afterwards as it is desired.
231 \index{pop3}
232 \index{imap}
236 \subsubsection*{Outgoing channels}
237 \index{outgoing channels}
239 Outgoing mail is commonly either sent using \SMTP, piped into local commands (for example \path{uucp}), or delivered locally by appending to a mailbox. The requirements were identified on page~\pageref{rf1}.
240 \index{uucp}
242 Outgoing channels are similar for \qmail, \postfix, and \name{sendmail~X}: All of them have a module to send mail using \SMTP\ and one for writing into a local mailbox. Local mail delivery is a job that should have root privilege to be able to switch to any user in order to write to his mailbox. Modular \MTA{}s do not require \name{setuid root} but the local delivery process (or its parent) should run as root. root privilege is not a mandatory requirement but any other approach has some disadvantages thus commonly root privilege is used.
243 \index{setuid}
245 Local mail delivery should not be done by the \MTA, but by an \NAME{MDA} instead. This decision was discussed in section~\ref{sec:functional-requirements}. This means only an outgoing channel that pipes mail into a local command is required for local delivery.
246 \index{local delivery}
248 Other outgoing channels, one for each supported protocol, should be designed like it was done in other \MTA{}s.
252 \subsubsection*{Mail queuing}
253 \index{mail queue}
255 The mail queue is the central part of an \MTA. This fact demands especially for robustness and reliability as a failure here can lead to mail loss. (See \RF\,2 on page~\pageref{rf2}.)
257 Common \MTA{}s feature one or more mail queues, they sometimes have effectively several queues within one physical representation.
259 \MTA\ setups that include content scanning tend to require two separate queues. To use \sendmail\ in such setups requires two independent instances with one own queue each. \exim\ can handle it with special \name{router} and \name{transport} rules but the data flow gets complicated. Hence an idea is to use two queues (\name{incoming} and \name{active} in \postfix's terminology) and have the content scanning within the move from the one to the other.
260 \index{exim}
261 \index{postfix}
263 \sendmail, \exim, \qmail, and \masqmail\ all use at least two files to store one message in the queue: one file contains the message body, another the envelope and header information. The one containing the mail body is not modified at all. \postfix\ takes a different approach in storing queued messages in an internal format within one file. \person{Finch} suggest yet another approach: The whole queue should be stored in one single file with pointers to separating positions \cite{finch-queue}.
265 All of the presented \MTA{}s use the file system to hold the queue; none uses a database to hold it. A database could improve the reliability of the queue through better persistence. This might be a choice for larger \MTA{}s but is none for \masqmail\ which should be kept small and simple. A running database system does likely require much more resources than \masqmail\ itself does. And as the queue's job is more storing data, than running data selection queries, a database does not gain enough to outweigh its costs.
266 \index{database system}
268 Hence the choice here is having a directory with simple text files in it. This is straight forward, simple, clear, and general \dots\ and thus a good basis for reliability. It is additionally always an advantage if data is stored in the operating system's natural form, which is plain text in the Unix' case.
270 Robustness of the queue is covered in the next section.
274 \subsubsection*{Mail sanitizing}
275 \index{mail sanitizing}
277 Mail coming into the system may be malformed, lacking headers, or can be an attempt to exploit the system. Care must be taken.
279 In \postfix, mail is sanitized by the \name{cleanup} module, which invokes \name{rewrite}. The position in the message flow is after the message comes from one of the several incoming channels and before the message is stored into the \name{incoming} queue. \name{cleanup} does a complete check to make the mail header complete and valid.
280 \index{postfix}
282 \qmail\ has the principle of ``don't parse'' which propagates the avoidance of parsing as much as possible. The reason is that parsing is a highly complex task which likely makes code exploitable.
283 \index{qmail}
285 In \masqmail's new design, mail should be stored into the queue without parsing. A scanning module should then parse the message with high care. It seems best to use a \name{parser generator} for this work. The parsed data should then get modified if needed and written into a second queue. This approach has several advantages. First, the receiving parts of the system are independent from content, they simply store it into the queue. Second, one single module does the parsing and generates new messages that contain only valid data. Third, the sending parts of the system will thus only work on messages that consist of valid data. Of course, it must be ensured that each message passes through the \name{scanning} module, but this is already required for spam and malware scanning.
286 %fixme: ref for parser generator
287 \index{parser generator}
289 The mail body will never get modified, except for removing and adding transfer protocol specific requirements like dot stuffing or special line ending characters. These translations are only done in receiving and sending modules.
291 \person{Jon Postel}'s robustness principle (``Be liberal in what you accept, and conservative in what you send.''), which can be found in this wording in \RFC\,1122 and in different wordings in numerous \RFC{}s, should be respected in the \name{scanning} module. The module should parse the given input in a liberal way and generate clean output. \person{Raymond}'s \name{Rule of Repair} (``Repair what you can -- but when you must fail, fail noisily and as soon as possible.'') \cite[page~18]{raymond03} can be applied too. But it is important to repair only obvious problems, because repairing functionality is likely a target for attacks.
292 \index{robustness!principle of}
297 \subsubsection*{Aliasing}
298 \index{aliases}
300 The functional requirements were identified under \RF\,4 on page~\pageref{rf4}. From the architectural point of view, the main question about aliasing is: Where should aliases get expanded?
302 Two facts are important to consider: (1) Addresses that expand to a list of users lead to more envelopes. (2) Aliases that change the recipient's domain part may make the message unsuitable for a specific online route.
304 Aliasing is often handled by expanding the alias and re-injecting the mail into the system. Unfortunately, the mail is processed twice then; additionally does the system have to handle more mail this way. If it is wanted to check the new recipient address for acceptance and do all processing again, then re-injecting it is the best choice. But already accepted messages may get rejected in the second go, though the replacement address was set inside the system. This seems not to be wanted.
306 Doing the alias expansion in the \name{scanning} module appears to be the best solution. Unfortunately, a second alias expansion must be made on delivery, because only then is clear which route is used for the message. This compromise should get accepted.
310 \subsubsection*{Route management}
311 \index{online routes}
313 The online state is only important for the sending modules of the system, thus it should be queried in the \name{queue-out} module which selects ready messages from the \name{outgoing} queue and transfers them to the appropriate sending module. Route-based aliasing, which was described in the last section, %fixme: is this still true?
314 should be done in the same go.
318 \subsubsection*{Archiving}
319 \index{archiving}
321 The best point to archive copies of every incoming mail is the \name{queue-in} module, respectively the \name{queue-out} module for copies of outgoing mail. But the changes that are made by the receiving modules (adding further headers) and sending modules (address rewrites) are not respected with this approach.
323 \qmail\ has the ability to log complete \SMTP\ dialogs. Logging the complete data transaction into and out of the system is a great feature which should be implemented into each receiving and sending module. Though, as this will produce a huge amount of output, it should be disabled by default.
324 \index{smtp!dialog}
326 Archiving's functional requirements were described as \RF\,10 on page~\pageref{rf10}.
332 \subsubsection*{Authentication and Encryption}
333 \index{auth}
334 \index{enc}
336 The topics were discussed as \RF\,6 and \RF\,7 on several places throughout this thesis remarkable ones are on page~\pageref{rf6} and \pageref{rf7}.
338 Authentication should be done within the receiving and sending modules. To encryption applies the same as to authentication here. Only receiving and sending modules should come in contact with it.
339 \index{incoming channels}
340 \index{outgoing channels}
342 In order to avoid code duplicates, the actual implementation of both functions should be provided by a central source, for example a library, which is used in the various modules.
349 \subsubsection*{Spam and malware handling}
350 \index{spam!handling}
351 \index{malware!handling}
353 The two approaches for spam handling were already presented to the reader in section~\ref{sec:functional-requirements} as \RF\,8 and \RF\,9. Here they are described in more detail:
355 \begin{enumerate}
356 \item Refusing spam during the \SMTP\ dialog: This is the way it was meant by the designers of the \SMTP\ protocol. They thought checking the sender's and recipient's mail addresses would be enough, but as they are forgeable, it is not. More and more complex checks are needed to be done. Checking needs time, but \SMTP\ dialogs time out if it takes too long. Thus during the \SMTP\ dialog, only limited time can be used for checking if a message seems to be spam. The advantage of this approach is that bad messages can simply get refused---no responsibility for them is taken and no further system load is added. See \RFC\,2505 (especially section 1.5) for detail.
357 \index{smtp!dialog}
359 \item Checking for spam after the mail was accepted and queued: Here it is possible to invest more processing time, thus more detailed checks can be done. But, as responsibility for messages was taken, it is no choice to simply delete spam mail. Checks for spam do not lead to sure results, they just indicate the possibility the message is unwanted mail. \person{Eisentraut} lists actions to take after a message is recognized as probably spam \cite[pages 18--20]{eisentraut05}. For mail the \MTA\ is responsible for, the only acceptable action is adding further or rewriting existing header lines. Thus all further work on the spam messages is the same as for non-spam messages.
360 \end{enumerate}
362 Modern \MTA{}s use both techniques in combination. Checks during the \SMTP\ dialog tend to be implemented in the \MTA\ to make them fast; checks after the message was queued are often done using external programs (\name{spamassassin} is a well known one). \person{Eisentraut} sees the checks during the \SMTP\ dialog to be essential: ``Ganz ohne Analyse w\"ahrend der \SMTP-Phase kommt sowieso kein \MTA\ aus, und es ist eine Frage der Einsch\"atzung, wie weit man diese Phase belasten m\"ochte.'' \cite[page 25, (translated: ``No \MTA\ can go without analysis during the \SMTP\ phase anyway, but the amount of stress one likes to put on this phase is left to his discretion.'')]{eisentraut05}
364 Checks before a message is accepted, like \NAME{DNS} blacklists and \name{greylisting}, need to be invoked from within the receiving modules. Like for authentication and encryption, the implementation of this functionality should be provided by a central source.
365 \index{dns blacklist}
366 \index{greylisting}
368 All checks on queued messages should be done by pushing the message through external scanners like \name{spamassassin}. The \name{scanning} module is the best place to handle this. Hence this module needs interfaces to external scanners.
371 Malware scanning is similar to spam scanning of queued messages. The \name{amavis} framework is a popular mail scanning framework that includes all kinds of malware and also spam scanners; it communicates by using \SMTP.
373 Providing \SMTP\ in and out channels from the \name{scanning} module to external scanner applications is thus a desired goal. Using further instances of the already available \name{smtp} and \name{smtpd} modules appears to be the best solution.
377 \subsubsection*{The scanning module}
379 A problem, which was probably noticed by the attentive reader, is the lot of work that was put onto the \name{scanning} module. This is not what is desired. Thus splitting this module into a set of single modules might be necessary.
381 The decision how to split shall not be discussed here. It is left up to the time of prototyping, because trying different approaches helps with the decision in such situations.
396 \subsection{The resulting architecture}
398 The result is a symmetric design, featuring the following modules:
400 \begin{enumerate}
401 \item Any number of receiver modules that handle incoming connections.
402 \item A module that stores the received mail into a first queue.
403 \item A central scanning module that takes mail from the first queue, processes it in various ways, and puts it afterwards into a second queue.
404 \item A module that takes mail out of the second queue and passes it to a matching transport module.
405 \item A set of transport modules that transfers the message to the destination.
406 \end{enumerate}
408 In other words three main modules (\name{queue-in}, \name{scanning}, \name{queue-out}) are connected by two queues (\name{incoming}, \name{outgoing}). On each end is a set of modules to receive or send mail---one for each protocol. The queue includes also a message \name{pool} where the bodies of the queued messages are stored. Figure~\ref{fig:masqmail-arch-new} depicts the new designed architecture.
410 \begin{figure}
411 \begin{center}
412 \includegraphics[width=\textwidth]{img/masqmail-arch-new.eps}
413 \end{center}
414 \caption{The new designed architecture for \masqmail}
415 \index{figure!The new designed architecture for \masqmail}
416 \label{fig:masqmail-arch-new}
417 \end{figure}
419 This architecture is heavily influenced by the ones of \qmail\ and \postfix. Both have different incoming channels which merge in the module that puts mail into the queue; central is the queue (or more of them); and one module takes mail from the queue and passes it to one of the outgoing channels. But mail processing is built into the architecture in a more explicit way in this design than it was done in \qmail\ and \postfix.
420 \index{qmail}
421 \index{postfix}
423 Special regard was put on addable support for further mail transfer protocols. Here the design appears to be most similar to \qmail, which was designed to handle multiple protocols.
426 \subsubsection*{The modules}
428 Now follows a description of the modules of the new architecture. They are described in the same order in which a message passes through them.
431 \paragraph{Receiver modules}
432 \index{incoming channels}
433 They are the communication interface between external senders and the \name{queue-in} module. Each protocol needs a corresponding \name{receiver module} to be supported. Most popular is the \name{sendmail} module, which is a command to be called from the local host, and the \name{smtpd} module which usually listens on port 25. Other modules to support other protocols may be added as needed. Receiving modules that need to listen on ports should get invoked by \name{inetd}, or by \person{Bernstein}'s more secure \name{ucspi-tcp}. This makes it possible to run them with least privilege.
436 \paragraph{The \name{queue-in} module}
437 \index{mail queue}
438 Its job is to store new messages into the queue. When one of the receiving modules has a new message, it invokes the \name{queue-in} module which creates a spool file in the \name{incoming} queue and a data file in the \name{pool}. The receiver module then sends the envelope, the message header, and the message body. The \name{queue-in} modules writes the first two into the spool file, the latter one into the \name{pool}.
441 \paragraph{The \name{scanning} module}
442 It is the central part of the system. It reads spool files from the \name{incoming} queue, works on the data, and writes new spool files to the \name{outgoing} queue. Then the message is removed from the \name{incoming} queue. The main job of this module is the processing of the message. Headers are fixed and missing ones are added if necessary, aliasing is done, and external processing of any kind is triggered. The \name{scanning} module processes primary the spool files but may read the mail body from the \name{pool} if necessary.
445 \paragraph{The \name{queue-out} module}
446 \index{mail queue}
447 This module takes messages from the \name{outgoing} queue, queries information about the online state, and passes the messages to the correct transport module. Successfully transferred messages are removed from the \name{outgoing} queue. The \masqmail\ specific tasks of the route management are handled by this module, too.
450 \paragraph{Transport modules}
451 \index{outgoing channels}
452 These modules send outgoing mail; they are the interface between \name{queue-out} and remote hosts or local commands. The most popular modules of this kind are the \name{smtp} module which acts as an \SMTP\ client and the \name{pipe} module to interface gateways to other systems or networks like \NAME{FAX} and \NAME{UUCP}. A module for local delivery is not included; \masqmail\ passes this job to an \NAME{MDA} which gets invoked through the \name{pipe} module. (See section~\ref{sec:functional-requirements} for reasons.)
457 \subsubsection*{The queue}
458 \index{mail queue}
460 The queuing system consists of two queues and a message pool. The queues store the spool files---in unprocessed form in \name{incoming} and in complete and valid form in \name{outgoing}. The \name{pool} is the storage of the data files. On disk, the three parts of the queuing system are represented by three directories within the queue path.
462 The representation of queued messages on disk is basically the same as in current \masqmail: One file for the envelope and message header information (the ``spool file'') and a second file for the message body (the ``data file'').
463 \index{spool file}
464 \index{data file}
466 The currently used internal structure of the spool files can remain. Following is a sample spool file from current \masqmail. The first part is the envelope and meta information. The annotations in parenthesis are only added to ease the understanding. The second part, after the empty line, is the message header.
468 \codeinput{input/sample-spool-file.txt}
470 The spool file owner's executable bit shows if a file is ready for further processing: The module that writes the file into the queue sets the bit as last action. Modules that read from the queue can process messages that have the bit set. This approach is derived from \postfix.
472 The data file is stored into the \name{pool} by \name{queue-in}; it never gets modified until it is deleted by \name{queue-out}. They consist of data in local default text format.
478 \subsubsection*{Inter-module communication}
479 \index{ipc}
481 Communication between modules is required to exchange data and status information. This is also called ``Inter-process communication'' (short: \NAME{IPC}) because the modules are independent programs in this case and processes are programs in execution.
483 The connections between \name{queue-in} and \name{scanning}, as well as between \name{scanning} and \name{queue-out}, is provided by the queues, only signals might be useful to trigger runs. Communication between receiver and transport modules and the outside world is organized by their specific protocol (e.g.\ \SMTP).
485 Left is only the communication between the receiver modules and \name{queue-in}, and between \name{queue-out} and the transport modules. Suggested for this communication is a simple protocol with data exchange through \unix\ pipes. Figure~\ref{fig:ipc-protocol} shows a state diagram for the protocol.
487 \begin{figure}
488 \begin{center}
489 \includegraphics[scale=0.75]{img/ipc-protocol.eps}
490 \end{center}
491 \caption{State diagram of the \NAME{IPC} protocol. (Solid lines indicate client actions, dashed lines indicate server responses.)}
492 \index{figure!State diagram of the \NAME{IPC} protocol.}
493 \label{fig:ipc-protocol}
494 \end{figure}
496 The protocol is described in more detail now:
497 \index{protocol}
499 \paragraph{Timing}
500 One dialog consists of exactly three phases: (1) The connection attempt, (2) The envelope and header transfer, and (3) The transfer of the message body. The order is always the same. The three phases are all initiated by the client process. After each phase the server process sends a success or failure reply. Timeouts for each phase need to be implemented.
502 \paragraph{Semantics}
503 The connection attempt is simply opening the connection. This starts the dialog. A positive reply by the server leads to the transfer of the envelope and the message header. If the server again sends a positive reply, the message data is transferred. A last server reply ends the dialog.
505 The client indicates the end of each data transfer with a special terminator sequence. The appearance of this terminator sequence tells the server process that the data transfer is complete. The server then needs to send its reply. The server process takes responsibility for the data in sending a success reply. A failure reply immediately stops the dialog and resets both client and server to the state before the connection attempt.
507 \paragraph{Syntax}
508 Data transfer is done by sending plain text data. \name{Line Feed} (`\texttt{\textbackslash{}n}')---the native line separator on Unix---is used as line separator. The terminator sequence used to indicate the end of the data transfer is the \NAME{ASCII} \name{null} character (`\texttt{\textbackslash0}'). Replies are one-digit numbers with `\texttt{0}' meaning success and any other number (`\texttt{1}'--`\texttt{9}') indicating failure.
514 \subsubsection*{Rights and permissions}
515 \index{permission}
517 The set of system users that is required for \qmail\ seems to be too complex for \masqmail. One system user, like \postfix\ uses, is more appropriate. \name{root} privilege and \name{setuid} permission should to be avoided if feasible.
519 The \name{queue-in} module is the part of the system that is most critical about permission. It either needs to run as deamon or be \name{setuid} or \name{setgid} in order to avoid a world-writable queue. \person{Ian~R.\ Justman} recommends to use \name{setgid} in this situation:
520 \index{setuid}
522 \begin{quote}
523 But if all you need to do is post a file into an area which does not have world writability but does have group writability, and you want accountability, the best, and probably easiest, way to accomplish this without the need for excess code for uid switching (which is tricky to deal with especially with setuid-to-root programs) is the setgid bit and a group-writable directory.
524 \hfill\cite{justman:bugtraq}
525 \end{quote}
527 \person{Bernstein} chose \name{setuid} for the \name{qmail-queue} module, \person{Venema} uses \name{setgid} in \postfix, yet the differences are small. Better than running the module as a deamon is each of them. A deamon needs more resources and therefore becomes inefficient on systems with low mail amount, like the ones \masqmail\ will probably run on. Short running processes are additionally higher obstacles for intruders, because a process will die soon if an intruder managed to take one over.
528 \index{qmail}
529 \index{postfix}
532 The modules \name{scanning} and \name{queue-out} are candidates for all-time running daemon processes. Alternatively they could be started by \name{cron} to do single runs.
534 Another possibility is to run a master process as daemon which starts and restarts the system parts. \postfix\ has such a master process, \qmail\ lacks it. The jobs of a master process can be done by other tools of the operating system too, thus making a master process abdicable. \masqmail\ does probably better go without a master process, because it aims to save resources, not to get the best performance.
535 \index{master process}
537 A sane permission management is very important for secure software in general. The \name{principle of least privilege}, as it is often called, should be respected. If it is possible to use lower privilege then it should be done. An example for doing so is the \name{smtpd} module. It is a server module which listens on a port. One way is to start it as root and let it bind to the port and drop all privilege before it does any other work. But root privilege is avoidable completely if \name{inetd}, or one of its substitutes, listens on the port instead of the \name{smtpd} module. \name{inetd} will then launch the \name{smtpd} module to handle the connection whenever a connection attempt to the port is made. The \name{smtpd} module needs no privilege at all this way.