Sunday, February 2, 2014

Effective Spam and Malware Countermeasures - Network Noise Reduction Using Free Tools

In order to keep you entertained while I work on a new edition of The Book of PF, I dug deep in the archives for material you might enjoy reading. Here, for your weekend reading pleasure, is a minimally edited version of my malware article, originally written for a BSDCan presentation (also presented at BLUG and UKUUG events):

A certain proprietary software marketer stated in 2004 that by 2006 the spam and malware problems would be solved.  This article explores what really happened, and presents evidence that the free software world we are in fact getting there fast and having fun at the same time. We offer an overview of principles and tools with real life examples and data, and cover the almost-parallel evolution of malware and spam and effective counter-measures.  We present recent empirical data interspersed with examples of practical approaches to ensuring a productive, malware and spam free environment for your colleagues and yourself, using free tools.  The evolution of content scanning is described and contrasted with other methods based on miscreants' (and their robot helpers') behavior, concluding with a discussing of recent advances in greylisting and greytrapping with an emphasis on those methods' relatively modest resource demands.

(Updated 2016-12-13, see the addendum at the end)

Note: This piece is also available without trackers but classic formatting only here.

Malware, virus, spam - some definitions

In this article we will be talking about several varieties of the mostly mass produced nuisances we as network admins need to deal with every day. However, you only need to pick up an IT industry newspaper or magazine or go to an IT subject web site to see that there is a lot of confusion over terms such as virus, malware and for that matter spam. Even if a large segment of the so called security industry does not appear to put a very high value on precision, we will for the sake of clarity spend a few moments defining the parameters of what we are talking about.

To that end, I've taken the time to look up the definitions of those terms at Wikipedia and a few other sources, and since the Wikipedia definitions agree pretty well with my own prejudices I will repeat them here:
  • Malware or Malicious Software is software designed to infiltrate or damage a computer system without the owner's informed consent.

  • A computer virus is a self-replicating computer program written to alter the way a computer operates, without the permission or knowledge of the user.

  • Another common subspecies of malware is the worm, commonly defined as “a program that self-propagates across a network exploiting security or policy flaws in widely-used services” (This definition is taken from a 2003 paper, Weaver, Paxson, Staniford and Cunningham: “A Taxonomy of Computer Worms”.)

  • The term zombie is frequently used to describe computers which are under remote control after a successful malware or manual attack by miscreants.

  • Spamming is the abuse of electronic messaging systems to send unsolicited, undesired bulk messages. While the most widely recognized form of spam is e-mail spam, the term is applied to similar abuses in other media [ … ]

You will notice that I have left out some parts at the end here, but if you're interested, you can look up the full versions at Wikipedia. And of course, if you read on, much of the relevant information will be presented here anyway, if possibly in a slightly different style and supplemented with a few other items, some even of distinct practical value. But first, we need to dive into the past in order to better understand the background of the problems we are trying to solve or at least keep reasonably contained on a daily basis.

A history of malware

The first virus: the Elk Cloner

According to the Wikipedia 'Computer Virus' article, the first computer virus to be found in the wild, outside of research laboratories, was the 1982 "elk cloner" written by Rich Skrenta, then a teenager in Southern California.

The virus was apparently non-destructive, its main purpose was to annoy Skrenta's friends into returning borrowed floppy disks to him. The code ran on Apple II machines and attached itself to the Apple DOS system files.

Apple DOS and its single user successors such as MacOS up to System 9 saw occasional virus activity over the following years, much like the other personal systems of the era which all had limited or no security features built into the system.

The first PC virus: the (c)Brain

It took a few years for the PC world to catch up. The earliest virus code for PCs to be found in the wild was a piece of software called (c)Brain, which was written and spread all over the world in 1986. (c)Brain attached itself to the boot sector on floppies. In contrast to quite a number of PC malware variants to follow, this particular virus was not particularly destructive beyond the damage done by altering the boot sectors.

Like most of the popular personal computer systems of the era, MS-DOS had essentially no security features whatsoever. In retrospect it was probably inevitable that PC malware blossomed into a major problem.

With system vendors unable or unwilling to rewrite the operating systems to eliminate the bugs which let the worms propagate, an entire industry grew out of enumerating badness. (The origin of the term enumerating badness is uncertain, but most frequently attributed to Marcus Ranum, in the must-read, often cited web accessible article “The Six Dumbest Ideas in Computer Security”. It's fun as well as useful and very readable.)

To this day a large part of the PC based IT sector remains dedicated to writing malware and producing ever more elaborate workarounds for the basic failures of the MS-DOS system and its descendants. Current virus lists typically contain signatures for several hundred thousands of variants of mainly PC malware.


The first Unix worm: The Morris Worm

Meanwhile in the Unix world, with its better connected and relatively well educated user base, things were relatively peaceful, at least for a while. The peace was more or less shattered on November 2, 1988 when the first Unix worm, dubbed the Morris worm hit Unix machines on the early Internet. This was both the first replicating worm in a Unix environment and the first example of a worm which used the network to propagate.

More than 20 years later, there is still an amazing amount of information on the worm available on the net, including what appears to be the complete source code to the worm itself and a number of analyses by highly competent people. It's all within easy reach from your favourite search engine, so I'll limit myself to repeating the main points. Some of the Morris worm's characteristics will be familiar.
  1. It was system specific Even though there are indications that the worm was intended to run on more architectures, it was in fact only able to run successfully on VAXes and sun3 machines running BSD.

  2. It exploited bugs and sloppiness Like pretty much all of its successors, the Morris worm exploited bugs in common programs, such as a buffer overflow in fingerd, used the commonly enabled debug mode in sendmail - which allowed remote execution of commands - along with a short dictionary of likely passwords.

  3. It replicated and spread Once the worm got in, it started the process of spreading. Fortunately, the worm was designed mainly to spread, not to do any damage.

  4. It lead to denial of service Unfortunately, the worm code itself had a bug which made it more efficient at spreading itself than its author had anticipated, and caused a large increase in network traffic, slowing down Internet traffic to a large number of hosts. Some hosts worked around the problem by disconnecting themselves from the Internet temporarily. In one sense, it may have been one of the earliest Denial of Service incidents recorded.
The worm was estimated to have reached rougly 10% of the hosts connected to the Internet at the time, and the most commonly quoted estimate of an absolute number is "around 6,000 hosts".

The event was quite stressful for, by today's standards, a very small group of people. In retrospect, it is probably fair to say that the episode mainly served to make Unixers in general aware that there was a potential for security problems, and developers and sysadmins set out to fix the problems.

Microsoft vs the internet

The final components to form the current mess arrived on the scene in the second part of the 1990s when Microsoft introduced modern networking components to the default setup of their PC system software which came preinstalled on consumer grade computers. This happened at roughly the same time that several office type applications started shipping with their own fairly complete programming environments for macro languages.

Riding on the coattails of the early 1990s commercialization of the Internet, Microsoft started real efforts to interface with the Internet in the mid 1990s. Up until some time in 1995, Internet connectivity was an optional extra to Microsoft users, mainly through third party stacks and frequently through hard to configure dial-up connections.

Like the third party offerings, Microsoft's own TCP/IP stack was an optional extra -- downloadable at no charge, but not installed by default until late editions of Windows 3.11 started shipping with the TCP/IP stack installed by default.

However, the all-out assault and their as good as claims to have invented the whole thing came only after a largely failed attempt at getting all Windows 95 users to sign up to the all-proprietary, closed-spec, dial-in Microsoft Network, which was in fact the first to use the name and the MSN abbreviation. The original Microsoft Network service did have some limited Internet connectivity; anecdotal evidence indicates that simple email transmissions to Internet users and back could take several days each way.

As luck or misfortune would have it, by the time Microsoft's Internet adventure started, several of their applications had been extended to include application macro programming languages which were pretty complete programming environments.

In retrospect we can confidently state that malware writers adapted more quickly to the changed circumstances than Microsoft did. The combination of network connectivity, powerful macro languages and applications which were network aware on one level but had not really incorporated any important security concepts and, of course, the sheer number of targets available proved quite impossible to resist.

The late 1990s and early 2000s saw a steady stream of network enabled malware on the Microsoft platform, sometimes with several new variants each day, and never more than a few weeks apart. A semi-random sampling of the more spectacular ones include Melissa, ILOVEYOU, Sobig, Code red, Slammer and others; some were quite destructive, while others were simply very efficient at spreading their payload.

They all exploited bugs and common misconfigurations much like the Morris worm had done a decade or more earlier. Greg Lehey's June 2000 notes on one of the more pervasive worms is still worth reading. (See Greg Lehey: Seen it all before?, Daemon's Advocate, The Daemon News ezine, June 2000 edition) The description is one of many indications that by 2000, malware writers had learned to mine the data in their victims' mail boxes and contact lists for useful data.

During the same few years, Microsoft's stance also developed somewhat. Their traditional response had been We do not have bugs, then moved gradually to releasing patches and 'hot fixes' at an ever increasing rate, and finally moving to a regime of a monthly “Patch Tuesday” in order introduce some predictability to their customers' workday.

Characteristics of modern malware

Back in the day, the malicious and destructive software got all the attention. From time to time a virus, worm or other malware would grab headlines for destroying people's systems, in one case even overwriting system BIOSes of a common variety of PCs. I have no real numbers to back this up, but one likely theory is that during the early years malware writers may have been mainly youthful pranksters and the odd academic, and getting attention may have been the main motivator.

In contrast, modern malware tries to take over your system without doing any damage a user or less attentive system administrator would notice. Typical malware today delivers its payload which then proceeds to take control of your computer - turning it into a zombie, usually to send spam, to infect other computers, or to perform any function the malware writer's customer needs to be done by remote control.

There is ample evidence that once machines are taken over, installed malware is likely to record users' keystrokes, mine the file systems for financial and identification data, and of course any sort of remote controlled network activity such as participation in attacks on specific networks. There is also anecdotal evidence to suggest that a significant subset of online casino players are in fact remote controlled game playing robots running on compromised computers.

Spam - the other annoyance

The first spam message sent is usually considered to be a message sent via ARPANET email in 1978, from a marketing representative at the Digital Equipment Corporation's Marlboro site. Acccording to much repeated anecdotes the message was sent to "every Arpanet address on the west coast" of the USA. (See Reflections on the 25th Anniversary of Spam, by Brad Templeton). The message announced a demo of the then new and exciting DEC20 line of computers and the TOPS-20 operating system, and like many of its successors showed signs of sender's incompetence - the list of intended recipients was longer than the mail application was able to accept, and the list overflowed into the message itself.

The message was well intended, but the reaction was overwhelmingly negative, and unsolicited commercial messages appear to have been close to non-existent, at least by modern standards, for quite a while after this particular incident.
The spam problem remained more or less a dormant, potential problem until the commercialization of the Internet started in the early 1990s. By then, email spam was still close to non-existent, but unsolicited commercial messages had started appearing on the USENET news discussion groups.

In 1994, there were several incidents involving messages posted to all news groups the originators were able to reach. The first incident, in January, involved a religious message, followed a few weeks later by message hawking the services of a US law firm. At the time this would have meant that several thousand unrelated discussion groups received the same message, crossposted or repeated.

The spam problem is sometimes cited as a major part of the reason why USENET declined in readership in favor of web forums, but in fact the USENET spam problem was largely solved within an impressively short time. Counter measures by USENET admins, including USENET Death Penalty (kicking a site off the USENET), cancelbots (automatic cancelling of articles which meet or exceed set criteria) and various semi-manual monitoring schemes were largely, if not totally effective in eliminating the spam problem.

However, with an increasing Internet user population, the number of email users grew faster than the number of USENET users, and spammers largely turned their attention back to email towards the end of the 1990s. As we mentioned earlier, mass mailed messages were found to be effective carriers of malware.

Spam: characteristics

The two main characteristics of spam messages have traditionally been summed up as: A typical spam run consists of a large number of identical messages, and the content of the messages tend to form recognizable patterns. In addition, we will be looking at some characteristics of spammer and malware writer behavior.

Into the wild: the problem and principles for solutions

The ugly truth

In order to understand how malware propagates, we need to recognize a few basic truths about people, programming and the code we produce and consume. Some groups, such as the OpenBSD project, has turned to code audits, motivated by what can be summed up as the following two clauses:
  1. All non-trivial software has bugs
  2. Some of these bugs are exploitable
Even though we all wish we were perfect and never made any mistakes, it is a fact of life that even highly intelligent, well educated, mentally balanced and well disciplined people do occasionally make mistakes.

The code audits, sometimes described as a process of reading the code like the Devil reads the Bible, concentrate on finding not only individual errors, but also recognizing patterns of the errors programmers make, and have turned up and eliminated whole classes of bugs in the source code audited.

For more information on the goals and methods of these code audits, see the OpenBSD Project's Security page and Damien Miller's AsiaBSDCon 2007 presentation, available from the OpenBSD project's Papers and presentations page.

The code audits also lead to the creation of a few exploit mitigation techniques, which are the subject of the next section.

Fighting back, on the system internals level

The code audits spearheaded by the OpenBSD project lead to the realization that even though we can become very good at eliminating bugs, we should always consider the possibility that we will not catch all bugs in time. We already know that some of the bugs in our code can be used or exploited to make the system do things we did not intend, so making it harder for a prospective attacker to exploit our bugs may be worthwhile. The OpenBSD project coined the term exploit mitigation for these techniques (The techniques described here are covered in far more detail in Theo de Raadt's OpenCON 2005 presentation Exploit Mitigation techniques, as well as the more recent Security Mitigation Techniques: An update after 10 years, also by Theo de Raadt.)

I will cover some of these techniqes briefly here:
  1. Stack smashing/random stack gap:
    In several types of buffer overflow bug exploits, the exploit depends critically on the fact that in most architectures, the stack and consequently the buffer under attack starts at a fixed position in memory. Introducing a random-sized gap at the top of the stack means that jumping to the fixed address the attackers 'know' contains their code kills a large subset of these attacks. The buggy program is likely to crash early and often.

  2. W^X: memory can be eXecutable XOR Writable
    Some bugs are possible to exploit because it is possible to have writable memory which is also executable. Implementing a sharp division involved some subtle surgery on how the binaries are constructed, with a slight performance hit. However, the performance was optimized back, and any attempts at writing to eXecutable memory will fail. Once again, buggy software fails early and often.

  3. Randomized mmap(), malloc()
    One of the more ambitious bits of work in progress is to introduce randomization in mmap() and malloc(). Like the other features we have touched on here, it has been eminently useful in exposing bugs. Flaws which just lead to random instabilities or odd behavior are much more likely to break horribly with randomized memory allocation.

  4. Privilege separation
    One classic problem which has proved eminently exploitable is that programs have tended to run effectively as root, with more privileges than they actually need once they've bound themselves to the reserved port. Some simple programs were easy to rewrite to drop privileges and execute their main task with only the privileges actually needed. Other, larger daemons such as sshd needed to be split into several processes, some running in chroot, some bits retaining privileges, others running at minimum privilege levels.
If it is not already obvious, one important effect of implementing these restrictions has been that these changes in the system environment has exposed bugs in a lot of software. For example, Mozilla's Firefox was for some time known to crash a lot more often on OpenBSD than almost anywhere else. However, the fixes for the exposed bugs tend to make it back into the various projects' main code bases.

Content scan

Virus scanners One of the first ideas security people hit upon when faced with files which could be carriers of something undesirable was to scan the files for specific kinds of content. Early content scanners were pure virus scanners which ran on MS-DOS and scanned local file systems for known bad content such as the byte sequences equal to known malware.

Over time as the number of known bad sequences grew, the technology to do hashed lookups was introduced. At present the total number of known types of malware is estimated to exceed 200,000 signatures. Makers of most malware scanning products issue updates on an as needed basis, recently this means that they might issue several signature updates per day.

Spam filters were at first close cousins to the bruteforce signature or substring lookup based virus packages. However, packages such as the freeware, Perl based SpamAssassin soon introduced rule based classification systems. The rule evaluation model SpamAssassin uses assigns weights to individual rules, allowing for site specific adjustments. Modern evaluation tools typically contain rules to evaluate both the message bodies and the message header information in order to determine the probability that a message is spam.

Another feature of modern filtering systems is that they are either built around or employ as optional modules various statistics based classification methods such as Bayesian logic, the Chi-Square method, Geometric and Markovian Discrimination. The statistics based methods are generally customized via training, based on a corpus of spam and legitimate mail collected by the site or user.

As the lists of signatures have grown to include an ever larger number of entries and have been supplemented with the more involved statistical calculations, content scanning has developed into one of the more resource intensive computations most of us will encounter.

The comedy of our errors: Content scanning measures and countermeasures


Even with such a formidable arsenal of tools at our disposal, it is important to keep in mind that all the methods we have mentioned have a nonzero error rate. Once you are done with setting up your filtering solution, you will find that care and feeding will include compensating for problems caused by various errors.

In a filtering context, our errors will fall into two categories, either false negatives or data which our system fails to recognize as undesirable even when it is, or false positives, where the system mistakenly classifies data as undesirable. Here is a sequence of events which illustrates some of the problems we face when we rely on content evaluation:

Keyword lookup: Matching on specific words which were known to be more common in unwanted messages than others was one of the early successes of spam filtering software. The other side soon hit on the obvious workaround - misspelling those keywords slightly, for a short time shrouding the message behind the likes of V1AGR4 or pr0n. Again the countermeasures were fairly obvious; soon all content filtering products included regular expression substring match code to identify variations on the key words.

Word frequency and similar statistics As the text analysis tools grew ever more accurate thanks to statistical analysis, the other side hit on the obvious countermeasure of including largish chunks of unrelated text in order to make the message appear as close as possible to ordinary communications to the content scanners. The text could be either semi-random strings of words or fragments of web accessible text, as illustrated by this example:

Spam message containing random text

Hidden in there is a very short sequence of characters which describes what they are trying to sell. At times we see messages which appear not to have any such payload, just the random text. It is not clear whether these messages are simply products of errors by inept spamware operators or, as some observers have speculated, if they are part of a larger scheme to distort the statistical basis for content scanners.

Text analysis vs graphics So it became rather obvious that we are getting rather good at scanning text, and the other side made their next move. shows an example of a stock scam, all text really, but promoted via an embedded graphic, along with a semi-random chunk of text grabbed from somewhere on the web:

This stock scam text is actually a picture
The text-as-picture messages spurred the development of optical character recognition (OCR) plugins for content scanning antispam tools, and a few weeks later text-as-picture spams started coming with distorted backgrounds, as seen in this example:

This could make you think they're selling flowers



All of these examples were taken from messages I have received, the last one in November 2006 when the various tools were not yet perfectly tuned to get rid of those specific nuisances. Newer SpamAssassin plugins such as FuzzyOcr are making good progress in identifying these variants, at the cost of some processing power.

Recent innovations in spam content obfuscation includes carrying as little content as possible such as a one-word subject line followed by a message body with at most half a dozen words in addition to a URL as well as the re-emergence of ASCII art, such as illustrated in here:

Spam with ASCII art

The figure displays the main message content. The main message as well as the web site URL are rendered as ASCII art, followed by apparently random text. The message came with enough spam characteristics that filtering system awarded this particular message a spamassassin score of 8.3, well into the 'likely but not definitely spam' range.

The sequence is certainly not unique, and we should probably expect to see similar mini arms races in the future. One obvious consequence of the ever-increasing complexity in content filtering is that mail handling, once a reasonably straightforward and undemanding activity, now requires serious number crunching capability. And it bears repeating that you should expect a non-zero error rate in content classification.

Behavioral methods

Up to this point we have looked at what we can achieve first by making any bugs in our operating system or applications harder to exploit, and next what can be done by studying the content of the messages once we've received them or while our mail transfer agent is processing the DATA part. From what we have seen so far, it is fairly obvious that the other side is trying to hide their tracks and avoid detection.

Spammers lie This shows even more clearly if we study their behavior on the network level. The often repeated phrase "Spammers lie, cheat and steal" at least to some extent proves to be rooted in reality when we study spam and malware traffic.

Forged headers Spammers may or may not be truthful when describing the wares they are promoting, but we can be more or less certain that they do their very best to hide their real identities and use other people's equipment and resources whenever possible. Studying the message headers in a typical spam message, we can expect to find several classes of forged headers, including but not limited to the Received:, From: and X-Mailer: headers. Perhaps more often than not, the apparent sender as taken from the From: header has no connection whatsoever to the actual sender.

Sender identification Some such discrepancies are easy to detect, such as when a message arrives from an IP address range radically different from the one you would expect when performing a reverse DNS lookup based on the stated sender domain. Traditional Internet standards do in fact not define a standard for determining whether a given host is a valid mail sender for a given domain.

However, by 2003 work started on extensions to the SMTP protocol incorporating checks for domain versus IP address mismatches. After a sometimes confusing process with attempts at formalizing workable standards, these ideas were formalized into two competing and somewhat incompatible methods, dubbed Sender Policy Framework (SPF) and Sender ID respectively, one championed by a group of independent engineers and researchers, the other originating at Microsoft.

The initial hope that the differences and incompatibilities would be resolved was further dashed in April 2006 when the two groups chose to formulate separate RFCs describing their experimental protocols (The relevant RFCs are RFC 4406 and RFC 4407 for the Microsoft method, which describe the Sender ID protocol and the Purported Responsible Address (PRA) algorithm it depends on respectively, and RFC 4408 for SPF.).

The world fortunately chose SPF and moved on to further work involving signing outgoing messages (DKIM) and finally the umbrella specification DMARC which builds on SPF and DKIM and adds its own wrapper, all to be stuffed into DNS TXT records for the sender domain. Expect more rants along these lines from here to follow.

Blacklists Once a message has been classified as spam, recording the IP address the message came from and adding the address to a list of known spam senders is a relatively straightforward operation. Such lists are commonly known as blacklists, which may in turn be used in blocking, tarpitting or filtering.

Greylisting Possibly as a consequence of their using other people's equipment for sending their unwanted traffic, spam and malware sender software needs to be relatively lightweight, and frequently the SMTP sending software does not interpret SMTP status codes correctly.

This can be used to our advantage, via a technique which became known as greylisting. Greylisting as a technique was presented in a 2003 paper by Evan Harris. The original Harris paper and a number of other useful articles and resources can be found at the greylisting.org web site. Even though Internet services are offered with no guarantees, usually described as 'best effort' services, a significant amount of effort has been put into making essential services such as SMTP email transmission fault tolerant, making the 'best effort' one with as close as does not matter to having a perfect record for delivering messages.

The current standard for Internet email transmission is defined in RFC5321, which in section 4.5.4.1, "Sending Strategy", states
"In a typical system, the program that composes a message has some method for requesting immediate attention for a new piece of outgoing mail, while mail that cannot be transmitted immediately MUST be queued and periodically retried by the sender."
and
"The sender MUST delay retrying a particular destination after one attempt has failed. In general, the retry interval SHOULD be at least 30 minutes; however, more sophisticated and variable strategies will be beneficial when the SMTP client can determine the reason for non-delivery."
RFC2821 goes on to state that
"Retries continue until the message is transmitted or the sender gives up; the give-up time generally needs to be at least 4-5 days."
(unfortunately retaining the vague language in the sections relevant to greylisting unchanged from earlier versions. This means that validity of the practice is still a matter of interpretation according to the updated RFC. The event was not widely reported, my own column on the subject is available at https://bsdly.blogspot.com/2008/10/ietf-failed-to-account-for-greylisting.html)

But the main points still stand: After all, delivering email is a collaborative, best effort thing, and the RFC states clearly that if the site you are trying to send mail to reports it can't receive anything at the moment, it is your DUTY (a MUST requirement) to try again later, after an interval which is long enough that your unfortunate communication partner has had a chance to clear up whatever was the problem.
 
The short version is, greylisting is the SMTP version of a white lie. When we claim to have a temporary local problem, the temporary local problem is really the equivalent of “my admin told me not to talk to strangers”. Well behaved senders with valid messages will come calling again later, but spammers have no interest in waiting around for the retry, since it would increase their cost of delivering the messages. This is the essence of why greylisting still works. And since it's really a matter of being slightly pedantic about following accepted standards, false positives are very rare.

Greytrapping The so far final advance in spam fighting is greytrapping, a technique pioneered by Bob Beck and the OpenBSD team as part of the spamd almost-but-not-quite SMTP daemon. This technique makes good use of the fact that the address lists spammers routinely claim are verified as valid, deliverable addresses are in fact anything but.

With a list of greytrap addresses which are not expected to receive valid mail, spamd adds IP addresses which try to deliver mail to the greytrap addresses to its local blacklist for 24 hours. Blacklisted addresses are then treated to the tarpit, where their SMTP dialog receives responses at a rate of one byte per second.
The intention, and to a large extent the actual effect, is to shift the load back to the sender, keeping them occupied with a very slow SMTP dialogue. We will return to this in a later section.


Combined methods and some common pitfalls

It is worth noting that products frequently use some combination of content scan and network behavior methods. For example, spamassassin incorporates rules which evaluate message header contents, using SPF data as a factor in determining a message's validity, while at the same time using locally generated bayesian token data to evaluate message contents.

We have already touched on the danger of false positives and the main downside of content filtering, and it is worth noting the possible downsides and pitfalls which come with the behavior based methods too.

The inner workings of proprietary tools are generally secret, but one particularly bizarre incident involving Microsoft's Exchange Hosted Services reveals at least some of the inner workings of that particular product. All available evidence indicates that their system treats substring match based on a phishing message to be a valid reason to block or “quarantine” messages from a domain, and that their data do not expire. The incident is chronicled by a still puzzled network administrator at this site.

Header mismatches While most simple header mismatch checks are reliable, the one important criticism of SPF and Sender ID is that the schemes are incompatible with several types of valid message forwarding, another that the problem of roaming users on dynamic IP adresses who still need to send mail has yet to be solved.

Blacklists The ways blacklists are generated, maintained and used are almost too numerous to list here. The main criticism and pitfalls lie in the way the lists are generated and maintained. Some lists have tended to include entire ISP networks' IP ranges as “know spam senders” in an attempt to force ISPs to cancel spammers' contracts. Another recurring complaint is that lists are less than actively maintained and may include out of date data. Both can lead to false positives and legitimate mail lost. Unfortunately, some popular blacklists have at times been abused and employed as instruments in personal vendettas. For those reasons, it always pays to check a list's maintenance policy and its reputation for accuracy before using a list as sufficent reason to reject mail.

Greylisting Even valid senders will experience a delay in delivery of the initial message. The length of the delay varies according to a number of factors, some of which are not under the greylister's control. A more serious issue is that some large sites do not necessarily perform the delivery retries from the same IP address as the one used for the initial attempt. A large enough pool of possible sending hosts and a sufficiently random retry pattern could lead to delivery timeout. Whitelisting the sites in question may be a temporary workaround, however with greylisting entering the mainstream it is expected that the problem of random redelivery will decrease and hopefully disappear entirely.

Greytrapping The only known risk of using greytrapping to date is that the backscatter of “message undeliverable” bounce messages resulting from spam messages sent with one of your trap addresses as apparent sender may cause mail servers configured to send nondelivery messages to enter your blacklist. 

This will cause loss or delayed delivery of valid mail if the backscattering mail server needs to deliver valid mail to your site. How often, if at all, this happens depends on several semi-random factors, including the configuration policies of the other sites' mail servers.

A working model

Where do we fit in?

Unix sysadmins find themselves in an inbetween position of sorts. We can never totally rule out that our systems are vulnerable, but malware which will actually manage to exploit a well run UNIX system is rarely seen in the wild, if at all.

A well run system means that best practice procedures are applied to system administration: we do not run unneccessary services, we install any security related updates, we enforce password policies and so on.

However, we more likely than not run services for users who run their main environment on vulnerable platforms. Malware for the vulnerable platforms more likely than not spreads via email, which is quite likely one of the services we handle.

We'll take a look at email handling, then move on to some productive uses of packet filtering (aka firewalls) later.

Setting up a mail server

Back when SMTP email was designed, the main emphasis was on making as sure as possible, without actually making hard guarantees, that mail would get delivered to the intended recipient. As we have seen, things get a little more complicated these days. The main steps to configuring the mail service itself are as follows:
  1. Choose your MTA
    BSDs generally come with sendmail as part of the base system. For our sites we have chosen to use exim for several reasons. Despite its human readable configuration files, it offers enormous flexibility, and on FreeBSD users will find that the package message offers a screenful of help to configure your mail service to do spam and malware filtering during message receipt.

    The main point is that your mail transfer agent needs to be able to cooperate with external programs for filtering. Most modern MTAs do; the other popular choices are postfix or sendmail, and in recent times, OpenSMTPd which is developed as part of the OpenBSD project, is showing great promise.

  2. Consider setting up your mailserver to do greylisting
    All the early greylisting implementations and several of the options in use today were written as optional modules for mail transfer agents. If, for example, you will not be using PF anywhere, using spamd (which we will be covering in more detail later) is not really an option, and you may want to go for and in-MTA option, such as a sendmail milter such as greylist-milter or a postfix policy server such as postgrey.

    In some environments, the initial delay in delivery of the first message may be undesirable or downright unacceptable; in such cases, the option of greylisting is unfortunately off the table.
    We feel your pain.


  3. Choose your malware scanner
    There are a number of malware scanners available, some free, some proprietary. The favorite seems to be the one we chose, clamav. clamav is GPL licensed and conveniently available through the package system on your favourite BSD.

    The product appears to be actively maintained with frequent updates of both the code itself and the malware signature database. Once it is installed and configured, clamav takes care of fetching the data it needs.

    Signature database update frequency appears to be on par with competing commercial and proprietary offerings.

  4. Choose your spam filtering

    Spam filtering is another well populated category in the BSD package systems. Several of the free offerings such as dspam and spamassassin are very complete filtering solutions, and with a little care it is even possible to combine several different systems in a sort of cooperative whole.

    We chose a slightly simpler approach and set up a configuration where messages are evaluated by spamassassin during message receipt. spamassassin is written mainly in perl, shepherded by a very active development team and is very flexible with all the customizability you could wish for.

Once all those bits have been configured and are running, any messages with malware in them are silently discarded with a log entry of the type

2007-04-08 23:39:17 1Haf6Q-000M6I-Cd => blackhole (DATA ACL discarded recipients): This message contains malware (Trojan.Small-1604)

Messages which do not contain known malware are handed off to spamassassin for evaluation. spamassassin evaluates each message according to its rule set, where each matching rule tallies up a number of points or fractions of points, and in our configuration, the very clear cases are discarded:

2007-04-08 02:39:35 1HaLRE-000Kq0-3P => blackhole (DATA ACL discarded recipients): Your message scored 116.0 Spamassassin points and will not be delivered.

The messages which are not discarded outright fall into two categories:

Clearly not spam A large number of rules are in play, and for various reasons valid messages may match one or several of the rules. We chose a definitely not spam limit which means that messages which accumulate 5 spamassasin points or less are passed with only a X-Spam-Score: header inserted.

The interval of reasonable doubt Messages which match a slightly larger number of rules are quite likely to be spam, but since they could still conceivably be valid, we change their Subject: header by prepending the string *****SPAM***** for easy filtering. The result ends up looking like the illustration below to the end user:

Likely spam message, tagged for filtering
Mainly for the administrator's benefit, a detailed report of which rules were matched and the resulting scores is included in the message headers.

Detailed spam scores for a likely spam message:


        Content analysis details:   (10.0 points, 5.0 required)
        pts rule name              description
        ---- ---------------------- --------------------------------------------------
        0.8 EXTRA_MPART_TYPE       Header has extraneous Content-type:...type= entry
        1.0 HTML_IMAGE_ONLY_28     BODY: HTML: images with 2400-2800 bytes of words
        0.0 HTML_MESSAGE           BODY: HTML included in message
        2.0 RCVD_IN_SORBS_DUL      RBL: SORBS: sent directly from dynamic IP address
        [62.31.124.248 listed in dnsbl.sorbs.net]
        1.3 RCVD_IN_BL_SPAMCOP_NET RBL: Received via a relay in bl.spamcop.net
        [Blocked - see <Mhttp://www.spamcop.net/bl.shtml?62.31.124.248>]
        3.1 RCVD_IN_XBL            RBL: Received via a relay in Spamhaus XBL
        [62.31.124.248 listed in sbl-xbl.spamhaus.org]
        1.7 RCVD_IN_NJABL_DUL      RBL: NJABL: dialup sender did non-local SMTP
        [62.31.124.248 listed in combined.njabl.org]
X-Spam-Flag: YES
Subject: *****SPAM***** conservatively enrichment

This means you have real data to work with for any fine tuning you need to do in your local customization files, and for valid senders who for some reason trigger too many spam characteristics, you may even whitelist using regular expression rules. Optional spamassassin plugins even offer the possibility of automated feedback to hashlist sites such as Razor, Pyzor and DCC - a few scripts will go a long way, and the spamassassin documentation is in fact quite usable.
Performing content scanning during message receipt means you run the risk of having mail delivery to your users stop if one of your content scanner services should happen to crash.

For that reason it can be argued that since content scanning, as opposed to greylisting, does not have to be performed during message receipt, it should be performed later. Server or end user processes can for example be set up to do filtering on user mail boxes, using tools such as procmail or even filtering features built into common mail clients such as Mozilla Thunderbird or Evolution.

Now of course all of this content scanning adds up to rather extensive calculations, well into what we until quite recently would have considered “serious number crunching”. The next section will present some recent advances which most likely will lighten the load on your mail handlers.


Giving spammers a harder time: spamd

The early days of pure blacklisting

As content filtering grew ever more expensive, several groups started looking into how to shift the burden from the recipient side back to the spammers. The OpenBSD project's spamd is one such effort which is inteded to integrate with OpenBSD's PF packet filter. Both PF and spamd have been ported to other BSDs, but here we will focus on how spamd works on OpenBSD in the present version.

The initial version of spamd was introduced in OpenBSD 3.3, released in May 2003. The basic idea was to have a basic tarpitting daemon which would produce extremely slow SMTP replies to hosts in a blacklist of known spammers. Known spammers would have their SMTP dialog dragged on for as long as possible, where the spamd at our end would serve its part of the SMTP dialog at a rate of one byte per second.

spamd was designed to operate independently, with no direct interactions with your real mail service. Instead, it integrates with any PF based packet filtering you have in place, and frequently runs on the packet filtering gateway. Typical packet filtering rules to set up the redirection to spamd looked something like this with the PF syntax of the time:


table <spamd> persist
table <spamd-white> persist
rdr pass on $ext_if inet proto tcp from <spamd> to { $ext_if, $int_if:network } \
            port smtp -> 127.0.0.1 port 8025
rdr pass on $ext_if inet proto tcp from !<spamd-white> to { $ext_if, $int_if:network } \
            port smtp -> 127.0.0.1 port 8025


Here the table definitions denote lists of addresses, <spamd> to store the blacklist, while the addresses in <spamd-white> are not redirected. (See eg this article -- also available untracked -- for a more recent configuration example - details of how spamd works has changed over the years).

Note: Since this was originally written, the uatraps list was unfortunately retired from service and is no longer available. See the update notes at the end of the article for some more information.

Blacklists and corresponding exceptions (whitelists) are defined in the spamd.conf configuration file, using a rather straightforward syntax:

all:\
:uatraps:whitelist:
uatraps:\
        :black:\
        :msg="SPAM. Your address %A has sent spam within the last 24 hours":\
        :method=http:\
        :file=www.openbsd.org/spamd/traplist.gz
whitelist:\
        :white:\
        :method=file:\
        :file=/etc/mail/whitelist.txt

Updates to the lists are handled via the spamd-setup program, run at intervals via cron.

spamd in pure blacklisting mode was apparently effective in wasting known spam senders' time, to the extent that logs started showing a sharp increase in the number of SMTP connections dropped during the first few seconds.

Introducing greylisting

Inspired by the early in-MTA greylisters (see the discussion of greylisting earlier), spamd was enhanced to include greylisting functions in OpenBSD 3.5, which was released in May 2004. The result was a further reduction in load on the content filtering mail handlers, and OpenBSD users and developers have found spamd's greylisting to be so effective that from OpenBSD 4.1 on, spamd greylists by default. Pure blacklisting mode is still available, but requires specific configuration options to be set.

A typical sequence of log entries in verbose logging mode illustrates what greylisting looks like in practice:

Oct  2 19:55:05 delilah spamd[26905]: (GREY) 83.23.213.115: 
<gilbert@keyholes.net> -> <wkitp98zpu.fsf@datadok.no> 
Oct  2 19:55:05 delilah spamd[26905]: 83.23.213.115: disconnected after 0 seconds.
Oct  2 19:55:05 delilah spamd[26905]: 83.23.213.115: connected (2/1)
Oct  2 19:55:06 delilah spamd[26905]: (GREY) 83.23.213.115: <gilbert@keyholes.net> -> 
<wkitp98zpu.fsf@datadok.no>
Oct  2 19:55:06 delilah spamd[26905]: 83.23.213.115: disconnected after 1 seconds.
Oct  2 19:57:07 delilah spamd[26905]: (BLACK) 65.210.185.131: 
<bounce-3C7E40A4B3@branch15.summer-bargainz.com> -> <adm@dataped.no>
Oct  2 19:58:50 delilah spamd[26905]: 65.210.185.131: From: Auto lnsurance Savings 
<noreply@branch15.summer-bargainz.com>
Oct  2 19:58:50 delilah spamd[26905]: 65.210.185.131: Subject: Start SAVlNG M0NEY on 
Auto lnsurance
Oct  2 19:58:50 delilah spamd[26905]: 65.210.185.131: To: adm@dataped.no
Oct  2 20:00:05 delilah spamd[26905]: 65.210.185.131: disconnected after 404 seconds. 
lists: spews1
Oct  2 20:03:48 delilah spamd[26905]: 222.240.6.118: connected (1/0)
Oct  2 20:03:48 delilah spamd[26905]: 222.240.6.118: disconnected after 0 seconds.

Here we see how hosts connect for 0 or more seconds to be greylisted, while the blacklisted host gets stuck for 404 seconds, which is roughly the time it takes to exchange the typical SMTP dialog one byte at the time up to the DATA part starts and the message is rejected back to the sender's queue. It is worth noting that spamd by default greets new correspondents one byte at the time for the first ten seconds before sending the full 451 temporary failure message.

The graph below is based on data from one of our greylisting spamd gateways, illustrating clearly that the vast number of connection attempts are dropped within the first ten seconds.

Number of SMTP Connections by connection length

The next peak, in the approximately 400 seconds range, represents blacklisted hosts which get stuck in the one byte at the time tarpit. The data in fact includes a wider range of connection lengths than what is covered here, however, the frequency of any connection length significantly longer than approximately 500 seconds is too low to graph usefully. The extremes include hosts which appear to have been stuck for several hours, with the outlier at 42,673 seconds, which is very close to a full 12 hours.

Effects of implementation: Protecting the expensive appliance

Users and administrators at sites which implement greylisting tend to agree that they get rid of most of their spam that way. However, real world data which show with any reasonable accuracy the size of the effect are very hard to come by. People tend to just move along, or maybe their frame of reference changes.

For that reason it was very refreshing to see a message with new data appear on the OpenBSD-misc mailing list on October 20, 2006 (See Steve Williams' October 20th, 2006 message to the OpenBSD-misc mailing list).

In that message, Steve Williams describes a setting where the company mail service runs on Microsoft Exchange, with the malware and spam filtering handled by a Mcafee Webshield appliance. During a typical day at the site, Williams states, "If we received 10,000 emails, our Webshield would have trapped over 20,000 spam" - roughly a two to one ratio in favor of unwanted messages. The appliance was however handling spam and malware with a high degree of accuracy.

That is, it was doing well until a new virus appeared, which the Webshield did not handle, and Williams' users was once again flooded with unwanted messages. Putting an OpenBSD machine with a purely greylisting spamd configuration in front of the Webshield appliance had dramatic effects.

Running overnight, the Webshield appliance had caught a total of 191 spam messages, all correctly classified. In addition, approximately 4,200 legitimate email messages had been processed, and the spamd maintained whitelist had reached a size of rougly 700 hosts.

By the metrics given at the start of Williams' message, he concludes that under normal circumstances, the unprotected appliance would have had to deal with approximately 9,000 spam or malware messages. In turn this means that the greylisting eliminated approximately 95% of the spam before it reached the content filtering appliance. This is in itself a telling indicator of the relative merits of enumerating badness versus behavior based detection.

spamdb and greytrapping

By the time the development cycle for OpenBSD 3.8 started during the first half of 2005, spamd users and developers had accumulated significant amounts of data and experience on spammer behaviour and spammer reactions to countermeasures.

We already know that spam senders rarely use a fully compliant SMTP implementation to send their messages. That's why greylisting works. Also, as we noted earlier, not only do spammers send large numbers of messages, they rarely check that the addresses they feed to their hijacked machines are actually deliverable. Combine these facts, and you see that if a greylisted machine tries to send a message to an invalid address in your domain, there is a significant probability that the message is a spam, or for that matter, malware.

Consequently, spamd had to learn greytrapping. Greytrapping as implemented in spamd puts offenders in a temporary blacklist, dubbed spamd-greytrap, for 24 hours. Twenty-four hours is short enough to not cause serious disruption of legitimate traffic, since real SMTP implementations will keep trying to deliver for a few days at least. Experience from large scale implementations of the technique shows that it rarely if ever produces false positives, and machines which continue spamming after 24 hours will make it back to the tarpit soon enough.

One prime example is Bob Beck's "ghosts of usenet postings past" based traplist, which rarely contains less than 20,000 entries. The reason we refer to it as a “traplist” is that the list is generated by greytrapping at the University of Alberta. At frequent intervals the content of the traplist is dumped to a file which is made available for download and can be used as a blacklist by other spamd users. The number of hosts varies widely and has been as high as almost 200,000.

The peak number of 198,289 entries was registered on Monday, February 25th 2008, at 18:00 CET.

The diagram here illustrates the number of hosts in the list over a period of a little more than two years.

Hosts in the uatraps list - active spam sending hosts

At the time this article was originally written (mid March, 2008), the list typically contained around 100,000 entries. While still officially in testing, the list was made publicly available on January 30th, 2006. The list has to my knowledge yet to produce any false positives and was available from http://www.openbsd.org/spamd/traplist.gz.

Note: Since this was originally written, the uatraps list was unfortunately retired from service and is no longer available. See the update notes at the end of the article for some more information.

 Setting up a local traplist to supplement your greylisting and other blacklists is very easy, and is straightforwardly described in the spamd and spamdb documentation.

Anecdotal evidence suggests that a limited number of obviously bogus addresses such as those which have already been seen in spamd's greylisting logs or picked from Unknown user messages in your mail server logs will make a measurable dent in the number of unwanted messages which still make it through.

Some limited ongoing experiments started in July 2007 (See the blog post http://bsdly.blogspot.com/2007/07/hey-spammer-heres-list-for-you.html and followups) indicate that publishing the list of greytrap addresses on the web has interesting effects. After a spike in undeliverable bounce messages to non-existent addresses, we began adding backscatter addresses in our own domains to the local greytrap list and publishing the greytrap addresses on a web page that was referenced with a moderately visible link on the target domains' home pages.

The greytrap list quickly grew to several thousand entries (The list, with some accompanying explanation, is maintained at bsdly.net, fed by what appears to be several different address generating operations with slighly different algorithms and patterns). See the field notes at http://bsdly.blogspot.com/2007/11/i-must-be-living-in-parallel-universe.html for some samples. Addresses would typically start to appear in our greylist dumps (and occasionally in mail server logs) as intended recipients for messages with From: addresses other than <> within days of being added to the published list.

The net effect of a sizeable list of published greytrap addresses is both a higher probability of detecting spam senders early and further worsening spammers' effective hit rate by lowering the quality of their address lists.

Incremental spamd improvements

One of the main overall characteristics of the changes implemented in the most recent OpenBSD release is that they tend to be what users and developers see as sensible, best practice compliant defaults.

Typical of the sensible defaults theme is the decision to have spamd run in greylisting mode by default. This change was implemented in OpenBSD 4.1, released May 1st, 2007.

Sites with several mail exchangers and corresponding spamd instances will appreciate the synchronization feature for greylisting databases between hosts, also an OpenBSD 4.1 improvement.

Sites and domains with several mail exhangers with different priorities have seen that spammers frequently attempt to deliver to secondary mail exchangers first. As a consequence, the greytrapping feature was extended to detect and act on such out of order mail exchanger use.

Conclusion

The main conclusions are that the free tools work, and that by using them intelligently you can actually make a difference.

If our goal is to achieve relative peace and quiet in our own networks so we get our real work done, there are real advantages in stopping undesirable traffic as early as possible, and stopping most of it at the perimeter is actually doable.

All the tools we have studied are open source. The open source model, which is closely related to the peer review style of development seen in academic research, produces effective, high quality tools which truly make your life easier. The often repeated argument that development in the open would make it easier for the other side to develop countermeasures does not match our experience. If anything we see that development in the open means that ideas get exposed to real world conditions quickly, exposing the less robust approaches in ways that closed development is apparently unable to match.

The data I presented earlier as graphs seem to indicate that our efforts have some effect. There appears to be a trend which has the number of greytrapped hosts seemingly stabilize at a higher level over time. This could be taken as an indicator that the number of compromised machines is rising, but could equally well be interpreted to mean that spammers and malware senders need to try harder now that effective countermeasures are becoming more widely deployed.

By studying our adversaries' behavior patterns we have trapped them, and we may just be starting to win.

Resources

  1. Slides for this talk
  2. Nicholas Weaver, Vern Paxson, Stuart Staniford and Robert Cunningham: A Taxonomy of Computer Worms
  3. Marcus Ranum: The Six Dumbest Ideas in Computer Security, September 1, 2005
  4. Greg Lehey: Seen it all before?, Daemon's Advocate, The Daemon News ezine, June 2000 edition
  5. Brad Templeton: Reflections on the 25th Anniversary of Spam
  6. The Morris Worm 18th anniversary site
  7. Sender Policy Framework
  8. Theo de Raadt: Exploit mitigation techniques and the update,  Security Mitigation Techniques: An update after 10 years
  9. Peter N. M. Hansteen: Firewalling with PF tutorial
    Now largely superseded by Network Management with the OpenBSD Packet Filter toolset, by Peter N. M. Hansteen, Massimiliano Stucchi and Tom Smyth (A PF tutorial, this is the BSDCan 2024 edition). An earlier, even more extensive set of slides can be found in the 2016-vintage PF tutorial.
  10. Peter N. M. Hansteen: The Book of PF, No Starch Press 2026 (first edition 2007, second edition 2010, third edition 2014)
  11. Peter N. M. Hansteen: That Grumpy BSD Guy, blog posts (prettified, tracked). New entries as well as still-relevant pieces that started out over there and have warranted updating will also be findable, untracked other than my webserver log, at https://nxdomain.no/~peter/blogposts/. Please let me know if there are pieces you think would warrant liberation to that space.
  12. Bob Beck: PF, it is not just for firewalls anymore and OpenBSD spamd - greylisting and beyond
  13. Barbie: Understanding Malware
If you enjoyed this article, please consider buying OpenBSD merchandise or donating to the project either directly or via the OpenBSD Foundation.




Update 2016-12-13: A discussion on the OpenBSD-misc mailing list lead me to review this article, and I found a couple of points I would like to add:

The uatraps greytrapping-based blacklist was unfortunately retired from service in May 2016 and is no longer available. My own bsdly list, which is another greytrapping-generated list stabilized at a slightly higher number of entries after uatraps dispappeared, and for that reason I chose to replace the uatraps reference with that one in a common example. Other good sources of information is the example spamd.conf in your /etc/mail directory if you're running OpenBSD. And if you want to explore a useful, if slightly unusual way to use routing protocols, take a look at Peter Hessler's BGP-spamd initiative.

The OpenBSD-misc discussion also touched on expected connection lengths for the SMTP traffic spamd captures, and I realized I could possibly shed some further light on the issue. The graph earlier in the article was based on logs covering approximately 1 million connections.

Even with slightly different log rotation settings between them, the still existing logs on the three gateways described in the Voicemail Scammers piece between them contained data on some 8,145,183 connections, graphed below.

 

That is, like I did with the earlier graph I chose to limit the data to the 0 to 1,000 seconds interval. The general pattern seems to be unchanged: The vast majority of the connections drop during the first few seconds, but the data includes some outliers, all the way out to the one that hung on for a whole 63423 seconds (17 hours, 37 minutes and 3 seconds). Which of course makes the full data impossible to graph.

Click on the image to get the raw size, and if you like you can download the spreadsheet or the CSV version. The full data runs into the gigabytes, but if you want to take a peek for research purposes, please contact me via the various conventional means. 

Update 2016-12-14: Added a paragraph mentioning DKIM and DMARC, which were either preliminary specifications or not yet thought up at the time this was originally written.

Sunday, December 22, 2013

The UK "Porn" Filter Blocks Kids' Access To Tech, Civil Liberties Websites

It fell to the UK Tories to actually implement the Nanny State. Too bad Nanny Tory does not want kinds to read up on tech web sites, or civil liberties ones. Read on for a small sample of what the filter blocks, from a blocked-by-default tech writer.

[Updated 2x, scroll down]

Regular readers (at least those of you who also follow me on twitter) will know that I'm more than a little skeptical of censorship in general. And you may have seen, as evidenced by this tweet that I found the decision to implement a nationwide, on-by-default-but-possible-to-opt-out-of web filtering scheme in the UK to be a seriously stupid idea.

But then I was never very likely to become a UK resident or anything more than a very temporary customer of any UK ISP during visits to the country, so I did not give the matter another thought until today, when this tweet announced that you could indeed check whether your web site was blocked. The tweet points you to http://urlchecker.o2.co.uk/urlcheck.aspx, which appears to be a checking engine for UK ISP O2, which is among the ISPs to implement the blocking regime.

I used that URL checker to find the blocking status of various sites where I'm either part or the content-generating team or sites that I find interesting enough to visit every now and then. The sites appear in the semi-random order that I visited them on December 22, 2013, starting a little after 16:00 CET:

bsdly.net: I checked my own personal web site first, www.bsdly.net. I was a bit surprised to find that it was blocked in the default Parental control regime. Users of the archive.org Internet Wayback Machine may be able to find one page that contained a reference to a picture of "a blonde chick with a cute pussy", but the intrepid searcher will find that the picture in question in fact was of juvenile poultry and felines, respectively. The site is mainly tech content, with some resources such as the hourly updated list of greytrapped spam senders (see eg this blog post for some explanation of that list and its purpose).

nuug.no: Next up I tried the national Norwegian Unix Users' group web site www.nuug.no, with a somewhat odd result - "The URL has not yet been classified. If you would like it to be classified please press Reclassify URL". There was no Reclassify URL option visible in the web interface, but I would assume that in a default to block regime, the site would be blocked anyway. It would be nice to have confirmation of this from actual O2 customers or other people in the UK.

But NUUG hosts a few specific items I care about, such as my NUUG home page with links to slides from my talks and other resources I've produced over the years. Entering http://home.nuug.no and http://home.nuug.no/~peter/pf/ (the path to my PF tutorial material) both produced an "Invalid URL" message. This looks like bug in the URL checker code, but once again it would be nice to have confirmation from persons who are UK residents and/or O2 customers about the blocking status for those URLs.

usenix.org:Next I tried www.usenix.org, the main site for USENIX, the US-based but actually quite international Unix user group. This also turned out to be apparently blocked in the Parental control regime.

ukuug.org and flossuk.org: But if you're a UK resident, your first port of call for finding out about Unix-like systems is likely to be UK Unix User Group instead, so I checked both www.ukuug.org and flossuk.org, and both showed up as blocked in the Parental control regime (ukuug.org, flossuk.org).

So it appears that it's the official line that kids under 12 in the UK should not be taught about free or open source software, according to the default filtering settings.

eff.org: You will have guessed by now that I'm a civil liberties man, so the next site URL I tried was www.eff.org, which was also blocked by the Parental Control regime. So UK kids need protection from learning about civil liberties and privacy online.

amnesty.org.uk: A little closer to home for UK kids, I thought perhaps a thoroughly benign organization such as Amnesty International would somehow be pre-approved. But no go: I tried the UK web site, amnesty.org.uk, and it, to was blocked by the Parental Control regime. UK kids apparently need to be shielded from the sly propaganda of an organization that has worked, among other things for releasing political prisoners and against cruel and unusual punishment such as the death penalty everywhere.

slashdot.org: Next up in my quasi-random sequence was the tech new site slashdot.org, which may at times be informal in tone, but still so popular that I was somewhat surprised to find that it, too was blocked by the Parental Control regime.

linuxtoday.com: Another popular tech news site is linuxtoday.com, with, as the name says, has a free and open source software slant. Like slashdot, this one was also blocked by the Parental Control regime.

bsdly.blogspot.com: Circling back to my own turf, I decided to check the site where I publish the most often, bsdly.blogspot.com. By this time I wasn't terribly surprised to find that my writing too has fallen afould of something or other and is by default blocked by the Parental Control regime.

nostarch.com: Blocking an individual writer most people probably haven't heard about in a default to block regime isn't very surprising, but would they not at least pre-approve well known publishers? I tried nostarch.com (home of among others a series of LEGO-themed tech/science books for kids as well as Manga guides to various sciences, as well as various BSD and Linux books). No matter, they too were blocked by the Parental Control regime.

blogspot.com: Along the same lines as in the nostarch.com case, if they default to block they may well have an unknown scribe blocked, but would they block an entire blogging site's domain? So I tried blogspot.com. The result is that it's apparently registered that the site has "dynamic content" so even the "default safety" settings may end up blocking. But of course, another one that's blocked by the Parental Control regime.

arstechnica.com: I still couldn't see any clear logic besides a probable default to block, so I tried another popular tech news site, arstechnica.com. I was a bit annoyed, but not too surprised that this too was blocked by the Parental Control regime.

The last four I tried mainly to get confirmation of what I already suspected:

www.openbsd.org: What could possibly be offensive or subversive about the most secure free operating system's website? I don't know, but the site is apparently too risky for minors, blocked by the Parental Control regime as it is.

undeadly.org: The site undeadly.org is possibly marginally better known under the name OpenBSD Journal. It exists to collect and publish news relevant to the OpenBSD operating system, its developers and users. For Nanny only knows what reason, this site was also blocked by the Parental Control regime.

www.freebsd.org: www.freebsd.org is the home site of FreeBSD, another fairly popular free BSD operating system (which among others Apple has found useful as a source of code that works better in a public maintenance regime). I thought perhaps the incrementally larger community size would have put this site on Nanny's horizon, but apparently not: FreeBSD.org remains blocked by the Parental Control regime.

www.geekculture.com: How about a little geek humor, then? www.geekculture.com is home to several web comics, and The Joy of Tech remains a favorite, even with the marked Apple slant. But apparently that too, is too much for the children of the United Kingdom: Geekculture.com is blocked by the Parental Control regime.

www.linux.com: And finally, the penguins: By now it should not surprise anyone that www.linux.com, a common starting point for anyone looking for information about that operating system, like the others is blocked by the Parental Control regime.

So summing up, checking a semi-random collection of mainly fairly mainstream and some rather obscure tech URLs shows that far from focusing on its stated main objective, keeping innocent children away from online porn, the UK Internet filter shuts the UK's children out of a number of valuable IT resources, was well as several important civil liberties resources.

And if this is the true face of Parental Controls, I for one would take using controls like these as a sufficient indicator that the parents in question are in fact not qualified to do their parenting without proper supervision.

If this is an indicator of how the collective of United Kingdom Internet Nannies is to maintain their filtering regime, they are most certainly part of a bigger problem than the one they claim to be working to solve.


If you are a UK resident or other victim of automated censorship, I would like to hear from you. Please submit your story in comments or send me an email at blockage@bsdly.net Unfortunately only a small number of useful responses turned up, immediately after the article was published. Please do not try contacting me via that address, please use other easily available methods. On 2019-01-24, I decided it had earned its place among the spamtraps.



Update 2013-12-23 13:05 CET: A reader alerted me to the fact that the URL Checker is down, and that URL now leads to a page that claims the operators are "in the process of reviewing and updating" their offerings.

Update 2013-12-24 19:30 CET: O2 contacted me via twitter direct message, pointing me to their FAQ at http://news.o2.co.uk/2013/12/24/parental-control-questions-answered/. As non-responsive responses go, it was fairly useful, if not entirely constructive. The most useful bit of information is possibly that the service as presented is apparently specific to O2 customers, not the frequently cited national, Tory-backed regime.

As the FAQ document clearly demonstrates, the underlying problem is that some of their customers, for whatever reason, have chosen to leave the monitoring and mentoring of their children's reading to an automated service.

The world contains a multitude of dangers, and most of us, in the UK or elsewhere, would agree that it is a parent's duty both to protect their offspring and to educate them in how to avoid danger or handle problems they encounter.


Ignorance has yet to help anyone solve a problem

There are several ways to protect and educate, and I feel that the approach offered by O2's service is the wrong approach in several important ways. First off, by limiting children's access to information, it strongly recommends choosing ignorance instead of education as the main defense against the perceived evils of the world.

If a person would advise that you chain your children to the wall and burn their library cards, you as a responsible parent would perhaps be reluctant to accept that advice as valid. But O2 has no qualms about offering a commercial service that does just that, only via digital means.

But the engineer in me also compels me to point out that the "Parental Control" is designed only to attack a specific symptom of a wider problem, and it fails to address that problem. And making matters slightly worse, the proposed solution is to apply a technical solution to a human or perhaps social problem.

The real problem is that some number of parents do not feel up to the task of mentoring and educating their children in safe and sensible use of their gadgets and the information that is accessible through the gadgets. Parents failing, or perceiving that they may be failing, to adequately educate or mentor their children is the real problem here. Fix that problem, and your symptoms go away.

If a significant subset of O2's customers feel they are unable to handle their parenting duties, the problem may very well be that society is failing to adequately support parents' needs during their child-rearing years.

The solution may well be political, and may very well involve matters that are best resolved by making a proper choice at the ballot box after well reasoned debates. In the meantime, O2 is only making matters worse by answering the needs of persons who feel the symptoms of the deeper problem by catering to a perhaps understandable, but in fact utterly counterproductive, drive for ignorance.

Ignorance never helped anybody solve a problem. Children need to be nurtured, educated, mentored and stimulated to explore. Please do not force them into ignorance instead.

Monday, December 16, 2013

Three Books You Too Should Read This Year (Or Early 2014)

For the holiday season, The Grumpy Reader fishes out a selecton of recent books you should read even if you think you're too busy.

I'm sure you've had that feeling too: There are times when there's too much coming your way when you're already busy, so some things just fall by the wayside for too long. In my case the victims of my unpredictable schedule were books that publishers sent me for review in one form or the other, and those reviews just never got written as I wanted to in between other projects that were likely less interesting to the public at large.

But enough about me, here by way of making up for not getting around to this before are my slightly compressed thoughts about some important books released this year, just in time for your holiday shopping:


The Practice of Network Security Monitoring: The Best Surveillance Book You'll Read Anytime Soon

When I first heard that Richard Beijtlich was working on a No Starch Press title quite some months back, I immediately told my contacts at No Starch that I'd love to have a review copy, the sooner the better.

If Richard's name does not ring a bell, you may not have followed Internet security writing too closely and you could do worse than head over to Richard's blog at Tao Security and browse his online articles. In addition to prolific blogging and consulting activities, he is also the author of several highly acclaimed books in the field, and every now and then it's possible to sign up for his classes (see the blog reference for links).

The Practice of Network Security Monitoring is one of those books that I've very much enjoyed reading, but also one that for various reasons I found surprisingly difficult to review in a way that I feel does the book and its author justice.

It reads well. Richard spends enough time on basic concepts of network security monitoring early that the novice will be encouraged to go on, and once the basic concepts are laid out, the text alternates nicely between short expositions of theory and follow-on hands on sections that offer enough detail that the techies will have enough pointers to start exploring further but are hopefully not extensive enough to scare off those readers who really want most of all to follow the logic of the may sub-activities in the network security monitoring field.

It offers a lot of useful information in a reasonably compact format. But interesting and useful in this context on a technical level also means that you, dear reader, may be entering an area with a large set of legal pitfalls.

The network security monitoring system described in The Practice of Network Security Monitoring (all of it free software, fortunately) is designed to capture and store all network traffic passing through designated interfaces. That certainly has its uses, and the book offers a few delightful examples of analysis, including one scenario that reconstructs the exact sequence of events in a targeted malware attack.

But the level of detail recorded by these tools, including the content of all traffic, comes with a big warning: While the details will vary from jurisdiction to jurisdiction, setting up and using the tools as described here outside of a strictly controlled lab environment for pure research purposes is likely to be unconditionally illegal or at least require you to obtain specific permission from the relevant authorities or to be a member of a government that has already acquired a specific warrant.

The fact that the book was published at more or less the same time the various revelations about NSA's surveillance activities became public may have helped it sales, but the somewhat charged atmosphere those revelations created also made it a little harder to write this review. The trickle of leaked documents looks set to go on for a while more, but I feel rather confident that The Practice of Network Security Monitoring is likely to be the best technical book about surveillance you read this year or the next.

The Practice of Network Security Monitoring: Understanding Incident Detection and Response by Richard Bejtlich, No Starch Press, July 2013, 376 pp. ISBN: 978-1-59327-509-9. Available Here and at better bookstores.


Sudo Mastery: You're Doing It Wrong, But Not For Want Of Trying

If you're a system administrator or a user of Unix-like systems, you're likely to at least know about the sudo command, which lets ordinary users execute commands with other than usual permissions and privileges. But it's a program that comes with its own set of quasi-mythological misunderstandings.

In fact, as this book aptly demonstrates, most people who use sudo on a daily basis more likely than not are doing it wrong. Contrary to common belief, sudo is not actually 'the program that gets you root access'.

There were no good books about sudo around, so Michael W. Lucas set out to write one as part of his Mastery series (I've covered some of the titles in the series before, see my reviews of SSH Mastery and DNSSEC Mastery).

Like the other titles in the series, Sudo Mastery is a compact book (the PDF version comes to 135) that focuses on an important tool in the sysadmin's toolbox. It's clearly written for a sysadmin audience, but Michael does walk the reader through the basics of the Unix users, groups and permissions based security model and discusses some of its problems before he dives into how to make sudo do its best for you.

The book's subtitle is User Access Control for Real People, and this thinking shows through clearly in the text. Sudo Mastery is written with the working sysadmin in mind, and at most times the description of a new feature comes with an anecdote that clearly stems from practical experience.

At the end of the book, you will have been exposed to the bulk of sudo's features, and you will have learned how to construct your own access system that for all practical purposes, Role Based Access Control system. Or, at the very least, a system that will be more logical and maintainable than what you started with, and one that is far superior the binary root/not root game sysadmins and their users play all too often.

Like anything else Michael has written, this comes highly recommended. You can get your copy of Sudo Mastery directly from Tilted Windmill press here or through good bookstores.

Sudo Mastery: User Access Control for Real People, Tilted Windmill Press, November 2013 ISBN-10: 1493626205 ISBN-13: 978-1493626205


Absolute OpenBSD, 2nd, edition: The Book About My Favorite Operating System

Regular readers will know that I have a favorite operating system, and it's called OpenBSD. Until April of this year, the most recent widely known book about OpenBSD was Michael W. Lucas' 2003 title Absolute OpenBSD. Then, finally, the much refreshed Absolute OpenBSD, 2nd edition was published.

I was close enough to the project myself as that book's technical editor that I was a little shy about writing much about the title myself when it came out, but after not looking at it for some months I can say that the result is definitely worth your time.

I even think that it would be a good idea to hand this book and an OpenBSD CD set to students as their first Unix. OpenBSD is a lot more compact and logically structured than a lot of the competition, and with Michael's 2nd edition to supplement the included man pages and FAQ, there's even a chance they will learn to expect that the system defaults are set to sane values and that there is a perfectly logical reason for everything your system does.

Absolute OpenBSD, 2nd Edition: Unix for the Practical Paranoid by Michael W. Lucas No Starch Press, April 2013, 536 pp. ISBN: 978-1-59327-476-4. Available from the publisher here and through good bookstores.

If you still haven't done your geek holiday shopping, these are my season's recommendations. Even if you read this some time past the holidays, all of these titles will be valuable additions to the actively used parts of your tech library.

Monday, November 11, 2013

Compatibility Is Hard: CHARTEST.DOC Is From 1989, Was Not Readable By 2003

A late 1980s ASCII table printer test, recently exhumed, reveals the perils and pitfalls of naive belief in document format compatibility.

Most documents, I am frequently told, are trivial things of two pages or less and with an expected useful lifetime measured in weeks or less. That may be true in some cases, but I've been a writer of some kind for long enough to care about keeping information available and editable.

The stuff I write tends to live on for years in some form, and tends to require revision at intervals that are just long enough that it's likely I've forgotten the exact details since last time I went over that particular text. If you're only a tiny bit like me, you'll be nodding intensely at those observations.

Note: This piece is also available without trackers but classic formatting only here.

And of course as a technical writer, I've had enough exposure to Microsoft Word that I concur emphatically with essentially all that Charlie Stross wrote in his recent blog post, Why Microsoft Word must Die.

Immediately after reading Charlie's post, I added some thoughts of my own in the comments. Do read the comments or at least skim some, there are some gems there. Including some comments from people who were apparently involved in developing Microsoft Word over the years. One of those commenters makes the claim that you can reliably read in current Word versions any files you may have created with earlier versions.

Reading that, I remembered an episode about ten years ago when Gisle Hannemyr asked for help on a mailing list we both subscribed to, for problems some ex-colleagues of his had accessing documentation of approximately 1998-1999 vintage.

The files had been created using whatever version of Microsoft Word was current at the time, but whatever version was current in 2003 was apparently either refusing to load the files or rendering them as complete gibberish. If I remember correctly, the problem was eventually solved by getting hold of a roughly same-vintage machine with an old Word version, loading the files and saving as RTF. That way, you would stand a fighting chance of preserving your work across versions (I've ranted about related matters earlier, read at your own peril).

At the time, I had several old versions of Word stashed away, including a possibly illicit copy of Word 5.0 for MS-DOS that I remembered keeping. I offered to help Gisle's colleagues of course, but as I remember they found a way to read their data without my help.

Anyway, when I looked in the program directory I must by then have copied across about a sequence of possibly a dozen different machines, there was also a copy of an extremely simple print test document, called CHARTEST.DOC. Do not click on that link unless you also have a copy of Microsoft Word for DOS around. It will be gibberish except for the sequence that represents an ASCII table.

Why this was interesting is probably better illustrated by the screen dump I made of the directory listing:



The document's time stamp, April 27, 1989, reminded me of a quick solution to an everyday need we had back then.

If you're old enough to remember MS-DOS code pages, you will understand why I found it necessary to generate an ASCII table for a print test.

The place I worked then was in the business of producing Norwegian and other Scandinavian language versions of software and related documentation. This was MS-DOS 3.something and Microsoft Windows 2.something era, when documentation came mainly in printed form, and to produce our camera-ready copy, we needed to make really sure that the machine was properly configured to make the Apple LaserWriter attached to its serial port produce copy that included the two characters IBM famously forgot when they created the initial IBM PC character set ('ø' and the uppercase version, 'Ø', which would otherwise appear on the printed page as cent and yen signs, respectively).

There were other characters we needed to see as well, some of them accessible in Word only by pressing and holding the Alt key while tapping a three-digit sequence on the numeric keypad.

My solution to the problem at hand was to generate a print sample of all printable ASCII characters, using a Turbo Pascal program that likely read something like this:

program chartest;

var
   outfile  : file;
   c        : byte;

begin
  outfile := "chartest.txt"
  for c := 0 to 255 do begin
     if isprint(c) then
        writeln(c, " = " chr(c), );
     end;
end;

It's been almost that long (1989-ish) since I wrote any Turbo Pascal code, and like the other software I'm writing about in this article, I no longer have access to a copy, so there may well be syntax errors in that, but you will get the general idea.

My next step was to load the resulting file into Word, saving as Word's .DOC format, and we used that as a test print before any important Scandinavian-language document was to be printed. The program itself (likely called CHARTEST.PAS and possibly saved somewhere in the Turbo Pascal directory tree on my machine, or more likely too trivial to merit even saving once it had produced the output we wanted), does not survive. Neither does CHARTEST.TXT, but the .DOC file survives because I found it so useful I copied it to the Word program directory.

Then when Gisle's request came, and I still had a machine somewhere that had Microsoft Word 2000 on it, which was unable to read the file correctly, as the first screenshot shows:


(You can get the raw version from here)

My offer then to help convert probably means I still had other historical versions available at the time, but none of them survive in my archives today. (I left the company in 2008 after selling off my founder's share and was very careful to keep only what I had a clear right to keep).

The PDF file shows expected printer output as I prepared it back then, generated from the PostScript file which I assume is closer to the original date.

Compare the screenshots in the "winword" sequence, winword1.jpg, winword2.jpg, winword3.jpg, winword4.jpg, winword5.jpg, winword6.jpg with what the document looked like in the DOS version, wordscreen1.jpg, wordscreen2.jpg, wordscreen3.jpg, wordscreen4.jpg, wordscreen5.jpg and finally wordscreen6.jpg. You can find a particularly puzzling screenshot chartest-after-convpack.jpg here, with both programs showing an overlapping sequence, or you can grab all the files from here if you like.

The question that lingers in my mind is, when a simple character set table is not an obvious conversion, and a relatively close successor version was clearly unable to read the original file correctly, what other possibly content-deforming incompatibilites will come back to bite us when we need to go back to earlier material?

To my mind, flatly denying the problem like the commenters over at Charlie's blog purporting to be Microsoft insiders do will simply not do.

I invite your comments.


You might also be interested in reading selected pieces via That Grumpy BSD Guy: A Short Reading List (also here).

Saturday, October 5, 2013

The Hail Mary Cloud And The Lessons Learned

Against ridiculous odds and even after gaining some media focus, the botnet dubbed The Hail Mary Cloud apparently succeeded in staying under the radar and kept compromising Linux machines for several years. This article, based on my BSDCan 2013 talk, sums up known facts about the botnet and suggests some common-sense measures to be taken going forward.

The Hail Mary Cloud was a widely distributed, low intensity password guessing botnet that targeted Secure Shell (ssh) servers on the public Internet.

Note: This piece is also available without trackers but more basic formatting here.

The first activity may have been as early as 2007, but our first recorded data start in late 2008. Links to full data and extracts are included in this article.

We present the basic behavior and algorithms, and point to possible policies for staying safe(r) from similar present or future attacks.

But first, a few words about the devil we knew before the incidents that form the core of the narrative.

The Traditional SSH Bruteforce Attack

If you run an Internet-facing SSH service, you have seen something like this in your logs:

Sep 26 03:12:34 skapet sshd[25771]: Failed password for root from 200.72.41.31 port 40992 ssh2
Sep 26 03:12:34 skapet sshd[5279]: Failed password for root from 200.72.41.31 port 40992 ssh2
Sep 26 03:12:35 skapet sshd[5279]: Received disconnect from 200.72.41.31: 11: Bye Bye
Sep 26 03:12:44 skapet sshd[29635]: Invalid user admin from 200.72.41.31
Sep 26 03:12:44 skapet sshd[24703]: input_userauth_request: invalid user admin
Sep 26 03:12:44 skapet sshd[24703]: Failed password for invalid user admin from 200.72.41.31 port 41484 ssh2
Sep 26 03:12:44 skapet sshd[29635]: Failed password for invalid user admin from 200.72.41.31 port 41484 ssh2
Sep 26 03:12:45 skapet sshd[24703]: Connection closed by 200.72.41.31
Sep 26 03:13:10 skapet sshd[11459]: Failed password for root from 200.72.41.31 port 43344 ssh2


This is the classic, rapid-fire type of bruteforce attack, with rapid-fire login attempts from one source. (And yes, skapet is the Internet-facing host on my home network.)

The Likely Business Plan

These attempts are often preceded by a port scan, but in other cases it appears that the miscreants are just blasting away at random. In my experience, with the gateway usually at the lowest-numbered address, the activity usually turns up first there, before trying higher-numbered hosts. I'm not really in a mind to offer help or advice to the people running those scripts, but it might be possible to scan the internet from 255.255.255.255 downwards next time. Anyway, looking at the log excerpts, miscreants' likely plan is

  1. Try for likely user names, hope for guessable password, keep guessing until successful.
  2. PROFIT!
But then the attempts usually come in faster than most of us can type, so with a little help from toolmakers, we came up with an inexpensive first line of defense, easily implemented in perimeter packet filters (aka firewalls).

Traditional Anti-Bruteforce Rules

Rapid-fire bruteforce attacks are easy to head off. I tend to use OpenBSD on internet facing hosts, so first we present the technique as it has been available in OpenBSD since version 3.5 (released in 2005), where state tracking options are used to set limits we later act on:

In your /etc/pf.conf, you add a table to store addresses, block access for all traffic coming from members of that table, and finally amend your typical pass rule with some state tracking options. The result looks something like this:

table <bruteforce> persist
block quick from <bruteforce>
pass inet proto tcp to $int_if:network port $tcp_services \
        keep state (max-src-conn 100, max-src-conn-rate 15/5, \
         overload <bruteforce> flush global)

Here, max-src-conn is the maximum number of concurrent connections allowed from one host

max-src-conn-rate is the maximum allowed rate of new connections, here 15 connections per 5 seconds.

overload <bruteforce> means that any hosts that exceed either of these limits are have their adress added to this table

and, just for good measure, flush global means that for any host that is added to our overload table, we kill all existing connections too.

Basically, problem solved - the noise from rapid-fire bruteforcers generally disappears instantly or after a very few attempts. If you are about to implement something like this (and many do -- the bruteforcer section in my PF tutorial appears to be among the more popular ones), you probably need to watch your logs to find useful numbers for your site, and tweak rules accordingly. I have yet to meet an admin who plausibly claims to never have been tripped up by their overload rules at some point. That's when you learn to appreciate having an alternative way in to your systems, such as a separate admin network.

Traditional Anti-Bruteforce Rules, Linux Style

For those not yet converted to the fine OpenBSD toolset (available in FreeBSD and other BSDs too, with only minor if any variations in details for this particular context), the Linux equivalent would be something like

sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 5 \ --hitcount 15 --rttl --name SSH -j DROP

But be warned: this will still be minus the maximum number of connections limit, plus the usual iptables warts. And you'd need a separate set of commands for ip6tables.

It's likely something similar is doable with other tools and products too, including possibly some proprietary ones. I've made something of an effort to limit my exposure to the non-free tools, so I can't offer you any more detail. To find out what your present product can do, please dive into the documentation for whichever product you are using. Or come back for some further OpenBSD goodness.

But as you can see, for all practical purposes the rapid-fire bruteforce or floods problem has been solved with trivial configuration tweaks.

But then something happened.

What's That? Something New!

On November 19th, 2008 (or shortly thereafter), I noticed this in my authentication logs:

Nov 19 15:04:22 rosalita sshd[40232]: error: PAM: authentication error for illegal user alias from s514.nxs.nl
Nov 19 15:07:32 rosalita sshd[40239]: error: PAM: authentication error for illegal user alias from c90678d3.static.spo.virtua.com.br
Nov 19 15:10:20 rosalita sshd[40247]: error: PAM: authentication error for illegal user alias from 207-47-162-126.prna.static.sasknet.sk.ca
Nov 19 15:13:46 rosalita sshd[40268]: error: PAM: authentication error for illegal user alias from 125-236-218-109.adsl.xtra.co.nz
Nov 19 15:16:29 rosalita sshd[40275]: error: PAM: authentication error for illegal user alias from 200.93.147.114
Nov 19 15:19:12 rosalita sshd[40279]: error: PAM: authentication error for illegal user alias from 62.225.15.82
Nov 19 15:22:29 rosalita sshd[40298]: error: PAM: authentication error for illegal user alias from 121.33.199.39
Nov 19 15:25:14 rosalita sshd[40305]: error: PAM: authentication error for illegal user alias from 130.red-80-37-213.staticip.rima-tde.net
Nov 19 15:28:23 rosalita sshd[40309]: error: PAM: authentication error for illegal user alias from 70-46-140-187.orl.fdn.com
Nov 19 15:31:17 rosalita sshd[40316]: error: PAM: authentication error for illegal user alias from gate-dialog-simet.jgora.dialog.net.pl
Nov 19 15:34:18 rosalita sshd[40334]: error: PAM: authentication error for illegal user alias from 80.51.31.84
Nov 19 15:37:23 rosalita sshd[40342]: error: PAM: authentication error for illegal user alias from 82.207.104.34
Nov 19 15:40:20 rosalita sshd[40350]: error: PAM: authentication error for illegal user alias from 70-46-140-187.orl.fdn.com
Nov 19 15:43:39 rosalita sshd[40354]: error: PAM: authentication error for illegal user alias from 200.20.187.222
Nov 19 15:46:41 rosalita sshd[40374]: error: PAM: authentication error for illegal user amanda from 58.196.4.2
Nov 19 15:49:31 rosalita sshd[40378]: error: PAM: authentication error for illegal user amanda from host116-164.dissent.birch.net
Nov 19 15:55:47 rosalita sshd[40408]: error: PAM: authentication error for illegal user amanda from robert71.lnk.telstra.net
Nov 19 15:59:08 rosalita sshd[40412]: error: PAM: authentication error for illegal user amanda from static-71-166-159-177.washdc.east.verizon.net

... and so on. The alphabetic progression of user names went on and on.

The pattern seemed to be that several hosts, in widely different networks, try to access our system as the same user, up to minutes apart. When any one host comes back it's more likely than not several user names later. The full sequence (it stopped December 30th), is available here.

Take a few minutes to browse the log data if you like. It's worth noting that rosalita was a server that had a limited set of functions for a limited set of users, and basically no other users than myself ever logged in there via SSH, even if they for various reason had the option open to them. So in contrast to busier sites where sequences like this might have drowned in the noise, here it really stood out. And I suppose after looking at the data, you can understand my initial reaction.

The Initial Reaction

My initial reaction was pure disbelief.

For the first few days I tried tweaking PF rules, playing with the attempts/second values and scratching my head, going, "How do I make this match?"

I spent way too much time on that, and the short version of the answer to that question is, you can't. With the simple and in fact quite elegant state tracking options, you will soon hit limits (especially time limits) that interfere with normal use, and you end up blocking legitimate traffic.

So I gave up on prevention (which really only would have rid me of a bit of noise in my authentication logs), and I started analyzing the data instead, trying to eyeball patterns that would explain what I was seeing. After a while it dawned on me that this could very well be a coordinated effort, using a widely distributed set of compromised hosts.

So there was a bit of reason in there after all. Maybe even a business plan or model. Next, I started analyzing my data, and came up with -

Bruteforcer Business Plan, Distributed Version

The Executive Summary would run something like this: Have more hosts take turns, round robin-ish, at long enough intervals to stay under the radar, guessing for weak passwords.

The plan is much like before, but now we have more host on the attacking side, so
  1. Pick a host from our pool, assign a user name and password (picked from a list, dictionary or pool)
  2. For each host,
    1. Try logging in to the chosen target with the assigned user name and password
    2. If successful, report back to base (we theorize); else wait for instructions (again we speculate)
  3. Go to 1).
  4. For each success at 2.2), PROFIT!

You're The Target

Let's recap, and take step back. What have we learned?

To my mind at least, it all boils down to the basics
  • Your Unix computer (Linux, OpenBSD, FreeBSD or other) is a desirable, powerful thing.
  • If your password is weak, you will be 0WN3D, sooner rather than later.
  • There's a whole fleet out there, and they're coordinated.
At this point I thought I had something useful, so I started my first writeup for publication. I had just started a new job at the time, and I think I mentioned the oddities to some of my new colleagues (that company is unfortunately defunct, but the original linked articles give some information). Anyway, I wrote and published, hoping to generate a little public attention for myself and my employer. And who knows, maybe even move a few more copies of that book I'd written the year before.


Initial Public Reaction

On December 2, 2008, I published the first blog post in what would become a longish sequence, A low intensity, distributed bruteforce attempt, where I summarized my findings. It's slightly more wordy than this piece, but if I've piqued your interest so far, please go ahead and read. And as to a little public attention, I got my wish. The post ended up slashdotted, the first among my colleagues to end up with their name on the front page of Slashdot.

That brought
  • more disbelief, (see slashdot and other comments) but also
  • confirmation, via comments and email, that others were seeing the same thing, and that the first occurrences may have been seen up to a year earlier (November-ish 2007).

The slow bruteforcers were not getting in, so I just went on collecting data. I estimated they'd be going on well past new year's if they were going to reach the end of the alphabet.


On December 30th, 2008, The Attempts Stopped

The attempts came to an end, conveniently while I was away on vacation. The last entries were:

Dec 30 11:03:08 rosalita sshd[51108]: error: PAM: authentication error for illegal user sophia from 201.161.28.9
Dec 30 11:05:08 filehut sshd[54932]: error: PAM: authentication error for illegal user sophia from 201.161.28.9
Dec 30 11:06:35 rosalita sshd[51116]: error: PAM: authentication error for illegal user sophia from static-98-119-110-139.lsanca.dsl-w.verizon.net
Dec 30 11:09:03 filehut sshd[54981]: error: PAM: authentication error for illegal user sophia from static-98-119-110-139.lsanca.dsl-w.verizon.net


That is, not even completing a full alphabetic cycle.

By then they had made 29916 attempts, all failed. You can find the full listing at here).

Trying 6100 user IDs (list by frequency here). More than likely you can guess the top one without even looking.

From a total of 1193 different hosts (list by frequency here).

As I said earlier, there were no successful penetrations. Zero.


Common characteristics

The slashdot story brought comments and feedback, with some observations from other sites. Not a lot of data, but enough that the patterns we had observed were confirmed. The attempts were all password authentication attempts, no other authentication methods attempted.

For the most part the extended incident consisted of attempts on an alphabetic sequence of 'likely' user names, but all sites also saw at least one long run of root only attempts. This pattern was to repeat itself, and also show up in data from other sources.

There would be anything from seconds to minutes between attempts, but attempts from any single host would come at much longer intervals.

First Round Observations, Early Conclusions

Summing up what we had so far, here are a few observations and attempts at early conclusions.

At the site where I had registered the distributed attempts, the Internet-reachable machines all ran either OpenBSD or FreeBSD. Only two FreeBSD boxes were contacted.

The attackers were hungry for root, so having PermitRootLogin no in our sshd config anywhere Internet facing proved to be a good idea.

We hadn't forced our users to keys only, but a bit of luck and John the Ripper (/usr/ports/security/john) saved our behinds.

The number of attempts per user name had decreased over time (as illustrated by this graph), so we speculated in the second article Into a new year, slowly pounding the gates (on slashdot as The Slow Bruteforce Botnet(s) May Be Learning) that success or not was measured at a command and control site, with resources allocated accordingly.

With the sequence not completed, we thought they'd given up. After all, the odds against succeeding seemed monumental.

After all, a couple of slashdotted blog posts couldn't have hurt, could they?


But Of Course They Came Back

As luck would have it, whoever was out there had not totally admitted defeat just yet. In the early hours CET, April 7th, 2009, the slow brutes showed up again:

Apr 7 05:02:07 rosalita sshd[4739]: error: PAM: authentication error for root from ruth.globalcon.net
Apr 7 05:02:15 rosalita sshd[4742]: error: PAM: authentication error for root from ip-206-83-192-201.sterlingnetwork.net
Apr 7 05:02:54 rosalita sshd[4746]: error: PAM: authentication error for root from cyscorpions.com
Apr 7 05:02:59 rosalita sshd[4745]: error: PAM: authentication error for root from smtp.bancomorada.com.br
Apr 7 05:03:10 rosalita sshd[4751]: error: PAM: authentication error for root from 82.192.86.217
Apr 7 05:03:25 rosalita sshd[4754]: error: PAM: authentication error for root from 66.135.60.203
Apr 7 05:03:52 rosalita sshd[4757]: error: PAM: authentication error for root from rainha.florianonet.com.br
Apr 7 05:04:00 rosalita sshd[4760]: error: PAM: authentication error for root from 72.11.144.34
Apr 7 05:04:34 rosalita sshd[4763]: error: PAM: authentication error for root from s1.serverhex.com
Apr 7 05:04:38 rosalita sshd[4765]: error: PAM: authentication error for root from mail.pitnet.com.br



Starting with 2318 attempts at root before moving on to admin and proceeding with the alphabetic sequence. The incident played out pretty much like the previous one, only this time I was sure I had managed to capture all relevant data before my logs were rotated out of existence.

The data is available in the following forms: Full log here, one line per attempt here, users by frequency here, hosts by frequency here.

I couldn't resist kicking up some more publicity, and indeed we got another slashdot storm out of the article The slow brute zombies are back, on slashdot as The Low Intensity Brute-Force Zombies Are Back.

And shortly afterwards, we learned something new -

Introducing dt_ssh5, Linux /tmp Resident

Of course there was a piece of malware involved.

A Linux binary called dt_ssh5 did the grunt work.

The dt_ssh5 file was found installed in /tmp on affected systems. The reason our perpetrators chose to target that directory is likely because the /tmp directory tends to be world readable and world writeable.

Again, this points us to the three basic lessons:




  • Stay away from guessable passwords
  • Watch for weird files (stuff you didn't put there yourself) anywhere in your file system, even in /tmp.
  • Internalize the fact that PermitRootLogin yes is a bad idea.

  • dt_ssh5: Basic Algorithm

    The discovery of dt_ssh5 made for a more complete picture. A rough algorithm suggested itself:


    1. Pick a new host from our pool, assign a user name and password
    2. For each host,
      1. Try user name and password
      2. if successful
        1. drop the dt_ssh5 binary in /tmp; start it
        2. report back to base
        else wait for instructions
    3. Go to 1.
    4. For each success at 2.2, PROFIT!

    I never got myself a copy, so the actual mechanism for communicating back to base remains unclear.


    The Waves We Saw, 2008 - 2012

    We saw eight sequences (complete list of articles in the References section at the end),

    From - To AttemptsUser IDsHostsSuccessful Logins
    2008-11-19 15:04:22 - 2008-12-30 11:09:0329916610011930
    2009-04-07 03:56:25 - 2009-04-12 21:01:371264124911040
    2009-09-30 21:15:36 - 2009-10-15 13:42:079998110710
    2009-10-28 23:58:35 - 2010-01-22 09:56:2444513811041580
    2010-06-17 01:55:34 - 2010-08-11 13:23:0123014388755680
    2011-10-23 04:13:00 - 2011-10-29 05:40:0747739443380
    2011-11-03 20:56:18 - 2011-11-26 17:42:19490724742520
    2012-04-01 12:33:04 - 2012-04-06 14:52:1147571081230


    The 2009-09-30 sequence was notable for trying only root, the 2012-04-01 sequence for being the first to attempt access to OpenBSD hosts.

    We may have missed earlier sequences, early reports place the first similar attempts as far back as 2007.


    For A While, The Botnet Grew

    From our point of view, the swarm stayed away for a while and came back stronger, for a couple of iterations, possibly after tweaking their code in the meantime. Or rather, the gaps in our data represent times when it focused elsewhere.

    Clearly, not everybody was listening to online rants about guessable passwords.

    For a while, the distributed approach appeared to be working.

    It was (of course) during a growth period I coined the phrase "The Hail Mary Cloud".

    Instantly, a myriad of "Hail Mary" experts joined the insta-punditry on slashdot and elsewhere.

    It Went Away Or Dwindled

    Between August 2010 and October 2010, things either started going badly for The Hail Mary Cloud, or possibly they focused elsewhere.

    I went on collecting data.

    There wasn't much to write about, except possibly that the botnet's command and control was redistributing effort based on past success. Aiming at crackable hosts elsewhere.


    And Resurfaced In China?

    Our last sighting so far was in April 2012. The data is preserved here.

    This was the first time we saw Hail Mary Cloud style attempts at accessing OpenBSD systems.

    The majority of attempts were spaced at at least 10 seconds apart, and until I revisited the data recently, I thought only two hosts in China were involved.

    In fact, 23 hosts made a total of 4757 attempts at 1081 user IDs, netting 0 successful logins.

    The new frequency data I thought interesting enough to write about, so I wrote up If We Go One Attempt Every Ten Seconds, We're Under The Radar, and netted another slashdotting. I took another look at the data later and slightly amended the conclusions, the article has been corrected with proper data extracted.


    Then What To Do?

    The question anybody reading this far will be asking is, what should we do in order to avoid compromise by the password guessing swarms? To my mind, it all boils down to common sense systems administration:

    Mind your logs. You can read them yourself, or train a robot to. I use logsentry, other monitoring tools can be taught to look for anomalies (failed logins, etc)

    Keep your system up to date. If not OpenBSD, check openssh.com for the latest version, check what your system has and badger the maintainer if it's outdated.

    And of course, configure your applications such as sshd properly -

    sshd_config: 'PermitRootLogin no' and a few other items

    These two settings in your sshd_config will give you the most bang for the buck:

    PermitRootLogin no
    PasswordAuthentication no
    

    Make your users generate keys, add the *.pub to their ~/.ssh/authorized_keys files.

    For a bit of background, Michael W. Lucas: SSH Mastery (Tilted Windmill Press 2013) is a recent and very readable guide to configuring your SSH (server and clients) sensibly. It's compact and affordable too.


    Keep Them Out, Keep Them Guessing

    At this point, most geeks would wax lyrical about the relative strengths of different encryption schemes and algorithms.

    Being a simpler mind, I prefer a different metric for how good your scheme is, or effectivness of obfuscation (also see entropy):

    How many bytes does a would-be intruder have to get exactly right?
    I've summed up the answer to that question in this table:

    Authentication methodNumber of bytes
    PasswordPassword length (varies, how long is yours?)
    Alternate PortPort number (2 bytes, it's a 16 bit value, remember)
    Port KnockingNumber of ports in sequence * 2 (still a 16 bit value)
    Single Packet Authentication2 bytes (the port) plus Max 1440 (IPv4/Ethernet) or 1220 (IPv6/Ethernet)
    Key OnlyNumber of bytes in key (depending on key strength, up to several kB)


    You can of course combine several methods (with endless potential for annoying your users), or use two factor authentication (OpenSSH supports several schemes).



    Keys. You've Got To have Keys!

    By far the most effective measure is to go keys only for your ssh logins. In your sshd_config, add or uncomment

    PasswordAuthentication no
    

    Restart you sshd, and have all users generate keys, like this:

    $ ssh-keygen -C "userid@domain.tld"
    

    There are other options to play with, see ssh-keygen(1) for inspiration.

    Then add the *.pub to their ~/.ssh/authorized_keys files.

    And I'll let you in on a dirty little secret: you can even match on interface in your sshd config for things like these



    Why Not Use Port Knocking?

    Whenever I mention the Hail Mary Cloud online, two suggestions always turn up: The iptables example I mentioned earlier (or link to the relevant slide), and "Why not use port knocking?". Well, consider this:

    Port knocking usually means having all ports closed, but with a daemon reading your firewalls logs for a predetermined sequence of ports. Knock on the correct ports in sequence, your're in.

    Another dirty little secret: It's possible to implement port knocking with only the tools in an OpenBSD base system. No, I won't tell you how.

    Executive Summary: Don't let this keep you from keeping your system up to date.

    To my mind port knocking gives you:
    1. Added complexity or, one more thing that will go wrong. If the daemon dies, you've bricked your system.
    2. An additional password that's hard to change. There's nothing magical about TCP/UDP ports. It's a 16 bit number, and in our context, it's just another alphabet. The swarm will keep guessing. And it's likely the knock sequence (aka password) is the same for all users.
    3. You won't recognize an attack until it succeeds, if even then. Guessing attempts will be indistinguishable from random noise (try a raw tcpdump of any internet-facing interface to see the white noise you mostly block drop anyway), so you will have no early warning.
    Port knocking proponents seem to have sort of moved on to single packet authentication instead, but even those implementations still contain the old port knocking code intact.

    If you want a longer form or those arguments, my November 4, 2012 rant Why Not Use Port Knocking? was my take (with some inaccuracies, but you'll live).



    There's No Safety In High Ports Anymore

    Another favorite suggestion is to set your sshd to listen on some alternate port instead of the default port 22/TCP.

    People who did so have had a few years of quiet logs, but recent reports show that whoever is out there have the resources to scan alternate ports too.

    Once again, don't let running your sshd on an alternate port keep you from keeping your system up to date.

    Of course I've ranted about this too, in February 2013, There's No Protection In High Ports Anymore. If Indeed There Ever Was. (which earned me another slashdotting).

    Reports with logs trickle in from time to time of such activity at alternate ports, but of course on any site with a default deny packet filtering policy will not see any traces of such scans unless you go looking specifically at the mass of traffic that gets dropped at the perimeter.



    Final thoughts, for now

    Microsoftish instapundits were quick to assert that ssh is insecure.

    They're wrong. OpenSSH (which is what essentially everyone uses) is maintained as an integral part of the OpenBSD project, and as such is a very thoroughly audited mass of code. And it keeps improving with every release.

    I consider the Hail Mary Cloud an example of distributed, parallel problem solving, conceptually much like SETI@Home but with different logic and of course a more sinister intent.

    Computing power is cheap now, getting cheaper, and even more so when you can leverage other people's spare cycles.

    The huge swarm of attackers concept is as I understand it being re-used in the recent WordPress attacks. We should be prepared for swarm attacks on other applications as soon as they reach a critical mass of users.

    There may not be a bullseye on your back yet (have you looked lately?), but you are an attractive target.

    Fortunately, sane system administration practices will go a long way towards thwarting intrusion attempts, as in
    • keep your system up to date,
    • allow only what's necessary for the task at hand and
    • keep watching your logs for weirdness.
    Keep it simple, stay safe.

    UPDATE 2013-11-21: A recent ACM Conference on Computer and Communication Security paper, "Detecting stealthy, distributed SSH brute-forcing," penned by Mobin Javed and Vern Paxson, references a large subset of the data and offers some real analysis, including correlation with data from other sites (Spoiler alert: in some waves, almost total overlap of participating machines). One interesting point from the paper is that apparently attack matching our profile were seen at the Lawrence Berkeley National Laboratory as early as 2005.

    And in other news, it appears that GitHub has been subject to an attack that matches the characteristics we have described. A number of accounts with weak passwords were cracked. Investigations appears to be still ongoing. Fortunately, GitHub appear to have started offering other authentication methods.

    UPDATE 2014-09-28: Since early July 2014, we have been seeing similar activity aimed at our POP3 service, with usernames taken almost exclusively from our spamtrap list. The article Password Gropers Take the Spamtrap Bait has all the details and log data as well as references to the spamtrap list.

    UPDATE 2014-12-10: My Passwords14 presentation, Distributed, Stealthy Brute Force Password Guessing Attempts - Slicing and Dicing Data from Recent Incidents has some further data as well as further slicing and dicing of the earlier data (with slightly different results). 

    UPDATE 2016-08-10: The POP3 gropers never went away entirely and soon faded into a kind of background noise. In June of 2016, however, they appeared to have hired themselves out to a systematic hunt for Chinese user names. The article Chinese Hunting Chinese over POP3 in Fjord Country has further details, and as always, links to log data and related files.

    UPDATE 2020-04-28: Somewhat belatedly added a link to the more recent (August 2018) article Badness, Enumerated by Robots which has updates on data we currently collect with some further explanation. Also see links therein.

    Update 2025-07-19: If you found this piece to be useful, informative, annoying or would for some other reason like to contact me or comment, please do.

    Update 2026-02-23: If you have read this far, and have tried some of the configuration enhancements mentioned already, you might also enjoy setting up endlessh to take care of otherwise annoying would-be visitors.

    You might also be interested in reading selected pieces via That Grumpy BSD Guy: A Short Reading List (also here).


    References

    The slides for the talk this article is based on live at http://home.nuug.no/~peter/hailmary2013/, with a zipped version including all data at http://home.nuug.no/~peter/hailmary2013.zip (approx. 26MB) for your convenience.

    Mobin Javed and Vern Paxson, "Detecting stealthy, distributed SSH brute-forcing," ACM International Conference on Computer and Communication Security (CCS), November 2013.

    The blog posts (field notes) of the various incidents, data links within:

    Peter N. M. Hansteen, (2008-12-02) A low intensity, distributed bruteforce attempt (slashdotted)

    Peter N. M. Hansteen, (2008-12-06) A Small Update About The Slow Brutes

    Peter N. M. Hansteen, (2008-12-21) Into a new year, slowly pounding the gates (slashdotted)

    Peter N. M. Hansteen, (2009-01-22) The slow brutes, a final roundup

    Peter N. M. Hansteen, (2009-04-12) The slow brute zombies are back (slashdotted)

    Peter N. M. Hansteen, (2009-10-04) A Third Time, Uncharmed (slashdotted)

    Peter N. M. Hansteen, (2009-11-15) Rickrolled? Get Ready for the Hail Mary Cloud! (slashdotted)

    Peter N. M. Hansteen, (2011-10-23) You're Doing It Wrong, Or, The Return Of The Son Of The Hail Mary Cloud

    Peter N. M. Hansteen, (2011-10-29) You're Doing It Wrong, Returning Scoundrels

    Peter N. M. Hansteen, (2012-04-06) If We Go One Attempt Every Ten Seconds, We're Under The Radar (slashdotted)

    Peter N. M. Hansteen, (2012-04-11) Why Not Use Port Knocking?

    Peter N. M. Hansteen, (2013-02-16) There's No Protection In High Ports Anymore. If Indeed There Ever Was. (slashdotted)

    Peter N. M. Hansteen (2018-08-13) Badness, Enumerated by Robots (updates on data we currently collect, also see links therein).

    Other Useful Texts

    Marcus Ranum: The Six Dumbest Ideas in Computer Security, September 1, 2005

    Michael W. Lucas: SSH Mastery, Tilted Windmill Press 2013

    Michael W. Lucas: Absolute OpenBSD, 2nd edition No Starch Press 2013

    Peter N. M. Hansteen, The Book of PF, 4th edition, No Starch Press 2026, also the online PF tutorial it grew out of, several formats http://home.nuug.no/~peter/pf/, more extensive slides matching the most recent session at http://home.nuug.no/~peter/pf/newest/. More recently I've done a rewrite of the PF tutorial with Max Stucchi and Tom Smyth co-authoring and co-presenting, the lastest slides from one of these sessions are available at https://nxdomain.no/~peter/pf_fullday.pdf (sorry, labs available for real attendees only).

    OpenBSDs web http://www.openbsd.org/ -- lots of useful information.


    If you enjoyed this: Support OpenBSD!

    If you have enjoyed reading this, please buy OpenBSD CDs and other items, and/or donate!

    Useful links for this are:

    OpenBSD Donations Page: http://www.openbsd.org/donations.html.

    OpenBSD Hardware Wanted Page: http://www.openbsd.org/want.html.

    Remember: Free software takes real work and real money to develop and maintain.

    If you want to support me, buy the book!.
    The Hail Mary Cloud And The Lessons Learned is © 2013 -2026 Peter N. M. Hansteen
    You might also be interested in reading selected pieces via That Grumpy BSD Guy: A Short Reading List (also here).

    Saturday, May 11, 2013

    DNSSEC Mastery, Or How To Make Your Name Service Verifiable And Trustworthy

    A DNSSEC book for the working sysadmin, likely to put you ahead of the pack in securing an essential Internet service.

    I have a confession to make. Michael W. Lucas is a long time favorite of mine among tech authors. When Michael descends on a topic and produces a book, you can expect the result to contain loads of useful information, presented along with humor and real-life anecdotes so you will want to explore the topic in depth on your own systems.

    In DNSSEC Mastery (apparently the second installment in what could become an extensive Mastery series -- the first title was SSH Mastery, reviewed here -- from Michael's own Tilted Windmill Press), the topic is how to make your own contribution to making the Internet name service more reliable by having your own systems present verifiable, trustworthy information.

    Before addressing the book itself, I'll spend some time explaining why this topic is important. The Domain Name System (usually referred to as DNS or simply 'the name service' even if nitpickers would be right that there is more than one) is one of the old-style Internet services that was created to solve a particluar set of problems (humans are a lot better at remembering names a than strings of numbers) in the early days of networking when security was not really a concern.

    Old-fashioned DNS moves data via UDP, the connectionless no-guarantees-ever protocol mainly because the low protocol overhead in most cases means the answer arrives faster than it would have otherwise. Reliable delivery was sacrificed for speed, and in general, the thing just works. DNS is one of those things that makes the Internet usable for techies and non-techies alike.

    The other thing that was sacrificed, or more likely never even considered important enough to care about at the time, was any hope of reliably verifying that the information received via the DNS service was in fact authentic and correct.

    When you ask an application to look up a name, say you want to see if anything's new at bsdly.blogspot.com or if you want to send me mail to be delivered at bsdly.net, the answer comes back, not necessarily from the host that answers authoritatively for the domain, but more likely from the cache of a name server near you, and serves mainly one or more IP addresses, with no guarantee other than it is, indeed a record type that contains one or more IP addresses that appear to match your application's query.

    Or to put it more bluntly, with traditional DNS, it's possible for a well positioned attacker to feed you falsfied information (ie leading your packets to somewhere they don't belong or to somewhere you never intended, potentially along with your confidential data), even if the original DNS designers appear to have considered the scenario rather unlikely back then in the nineteen-eighties.

    With the realization that the Internet was becoming mainstream during the 1990s and that non-techies would rely on it for such things as banking services came support cryptographically enhanced versions of several of the protocols that take care of the bulk of Internet traffic payloads, and even the essential and mostly ignored (at least by non-techies) DNS protocol was enhanced several times over the years. Around the turn of the century came the RFCs that describe cryptographic signatures as part of the enhanced name service, and finally in 2005 the trio of RFCs (4033, 4034 and 4035) that form the core of the modern DNSSEC specification were issued.

    But up until quite recently, most if not all DNSSEC implementations were either incomplete or considered experimental, and getting a working DNSSEC setup in place has been an admirable if rarely fulfilled ambition among already overworked sysadmins.

    Then at what seems to be the exactly right moment, Michael W. Lucas publishes DNSSEC Mastery, which is a compact and and extremely useful guide to creating your own DNSSEC setup, avoiding the many pitfalls and scary manouvres you will find described in the HOWTO-style DNSSEC guides you're likely to encounter after a web search on the topic.

    The book is aimed at the working sysadmin who already has at least basic operational knowledge of running a name service. Starting with one DNSSEC implementation that is known to be complete and functional (ISC BIND 9.9 -- Michael warns early on very clearly that earlier versions will not work -- if your favorite system doesn't have that packaged yet, you can build your own or start bribing or yelling at the relevant package maintainer), this book takes a very practical, hands on approach to its topic in a way that I think is well matched to the intended audience.

    Keeping in mind that the one thing a working sysadmin is always short on is time, it is likely a strong advantage that this book is so compact. With 12 chapters, it comes in at just short of 100 pages in the PDF version I used for most of this review. With the stated requirement that the reader needs to be reasonably familiar with running a DNS service, the introductory chapters fairly quickly move on to give an overview of public key cryptography as it applies to DNSSEC, with pointers to wordier sources for those who would want to delve into details, before starting the steps involved in setting up secure name service using ISC BIND 9.9 or newer.

    Always taking a practical approach, DNSSEC Mastery covers essentially all aspects of setting up and running a working service, including such topics as key management, configuring and debugging both authoritative and recursive resolvers, various hints for working with or around strengths or deficiencies in various client operating systems, how the new world of DNSSEC influences how you manage your zones and delegations, and did I mention debugging your setup? DNSSEC is a lot less forgiving of errors than your traditional DNS, and Michael includes both some entertaining examples and pointers to several useful resources for testing your work before putting it all into production. And for good measure, the final chapter demonstrates how to distribute data you would not trust to old fashioned DNS: ssh host key fingerprints and SSL certificates.

    As I mentioned earlier, this title comes along at what seems to be the perfect time. DNSSEC use is not yet as widespread as it perhaps should be, in part due to incomplete implementations or lack of support in several widely used systems. The free software world is ahead of the pack, and just as the world is getting to realize the importance of a trustworthy Internet name service, this book comes along, aimed perfectly at the group of people who will need an accessible-to-techies book like this one. And it comes at a reasonable price, too. If you're in this book's target group, it's a recommended buy.

    The ebook is available in several formats from Tilted Windmill Press, Amazon and other places. A printed version is in the works, but was not available at the time this review was written (May 11, 2013).

    Note: Michael W. Lucas gives tutorials, too, like this one at BSDCan in Ottawa, May 15 2003.

    Title: DNSSEC Mastery: Securing The Domain Name System With BIND
    Author: Michael W. Lucas
    Publisher: Tilted Windmill Press (April 2012)

    Michael W. Lucas has another, somewhat chunkier book out this year too, Absolute OpenBSD, 2nd edition, a very good book about my favorite operating system. It would have been reasonable to expect a review here of that title too, except that I served as the book's technical editor, and as such a review would be somewhat biased.

    But if you're interested in OpenBSD and haven't got your copy of that book yet, you're in for a real treat. If a firewall or other networking is closer to your heart, you could give my own The Book of PF and the PF tutorial (or here) it grew out of. You can even support the OpenBSD project by buying the books from them at the same time you buy your CD set, see the OpenBSD Orders page for more information.

    Upcoming talks: I'll be speaking at BSDCan 2013, on The Hail Mary Cloud And The Lessons Learned. There will be no PF tutorial at this year's BSDCan, fortunately my staple tutorial item was crowded out by new initiatives from some truly excellent people. (I will, however, be bringing a few copies of The Book of PF and if things work out in time, some other items you may enjoy.)