137
Covert Channel Analysis and Data Hiding in TCP/IP David Llamas A thesis submitted in partial fulfilment of the requirements of Napier University for the degree of Bachelor of Science with Honours in Software Technology May 2004 Supervisor: Dr. William Buchanan 2 nd Marker: Professor Peter Ross

Covert Channel Analysis and Data Hiding in TCP/IP

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Covert Channel Analysis and Data Hiding in TCP/IP

David Llamas

A thesis submitted in partial fulfilment of the requirements of Napier University for the degree of Bachelor of Science

with Honours in Software Technology

May 2004

Supervisor: Dr. William Buchanan 2nd Marker: Professor Peter Ross

David Llamas 1 BSc (Hons) Software Technology, 2004

AUTHORSHIP DECLARATION ........................................................................................................ 4

ABSTRACT ............................................................................................................................................ 5

LIST OF TABLES ................................................................................................................................. 7

LIST OF FIGURES ............................................................................................................................... 7

1 ACKNOWLEDGEMENTS ......................................................................................................... 8

2 INTRODUCTION ........................................................................................................................ 9

2.1 INTRODUCTION ...................................................................................................................... 9 2.2 SCOPE, AIMS AND CONTRIBUTION OF THIS HONOURS PROJECT ............................................. 9 2.3 BACKGROUND...................................................................................................................... 10 2.4 HISTORY .............................................................................................................................. 10 2.5 INFORMATION HIDING ......................................................................................................... 12

2.5.1 Classification.................................................................................................................. 12

3 THEORY..................................................................................................................................... 14

3.1 INTRODUCTION .................................................................................................................... 14 3.2 COVERT CHANNELS ............................................................................................................. 14

3.2.1 Classification.................................................................................................................. 14 3.2.2 Potential uses ................................................................................................................. 15

3.3 TCP/IP PROTOCOL SUITE .................................................................................................... 15 3.3.1 Physical Layer/Device Layer.......................................................................................... 15 3.3.2 Internet Layer ................................................................................................................. 17 3.3.3 Transport Layer.............................................................................................................. 17 3.3.4 Application Layer ........................................................................................................... 17 3.3.5 Security........................................................................................................................... 17

3.4 REVERSE PROXY SERVER..................................................................................................... 18 3.5 WINDOWS NT/2000 NETWORK SUBSYSTEM ARCHITECTURE ............................................... 19

3.5.1 Microsoft Windows NT/2000 network architecture components.................................... 19 3.5.2 Network traffic filtering technologies for Windows........................................................ 21

4 LITERATURE REVIEW .......................................................................................................... 23

4.1 INTRODUCTION .................................................................................................................... 23 4.2 LAN ENVIRONMENTS .......................................................................................................... 23 4.3 LAN PROTOCOLS................................................................................................................. 24 4.4 DATA HIDING IN OSI MODEL .............................................................................................. 24

4.4.1 Physical layer ................................................................................................................. 24 4.4.2 Data Link layer............................................................................................................... 25

David Llamas 2 BSc (Hons) Software Technology, 2004

4.4.3 Network layer ................................................................................................................. 25 4.4.4 Transport layer............................................................................................................... 25 4.4.5 Session layer................................................................................................................... 25 4.4.6 Presentation layer .......................................................................................................... 25 4.4.7 Application layer ............................................................................................................ 26

4.5 COVERT CHANNELS IN THE TCP/IP PROTOCOL SUITE ......................................................... 26 4.5.1 Method One - Manipulation of the IP Identification Field............................................. 27 4.5.2 Method Two - Initial Sequence Number Field................................................................ 27 4.5.3 Method Three - The TCP Acknowledge Sequence Number Field "Bounce" .................. 27 4.5.4 Method Four – Through the packet sorting (IPSec)....................................................... 27

5 DESIGN....................................................................................................................................... 33

5.1 INTRODUCTION .................................................................................................................... 33 5.2 SYSTEM SPECIFICATION ....................................................................................................... 33 5.3 DEVELOPMENT METHODOLOGY ........................................................................................... 35 5.4 CLASSES, GLOBAL FUNCTIONS, VARIABLES AND STRUCTURES............................................. 36

6 IMPLEMENTATION ................................................................................................................ 43

6.1 COVERT AGENT ................................................................................................................... 43 6.2 COVERT CONTROLLER ......................................................................................................... 45 6.3 REVERSE PROXY SERVER..................................................................................................... 46 6.4 COVERT VIEWER.................................................................................................................. 47 6.5 PACKET SNIFFER.................................................................................................................. 47

7 RESULTS.................................................................................................................................... 49

7.1 MONITORING AND DETECTION ............................................................................................. 49 7.2 PREVENTION AND COUNTERMEASURES ............................................................................... 53 7.3 CAPACITY, PERFORMANCE AND PAYLOAD .......................................................................... 53

8 CONCLUSIONS AND FUTURE WORK ................................................................................ 56

9 REFERENCES ........................................................................................................................... 60

10 APPENDIX.................................................................................................................................. 63

10.1 HONOURS PROJECT CONTRACT............................................................................................ 63 10.2 DIARY SHEETS...................................................................................................................... 69 10.3 ECIW 2004 CONFERENCE PAPER......................................................................................... 79 10.4 SOURCE CODE...................................................................................................................... 90

10.4.1 Agent.cs .......................................................................................................................... 90 10.4.2 Sniffer.cs ......................................................................................................................... 93 10.4.3 MainForm.cs .................................................................................................................. 99 10.4.4 ReverseProxyServer.cs ................................................................................................. 105

David Llamas 3 BSc (Hons) Software Technology, 2004

10.4.5 SnifferStateObject.cs .................................................................................................... 110 10.4.6 CovertViewer.cs............................................................................................................ 112 10.4.7 CovertViewerStateObject.cs ......................................................................................... 118 10.4.8 CovertAgent.h............................................................................................................... 120 10.4.9 CovertAgent.cpp ........................................................................................................... 122 10.4.10 ColumnDataCollection.cs............................................................................................. 130 10.4.11 ColumnData.cs ............................................................................................................. 133

David Llamas 4 BSc (Hons) Software Technology, 2004

Authorship declaration I, David Llamas, confirm that this dissertation and the work carried out to complete it are all of my own achievement. 1. Where I have consulted and used work of others in the context of this dissertation,

this has been clearly accredited 2. This dissertation is all my own work. 3. I have acknowledged all main sources of help. Signed: David Llamas BSc (Hons) Software Technology Student 01009322 Phone : +44 (0) 1312283123 Fax : +44 (0) 1312285532 Mobile : +44 (0) 7740984199 Email : [email protected] [email protected]

[email protected] Web : http://www.dcs.napier.ac.uk/~01009322

http://www.steganography.org http://www.inchcolm.org Napier University School of Computing 10 Colinton Road Edinburgh EH10 5DT Scotland Date: 5th May 2004

David Llamas 5 BSc (Hons) Software Technology, 2004

Abstract Data hiding methods can be used by intruders to communicate over open data channels (Rowland 1996; deVivo, deVivo et al. 1999), and can be used to overcome firewalls, and most other forms of network intrusion detection systems. In fact, most detection systems can detect hidden data in the payload, but struggle to cope with data hidden in the IP and TCP packet headers, or in the session layer protocol. This Honours Project proposes a novel architecture for data hiding, and presents methods which can be used to detect the hidden data and prevent the use of covert channels for its transmission. It also presents the method used in creating a system for Microsoft Windows platforms. The scenario consists of one user that from his computer connects to a web server. In fact, the connection is done to a Reverse Proxy Server (RPS) and this is the one in charge of connecting with the Web Server, collect the information requested and returns it to the user. For the user, this action takes place in a transparent manner as if he had connected directly to the Web Server. It has to be highlighted that the RPS does not need to be configured in advanced by the user. Because of that, the RPS becomes a strategic middleware piece of software able to analyze and manipulate the traffic between one user and a server in the Internet in a discrete mode. This ability has been used in this project to send covert messages in the outgoing packets that leave from the RPS going to the user. Whilst the user is navigating can observe, through a separate window provided by an application denominated Covert Viewer, the incoming covert message. In this Honours Project it has also been developed a network packet sniffer so the user can observe how the message is transmitted by the network packets through a technique that will be explained further later on. In the RPS side, we have basically two applications: the Data Hiding Intelligent Agent (DHIA) and the RPS itself. As has been explained above, the mission of the RPS it is to capture the requests of the user, transmit them to the relevant server, collect the answer from the server and sent it back to the user. The DHIA is in charge of manipulating the outgoing packets to send the covert message. The technique used by this component is inserting in the identification field of the IP header (version 4) the ASCII value of the character that wants to be sent. As explained further on, the TCP/IP Protocol Suite has some weaknesses on its design that facilitates the manipulation of its characteristics. The DHIA allows the configuration, through a XML File, of sending covert messages to specific IP addresses that have requested a specific port. This Honours Project has based the design and the implementation of the RPS and DHIA in the Microsoft Windows platform, which has increased the complexity of the development. Usually the development of tools for this kind of projects are done in Unix platforms as the source code of the operating system is available and can be manipulated for this purpose. In this case, we had to work with techniques that allow the interception of a subset of functions from the Kernel mode. There are several

David Llamas 6 BSc (Hons) Software Technology, 2004 techniques to do this, and in this case, for the Kernel mode traffic filtering we have used the NDIS Hooking Filter Driver. All the attempts to manipulate the IP header in the user mode, above the TCP/IP driver layer, have not been successful as the proprietary driver from Microsoft Windows Platforms did not allow it. At the Kernel mode level, intercepting the NDIS functions working below the TCP/IP driver of Microsoft Windows platform was possible although several issues had to be taken into account. For example, if a manipulated IP packet was requested again from the destination host to the sender, the sender did not recognize the manipulated packet so this had to be un-manipulated before. The implementation of all the pieces of software involved in this Honours Project has been successfully done by using the techniques explained earlier but, initially, an exhaustive research had to be done to learn the different systems and programming languages that could fulfil the objectives. The implementation has finally been done with the creation of a DLL in C++ in charge of the lower level aspects, such as the extraction at Data Link level of the Ethernet packets by then extracting the IP packets, manipulate the identification field, recalculate the checksum and resend. For the remaining functionalities, as we were using Microsoft Windows platforms, everything has been done in C#: the main functionality of the RPS, the Network packet sniffer and the covert message viewer. Regarding the results, it has been very interesting to observe, in the first place, that what was pretended by this Honours Project has been reached as the user receives the covert message according its specifications, taking into account that those were sent from a Microsoft Windows server using the techniques specified above. To test this, the results offered by the network packet sniffer have been essential. Secondly, has also been possible to probe that the DHIA combined with the RPS can do functions of monitoring, detection, prevention and countermeasures actions. Finally, we have obtained some metrics about capacity and performance that have confirmed the significant impact that the manipulation of IP packets has in comparison to the usual working of a network. Keywords: Data Hiding, Covert Channel, TCP/IP, Reverse Proxy Server, Microsoft

Windows Note: This report follows the requirements specified in the Project Handbook v2 (Lawson and Varey 2001), and it is within the expected length of 12000 words for the main text. Report appendices are not considered part of the main text.

David Llamas 7 BSc (Hons) Software Technology, 2004

List of Tables TABLE 1 - NUMBER OF PUBLICATION ON DIGITAL WATERMARKING, INSPEC JANUARY 99.................... 10 TABLE 2 - CAPACITY ESTIMATION........................................................................................................... 54

List of Figures FIGURE 1 - INFORMATION HIDING TERMINOLOGY ................................................................................... 12 FIGURE 2 - A CLASSIFICATION OF INFORMATION HIDING TECHNIQUES ................................................... 13 FIGURE 3 - COVERT CHANNELS............................................................................................................... 15 FIGURE 4 - TCP/IP PROTOCOL SUITE ...................................................................................................... 16 FIGURE 5 - OSI NETWORK MODEL VS. TCP/IP NETWORK MODEL ......................................................... 16 FIGURE 6 - CONVERT CHANNELS WITH DATA HIDING ON THE PROXY ...................................................... 19 FIGURE 7 - WINDOWS 2000 NETWORK ARCHITECTURE DIAGRAM.......................................................... 20 FIGURE 8 - OSI NETWORK MODEL ........................................................................................................... 25 FIGURE 9 - IP HEADER V4........................................................................................................................ 26 FIGURE 10 - THE AH HEADER ................................................................................................................. 30 FIGURE 11 - THE ESP HEADER ................................................................................................................ 30 FIGURE 12 - PACKETS GENERATED FROM IPSEC IMPLEMENTED NODE HAVING SORTED SEQUENCE

NUMBERS....................................................................................................................................... 32 FIGURE 13 – COMPONENTS DATA FLOW OF THE REVERSE PROXY SYSTEM ............................................. 33 FIGURE 14 - NETWORK PACKETS............................................................................................................. 34 FIGURE 15 - SPIRAL MODEL..................................................................................................................... 35 FIGURE 16 – FROM COVERT AGENT ........................................................................................................ 43 FIGURE 17 – FROM COVERT AGENT ........................................................................................................ 44 FIGURE 18 - FROM COVERT CONTROLLER............................................................................................... 45 FIGURE 19 - FROM REVERSE PROXY SERVER .......................................................................................... 46 FIGURE 20 – FROM COVERT VIEWER....................................................................................................... 47 FIGURE 21 - FROM PACKET SNIFFER........................................................................................................ 47 FIGURE 22 – MINI-LABORATORY ............................................................................................................ 48 FIGURE 23 - PACKET SNIFFER ................................................................................................................. 49 FIGURE 24 - COVERT VIEWER ................................................................................................................. 50 FIGURE 25 - COVERT CONTROLLER......................................................................................................... 51 FIGURE 26 - COVERT CONTROLLER XML FILE ....................................................................................... 52 FIGURE 27 - DATA-HIDING PROBLEM SPACE ........................................................................................... 53 FIGURE 28 - CAPACITY ESTIMATION ....................................................................................................... 54

David Llamas 8 BSc (Hons) Software Technology, 2004

1 Acknowledgements I would like to thank my supervisor, Dr William Buchanan, for his help and encouragement throughout this project. Also I am grateful to Professor Peter Ross for being part of my Honours Project committee. In addition, I would also like to thank Colin MacKay for his advice about the technology aspects of the project, Charlie Hussey for his constant inspiration and unconditional support and Loreta Gaiteiro for her assistance in providing constant coffee during several weeks.

David Llamas 9 BSc (Hons) Software Technology, 2004

2 Introduction

2.1 Introduction This section is about an introduction to the report, by specifying the scope, aims and the contribution of this Honours Project, and by offering an introductory background to the subjects.

2.2 Scope, Aims and Contribution of this Honours Project A covert channel is an information flow mechanism within a system that is based on the use of system resources not normally intended for communication between the users of the system (McHugh 1995). The main aim of this project is investigate data hiding in general and to focus on the application of covert channels in the TCP/IP protocol suite. For this several pieces of software have been developed: • A Reverse Proxy Server with an embedded Data Hiding Intelligent Agent

(DHIA). • A Data Hiding Viewer. • A Packet Sniffer to analyse the network traffic and some specific aspects of the

covert channel technique. This prototype, composed by all these elements, is focused on the manipulation of the IP Identification field technique on the IP header version 4 (Rowland 1996). While the user is navigating around a web site through the Reverse Proxy Server, the Data Hiding Viewer, on the client side, shows in a separated window the hidden data that is sent by the DHIA embedded in the Reverse Proxy Server. The Packet Sniffer shows the content of all IP packets. This project also makes the contribution of creating a full functional design and prototype to be run in Microsoft Windows™ proprietary platform. The Reverse Proxy Server and the DHIA, which have the ability of using covert channels techniques within the TCP/IP protocol suite in Microsoft Windows platforms, is a novel contribution to the community. No other application with these features using the Microsoft Windows platforms has been found, at least, at public domain level, after researching hundreds of papers and journal articles, Internet newsgroups and software databases. Most of the currently available tools related to data hiding techniques are based around the UNIX operating system, as the source code of this operating system is available and it can be modified for these purposes. To highlight the success of this project, a paper has been accepted for the 3rd European Conference on Information Warfare and Security (ECIW), held at Royal Holloway, University of London, on 28 and 29 June 2004. See appendixes for reading the paper.

David Llamas 10 BSc (Hons) Software Technology, 2004

2.3 Background Security is now one of the major issues in computing. There is thus an increasing interest in information hiding, such as steganography, covert channels, watermarking, anonymity and so on, as they have been considered one of the most sophisticated and advanced techniques for attacking systems, networks, and so on, and can be used for passing information without being it detected. The increasing interest can be seen in Table 1 - Number of publication on digital watermarking, INSPEC January 99. No recent information can be found on this, but it can be seen that there has been a large number of publications in the past few years.

Year 1992 1993 1994 1995 1996 1997 1998 Publications 2 2 4 13 29 64 103 Table 1 - Number of publication on digital watermarking, INSPEC January 99 The covert channel technique is, in essence, communications which is not part of the actual or original computer or design, but can be used to transfer information between users. Covert channels have existed in many systems including in protocols used for internetworking and communication. These channels can go easily unnoticed, thus providing an excellent means for hiding information in them (Venkatesh 2003). Proxy servers are probably one of the most interesting applications for doing interventions in networks, as they can act at any level and can run in a discrete mode, where no-one can detect its observation or traffic manipulation. Because of this, proxy servers are the type of application that has been chosen for adding the DHIA embedded on it, in order to apply the covert channel technique. Along with this, in the TCP/IP protocol suite, there are numerous ways in which covert channels can be established and data can be surreptitiously passed between any two hosts. This Honours Project attempts to illustrate the weaknesses of the TCP/IP protocol suite, by analysing and using the data hiding covert channel techniques based on reverse proxy servers, in both, theoretical and practical examples, which are implemented in Microsoft Windows™ proprietary platform.

2.4 History Throughout history people have hidden messages using very different methods and techniques (Kahn 1996). These techniques have helped to win or lose wars, disguised secret religions or secure financial transactions (Wrixon 1998). Examples of Steganography go back to antique days. A famous example can be found at around 440 BC where two significant Persians leaders communicated secretly by shaving the head of one of their slaves with a tattooed message. Once the hair grew back, the slave was sent to co-conspirators who read the message by shaving the head again (Johnson and Jajodia 1998). A technique as simple as this was also used years later by Germans in the Second World War. Also another antiqued technique can be found in ancient Greece where a man warned Sparta of an imminent invasion by writing a message by scrapping wax off of a table. Once the message was written, he covered

David Llamas 11 BSc (Hons) Software Technology, 2004 the table back with wax again so it was not noticed that it had a message (the table looked like a blank one) (Petitcolas, Anderson et al. 1999). Another example of the technique was to hide messages with invisible ink. For this an innocent letter can cover a very different message written between the lines (Johnson and Jajodia 1998). As early as CE 600, the Arabs were using invisible inks to communicate throughout their extent empire (Wrixon 1998). Originally, these inks were made of commonly used organic substances such as onion, milk and vinegar (Katzenbeisser and Petitcolas 2000), and were developed in Europe in the Middle ages and, by 1700, knowledge of these methods has crossed the Atlantic (Wrixon 1998). Invisible ink was also used commonly during the first World War, however, with the invention of universal developers in the 20th Century they were capable of determining which part of a paper had been treated with these techniques (Petitcolas, Anderson et al. 1999). In 1857 Brewster suggested the idea of hiding secret messages in spaces not larger than a full stop or a small dot of ink (Petitcolas, Anderson et al. 1999). These techniques started to be developed during the Franco-Prussian War of 1870-1871 were René dragon reduced military documents on film to a few millimetres. Although this did not helped French to win the war, it was important for what would be later be called the Microdot (Wrixon 1998). The microdot technique was further developed by the Germans during the First World War and was also used during the Second World War. The FBI director Edward Hoover referred to this technique as the enemy’s masterpiece of espionage (Wrixon 1998). A modern adaptation of this techniques is still in use nowadays for document security (Katzenbeisser and Petitcolas 2000). Documents themselves can hide information. Open-coded messages, such an apparent innocent letter can hide information through the use of null ciphers (unencrypted messages). A good example of this it is the text below that was sent by a German spy in World War II (Johnson and Jajodia 1998):

Apparently neutral´s protest is thoroughly discounted and ignored. Isman hard hit. Blockade issue affects pretext for embargo on by-products, ejecting suets and vegetable oils.

By extracting the second letter in each word the following hidden message can be read:

Pershing sails from NY June 1 In the case of the watermarking, this technique has been used for more than 700 years ago in Italy to differentiate the paper brand and the mill that produced it (Al-Ahmad and Mualla) By the 1900s, watermarks on paper in Europe and America had been used as trademarks to record the manufactured date, or to indicate the size of original sheets. Watermarks are commonly used on paper money to avoid counterfeiting (Huang 2002) Nowadays, information-hiding techniques have gone public and are more commonly used. In any case, as has happened in the past, the military and security entities are the ones who contribute more to the developments of these techniques.

David Llamas 12 BSc (Hons) Software Technology, 2004 2.5 Information Hiding Information hiding has been around for centuries. This section defines some of the terminology used in this topic and a classification proposal. Given the increased general interest over data hiding technique, some common terminology was agreed in the Information Hiding First International Workshop hold in Cambridge in 1996. It was decided that most of the applications have the common core explained in Figure 1 - Information hiding terminology (Pfitzmann 1996). The items used are: • Embedded <datatype>. Something to be hidden, in something else. • Stego-<datatype>. The output of the hiding process; something that has the

embedded message hidden in it. • Cover-<datatype>. An input with an original form of the stegomessage. In some

applications, such a cover message is given from the outside, in others, it can be chosen during the hiding process. The latter is represented by the dashed extension to the inner hiding process.

• Stegokey or simply key. This is additional secret data that may be needed in the hiding process. In particular, the same key (or a related one) is usually needed to extract the embedded message again.

Figure 1 - Information hiding terminology

2.5.1 Classification

Data hiding techniques have become much more open and public in the last few years. This has created some confusion in the terminology and the differences between the different techniques. In (Petitcolas, Anderson et al. 1999) it is suggested a classification of the information hiding techniques as can be seen in Figure 2 - A Classification of information hiding techniques. This is based on the agreements reached at the Information Hiding First International Workshop on the subject (Anderson 1996). Steganography it is the art of hiding information in ways that prevents the detection of hidden messages (Johnson and Jajodia 1998). In this case, the existence of the message it is not known, hence a successful attack will consist in detecting the existence. In the linguistic Steganography, the carrier medium is text whilst in the technical Steganography the carrier medium in non-text, such as graphic files, photos, and so on.

David Llamas 13 BSc (Hons) Software Technology, 2004 In the case of the copyright marking, the most important characteristic it is the robustness against possible attacks (Petitcolas, Anderson et al. 1999). In fact, there are many copyright marks that are not hidden, such as a company logo, and whose main purpose it is to differentiate one product, or service, against others and thus give a unique identity. Cryptography is commonly used in information hiding. However, it not included within this area as the message is not hidden, and is thus it is clear that there is a message, but it cannot be read unless the required decoding method is known. Unlike Steganography, the main issue it is not to detect the message, as this can be easily intercepted, but to decrypt it once has been intercepted.

Figure 2 - A Classification of information hiding techniques

David Llamas 14 BSc (Hons) Software Technology, 2004

3 Theory

3.1 Introduction This section provides the theory behind the main aspects of the project, which are: • Covert channels. • TCP/IP communications and its protocol suite. • Reverse proxy servers. • The kernel mode in Microsoft Windows NT platforms.

3.2 Covert Channels A covert channel is a communication channel that allows two cooperating processes to transfer information in a manner that violates the system’s security policy (Berg 1998). It is thus a way of communicating which is not part of the original design of the system, but can be used to transfer information to a process or user, that, a priori, would not be authorised to access to that information. They typically only exist in systems with multilevel security (Proctor and Neumann 1992), which contain and manage information with different sensitivity levels. Thus they allow different users to access to the same information, at the same time, but from different points-of-view, depending on their requirements to know and their access privileges.

3.2.1 Classification

The covert channel concept was introduced in 1973 (Lampson 1973), and are now generally, classified based on (Gligor 1993): • Scenarios. In general, when building covert channels scenarios, there is a

differentiation between storage and timing covert channels (Lipner 1975). Storage covert channels are where one process uses direct (or indirect) data writing, whilst another process reads the data. They generally use a finite system resource that is shared between entities with different privileges. Covert timing channels use the modulation of certain resources, such as the CPU timing, in order to exchange information between processes.

• Noise. As with any other communication channel, covert channels can be noisy, and vary in their immunity to noise. Ideally, a channel immune to noise is one where the probability of the receiver receiving exactly what the sender has transmitted is unity, and there are no interferences in the transmission. Obviously, in real-life, it is very difficult to obtain these perfect channels; hence, it is common to apply error correction codes, which can obviously reduce the bandwidth.

• Information flows. With conventional lines of transmission different techniques are applied to increase the bandwidth. A similar method can be achieved in the covert channels. Channels where several information flows are transmitted between sender and receiver are defined as aggregated channels, and depending on how sent variables are initialized, read and reset, aggregations can be classified as serial, parallel, and so on. Channels with a unique information flow are denominated non-aggregated.

David Llamas 15 BSc (Hons) Software Technology, 2004 3.2.2 Potential uses

The concern for the presence of covert channels is common in high security systems (Figure 3 - Covert Channels), such as military ones, where typically two observed users know that someone wishes to listen to their conversations. Many of the studies on these attacks, based on covert channels and their prevention, have been done by US government and military bodies, such as the National Security Agency, US Air Force, National Computer Security Centre, and so on (Buchanan and Llamas 2004). However, in other environments it is also possible the existence of covert channels, especially in protocols like the TCP/IP protocol suite (Rowland 1996).

Suspect A Suspect B

A covert channel is typically used when thesuspects know that theyare being monitored

A covert channel is typically used when thesuspects know that theyare being monitored Mail messages

Postal messages

Bank records

Wire taps

Internet communications

Figure 3 - Covert Channels

3.3 TCP/IP Protocol Suite TCP/IP is a set of protocols developed for the Internet in the 1970s to provide an orderly flow of information between one host and another, over a network. A high-level explanation based on Figure 4 - TCP/IP Protocol Suite is offered by (Johnston 2003). The layers of model are covered next.

3.3.1 Physical Layer/Device Layer

At the lowest layer is the Physical Layer, which is concerned with the electrical and mechanical connections to the network (HyperDictionary 2003). Above this is the Device Layer which is a set of software protocols. These check for transmission errors in the device layer and control the line discipline of setting up the connection.

David Llamas 16 BSc (Hons) Software Technology, 2004

Figure 4 - TCP/IP Protocol Suite

Figure 5 - OSI Network Model vs. TCP/IP Network Model

David Llamas 17 BSc (Hons) Software Technology, 2004 See Figure 5 - OSI Network Model vs. TCP/IP Network Model for comparing both network models.

3.3.2 Internet Layer

The network layer provides network addressing and data routing. It also ties all the device layers together and enables data packets to be routed between networks that are not directly connected, where each packet can go through multiple hops. A good example of network address is IP which stands for Internetworking Protocol. Also with this other protocols such as ICMP provides the control messages this requires like Host unreachable and Connection refused. BGP and OSPF are vital, as they let routers exchange information about who is connected to whom. This is what enables a data packet to go from a host to anywhere on the Internet.

3.3.3 Transport Layer

Above the network layer there are various protocols in the Transport Layer. This layer determines uses the network layer to provide a virtual error-free, point-to-point connection so that host A can send messages to host B, so that they will arrive un-corrupted and in the correct order. For this it establishes and dissolves connections between hosts (HyperDictionary 2003). Two of the most popular transport layer protocols are UDP and TCP. UDP provides a quick, but not-guaranteed way to send individual data packets. On the other hand, TCP uses a complex system of acknowledgements and retransmissions to provide a reliable two-way data stream. An important feature of these transport protocols is that they contain the port number that enables multiple network applications to run on a single host.

3.3.4 Application Layer

At the top is the Application Layer which contains all the protocols used for the application such as for email, remote administration, and so on. This layer handles issues like network transparency, resource allocation and problem partitioning. The application layer is concerned with the user’s view of the network, such as formatting electronic mail messages (HyperDictionary 2003). An important application is DNS (Domain Name System) which translates host names into IP addresses. As TCP and IP provide the foundation to the connection, these protocols can be relatively simple. In the simplest case a WWW browser just says "GET /" and the server sends back the index page.

3.3.5 Security

There are two main provisions for Security: SSL (Secure Sockets Layer) and IPSec. SSL provides encryption for a TCP connection. First a digital certificate is presented by the server so that the client knows that the site really does match the domain name, and then all communication is encrypted to prevent eavesdropping. Most high-level protocols work the same over SSL, such as HTTPS which is just HTTP over SSL. IPSec is an alternative approach that provides encryption without the TCP layer; this is more useful in creating a Virtual Private Network (VPN).

David Llamas 18 BSc (Hons) Software Technology, 2004 3.4 Reverse Proxy Server The systems used in covert channels typically have to be fairly standard in their design. Thus an ordinary proxy server could be used as an intermediate server that sits between the client and the origin server. In order to get content from the origin server, the client sends a request to the proxy naming the origin server of the target. The proxy then requests the content from the origin server, and returns it to the client. The client must thus be specially configured to use the forward proxy to access other sites (Apache 2001). These proxies can either be forward-looking devices, or work in reverse. A forward proxy typically provides Internet access to internal clients that are otherwise restricted by a firewall, and can use caching to reduce network usage. A reverse proxy, by contrast, appears to the client just like an ordinary WWW server, where no special configuration on the client is necessary. The client thus makes ordinary requests for content in the name-space of the reverse proxy. The proxy then decides where to send these requests, and returns the content as if it was itself the originator (Apache 2001). A typical usage of a reverse proxy is to provide Internet users access to a server that is behind a firewall (Buchanan and Llamas 2004). With security, with control over the information transport mechanisms it is more important than ever to guarantee its correct operation under normal circumstances and also when attacks take place. It is also required to ensure that these transport mechanisms, which are typically the protocols used, are not used to hide information. An ordinary proxy server is thus useful for this as it concentrates on the traffic associated to the user, both incoming and outgoing, and allows the creation of different kinds of restriction rules, authentication rules, and so on. The use of forward proxy servers implies a specific configuration in on client-side, which, in some ways, assumes that the user is aware of their connection with external networks, and will be subject to some rules and controls. In a reverse proxy server, the client views the accessed device like an ordinary service (for example, a WWW server). Thus, no special configuration on the client is required. Depending on the kind of reverse proxy server, the returned content can be as if it was itself the origin. This project proposes a novel architecture for data hiding and detection through a Data Hiding Intelligent Agent (DHIA) which is embedded on a reverse proxy server (Figure 6 - Convert channels with data hiding on the proxy). The DHIA is responsible for hiding and detection activities, as well as prevention management and for the application of countermeasures to the use of protocols as a mechanism of transport of information. In the current security context, where almost anything can be considered as information, it is highly recommended the use of solutions based on stegano-components, which allow for hidden components that can work in a discrete mode (Buchanan and Llamas 2004). Although it is not the focus of this project, a novel technique known as Dynamic Reverse Proxy (DRP) is presented, where a dynamic connection is established between the user and the reverse proxy server, without requiring any configuration in the client-side. This link is totally independent and with its own properties and methods, and is in charge of the control and analysis of the traffic, and is always operating in a hiding way, and in a discrete mode.

David Llamas 19 BSc (Hons) Software Technology, 2004

ProxyProxy

F

F

PacketPacketPacketPacket

PacketPacket

PacketPacketPacketPacket

PacketPacket

AB

A modifies the datapackets by adding informationinto the unused parts of the packet

B uses a WWW browser to access and view page, but uses a packet reader to read the required field in the packet

Firewall treats the page as a valid one.

Figure 6 - Convert channels with data hiding on the proxy

3.5 Windows NT/2000 Network subsystem architecture A novel aspect of this project is the implementation of the covert channels on a Microsoft Windows™ platform. In all the Windows operating systems, the TCP/IP protocol is proprietary, and its source code is not accessible which means that the manipulation of the packets in any of the TCP/IP protocol suite is not possible from levels above the TCP/IP driver layer. This makes the use of these techniques in a Windows platform more complex.

3.5.1 Microsoft Windows NT/2000 network architecture components

The Microsoft Windows NT/2000 network architecture is composed of software components that provide networking abilities to the operating system. Network communication begins when an application program attempts to access resources on another computer, normally using a layered approach (such as using the network layer for network addressing, and the transport layer for data segmentation). Each layer is thus able to communicate with the layer immediately above and below itself (Microsoft Corporation 2000). From operation point-of-view, this layered approach is typically seen from two levels: • Kernel mode. This is where the processor executes all instructions, including

those designated privileged, and can access all of the memory. The mode provides a set of services that the rest of system can use. In Windows, it calls the Hardware Abstraction Layer (HAL) to handle any necessary platform-specific operations.

David Llamas 20 BSc (Hons) Software Technology, 2004

Figure 7 - Windows 2000 Network Architecture Diagram

• User mode. This is where an application can only access the memory to which the operating system has granted it permission. A user-mode program can ask the operating system to change the memory map, but, it is the Kernel mode which actually makes the change, if it decides the change is permissible.

Figure 7 - Windows 2000 Network Architecture Diagram shows the view of these modes and the affected drivers and components.

Kernel Mode

User Mode

(MAC)

(LLC)

RPC Providers Named Pipes

7 Application

6 Presentation

Network Interface Card(s)

Network Adapter Card Drivers

NDIS Interface STREAMS

Transport protocols

Transport Driver Interface

NetBios driver Redirector Servers Winsock Drv 5 Session

STREAMS

4 Transport

3 Network

2 Data Link

1. Physical

0. Media

David Llamas 21 BSc (Hons) Software Technology, 2004

3.5.2 Network traffic filtering technologies for Windows

The research has involved an extensive search for methods which could be used to implement a system which allowed a system to hook into the data transmissions. In Microsoft Windows this is not an easy task. In general there are several ways to network traffic filtering (Divine 2002) on a Windows system. For user-mode traffic filtering the methods are: • Winsock Layered Service Provider (LSP). This is method determines the

process that called Windows Sockets, such as for QOS (Quality Of Service), encryption of data streams, etc. Unfortunately, this approach cannot be used on routers, because packets are routed on the TCP/IP level (or even on MAC level).

• Windows 2000 Packet Filtering Interface. Windows 2000 provides API which can install a set of filter descriptors, which can be used by TCP/IP for packet filtering (PASS/DROP). However, rules for filtering are rather limited (pass/drop based on IP address and port information), and this approach can be only be used from Windows 2000 and onwards.

• Substitution of Winsock DLL. This approach mentioned only for security reasons, and is thus not recommend.

• Global hook of all dangerous functions. These might include starting with Windows sockets, DeviceIoControl, and so on, and can be done, but it may have an impact on overall system stability and security.

For a kernel-mode traffic filtering: • Kernel-mode sockets filter. This technology is applicable for Windows

NT/2000, and is based on the interception of all calls from msafd.dll (the lowest level user-mode Windows Sockets DLL) to the kernel-mode module afd.sys (the TDI [Transport Driver Interface]-client, which is a kernel-mode a part of Windows Sockets). This method is interesting, but its possibilities are no much wider, than LSP’s. Unfortunately, it has limited portability.

• TDI-filter driver. This technology can be implemented on a wide range of Windows platforms, but they vary in their implementation method. As for Windows NT/2000, in the case of TCP/IP filtering, it is necessary to intercept all calls directed to devices created by tcpip.sys driver.

• NDIS Intermediate Driver. NDIS Intermediate drivers introduced in NT 4.0 to allow developers to write packet capture drivers. These drivers can see all the network traffic on the system as they are placed between protocol drivers and network drivers. Many developers use NDIS Intermediate drivers to provide fault-tolerant and load-balancing options for NICs. Unfortunately, the driver must be digitally sign at Microsoft.

• Windows 2000 Filter-Hook Driver. The Filter-Hook Driver was introduced by Microsoft in Windows 2000 DDK (Driver Development Kit). It is not a new network driver class and it is only a way to extend IP Filter Driver to Windows 2000 functionality.

• NDIS Hooking Filter Driver. The technique is based on the interception of a subset of NDIS functions which allows it to trace the registration of all protocols installed in the operating system, and opening of network interfaces by them.

David Llamas 22 BSc (Hons) Software Technology, 2004 Among advantages of this is that it has an ease of installation and is transparent support of Dial-Up interfaces. This technique is the one that has been used to implement the Data Hiding Intelligent Agent (DHIA).

The Network Driver Interface Specification allows a hook into the network layer as Ethernet data frames are being passed to and from the Network Interface Card at the Windows Kernel mode. Through API’s, the interception of these packets can be finally done in the Windows User mode where most of the Windows software runs. A C DLL was written to intercept and modify outgoing packets and to allow information to be reported to a controlling application.

David Llamas 23 BSc (Hons) Software Technology, 2004

4 Literature Review

4.1 Introduction As it has been said before, the number of articles related to information hiding and covert channels and their techniques has been increasing. It has to be taken into account that covert channels techniques can be involved in anything based on a protocol, even out of the networking scope. In this section, covert channels are analysed within the scope of computer networks, by focusing on its relationship with the LAN environment, LAN protocols, the OSI network model and the TCP/IP protocol suite.

4.2 LAN Environments According to (Ahsan 2002), Local Area Network environments are susceptible of being used for creating covert channels. (Girling 1987) first analyzed covert channels in a network environment, where he focused on local area networks (LANs) in which have three obvious covert channels (two storage channels and one timing channel). This demonstrates the real examples of the bandwidth possibilities for simple covert channels in LANs. For a specific LAN environment, he introduced the notion of a wiretapper which monitors the activities of a specific transmitter on a LAN. The covertly communicating parties are the transmitter and the wiretapper. The covert information, according to Girling, can be communicated through any of the following obvious ways: • By observing the addresses as approached by the transmitter. If total number of

addresses, a sender can approach is 16, then there is a possibility of secret communication having 4 bits for the secret message. The author termed this possibility as covert storage channel as it depends on what is sent (i.e. which address is approached by the sender).

• In the same way, the other obvious storage covert channel would depend on the size of the frame sent by the sender. For the 256 possible sizes, the amount of covert information deciphered from one size of the frame would be of 8 bits. Again this scenario was termed as the covert storage channel.

• The third scenario presented is pertaining to the existence of covert timing channel. The time between the successive sends can be observed by the wiretapper to decipher for instance “0” for the odd time difference and “1” for the even time difference. The scenario transmits covert information through a “when-is-sent” strategy therefore termed as the timing covert channel.

The time to transmit a block of data is calculated as a function of software processing time, network speed, network block sizes and protocol overhead. Assuming blocks of various sizes are transmitted on the LAN, the software overhead is computed on average and novel time evaluation is used to estimate the bandwidth (capacity) of the covert channel. Furthermore, solutions for reducing the bandwidth of covert channels are also presented. The work paves the way for future research.

David Llamas 24 BSc (Hons) Software Technology, 2004 In particular, (Girling 1987) does not take into account the effect of the existence of covert channels on the overall network performance.

4.3 LAN Protocols Focusing the research on Local Area Network protocols, (Ahsan 2002) identifies what it has been done after (Girling 1987) investigations. In (Wolf 1989), Wolf presents results that can be regarded as a logical extension of (Girling 1987), but applied to LAN protocols. Wolf establishes the fact that encryption, the basic mechanism of LAN security, cannot ensure the proper blocking of unauthorized information via covert channels. The work points to the unused bandwidth possible for covert transmission in most commonly used LAN architecture standards such as IEEE 802.2, 802.3, 802.4, and 802.5. The focus is on LAN implementations opposed to the architecture itself. The work implies that covert channels can be expected in every system in which resources are shared. It also highlights the relationship between covert storage channels and protocol format, and the link between covert timing channels and protocol procedure elements taking into account the frame layouts of the LAN protocols. Covert storage channels utilize the reserved fields, pad fields and undefined fields of the frames. The fields identified, as means to covertly send information, can easily be detected through the implementation of automated mechanisms. Such mechanisms only monitor such fields, which would discard such frames utilizing these fields irrespective of their purpose.

4.4 Data Hiding in OSI Model In (Handel and Sandford 1996) the OSI (Open System Interconnection) network model (see Figure 8 - OSI network model) is taken as a basis of their development in which they characterize system elements having potential to be used for data hiding. Foolproof steganographic schemes are not devised. Rather, basic principles for data hiding in each of the seven OSI layers are established and identifies covert channel figures of merit such as (Ahsan 2002): • Detectability: covert channel must be measurable by the intended recipient only. • Indistinguishability: covert channel must lack identification; must appear as overt

channel. • Bandwidth: number of data hiding bits per channel use. Each layer has specific characteristics for hiding data (Handel and Sandford 1996).

4.4.1 Physical layer

The physical layer transmits data through the network’s communications channels. Clear to Send, Ready to Send (CTS/RTS) can be adjusted independently from the data rate (this method is limited to point to point connections). The collision detection system (Carrier Sense Multiple Access / Collision Detection CSMA/CD) in the Ethernet physical layer can also be modified to transmit hidden data by adjusting the control mechanism of collision.

David Llamas 25 BSc (Hons) Software Technology, 2004 4.4.2 Data Link layer

The data link layer shapes the network data structure. Frames are created containing data to be transmitted over physical circuits. In this case, unused portions of the frame can be used to store covert data. Hiding data is stored in the buffer, beginning at the end of the buffer and working toward the valid data. When the packet is transmitted, the entire buffer is exported, including the covert data.

4.4.3 Network layer The OSI network model The network layer is the internal delivery system. Fields from the header of the packets that work at this level can be manipulated to store covert data. For instance, the identification field of the IP protocol helps with re-assembly of packet data by remote routers and host systems. Its purpose is to give a unique value to packets so if fragmentation occurs along a route, they can be accurately re-assembled. This value it is generated at the origin, which means that the Identification field can be used to store a specific value to be passed to the other end. This will be extended in the next section.

Application

Presentation

Session

Transport

Network

Data-Link 4.4.4 Transport layer

The transport protocol is responsible for delivering data from the network to the correct process within the computer. In this case as well, the manipulation for storing covert data can be done by, for instance, by utilizing the unused data bits in the TCP header.

Physical

Figure 8 - OSI network model

4.4.5 Session layer

The session layer is the user’s access point to the network. Once there, users may have access to restricted resources of other users on the network, including servers that may require further authentication. Functionality at the session layer is archived through the use of a redirector, that determines if the requested function call can be processed by the local operating system, or processed on the remote system using a remote procedure calls (RPC). If a user can interact with a remote device, for instance, then a covert channel can be established by creating a protocol about its activity.

4.4.6 Presentation layer

The presentation layer handles the network’s interface to devices, such as printer, video displays, and the file system. The presentation layer is the proper location for encryption and compression processes, etc. In this case, the multimedia components of the presentation layer can act as hidden data transport mechanisms, for example, by replacing properties of audio and video information (that contains stochastic noise) by pseudo-random noise containing hidden data.

David Llamas 26 BSc (Hons) Software Technology, 2004 4.4.7 Application layer

The application layer is nearest the user. Users create applications utilizing system resources, including the network. Many of classical steganographic approaches can be used at the application level. What is originally done with pencil and paper can be done here. For example, a covert messaging system can be devised using word substitution by using an email system. As it can be seen, the OSI model reveals that a variety of locations exist for hiding data.

4.5 Covert Channels in the TCP/IP Protocol Suite As a protocol suite based on layers, the TCP/IP has a number of weaknesses that allow an attacker to leverage techniques in the form of covert channels to surreptitiously pass data in otherwise benign packets. Many techniques are based on encoding data in the protocol header.

Figure 9 - IP header v4 Some explanation and detailed methods will be illustrated next (Rowland 1996). Within each header there are multitudes of areas that are not used for normal transmission or are "optional" fields to be set as needed by the sender of the datagrams. An analysis of the areas of a typical IP header (see Figure 9 - IP header v4) that is either unused or optional reveals many possibilities where data can be stored and transmitted. The basis of the exploitation here relies in encoding ASCII values of the range 0-255 into the selected fields. Using this method it is possible to pass data between hosts in packets that appear to be initial connection requests, established data streams, or other intermediate steps. These packets can contain no actual data, or can contain data designed to look innocent. These packets can also contain forged source and destination IP addresses as well as forged source and destination ports. This can be

David Llamas 27 BSc (Hons) Software Technology, 2004 useful for tunnelling information past some types of packet filters. Additionally, forged packets can be used to initiate an anonymous TCP/IP "bounced packet network" whereby packets between systems can be relayed off legitimate sites to thwart tracking by sniffers and other network monitoring devices.

4.5.1 Method One - Manipulation of the IP Identification Field

The identification field of the IP protocol helps with re-assembly of packet data by remote routers and host systems. Its purpose is to give a unique value to packets so if fragmentation occurs along a route, they can be accurately re-assembled. The first encoding method simply replaces the IP identification field with the numerical ASCII representation of the character to be encoded. This allows for easy transmission to a remote host which simply reads the IP identification field and translates the encoded ASCII value to its printable counterpart.

4.5.2 Method Two - Initial Sequence Number Field

The Initial Sequence Number field (ISN) of the TCP/IP protocol suite enables a client to establish a reliable protocol negotiation with a remote server. As part of the negotiation process for TCP/IP, several steps are taken in what is commonly called a "three way handshake" as was described earlier. For our purposes the sequence number field serves as a perfect medium for transmitting clandestine data because of its size (a 32 bit number). In this light, there are a number of possible methods to use. The simplest is to generate the sequence number from our actual ASCII character we wish to have encoded.

4.5.3 Method Three - The TCP Acknowledge Sequence Number Field "Bounce"

This method relies upon basic spoofing of IP addresses to enable a sending machine to "bounce" a packet of information off of a remote site and have that site return the packet to the real destination address. This has the benefit of concealing the sender of the packet as it appears to come from the "bounce" host. This method could be used to set up an anonymous one-way communication network that would be difficult to detect especially if the bounce server is very busy. This method relies on the characteristic of TCP/IP where the destination server responds to an initial connect request (SYN packet) with a SYN/ACK packet containing the original initial sequence number plus one (ISN+1).

As discussed above, other protocols can be used in a similar manner and in some cases may provide a more reliable channel of data transmission as the packet can hold much more data.

4.5.4 Method Four – Through the packet sorting (IPSec)

This method presented by (Ahsan 2002) deals with the use of packet ordering to convey covert information. The possible ways to arrange objects in a set is surprisingly complex and offers a correspondingly large opportunity for steganography. Changing the order of the packets requires no change in the packet content (i.e. the payload and the headers are not affected).

David Llamas 28 BSc (Hons) Software Technology, 2004 Therefore no major modifications are expected either in the protocol definition/design or in the overall system in order to implement a data-hiding scenario. The sorting/resorting process holds a surprisingly large amount of information. Based on these facts, data hiding feasibility is explored in the TCP/IP protocol based on packet sorting and resorting processes at source and destination, respectively. The packet sorting and resorting processes require some reference in order to relate packet numbers to their actual order. The natural packet ordering is needed so that the stego packet ordering (sorting) can be undone (resorting). This reference is not available at the transport layer using TCP. Sequence number field and acknowledgement number field point to the number of octets of data and are not directly related to the packet number. Moreover, the data packetised at the transport layer can be broken down into fragments at the Internet layer and would further complicate the notion of a packet order. Similarly, if we look at the IP, the Identification field (16 bit) of the IPv4 header, as mentioned in the previous section, is unique to the specific source-destination and protocol fields and cannot be associated with a packet sequencing mechanism. In contrast, within the IPSec environment, the two protocol headers, ESP and AH headers provide a 32-bit sequence number field. The primary aim of this field is to detect replay attacks; hence it is directly related to packet numbers. Anti-replay mechanism is intended to determine whether a packet received is a duplicate or not. When a Security Association (SA) is first established for a flow of data, this field is set to zero. The sequence number of each packet under this SA is incremented by 1 during outbound processing. Thus, this replay protection identifies a natural ordering of the packet stream that can be used for packet sorting and resorting processes at both ends. The term IPSec refers to a set of mechanisms designed to protect the traffic at the IP level, suited for both versions of IP i.e. IPv4 and IPv6. The security services afforded by this security protocol are: • Connectionless Integrity, • Data origin authentication • Protection against replays and • Confidentiality IPSec implementation is optional in IPv4. It is however, mandatory for any implementation of IPv6, therefore can rightly be regarded as the security architecture for the current as well as the future IP traffic. The kind of security services it offers made this set of mechanisms an industry standard in December 1998. As mentioned above, IPSec fulfills the following: • Encryption and/or Authentication of all traffic at IP level. • Supports all varied distributed applications. Thus remote log on, Client/Server,

email, file transfer, Web access can be secured.

David Llamas 29 BSc (Hons) Software Technology, 2004 The following are relevant features of IPSec: • IPSec is meant for off site traffic. Therefore traffic within a company or work

group does not incur the overhead of security related processing. • IPSec in a firewall is resistant to by-pass if all incoming traffic must use IPSec

and firewall is the only means of entrance from the Internet into the organization. • The IPSec implementation in a firewall or router or end system, requires no

change in the software on a user or server system. • The architecture does not need keys specific to users. • IPSec is useful for off site workers and for setting up a secure virtual sub network

within an organization for sensitive applications. Several possible ways to utilize IPSec are outlined: • IPSec protocols operate in networking devices like routers or firewalls that

connect each LAN to the outside world. These routers or firewalls (IPSec networking device) will typically encrypt and compress all traffic going into the WAN and decrypt and decompress traffic coming from the WAN. The above operations are transparent to work stations and servers on the LAN.

• For individual users who dial into the WAN (connected directly), they must implement the IPSec protocols to ensure security.

IPSec provides security services at the IP layer by: • Enabling a system to select required security protocols • Determining the algorithms to use for the services • Putting in place any cryptographic keys required to provide the requested services The following are a list of key security technologies enabling IPSec: • The Diffie Hellman key exchange to deliver keys between systems on the public

network. • Public key cryptography for signing the Diffie Hellman exchanges, which

guarantees both sides of the negotiation. • Support for standard keyed hash algorithms for authenticating packets. The

standard authenticators are (RFC 2403 1996) and (RFC 2404 1996). • Support for a variety of encryption algorithms. Mandatory to implement cipher is

DES-CBC (with an explicit Initialization Vector) (RFC 2405 2000). After the standardization of AES (Advanced Encryption Standard) by the US Government in Fall 2001, the current status of the standard cipher is not yet known.

• Support for X.509 digital certificates for validating public keys. The objectives of IPSec are met through the use of two security mechanisms, the AH (Authentication header) and the ESP (Encapsulating Security Payload). Authentication Header (AH) is conceived to ensure integrity and authentication of IP datagrams, without data encryption i.e. without confidentiality. AH adds an additional header to the traditional IP datagram; this header makes it possible for the

David Llamas 30 BSc (Hons) Software Technology, 2004 receiver to check the authenticity of the data included in the datagram. The header can be shown as per Figure 10 - The AH header.

Figure 10 - The AH header Encapsulating Security Payload (ESP) is designed for ensuring confidentiality, but can also provide data authenticity. It generates from a traditional IP datagram, a new datagram having additional ESP header, in which the data and eventually the original header are encrypted. The ESP header is shown in Figure 11 - The ESP header.

Figure 11 - The ESP header These protocols can be made to operate in either of the following modes (Doraswamy and Harkins 1999):

David Llamas 31 BSc (Hons) Software Technology, 2004 Transport Mode: In transport mode, AH and ESP protect the transport header. In this mode, AH and ESP intercept the packets flowing from the transport layer into the network layer and provide the configured security. Tunnel Mode: IPSec in tunnel mode is normally used when the ultimate destination of the packet is different from the security termination point. Tunnel mode, by adding an additional IP header, protects the complete IP datagram i.e. data with TCP header and the IP header. Security Association (SA) is a one way connection that affords security services to the traffic carried by it. A SA is unidirectional, therefore a typical bi-directional communication requires two SAs. The security services are provided either by the use of either AH or ESP (not both). If both of them are applied to the traffic in question, then two (or more) SAs are expected to protect the traffic. Such a situation would be termed as security bundle. Each security association is uniquely identified by the following triple: • Packet’s Destination Address • Security Protocol Identifier (AH or ESP) and • Security Parameter Index (SPI); A SPI is a 32 bit block transmitted in clear in the

header of each exchanged packet; the receiver chooses it. Security Association Database (SADB); IPSec stores active security associations in a database called security association database. It contains all the parameters related to each SA and is consulted to know how to treat each received or sent packet. The SADB is maintained with SAs either manually or via an automatic key management system such as IKE (Internet Key Exchange). Security Policy Database (SPD); IPSec policy is maintained in the security policy database. Each entry of the SPD defines the traffic to be protected, how to protect it and with whom the protection is shared. For each packet entering or leaving the IP stack, the SPD must be consulted for the possible applications of security. Let’s continue with the explanation of the method. The Packet Sorting / Resorting technique employs packet ordering to convey covert information. As mentioned earlier, this does not require changes either in the header or in the process of the system. The suggested packet sorting technique, as mentioned earlier, utilizes the sequence number field of AH and ESP headers (IPSec Protocols). Before discussing the technique, let consider three packets generated from an IPSec implemented node having packet-sorting algorithm incorporated. Figure 12 - Packets generated from IPSec implemented node having sorted sequence numbers shows these packets, only indicating their sequence numbers (original and sorted both):

David Llamas 32 BSc (Hons) Software Technology, 2004

Figure 12 - Packets generated from IPSec implemented node having sorted

sequence numbers Here there are two types of ordering: • Original Ordering; the sequence numbers assigned to the packets by the standard

IPSec process. • Sorted Ordering; the sequence numbers assigned to the packets by any “structure”

which would sort the original ordering by any set “criteria”. The covert information intended to be communicated is the difference between these two orderings. Referring to Figure 12 - Packets generated from IPSec implemented node having sorted sequence numbers, for three packets, there can be six possible permutations (i.e. 123, 132, 231, 213, 321, 312). Generally speaking, the packet-sorting algorithm generates specific sorted sequence of packets from six possible permutations based on some structure (as defined in the algorithm, below). Figure 12 - Packets generated from IPSec implemented node having sorted sequence numbers shows the generated packets, from left to right, having sorted sequence as 132 against the original 123. These packets traverse the network and reach the destination bearing the same numbers. The packet resorting process at the destination node, recovers the original sequence from the received sorted sequence based on some “structure”. The difference between the original sequence and the sorted sequence carries the covert information for the destination. Ideally speaking, for packet sequence comprising three packets, there would be six possible covert messages bearing covert information of 3 bits, as expressed in Figure 10 - The AH header. This is the basic concept of packet sorting and how this process would transmit covert information, and it has been identified the reference, providing the original sequence of packets which would be sorted according to a “structure”.

David Llamas 33 BSc (Hons) Software Technology, 2004

5 Design

5.1 Introduction This section explains the proposed architecture for the management of hidden information, as well as the mechanism for its monitoring and detection, prevention and countermeasures activation is the DHIA which is embedded in a Reverse Proxy Server. It is specified as well the application, classes, member functions, member variables and structures that have been used for building the whole prototype.

5.2 System specification As it has been said, four main pieces of software have been developed for this project: A Reverse Proxy Server with an embedded Data Hiding Intelligent Agent, a Data Hiding Viewer and a Packet Sniffer to analyse the network traffic and some specific aspects of the covert channel technique.While the user is navigating around a web site through the Reverse Proxy Server, the Data Hiding Viewer, on the client side, shows in a separated window the hidden data that is sent by the Data Hiding Intelligent Agent embedded in the Reverse Proxy Server. The Packet Sniffer shows the content of all IP packets. This prototype will be focus on the manipulation of the IP Identification field technique on the IP header version 4 (Rowland 1996).

Figure 13 – Components Data Flow of the reverse proxy system At present, the designed prototype manages requests at the full range of session/application layer protocols, such as HTTP, FTP, TELNET, etc. All protocol channels are implemented. The user thus thinks that they are connecting to a WWW server and navigates on it, and is transparent for the navigation.

David Llamas 34 BSc (Hons) Software Technology, 2004 Figure 13 – Components Data Flow of the reverse proxy system outlines the mechanics of such a system, which are: • Reverse Proxy Server. • Embedded DHIA. The DHIA component must be tested in different location

within the scenario where it should operate, in order to find its most convenient situation, taking also into account the Dynamic Reverse Proxy technique.

• Data Hiding Viewer. This is run on the client side and shows the hidden data sent by the DHIA embedded in the Reverse Proxy Server.

The system implements covert communication through the manipulation of the Identification field of the IP protocol header (Rowland 1996). In this case, it is implemented using the first byte as sequencer, and the second byte to host the character in ASCII code (multiple packets will thus contains the overall message). The Identification field of the IP protocol header helps with the re-assembly of packet data by remote routers and host systems. Its purpose is to give a unique value to packets, so, if fragmentation occurs along a route, they can be accurately re-assembled (see Figure 14 - Network packets).

Figure 14 - Network packets

David Llamas 35 BSc (Hons) Software Technology, 2004 The incoming packets processed by the software proposed for this project, process the packets at Ethernet level. From that point, the IP packet is extracted (see Figure 9 - IP header v4).

5.3 Development methodology The software developed for this Honours Project has been created following the basic concepts of Waterfall Methodology and Rapid Application Development (RAD) methodology, by using the defined sections from the former, and the evolutionary developing methodology and the early prototyping and reiterative testing of designs from the second.

Figure 15 - Spiral model The main reason of doing that is because the project was well defined from the beginning. Based on this evolutionary developing method, the purpose of the individual elements could be well defined according the temporary implementation results, as well as coordinated and synchronised with the system. Figure 15 - Spiral model shows an approach to this methodology and its life-cycle.

David Llamas 36 BSc (Hons) Software Technology, 2004 The Spiral Model (Boehm 1988) can be summarised as follows: • Emphasis is on the problematic areas of software development & importantly the

use of an iterative non-linear approach to projects. • Basically, the idea is evolutionary development, using the waterfall model for

each step; it's intended to help manage risks. • Don't define in detail the entire system at first. • The developers should only define the highest priority features. • Define and implement those, then get feedback from users/customers (such

feedback distinguishes "evolutionary" from "incremental" development). • With this knowledge, they should then go back to define and implement more

features in smaller chunks.

5.4 Classes, global functions, variables and structures In this section the global functions, variables and structures of each application involved in this project is shown. Because not a lot of object orientation development has been needed, the modules are shown in structural view instead of UML representation. See appendixes for seeing the source code. These are the meanings of the icons:

- Application

- Class

- Method or Member function

- Member variables

- Structures

David Llamas 37 BSc (Hons) Software Technology, 2004 CovertAgent

David Llamas 38 BSc (Hons) Software Technology, 2004 CovertController

David Llamas 39 BSc (Hons) Software Technology, 2004 CovertViewer

David Llamas 40 BSc (Hons) Software Technology, 2004 Kernel

ReverseProxyServer

David Llamas 41 BSc (Hons) Software Technology, 2004 Packet Sniffer

David Llamas 42 BSc (Hons) Software Technology, 2004 Packet Sniffer (cont)

David Llamas 43 BSc (Hons) Software Technology, 2004

6 Implementation The controlling application was written with Microsoft Visual C#.NET 1.1. Due to security in Windows, the .NET Framework raw sockets and the Berkeley specification are not fully supported. Thus modifying packets at this level is not possible, as the .NET Framework and the Windows operating system will correct any faults it perceives in the header or ignores the header completely and treats it as the payload. This is undesirable behaviour for a system which requires direct hooks into the data traffic flow. For this reason, a Covert Agent based on NDisAPI driver has been developed in C++.

6.1 Covert Agent

Figure 16 – from Covert Agent

David Llamas 44 BSc (Hons) Software Technology, 2004 The code that is shown on Figure 16 – from Covert Agent, reads the packets that are passing through the network adapter in either direction. Incoming packets are ignored and passed straight through, however out going IP packets are checked against the filter criteria. The agent has a list of clients that are registered to receive covert messages and it will modify the packet that is destined for any of these clients. If the destination of the packet is not registered, but the port number matches the port for default messages then a new client registration is made and the packet is modified.

Figure 17 – from Covert Agent

The code shown in Figure 17 – from Covert Agent, modifies a packet. The function takes a pointer to a covert information structure that contains the details for the covert message for the current client. There is also a parameter that points to the packet to be modified. The packet’s identification element is replaces with the covert information. In the high order byte is placed the offset of the character, this ensures that while the message is being sent the ID field in the IP Header is always ascending making it look like the packet is coming from a busy server. The low order byte of the ID field contains a single character from the covert message. The covert information structure is also updated by incrementing the offset so that the next time a packet is modified the next character in the message is set. Finally a datastamp is applied to the covert information structure. This is because as new clients are registered the array that holds details on the clients will become full and a “last accessed-first out” algorithm is in place to determine which of the clients drops off the list to make way for a new client registration.

David Llamas 45 BSc (Hons) Software Technology, 2004 6.2 Covert Controller

Figure 18 - from Covert Controller Figure 18 - from Covert Controller is part of the packet processing on the Covert Controller. In a normal .NET application a callback method can be set up when the application enters idle time. Nortmally this would perform some low priority task and return control to the built in message pump, however there is no mechanism to repeatedly call this callback method. Here, the callback method repeatedly calls the DoIdleTimeProcessing which returns false when it doesn’t need to be called again, and during each loop the events are processes as normal so that the application will respond normally to events, such as the user pressing the stop button, or closing the application. The DoIdleTimeProcessing calls into the CovertAgent to process packets for 1000 milliseconds before returning control to the .NET application.

David Llamas 46 BSc (Hons) Software Technology, 2004

6.3 Reverse Proxy Server

Figure 19 - from Reverse Proxy Server

When the proxy receives a request (see Figure 19 - from Reverse Proxy Server), it needs to forward it on to the relevant server; the above method takes the HTTP request, locates the host entry in the header and replaces it with the real IP and port. This can then be used to form the request to the actual server.

David Llamas 47 BSc (Hons) Software Technology, 2004

6.4 Covert Viewer

Figure 20 – from Covert Viewer Figure 20 – from Covert Viewer takes the covert information and displays it on the form. The form displays the information as a hexadecimal display and of the characters. Each of these is a set of 16 label controls that contain 16 characters. When a new covert character is received the existing string in the control is modified by replacing the relevant character with the covert character.

6.5 Packet Sniffer

Figure 21 - from Packet Sniffer The code shown in Figure 21 - from Packet Sniffer is used in both the sniffer and the covert viewer. This sets the socket option “Receive All” which allows the socket to receive all packets. This is necessary as the socket will not be the primary target of the communication and is only a passive participant in the communication.

David Llamas 48 BSc (Hons) Software Technology, 2004 The ‘laboratory’, that it has been used for developing, testing and getting results, looks like:

Figure 22 – Mini-laboratory

Web pages come originally from MULL Server (192.168.1.17) but, in fact, they are requested by the Reverse Proxy Server and sent to you as if it was itself the origin (see Figure 22 – Mini-laboratory). For getting results, extra hubs and a laptop were added at specific segment, according the purpose of the test.

David Llamas 49 BSc (Hons) Software Technology, 2004

7 Results Results are explained in this section by showing some screenshots of the tools that have been developed for monitoring the network traffic packets, for seen the covert messages, for managing them and so on. It also includes results related to the capacity estimation, performance and payload..

7.1 Monitoring and detection The monitoring is performed using the common method of placing the network card in promiscuous mode and sniffing the network traffic. It is well-known that covert channels, as well as the steganographical techniques, have a high level of difficulty relating to detection issues. The methods designed by the DHIA are those related with the detection of sequences in the fields of the headings of the different packets that propagate in the network. Other techniques such as the extra traffic payload sensoring and the analysis of encrypted content or the creation of packets ad-hoc have no effect. For Monitoring, a special version of Packet Network Sniffer has been developed (see Figure 23 - Packet Sniffer):

Figure 23 - Packet Sniffer

David Llamas 50 BSc (Hons) Software Technology, 2004 This version shows the covert index and the covert character values. From them, the packet identification field value is calculated and, as it can be seen, it appears as a standard value for this field. CovertIndex field is taken from the sequencer field from the TCP header and it represents the first byte of the identification field (which has 16 bits length). The second byte has the ASCII code of the character that has to be stored. Both values are summed for the final value of the packet identification field.

Figure 24 - Covert Viewer The Covert Viewer (see Figure 24 - Covert Viewer) is the application that shows the covert message while you are navigating using your favourite Internet browser. In this case it can be seen the message “This is a covert message from the heart of the universe … 8-D”. The Covert Controller (see Figure 25 - Covert Controller) is in the server side interacting with the Data Hiding Intelligent Agent, which is embedded in the Reverse Proxy Server. From that place, the covert messages can be managed through a XML file (see Figure 26 - Covert Controller XML file). The Covert Controller can send general message or a specific one if the remote IP address is specified. All outgoing packets to that address will be manipulated to store the covert message. Apart from that, as an advanced feature, it can be specified as well to which port the connection has to be established for sending a specific covert message (see Figure 26 - Covert Controller XML file for further details). To ensure that the performance would be good enough, the server that has been used for this implementation is a very old PC Pentium 166 Mhz with 256 Mb RAM, 2 network cards and 8 Gb HD. More details are given below.

David Llamas 51 BSc (Hons) Software Technology, 2004

Figure 25 - Covert Controller

David Llamas 52 BSc (Hons) Software Technology, 2004 Figure 26 - Covert Controller XML file

David Llamas 53 BSc (Hons) Software Technology, 2004

7.2 Prevention and Countermeasures The prevention and countermeasures for the communication based on covert channels will depend on the techniques from which protection is required. The use of the reverse proxy server as a middleware element implies a scenario based on a minimum of two connections. This is where one is done by the user from his computer to the reverse proxy server in a transparent way, and the other is between the reverse proxy

d the WWW server which the user wants to navigate in. This system allows sy control of the packets when they go from one segment to another, and

v e ch will automatically mean the elim ld will not be use n his is because the n h on interconnection system

server anor an eaf

in olv s the overwriting of the Identification field, whiination of the original content of the field. The Identification fie

kets. Td i communications which do not have fragmented data pac wi dow size of the TCP connection is normally large enoug

s

7.3 Capacity, Performance and Payload

According (Bender, Gruhl et al. icat g nt l e

ta rate. Thes rm the ta-hiding problem space 27 ng e). The nt ween nd or the ch

the data are immune to attack or transformations that occur to the host signal through normal usage, e.g., compression, resampling, etc. The more data to be hidden, e.g., a caption for a photograph, the less secure the encoding. The less data to be hidden, e.g., a watermark, the more secure the encoding.

Figure 27 - Data-Hiding problem space In this section, both types of network packets (normal network packets and stego network packets) are messured to get some results about the difference in capacity of network traffic. (Ahsan 2002) concludes that the capacity is one of the most significant performance measures of covert channels. The capacity estimation relates the cost of data hiding,

to process stegano-network ads with the total time to transmit a stego-network

1996), each applrequires a differe

ion of data hidinevel of resistanc

to modification and a different embedded da e fotheoretical da

Figure(see problem spac

- D -Hidire is an inhere

ata

trade-off bet bandwidth a“robustness,” degree to whi

both in terms of the time taken by the TCP/IP software packet and protocol header overhe

David Llamas 54 BSc (Hons) Software Technology, 2004 packet from a source. Covert channel capacity is the number of bits used for data hiding per packet which can be evaluated from the total time taken to transmit a stego network packet from the network layer. The capacity estimation would be equivalent to (Girling 1987) estimation, as the scenario presented in this Honours Project is also applicable to a LAN environment. Based on this, capacity can be estimated as follows:

Where:

• T = Time to transmit a block of data (seconds) • S = Time used in software; independent of block size (seconds) • B = Size of transmitted block or frame [Ethernet] (bytes) • N = Size of network protocol overhead (bytes) • V = Network Speed (bits per second)

Surprisingly the results are proportionally quite similar to the ones obtained by irling 1987), as it can be seen in Table 2 - Capacity estimation. A graphic has en created for improving the view (see Figure 28 - Capacity estimation)

Table 2 - Capacity estimation

(Gbe

0100200300400500600700

Bits / sec

1 2 3

Type of netw ork

Girling's

This project

Figure 28 - Capacity estimation

Network Speed (V) Frame Size (B) Capacity (Girling 1987)

Capacity This Project

10 Mbps 64 octets 113 bits / sec X 100 Mbps 64 octets 114 bits / sec X 1000 Mbps 64 octets 114 bits / sec X

10 Mbps 1518 octets 100 bits / sec 566 bits / sec 100 Mbps 1518 octets 113 bits / sec 669 bits / sec 1000 Mbps 1518 octets 114 bits / sec 679 bits / sec

David Llamas 55 BSc (Hons) Software Technology, 2004

e performance of the Honours Project offers

results change as well. (Girling 1987) also

As it can be seen in Table 2 - Capacity estimation, the impact of the software that has to be used for manipulating the header, affects a lot th

eneration of network packets. The software proposed in this gbetter results in this aspect, taking into account as well that, despite it has been used a very old PC Pentium 166 Mhz with 256 Mb RAM, this is better than the one used by (Girling 1987), despite the analysis have to be focused in the proportionality of the results within the different scenarios. It has been notice as well that depending on the echnique used for this purpose, thet

concludes that channel capacity decreases with the increase in the size of the frame. Another interesting result that has been analysed is that the network speed does not make considerable increase in the covert channel capacity. .

David Llamas 56 BSc (Hons) Software Technology, 2004

red

d such as applications where video and

of acting in the most

8 Conclusions and future work Modern information systems provide a very rich environment for hiding data. The lexibility intentionally designed into network communications using the layef

model makes identifying and exploiting covert channels easier than for stand-alone systems (Handel and Sandford 1996). This work has shown that, applications that can operate in a middleware location and in a discrete mode, such as the Reverse Proxy Server presented in this Honours Project, can be essential components involved in the monitoring, detection and prevention of the use of information hiding techniques. The middleware location offers the possibility of observing the communication between the two parts. It is obvious that the existence of these two parts is inherent to any communication process hence, being between these two parts it is the most adequate position for the analysis of that communication. About doing this analysis in discrete mode, we can say that it is also essential as, if the parts detect that the communication is being observed and / or altered, the parts could change the original

eaning of the communication. m As explained through this Honours Project as well as demonstrated in the implementation, the Reverse Proxy Server it is a highly strategic tool as can interact with both sides: the users and the content servers. In the weaknesses side, the Reverse Proxy Server should be the only connection point between these parts as, if not, would allow the user to reach the conclusion that the results obtained through the proxy server differ from those obtained connecting directly with the content server. Those results are based on parameters such as the answer timing, the packets route and so on. Another weak point of the Reverse Proxy Server, which has been identified through the test results, is that the time that the component needs to manipulate the packets where the covert message is injected can be too long to be used in ommunications where high speed is requirec

audio are used through the network. Because of this, and as an experimental concept, the word intelligent was added to the agent in charge of the information hiding management, which is called Data Hiding Intelligent Agent. This indicates that it is essential to give some artificial intelligent to these kind of operations as this component should only act when the performance metrics where the appropriate ones. It is well known that in order to observe what takes place in a process and obtain metrics of the way it works, the process itself is affected somehow. Due to the importance that the interception it is not identified by the parts, the agent in charge of he information hiding management needs some capacityt

optimized way within the established parameters so it is not identified. Everything explained above would be part of a scenario where a corporation, company or association is affected by these techniques. But things would be very different if the scenario were one where someone wants to use these tools for the direct covert communication with other people. This would be the case of a web server with apparently innocuous content that, in order to be accessed requires going through the Reverse Proxy Server. The final user that deliberately wants to receive the

David Llamas 57 BSc (Hons) Software Technology, 2004

he scope of this Honours Project also defines the problems that the Windows

e ersonal believe that there are better techniques that can improve the obtained results

tegrated in a network system y plugging the network cable from both sides into it. In this case, the Microsoft

ture works could be one related to the manipulation of the TCP packet header. For example, the TCP

covert message would not be affected at all by the time required by the Reverse Proxy Server and the Data Intelligent Agent. In this case the weak points would almost not exist in the covert message communicating system, so future work should include research in identification and detection of the use of these techniques, otherwise the use of these techniques on peer-to-peer scenarios would difficultly be detectable. T2000/NT architecture causes in covert channel development, and proposed the use of the NDIS Hooking Filter Driver. Different aspects of working with this proprietary platform such as packet retry control, the effects of having to install a driver, the massive use of this operating system, etc., will be aspects to develop in the future, but that need to be taken into account as, as the Microsoft Windows TCP/IP driver source code it is not available, the only way of ensuring that the system works it is through the control of its behaviour. Also it is concluded that, although it has been possible the implementation of this Honours Project in Microsoft Windows platforms, the low performance level suggests future research in this area in order to obtain better speed metrics. In this thought would be included all the scenarios where these techniques could not be implemented by modifying directly the driver source code. I have thpunder Microsoft Windows, and this would be one of the future work areas. Due to this conclusion a proposal for future research would be the design and implementation of a similar solution using the real-time systems methodology, this means, by using a hardware device that could integrate the functionality of the Reverse Proxy Server and the Data Hiding Intelligent Agent. This hardware device should be located at any place between the user and the content server where its traffic could be seen. This hardware device would be inbWindows would not be involved and the analysis and manipulation of the traffic would be done through a program, supposedly developed in C, and integrated in the hardware device, which without any doubt would increase the performance and would be operating system platform independent. Future work would be continuing in performing more extensive experiments that will involve the inclusion of new covert channel techniques associated to the manipulation of the heading fields of any of the TCP/IP protocol suite (or other techniques that we are currently investigating such as the use of the TTL field), the implementation of the techniques specified in this scenario in a hardware device, an extension to the Reverse Proxy Server to manage requests at different levels and with better performance under proprietary platforms and the effect of all this under new versions of any of the protocols of the TCP/IP protocol suite, such as IP version 6. Talking about other protocols in the TCP/IP protocol suite, fudheader has a 6 bit field labelled as code bits (URG, ACK, PSH, RST, SYN, FIN). These bits determine the purpose and content of the TCP segment; these 6 bits tell a network how to interpret other fields in the header. This fields allows 64 potential combinations, of which only 29 have a meaning. Managing this redundancy, a covert channel could be done through the TCP packet header. Protocols such as the IGMP

David Llamas 58 BSc (Hons) Software Technology, 2004

ived from this Honours Project would be the impact nd use of these techniques in the running of our society. Our society is prepared to

ply could no be detected as can not be entified. As I usually comment with my colleagues, “there is no worst attack than e one that can not be identified”. I have observed that in the actual literature about ese matters, there is an attempt to involve methodology designed for cryptography

to detect the use of steganographical or covert channels techniques. In my opinion, I think that all cryptography related matters should be taken into account and, probably, in some cases, the use of some of the proposals would be of help in the information hiding field, but I also believe that it is required to do specific research in this area. It has always been said that these advanced information hiding techniques have, and are used, by terrorist groups, criminal bands, military organisations and so on. The nature of the main groups interested in the use of these techniques it has a significant importance in the society, so this means that this matter has to be taken into account. The main problem of information hiding, specifically in the steganography and covert channels, is that any communication apparently innocuous can contain a covert message. This makes society highly vulnerable, especially society nowadays where the exchange of information reaches very high volumes. In this current society, laws for the control of that information and the security of its custody are being developed. Even though if that laws and controls are very advanced, the actual techniques for covert channels communication can break the final aim of them. I will try to explain this by this example: A secretary needs the details of a customer. To obtain this she accesses the database through a software application. The data is stored in an encrypted way in the database and are unencrypted by the software application. The database and the software application are in the secretary PC. This is not connected to any type of wired or wireless network. The monitor is facing to the wall so, what is displayed can not be seen by anyone else (I am specifying this because very often confidential information is obtained by seeing what the monitor displays through a window or from another desk using a mini-telescope). The secretary’s computer is therefore aisled, and the monitor away from undesired viewers. How could we get the information that the secretary is viewing by using a system that appears innocuous?. There are probably several answers to this question but the one I have been working in is a middleware component that interacts very close to the hardware abstract layer (HAL in Windows Microsoft Platforms) and is capable of modifying slightly the frequency that the video card produces to the monitor. This is inspired in the spread spectrum techniques, another great field that can be related to the Information Hiding.

(Internet Group Management Protocol) and the ICMP (Internet Control Message Protocol) are also possible candidates to be used for covert communication through the manipulation of their headers. Other examples can take place in other layers such as the application layer. The commonly used HTTP protocol has multiple possibilities for its structure to be used as a covert channel as well, as many parameters of this header are used in a way that creates spaces for storing extra information. Other important conclusions derareact to the detection of a problem but things become more complicated if that problem not only it is not detected but simidthth

David Llamas 59 BSc (Hons) Software Technology, 2004 Components from the monitor produce different low level noise depending on the

hich is called high-frequency background noise. This f sending covert messages that can be received within

e local area around the secretary by using an appropriate frequency scanner device.

Hiding for Microsoft Windows Platforms.

As it c is an interesting area for research where I would like to go further.

frequency that is working, wdifference gives the chance othThat middleware component can be, in a more sophisticated scenario, the display driver itself as it would be possible as well that the Reverse Proxy Server and the Data

Intelligent Agent would be implemented in a TCP/IP clone driver

an be seen, this

David Llamas 60 BSc (Hons) Software Technology, 2004

9 R

Ahsan, sis and Data Hiding in TCP/IP. Department

eferences

K. (2002). Covert Channel Analyof Electrical and Computer Engineering. Toronto, University of Toronto.

Al-Ahmad, H. A. and M. A.-M. Mualla Information Hiding: Steganography and

Anderson, R. (1996). Lecture Notes in Computer Science

Watermarking.

.Information Hiding: First

ttpd.apache.org/docs

International Workshop, Cambridge.

Apache (2001). HTTP Server documentation. v. 1.3, http://h .

Bender, W., D. Gruhl, et al. (1996). "Techniques for Data Hiding." IBM Systems Journal 35.

Berg, S. (1998). Glossary of Computer Security Terms. Technical Report NCSC-TG-004, National Computer Security Centre.

Boehm del of Software Development and , B. W. (1988). A Spiral MoEnhancement.5th international software process workshop, 61-72, IEEE

th

Computer Society Press.

Buchanan, W. and D. Llamas (2004). Covert Channel Analysis and Detection wiReverse Proxy Servers using Microsoft Windows.The 3rd European Conference on Information Warfare and Security, Royal Holloway, University

deVivo, M., G. O. deVivo, et al. (1999). "Internet Vulnerabilities Related to TCP/IP." ommunication Review

of London, UK, Management Centre International Limited.

SIGCOMM Computer C 29.

Divine, a and Packet Filtering T. F. (2002). Windows Network Dat . I. Printing Communications Assoc.

Dorasw 1999). IPSec; The New Security Standard for the amy, N. and D. Harkins (Internet, Intranets and Virtual Private Networks., Prentice Hall.

Girling, C. G. (1987). Covert Channels in LAN`s.IEEE Transactions on Software Engineering, 292-296.

Gligor, V. D. (1993). A Guide to understanding Covert Channel Analysis of Trusted Systems, National Computer Security Centre.

David Llamas 61 BSc (Hons) Software Technology, 2004

I ModelHandel, T. G. and M. T. Sandford (1996). Hiding Data in OS .Information Hiding: First International Workshop, Cambridge, Springer.

Huang, C.-H. (2002). Digital Watermarking. Communication and Multimedia Lab.Department of CSIE, NTU.

HyperDictionary (2003). HyperDictionary.

Johnson, N. F. and S. Jajodia (1998). "Exploring Steganography: Seeing the Unseen." IEEE Computer Feb 1998: 26-34.

Johnston, P. (2003). The TCP/IP protocol suite. http://pajhome.org.uk.

Kahn, D. (1996). The Code Breakers New York, Scribner.

Katzen hiding techniques for beisser, S. and F. A. P. Petitcolas (2000). Informationsteganography and digital watermarking / Stefan Katzenbeisser, Fabien A.P. Petitcolas, editors. Artech House computer security series Boston, Artech House.

Lampson, W. (1973). "A note on the Confinement Problem.Communications of the ACM." (16(10)): 613-615.

Lawson, A. and A. Varey (2001). Project Handbook, Napier University.

Lipner, S. B. (1975). "A note on the Confinement Problem." Operating Systems Review, 9(5): 192-196.

McHugh, J. (1995). "Covert Channel Analysis." Handbook for the Computer Security Certification of Trusted Systems.

Microsoft Corporation (2000). http://www.microsoft.com/resources/documentation/windows/2000/server/reskit/en-us/tcpip/part4/tcpappb.mspx.

Petitcolas, F., R. Anderson, et al. (1999). Information Hiding - A survey.Proceedings of the IEEE, 1062-1078.

Pfitzmann, B. (1996). Information Hiding Terminology.Information Hiding: First International Workshop, Cambridge, 347-350, Springer.

Proctor, N. E. and P. G. Neumann (1992). "Architectural implications of Covert Channels." 15th National Computer Security Conference Proceedings of the 15th National Computer Security Conference: 28-43.

David Llamas 62 BSc (Hons) Software Technology, 2004 RFC 2403 (1996). "HMAC-MD5-96." http://www.ietf.org/.

A-96." http://www.ietf.org/RFC 2404 (1996). "HMAC-SH .

/www.ietf.org/RFC 2405 (2000). "DES-CBC." http:/ .

Rowland, C. H. (1996). "Covert Channels in the TCP/IP Protocol Suite." First Monday Peer-Reviewed Journal on the Internet.

Venkatesh, B. (2003). Securing Network Protoclls Using Active Wardens. Computing Department. Arizona, Ariona State University.

Wolf, M. (1989). "Covert channels in LAN protocols." LANSEC’89.

Wrixon, F. B. (1998). Codes Ciphers & Other Cryptic & Clandestine Communication New York, Black Dog & Leventhal Publisher , Inc.

David Llamas 63 BSc (Hons) Software Technology, 2004

10 Appendix

10.1 Honours Project Contract

David Llamas 64 BSc (Hons) Software Technology, 2004

David Llamas 65 BSc (Hons) Software Technology, 2004

David Llamas 66 BSc (Hons) Software Technology, 2004

David Llamas 67 BSc (Hons) Software Technology, 2004

David Llamas 68 BSc (Hons) Software Technology, 2004

David Llamas 69 BSc (Hons) Software Technology, 2004

10.2 Diary sheets

David Llamas 70 BSc (Hons) Software Technology, 2004

David Llamas 71 BSc (Hons) Software Technology, 2004

David Llamas 72 BSc (Hons) Software Technology, 2004

David Llamas 73 BSc (Hons) Software Technology, 2004

David Llamas 74 BSc (Hons) Software Technology, 2004

David Llamas 75 BSc (Hons) Software Technology, 2004

David Llamas 76 BSc (Hons) Software Technology, 2004

David Llamas 77 BSc (Hons) Software Technology, 2004

David Llamas 78 BSc (Hons) Software Technology, 2004

David Llamas 79 BSc (Hons) Software Technology, 2004

10.3 ECIW 2004 Conference paper

David Llamas 80 BSc (Hons) Software Technology, 2004

David Llamas 81 BSc (Hons) Software Technology, 2004

David Llamas 82 BSc (Hons) Software Technology, 2004

David Llamas 83 BSc (Hons) Software Technology, 2004

David Llamas 84 BSc (Hons) Software Technology, 2004

David Llamas 85 BSc (Hons) Software Technology, 2004

David Llamas 86 BSc (Hons) Software Technology, 2004

David Llamas 87 BSc (Hons) Software Technology, 2004

David Llamas 88 BSc (Hons) Software Technology, 2004

David Llamas 89 BSc (Hons) Software Technology, 2004

David Llamas 90 BSc (Hons) Software Technology, 2004

10.4 Source Code

10.4.1 Agent.cs

//////////////////////////////////////////////////////////////////// // ule s Project 2003/2004 //

// Covert /IP //

// o //

// n //

// H Sof //

/ // //

// //

// /

// nography.org //

://www.inchcolm.org // //

// yri s 2004 //

// //

veloped **ONLY** for educational // //

// rpose. //

// r ersity //

ool // l //

nbu // a //

// //////////////////////////////

stee

stee

in Syste

me pace C

</summc

string ss ge);

Agent.dll")] ng message);

gent.dll",

// / Mod 42019 - Honour///

Channel Analysis and Data Hiding in TCP//// Auth// r: David Llamas

// Stude// t 01009322

// BSc (// ons) tware Technology

/// Napier University Edinbu // rgh

// Email: 932 // 0100 [email protected]

phy.org // david@steganogra// [email protected]

/// apier.ac.uk // Web : http://www.dcs.n

www,stega// http:// http//

// //

ersity and David Llama// Cop ght (C) Napier UNiv //

// // This software has been de

// purposes. // //

// // It is provided "as is", and the owner makes no warranty, not limited to, // either express or implied, including but

or a particular pu// warranties of fitness f //

Napie Univ//// Sch of Computing 10 Co// inton Road

// Edi rgh EH10 5DT Scotl// nd

// ////////////////////////////////////// using Sy m; in Systus g m.Collections;

alized; using Sy m.Collections.Speciin Systus g m.Runtime.InteropServices;

us g m.Net; na s overtController { /// <summary>

he ss for accessing the Covert Agent. /// T interop cla/// ary>

publi class Agent {

#region DLL Imports [DllImport("CovertAgent.dll")]

Int16 port, private static extern int AddCovertInformation(UInt32 ipaddress, Ume a [DllImport("CovertAgent.dll")]

te static extern int RemoveCovertInformation(UInt32 ipaddress, UInt16 port); priva [DllImport("Covert private static extern void SetDefaultCovertInformation(UInt16 port, stri [DllImport("CovertA CallingConvention=CallingConvention.StdCall)] private static extern int SetupAdapters();

David Llamas 91 BSc (Hons) Software Technology, 2004

mport("CovertAgent.dll")]

[DllImport("CovertAgent.dll")] ern string GetAdapterName(int index);

gent.dll")] nt index);

te static extern int Cycle(int timeout);

llImpearDown();

egion

ing[] _adapterNames;

string name = GetAdapterName(i); _adapterNames[i] = name;

apter names

c static StringCollection AdapterNames

get {

ingCollection ret = new StringCollection();

rn ret;

TearDown();

/// <summary> /// Add a covert message filter to the agent /// </summary> /// <param name="ipAddress">The IP addres of the destination machine</param>

/// <param name="tcpPort">The port on the source machine</param> /// <param name="message">The covert message</param> public static void AddCovertMessage(string ipAddress, string tcpPort, string message) { AddCovertInformation(ParseIPAddress(ipAddress), ParsePortAddress(tcpPort), message); } /// <summary> /// Removes a covert message filter from the agent /// </summary> /// <param name="ipAddress">The IP Address of the destination machine</param> /// <param name="tcpPort">The port on the source machine</param> public static void RemoveCovertMessage(string ipAddress, string tcpPort) { RemoveCovertInformation(ParseIPAddress(ipAddress), ParsePortAddress(tcpPort)); } /// <summary> /// Sets the covert message sent to machines when there is no specific /// filter set up /// </summary> /// <param name="tcpPort">The Port on the source machine</param> /// <param name="message">The covert message</param> public static void SetDefaultCovertMessage(string tcpPort, string message)

[DllI private static extern int GetAdapterCount(); private static ext [DllImport("CovertA private static extern int Initialise(i [DllImport("CovertAgent.dll")] priva [D ort("CovertAgent.dll")] private static extern int T #endr private static str /// <summary> /// Intialises the underlying agent /// </summary> public static void Init() { // Get the adapter information from the agent. int result = Agent.SetupAdapters(); int count = Agent.GetAdapterCount(); _adapterNames = new string[count]; for (int i = 0; i<count; i++) { } } /// <summary> /// Gets a collection of ad /// </summary> publi { Str ret.AddRange(_adapterNames); retu } } /// <summary> /// Instructs the agent to unhook from the adapter. /// </summary> public static void OnAppExit() { }

David Llamas 92 BSc (Hons) Software Technology, 2004

{ vertInformation(ParsePortAddress(tcpPort), message);

/// <summary> eger

interger.

essBytes();

etrNames

/// <param name="timeout">the timeout in milliseconds</param> <returns>The number of packets that have passed through the

/returns> is very important to call this method frequently as

ets will be processed while outside this method. e client or server process on this machine the

ssion that the network is not available.</remarks> t ProcessPackets(int timeout)

{ return Cycle(timeout);

}

SetDefaultCo}

/// Parse the port string in to a network order 16 bit int /// </summary> /// <param name="tcpPort"></param> /// <returns></returns> private static UInt16 ParsePortAddress(string tcpPort) { UInt16 port = Convert.ToUInt16(tcpPort); UInt16 temp = (UInt16)((port & 0xFF) << 8); port >>= 8; port += temp; return port; } /// <summary> /// Parse the IP Address string into a network order 32 bit /// </summary> /// <param name="ipAddress"></param> /// <returns></returns> private static UInt32 ParseIPAddress(string ipAddress) { byte[] address = IPAddress.Parse(ipAddress).GetAddr UInt32 ui32address = (UInt32)(address[0] << 0) + (UInt32)(address[1] << 8) + (UInt32)(address[2] << 16) + (UInt32)(address[3] << 24); return ui32address; } /// <summary> /// Hooks the agent on to the adapter at the given index /// </summary> /// <param name="index">The index of the adapter in the Adap /// collection</param> public static void SetAdapter(int index) { Initialise(index); } /// <summary> /// Processes Network packets until the timeout occurs /// </summary> /// /// adapter< /// <remarks>It /// no network pack /// This could giv /// impre public static in } }

David Llamas 93 BSc (Hons) Software Technology, 2004

/ // //

//

ho avid Llamas // //

den // //

(H ology // Napier //

nbu // //

ac.uk // //

// //

c.uk // nography.org //

// //

// Copyri 4 //

// This s //

pos // //

is "as is", and the owner makes no warranty, //

warran of

in Syste .So

blic class Fo

ivateox;

ows.Forms.Button GoButton; bel label2;

ows.Forms.Label label1; ;

ivate

ivateonsContextMenu; utoScrollMenuItem;

ble.

ivate

ivate ;

10.4.2 Sniffer.cs

///////////////////////////////////////////////////////////////////// Module 42019 - Honours Project 2003/2004 //

// Covert nel// Chan Analysis and Data Hiding in TCP/IP //

// // // Aut r: D//// Stu t 01009322 // // BSc ons) Software Techn// University // Edi rgh // // Email: 01009322@napier.// [email protected] // [email protected] // // Web : http://www.dcs.napier.a// http://www,stega// http://www.inchcolm.org // //// ght (C) Napier University and David Llamas 200// // // // oftware has been developed **ONLY** for educational // pur es. // // It provided// either express or implied, including but not limited to, // // ties fitness for a particular purpose. // // // // Napier University // // School of Computing // // 10 Colinton Road // // Edinburgh EH10 5DT // // Scotland // // // //////////////////////////////////////////////////////////////////// using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Diagnostics; using System.Net; us g m.Net ckets; namespace Sniffer { /// <summary> /// Summary description for Form1. /// </summary> pu rm1 : System.Windows.Forms.Form { pr System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox RemoteIPTextB private System.Windows.Forms.Button stopButton; private System.Wind private System.Windows.Forms.La private System.Wind private System.Windows.Forms.TextBox PortTextBox pr System.Windows.Forms.TextBox LocalIPTextBox; private System.Windows.Forms.GroupBox groupBox1; pr System.Windows.Forms.Button optionsButton; private System.Windows.Forms.ContextMenu opti private System.Windows.Forms.MenuItem optionsA private System.Windows.Forms.ListView packetListView; /// <summary> /// Required designer varia /// </summary> pr System.ComponentModel.Container components = null; pr ColumnDataCollection _cdc = new ColumnDataCollection()

David Llamas 94 BSc (Hons) Software Technology, 2004

blic

for Windows Form Designer support

fter InitializeComponent call

/ Cle

otect

components != null)

components.Dispose();

support - do not modify this method with the code editor.

.Forms.TextBox(); );

on = new System.Windows.Forms.Button(); stem.Windows.Forms.Label();

= new System.Windows.Forms.Label(); indows.Forms.TextBox();

stem.Windows.Forms.GroupBox();

); s.ContextMenu(); .Forms.MenuItem();

(64, 20);

ContentAlignment.MiddleRight;

TextBox

IPTextBox.Location = new System.Drawing.Point(248, 24);

x";

false; tton.Location = new System.Drawing.Point(504, 24);

awing.Size(64, 20);

top"; Button_Click);

private bool _stopping = false; pu Form1() { // // Required // InitializeComponent(); // // TODO: Add any constructor code a // } /// <summary> // an up any resources being used. /// </summary> pr ed override void Dispose( bool disposing ) { if( disposing ) { if ( { } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer /// the contents of /// </summary> private void InitializeComponent() { this.label3 = new System.Windows.Forms.Label(); this.RemoteIPTextBox = new System.Windows this.stopButton = new System.Windows.Forms.Button( this.GoButt this.label2 = new Sy this.label1 this.PortTextBox = new System.W this.LocalIPTextBox = new System.Windows.Forms.TextBox(); this.groupBox1 = new Sy this.optionsButton = new System.Windows.Forms.Button(); this.packetListView = new System.Windows.Forms.ListView( this.optionsContextMenu = new System.Windows.Form this.optionsAutoScrollMenuItem = new System.Windows this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // label3 // this.label3.Location = new System.Drawing.Point(184, 24); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size this.label3.TabIndex = 18; this.label3.Text = "Remote IP:"; this.label3.TextAlign = System.Drawing. // // RemoteIP // this.Remote this.RemoteIPTextBox.MaxLength = 15; this.RemoteIPTextBox.Name = "RemoteIPTextBo this.RemoteIPTextBox.Size = new System.Drawing.Size(104, 20); this.RemoteIPTextBox.TabIndex = 1; this.RemoteIPTextBox.Text = "213.123.198.144"; // // stopButton // this.stopButton.Enabled = this.stopBu this.stopButton.Name = "stopButton"; this.stopButton.Size = new System.Dr this.stopButton.TabIndex = 4; this.stopButton.Text = "S this.stopButton.Click += new System.EventHandler(this.stop // // GoButton // this.GoButton.Location = new System.Drawing.Point(432, 24); this.GoButton.Name = "GoButton"; this.GoButton.Size = new System.Drawing.Size(64, 20);

David Llamas 95 BSc (Hons) Software Technology, 2004

on.Click += new System.EventHandler(this.GoButton_Click);

.Size = new System.Drawing.Size(32, 20);

.Text = "Port:"; t.MiddleRight;

tion = new System.Drawing.Point(16, 24); .Name = "label1";

tentAlignment.MiddleRight;

ing.Point(384, 24);

this.PortTextBox.Name = "PortTextBox"; this.PortTextBox.Size = new System.Drawing.Size(40, 20);

rtTextBox.TabIndex = 2; this.PortTextBox.Text = "8003";

alIPTextBox.Location = new System.Drawing.Point(72, 24); extBox.MaxLength = 15;

this.LocalIPTextBox.Name = "LocalIPTextBox"; .Drawing.Size(104, 20);

this.LocalIPTextBox.TabIndex = 0; this.LocalIPTextBox.Text = "192.168.1.21";

// groupBox1

this.groupBox1.Anchor = System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | st m.Wind

| System.Windows.Forms.AnchorStyles.Right))); ionsButton);

pBox1.Controls.Add(this.label2); n);

PTextBox); s.label3);

pBox1.Controls.Add(this.PortTextBox); this.groupBox1.Controls.Add(this.LocalIPTextBox);

this.groupBox1.Location = new System.Drawing.Point(12, 8); Box1.Name = "groupBox1";

x1.TabIndex = 19; ;

ols";

// optionsButton

indows.Forms.Cursors.Hand;

ionsButton.Location = new System.Drawing.Point(584, 24); on";

ize = new System.Drawing.Size(56, 20); Index = 5;

sButton.Text = "Options";

.Windows.Forms.AnchorStyles.Top |

rStyles.Right))); etListView.FullRowSelect = true;

es = true; etListView.Location = new System.Drawing.Point(8, 72);

this.GoButton.TabIndex = 3; this.GoButton.Text = "Listen"; this.GoButt // // label2 // this.label2.Location = new System.Drawing.Point(352, 24); this.label2.Name = "label2"; this.label2 this.label2.TabIndex = 13; this.label2 this.label2.TextAlign = System.Drawing.ContentAlignmen // // label1 // this.label1.Loca this.label1 this.label1.Size = new System.Drawing.Size(48, 20); this.label1.TabIndex = 12; this.label1.Text = "Local IP:"; this.label1.TextAlign = System.Drawing.Con // // PortTextBox // this.PortTextBox.Location = new System.Draw this.PortTextBox.MaxLength = 5; this.Po // // LocalIPTextBox // this.Loc this.LocalIPT this.LocalIPTextBox.Size = new System // // ((Sy e ows.Forms.AnchorStyles.Left) this.groupBox1.Controls.Add(this.opt this.grou this.groupBox1.Controls.Add(this.GoButto this.groupBox1.Controls.Add(this.stopButton); this.groupBox1.Controls.Add(this.RemoteI this.groupBox1.Controls.Add(thi this.groupBox1.Controls.Add(this.label1); this.grou this.group this.groupBox1.Size = new System.Drawing.Size(648, 56); this.groupBo this.groupBox1.TabStop = false this.groupBox1.Text = "Contr // // this.optionsButton.Cursor = System.W this.optionsButton.Enabled = false; this.opt this.optionsButton.Name = "optionsButt this.optionsButton.S this.optionsButton.Tab this.option // // packetListView // this.packetListView.AllowColumnReorder = true; this.packetListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((SystemSystem.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.Ancho this.pack this.packetListView.GridLin this.pack this.packetListView.Name = "packetListView"; this.packetListView.Size = new System.Drawing.Size(656, 344);

David Llamas 96 BSc (Hons) Software Technology, 2004

is.paorms.View.Details;

onsContextMenu

System.Windows.Forms.MenuItem[] {

this.optionsAutoScrollMenuItem}); //

this.optionsAutoScrollMenuItem.Checked = true; = 0;

// Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

tSize = new System.Drawing.Size(672, 421);

s.Add(this.groupBox1);

this.Load += new System.EventHandler(this.Form1_Load);

ndreg

/ <su/ The

/s y> [STAThread]

Run(new Form1());

rgs e)

ColumnHeaders()

for(int i = 0; i<_cdc.Count; i++)

a cd = _cdc[i]; lumnH

100; is.packetListView.Columns.Add(ch);

nder"></param> ram>

on_Click(object sender, System.EventArgs e)

toppi

TextBox.Text);

nt16(this.PortTextBox.Text); the Asynchronous socket

cket = new ddr y.InterNetwork,SocketType.Raw,ProtocolType.IP);

socket.Bind(new IPEndPoint(localIpa,0)); upSocket(socket);

ion ex)

riteLine(ex.Message); kTrace);

th cketListView.TabIndex = 0; this.packetListView.View = System.Windows.F // // opti // this.optionsContextMenu.MenuItems.AddRange(new // optionsAutoScrollMenuItem // this.optionsAutoScrollMenuItem.Index this.optionsAutoScrollMenuItem.Text = "Auto Scroll"; // this.Clien this.Controls.Add(this.packetListView); this.Control this.Name = "Form1"; this.Text = "Sniffer"; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #e ion // mmary> // main entry point for the application. /// < ummar static void Main() { Application. } private void Form1_Load(object sender, System.EventA { CreateColumnHeaders(); } private void Create { { ColumnDat Co eader ch = new ColumnHeader(); ch.Text = cd.ColumnName; ch.Width= th } } /// <summary> /// Event Handler - The user has clicked the GO button to start sniffing /// </summary> /// <param name="se /// <param name="e"></pa private void GoButt { _s ng = false; this.GoButton.Enabled=false; this.stopButton.Enabled=true; IPAddress localIpa, remoteIpa; UInt16 port; Socket socket; try { localIpa = IPAddress.Parse(this.LocalIP remoteIpa = IPAddress.Parse(this.RemoteIPTextBox.Text); port = Convert.ToUI // Set up soSocket(A essFamil Set } catch(Except { System.Diagnostics.Debug.W System.Diagnostics.Debug.WriteLine(ex.Stac

David Llamas 97 BSc (Hons) Software Technology, 2004

MessageBox.Show("An error occurred when setting up the sniffer"+

ng(), MessageBoxButtons.OK,

this.GoButton.Enabled=true; this.stopButton.Enabled=false;

urn;

will manage the sniffing state ject(socket, remoteIpa, port);

// Begin receiving sniffed packets. r, 0, so.Buffer.Length, SocketFlags.None, new

}

/// <summary> /// Sets up the sniffer socket to accept all packets /// </summary> /// <param name="socket">The socket to become the sniffer</param>

private void SetupSocket(Socket socket) { // NOTE: This doesn't work with the loopback adapter. // and neither with wireless network cards??? socket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.HeaderIncluded,1); byte []IN = new byte[4]{1, 0, 0, 0}; byte []OUT = new byte[4]; int SIO_RCVALL = unchecked((int)0x98000001); int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT); ret_code = OUT[0] + OUT[1] + OUT[2] + OUT[3]; } /// <summary> /// Callback - When a packet is received /// </summary> /// <param name="result">Details about the connection, also contains /// the StateObject</param> private void ReceivePacket(IAsyncResult result) { StateObject so = (StateObject)result.AsyncState; Socket socket = so.Socket; try { int bytes = socket.EndReceive(result); if (so.MatchFilter) { // Add the packet data to the list view this.packetListView.Items.Add(LviFromPacket(so.Buffer)); } } catch(Exception e) { Debug.WriteLine(e); Debug.WriteLine(e.StackTrace); MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { // Because the packet sniffing is preventing the events from // being properly processes - process them here. Application.DoEvents(); if (_stopping == true) { this.GoButton.Enabled=true; this.stopButton.Enabled=false; } else { // Get the next packet. socket.BeginReceive(so.Buffer,0, so.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceivePacket), so); } } } /// <summary> /// Construct a list view item from the given packet buffer /// </summary> /// <param name="packetBuffer">a buffer containing the packet</param> /// <returns>A list view item</returns> private ListViewItem LviFromPacket(byte[] packetBuffer)

Environment.NewLine+ ex.Message, ex.GetType().ToStriMessageBoxIcon.Error); ret } // Setup the state object that StateObject so = new StateOb socket.BeginReceive(so.BuffeAsyncCallback(ReceivePacket), so);

David Llamas 98 BSc (Hons) Software Technology, 2004

{ _cdc.ToStringArray(packetBuffer); = new ListViewItem(data);

retu }

s e)

string[] data = ListViewItem lvi

rn lvi; /// <summary> /// Event Handler - The user has clicked the stop button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void stopButton_Click(object sender, System.EventArg { this._stopping=true; this.GoButton.Enabled=true; this.stopButton.Enabled=false; } } }

David Llamas 99 BSc (Hons) Software Technology, 2004

/// /

// //

d Data Hiding in TCP/IP //

s // //

Student 01009322 // //

BSc (H // ier //

Edinbu // //

// phy.org //

// //

// y.org //

olm.org // //

// Copyright (C) Napier University and David Llamas 2004 // //

// This s purpos //

// It is no warranty, //

her or implied, including but not limited to, //

Napier ers

10 Col Ro Edinbu H10

// ////// ///

me pace C Con

/ <su ry>

/ </s ary>

cessingPackets = false; cessed = 0;

Form _onlyMe;

ivateomboBox;

ivatedressColumnHeader;

lumnHeader; ivate

ows.Forms.GroupBox groupBox3; .Button startStopButton;

ows.Forms.Button fileBrowseButton;

ivate

/ Req

10.4.3 MainForm.cs // ////// ///// / ///// //////////////////////////////////////////////

/// // Module 42019 - Honours Project 2003/2004 //

// Covert Channel Analysis an // //

// Author: David Llama// //// // ons) Software Technology // Nap University // rgh // // Email: [email protected] // david@steganogra// [email protected] // // Web : http://www.dcs.napier.ac.uk // http://www,steganograph// http://www.inchc// // //// // // oftware has been developed **ONLY** for educational // // es. // // provided "as is", and the owner makes// eit express// warranties of fitness for a particular purpose. // // // // Univ ity // // School of Computing // // inton ad // // rgh E 5DT // // Scotland // // // // / ///// ///////////////////////////////////////////////// using System; using System.Drawing; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Xml; using System.Diagnostics; using System.IO; na s overt troller { // mma /// Summary description for Form1. // umm public class MainForm : System.Windows.Forms.Form { private bool _isClosing = false; private bool _isPro private int _totalPacketsPro private static Main pr System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox adapterNameC pr System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.ColumnHeader IPAd private System.Windows.Forms.ColumnHeader PortCo pr System.Windows.Forms.ColumnHeader MessageColumnHeader; private System.Wind private System.Windows.Forms private System.Wind private System.Windows.Forms.ListView covertMessages; private System.Windows.Forms.TextBox packetsProcessedTextBox; pr System.Windows.Forms.Label label1; /// <summary> // uired designer variable. /// </summary>

David Llamas 100 BSc (Hons) Software Technology, 2004

ts = null;

his;

/ Cle

otect

e();

m Designer generated code

for Designer support - do not modify he code editor.

rNameComboBox = new System.Windows.Forms.ComboBox(); .Windows.Forms.GroupBox();

ox2 = new System.Windows.Forms.GroupBox();

lumnHeader(); ;

ws.Forms.ColumnHeader(); Forms.Button();

topButton = new System.Windows.Forms.Button(); dTextBox = new System.Windows.Forms.TextBox();

= new System.Windows.Forms.Label();

= st m.Wind orm

rNameComboBox.Font = new System.Drawing.Font("Courier New", 9.75F, ing.GraphicsUnit.Point, ((System.Byte)(0)));

rNameComboBox.Location = new System.Drawing.Point(8, 16);

st m.Even ler

ox1.Controls.Add(this.adapterNameComboBox); em.Drawing.Point(8, 136);

ox1.Name = "groupBox1";

apter";

ox2.Controls.Add(this.covertMessages); ntrols.Add(this.fileBrowseButton);

ox2.Location = new System.Drawing.Point(8, 8);

wing.Size(424, 120);

private System.ComponentModel.Container componen private MainForm() { _onlyMe = t // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> // an up any resources being used. /// </summary> pr ed override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispos } } base.Dispose( disposing ); } #region Windows For /// <summary> /// Required method /// the contents of this method with t /// </summary> private void InitializeComponent() { this.adapte this.groupBox1 = new System this.groupB this.covertMessages = new System.Windows.Forms.ListView(); this.IPAddressColumnHeader = new System.Windows.Forms.Co this.PortColumnHeader = new System.Windows.Forms.ColumnHeader() this.MessageColumnHeader = new System.Windo this.fileBrowseButton = new System.Windows. this.groupBox3 = new System.Windows.Forms.GroupBox(); this.startS this.packetsProcesse this.label1 this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // adapterNameComboBox // this.adapterNameComboBox.DropDownStyle Sy e ows.F s.ComboBoxStyle.DropDownList; this.adapteSystem.Drawing.FontStyle.Regular, System.Draw this.adapte this.adapterNameComboBox.Name = "adapterNameComboBox"; this.adapterNameComboBox.Size = new System.Drawing.Size(408, 24); this.adapterNameComboBox.TabIndex = 0; this.adapterNameComboBox.SelectedIndexChanged += new Sy e tHand (this.adapterNameComboBox_SelectedIndexChanged); // // groupBox1 // this.groupB this.groupBox1.Location = new Syst this.groupB this.groupBox1.Size = new System.Drawing.Size(424, 48); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Step 2 - Choose Ethernet Ad // // groupBox2 // this.groupB this.groupBox2.Co this.groupB this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Dra this.groupBox2.TabIndex = 2;

David Llamas 101 BSc (Hons) Software Technology, 2004

sage File";

ssages

Messages.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { ColumnHeader,

this.PortColumnHeader,

this.MessageColumnHeader}); ;

rawing.Point(8, 24); ;

stem.Drawing.Size(408, 88); this.covertMessages.TabIndex = 1;

this.covertMessages.View = System.Windows.Forms.View.Details; vertMessages.ItemCheck += new

stem.Windows.Forms.ItemCheckEventHandler(this.covertMessages_ItemCheck);

ddressColumnHeader.Text = "IP Address"; sColumnHeader.Width = 100;

// mnHeader

eColumnHeader

ageColumnHeader.Text = "Message"; 50;

// fileBrowseButton //

rowseButton.Location = new System.Drawing.Point(192, 0);

wseButton.Size = new System.Drawing.Size(24, 16); = 0;

= "..."; this.fileBrowseButton_Click);

//

ls.Add(this.label1); sedTextBox);

opButton); pBox3.Location = new System.Drawing.Point(8, 192);

pBox3.Size = new System.Drawing.Size(424, 100); this.groupBox3.TabIndex = 3;

this.groupBox3.TabStop = false; this.groupBox3.Text = "Step 3 - Add Covert Information";

w System.Drawing.Font("Verdana", 8.25F, raw ng.GraphicsUnit.Point, ((System.Byte)(0)));

this.startStopButton.Name = "startStopButton"; ze = new System.Drawing.Size(40, 16);

this.startStopButton.TabIndex = 0; this.startStopButton.Text = "Go";

StopButton.Click += new System.EventHandler(this.startStopButton_Click);

ocessedTextBox

this.packetsProcessedTextBox.Location = new System.Drawing.Point(16, 24); "packetsProcessedTextBox";

ProcessedTextBox.Text = "---";

stem.Windows.Forms.HorizontalAlignment.Right; //

// label1

Name = "label1"; Drawing.Size(104, 20);

this.groupBox2.TabStop = false; this.groupBox2.Text = "Step 1 - Open Covert Mes // // covertMe // this.covert this.IPAddress this.covertMessages.FullRowSelect = true this.covertMessages.GridLines = true; this.covertMessages.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.covertMessages.Location = new System.D this.covertMessages.Name = "covertMessages" this.covertMessages.Size = new Sy this.coSy // // IPAddressColumnHeader // this.IPA this.IPAddres // PortColu // this.PortColumnHeader.Text = "Port"; // // Messag // this.Mess this.MessageColumnHeader.Width = 2 // this.fileB this.fileBrowseButton.Name = "fileBrowseButton"; this.fileBro this.fileBrowseButton.TabIndex this.fileBrowseButton.Text this.fileBrowseButton.Click += new System.EventHandler( // groupBox3 // this.groupBox3.Contro this.groupBox3.Controls.Add(this.packetsProces this.groupBox3.Controls.Add(this.startSt this.grou this.groupBox3.Name = "groupBox3"; this.grou // // startStopButton // this.startStopButton.Font = neSystem.D ing.FontStyle.Regular, System.Drawi this.startStopButton.Location = new System.Drawing.Point(176, 0); this.startStopButton.Si this.start // // packetsPr // this.packetsProcessedTextBox.Name = this.packetsProcessedTextBox.ReadOnly = true; this.packetsProcessedTextBox.TabIndex = 1; this.packets this.packetsProcessedTextBox.TextAlign = Sy // this.label1.Location = new System.Drawing.Point(120, 24); this.label1. this.label1.Size = new System.

David Llamas 102 BSc (Hons) Software Technology, 2004

this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;

;

this.Controls.Add(this.groupBox2);

entModel.CancelEventHandler(this.MainForm_Closing);

se); );

/ <su/ The

cation_Idle);

finally

AppExit();

ist of adapters the user.

NameComboBox.Items.Add(names[i]);

s the adapter

nder"></param> "e"></param>

te void adapterNameComboBox_SelectedIndexChanged(object sender, System.EventArgs e) {

/// <summary> lteres the state of the buttons based on the adapter selection

is.startStopButton.Enabled=true;

is.startStopButton.Enabled=false;

for when the user pressed the file Browse button /summary>

/// <param name="sender"></param>

this.label1.TabIndex = 2; this.label1.Text = "Packets Processed"; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13) this.ClientSize = new System.Drawing.Size(440, 301); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox1); this.Name = "MainForm"; this.Text = "Covert Controller"; this.Closing += new System.Compon this.Load += new System.EventHandler(this.MainForm_Load); this.groupBox1.ResumeLayout(fal this.groupBox2.ResumeLayout(false this.groupBox3.ResumeLayout(false); this.ResumeLayout(false); } #endregion // mmary> // main entry point for the application. /// </summary> [STAThread] static void Main() { try { Application.Idle+=new EventHandler(Appli Application.Run(new MainForm()); } { Agent.On } } /// <summary> /// Peforms actions to get the initial information onto the form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, System.EventArgs e) { // Initialise the agent and retrieve the l // for display to Agent.Init(); StringCollection names = Agent.AdapterNames; for(int i=0; i<names.Count; i++) { this.adapter } } /// <summary> /// Event handler for when the user change /// </summary> /// <param name="se /// <param name= priva StateChanged(); } /// A /// </summary> private void StateChanged() { // If there is no adapter selected if (adapterNameComboBox.SelectedIndex!=-1) th else th } /// <summary> /// Event handler /// <

David Llamas 103 BSc (Hons) Software Technology, 2004

"></param> em.EventArgs e)

vironment - Go to the project's lopment environment go to My Documents

string defPath = dir+"\\CovertInformation.xml";

dir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

and call the File Open Dialog leDialog();

n";

dlg.InitialDirectory=dir; r="XML files (*.xml)|*.xml|All files (*.*)|*.*";

xt="xml"; ult res = dlg.ShowDialog();

leName = dlg.FileName; XmlDocument xDoc = new XmlDocument();

xDoc.Load(fileName); c = xDoc.DocumentElement;

ldNodes)

the XML file. eType==XmlNodeType.Comment)

);

ss = covertNode.Attributes["TO_IP"].Value;

string port = covertNode.Attributes["FROM_PORT"].Value;

FirstChild.FirstChild; ring message = dataNode.Value;

stViewItem lvi; if (def.ToLower()=="true")

{ Agent.SetDefaultCovertMessage(port, message);

lvi = this.covertMessages.Items.Add("Any"); ort);

e(ipAddress, port, message); lvi = this.covertMessages.Items.Add(ipAddress); lvi.SubItems.Add(port);

lvi.Checked=true;

he Covert Message list has no check button so this meth

private void covertMessages_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs

int i = e.Index; em lvi = this.covertMessages.Items[i];

= lvi.SubItems[0].Text; nchecked)

} d)

string message = lvi.SubItems[1].Text; Agent.AddCovertMessage(ipAddress, port, message);

} }

/// <param name="e private void fileBrowseButton_Click(object sender, Syst { // While in the development en // target dir. In a non-deve string dir = Environment.CurrentDirectory; if (!File.Exists(defPath)) // Set up System.Windows.Forms.FileDialog dlg = new OpenFi dlg.CheckFileExists=true; dlg.CheckPathExists=true; dlg.Title="Open a file containing covert informatio dlg.ValidateNames=true; dlg.Filte dlg.DefaultE DialogRes if (res != DialogResult.OK) return; // The user has selected a file. Parse the XML // to obtain the covert filter information. string fi XmlNode do foreach(XmlNode covertNode in doc.Chi { // Skip comment nodes in if (covertNode.Nod continue; Debug.WriteLine("covertNode.Name = "+covertNode.Name string def = covertNode.Attributes["DEFAULT"].Value; Debug.WriteLine("Default = "+def); string ipAddre Debug.WriteLine("IP Address = "+ipAddress); Debug.WriteLine("Port = "+port); XmlNode dataNode = covertNode. st Debug.WriteLine("Message = "+message); Li lvi.SubItems.Add(p } else { Agent.AddCovertMessag } // lvi.SubItems.Add(message); } } // Out of order - T // od will never be called. e) { ListViewIt string ipAddress = lvi.Text; string port if (e.NewValue == CheckState.U { Agent.RemoveCovertMessage(ipAddress, port); else if (e.NewValue == CheckState.Checke {

David Llamas 104 BSc (Hons) Software Technology, 2004

e Star/Stop Button

/// </summary> /// <param name="sender"></param>

ntArgs e)

nt state

ctedIndex);

er from it. e

any of then

s e)

;

Application.DoEvents();

t process some packets

<returns>false if the application is closing or the user has said to stop processing</returns>

private static bool DoIdleTimeProcessing()

ets)

mAltered = Agent.ProcessPackets(1000); );

totalPacketsProcessed;//.ToString(); essedTextBox.Text=tpp.ToString();

ion is remaining open and packets are to be oc ssed.

onlyMe._isClosing) & (_onlyMe._isProcessingPackets);

he user has clicked the form's close button /s

/ <pa

celEventArgs e)

/// <summary> /// Event Handler - User presses th

/// <param name="e"></param> private void startStopButton_Click(object sender, System.Eve { // Change the user interface according to the curre if (_isProcessingPackets) { startStopButton.Text = "Start"; _isProcessingPackets = false; this.adapterNameComboBox.Enabled=true; this.fileBrowseButton.Enabled=true; //Agent.OnAppExit(); } else { startStopButton.Text = "Stop"; _isProcessingPackets = true; this.adapterNameComboBox.Enabled=false; this.fileBrowseButton.Enabled=false; Agent.SetAdapter(this.adapterNameComboBox.Sele } } /// <summary> /// Event Handler - Do Idle time processing /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks>When the covert agent is running this takes ov /// the normal message pump by not yielding control back to /// Instead, packets are processed then any queued events ar /// processed and it returns to processing more packets. If /// the events stop the covert agent from processing packets /// the agent will unhook and return control to the normal /// message pump.</remarks> private static void Application_Idle(object sender, EventArg { Debug.WriteLine("Idle at "+DateTime.Now.ToString()) while(DoIdleTimeProcessing())

{ } }

mary> /// <sum /// Let the agen

/// </summary> ///

/// {

_onlyMe._isProcessingPack if( {

int nu Debug.WriteLine("Number of packets = "+numAltered.ToString()

_onlyMe._totalPacketsProcessed += numAltered; int tpp = _onlyMe._ _onlyMe.packetsProc } // Return True while the applicat

epr return (!_ } /// <summary>

vent Handler - T /// E// < / ummary>

// ram name="sender"></param> /// <param name="e"></param>

ender, System.ComponentModel.Can private void MainForm_Closing(object s { Debug.WriteLine("Form Closing"); _isClosing = true; } } }

David Llamas 105 BSc (Hons) Software Technology, 2004

e 9 - //

t and Data Hiding in TCP/IP // // o //

// den // //

// //

Edinbu

// //

//

://

// //

niversity and David Llamas 2004 // // // s s // pos //

It is her , //

a particular purpose. // //

// // //

// //

// ////////////

/ <su ry>

te static readonly char[] crlf = Environment.NewLine.ToCharArray();

su/ Ret ile.

roxy Server"); m ");

tings["RealIP"];

ort"];

_realIP);

10.4.4 ReverseProxyServer.cs //////////////////////////////////////////////////////////////////// // // // 4201 Honours Project 2003/2004 // Modul// // Cover Channel Analysis//

r: David Llamas // Auth //

/ Stu/ t 01009322 //

// BSc (Hons) Software Technology / Napier University /// rgh // // // // Email: [email protected]

// [email protected] / [email protected] /// // / Web : http://www.dcs.napier.ac.uk // /// http www,steganography.org //

// // http://www.inchcolm.org //

// yri C) Napier U// Cop ght (

/ /// / Thi/ oftware has been developed **ONLY** for educational

// pur es. / / //

, // // provided "as is", and the owner makes no warrantyess or implied, including but not limited to// eit expr

// warranties of fitness for //

// Napier University // School of Computing

// 10 Colinton Road // Edinburgh EH10 5DT

// Scotland // //////////////////////////////////////////////////////// using System; using System.Configuration; using System.IO; using System.Net; using System.Net.Sockets; sing System.Text; uusing System.Diagnostics; namespace RPS { // mma /// The reverse proxy server application. /// </summary>

class ReverseProxyServer {

priva private static string _realIP;

ing _realPort; private static str private static IPEndPoint _realEP; private static IPEndPoint _listeningEP;

// < / mmary> m the config f // rieve the information fro

/// </summary> static void Setup()

{ Console.WriteLine("Setting up the Reverse P

Console.Write("Proxy retrieves information fro _realIP = ConfigurationSettings.AppSet

alIP); Console.Write(_re _realPort = ConfigurationSettings.AppSettings["RealP Console.WriteLine(":{0}",_realPort);

realIPAddress = IPAddress.Parse( IPAddress int realPort = Convert.ToInt32(_realPort);

EndPoint(realIPAddress, realPort); _realEP = new IP Console.Write("Proxy listening on ");

David Llamas 106 BSc (Hons) Software Technology, 2004

s.AppSettings["ListeningIP"];

IPAddress = IPAddress.Parse(listeningIP); ningPort =

ngPort"]); gPort);

_listeningEP = new IPEndPoint(listeningIPAddress, listeningPort);

/// <summary> / The/ </s

Setup();

et(AddressFamily.InterNetwork, SocketType.Stream, otocolType.Tcp);

syncCallback(ProcessRequest), server);

e running until the user presses a key to exit the ation.

/// </summary> / <pa name sulatic void Pro Req

WriteLine("");

Console.WriteLine(e.Message);

ole.WriteLine("");

y - Begin the acceptance of another connection so that even if this request failed

ing. Socket proxyServer = (Socket)result.AsyncState;

ccept(new AsyncCallback(ProcessRequest), proxyServer);

}

individual request /// </summary>

param name="result">Details about the connection.</param> d ProcessRequestProtected(IAsyncResult result)

he clients.

5000;

{ .TickCount > end)

dClient.Shutdown(SocketShutdown.Both);

string listeningIP = ConfigurationSetting Console.Write(listeningIP); IPAddress listening int listeConvert.ToInt32(ConfigurationSettings.AppSettings["Listeni Console.WriteLine(":[0}", listenin } // main entry point for the application. // ummary> [STAThread] static void Main() { Socket server = new SockPr server.Bind(_listeningEP); server.Listen(5); server.BeginAccept(new A // Continu // applic while(Console.In.Peek() == -1); } /// <summary> /// Callback - When a client connection is accepted // ram ="re t">Details about the connection</param> st cess uest(IAsyncResult result) { try { // Process the request ProcessRequestProtected(result); } catch(Exception e) { Console. Console.WriteLine(""); Console.WriteLine(new string('-',80)); Console.WriteLine(e.StackTrace); Console.WriteLine(new string('-',80)); Console.WriteLine(""); Cons } finally { // Finall // // some how the RPS keeps go proxyServer.BeginA } /// <summary> /// Processes an /// < static voi { const int bufferSize = 65536; // 64Kb // Accepts t Socket proxyServer = (Socket)result.AsyncState; Socket endClient = proxyServer.EndAccept(result); byte[] response = new byte[bufferSize]; // Read the request from the client. int size; int end = System.Environment.TickCount+ while((size = endClient.Available) == 0) if (System.Environment { // Waiting too long. en

David Llamas 107 BSc (Hons) Software Technology, 2004

[size];

st so it can be sent to the real server quest = ModifyRequest(buffer);

he request to the real server pClieoxyCltwork

it directly

int bytes = ns.Read(response,0,bufferSize); WriteResponse(counter, response, bytes);

nter += bytes;

ponseHeader(response, bytes);

e go use a different // calculation to get the header length;

e); else

th = GetHeaderLength(response, bytes, false); th = expectedLength + headerLength;

SocketFlags.None);

th) continue; // End of data???

ata. ironment.TickCount+5000;

ent.TickCount; ticks<end;

break;

ble);

ections ns.Close();

Shutdown(SocketShutdown.Both);

ader">The buffer containing the header</param>

are in use</param> rch forwards,

/// false = search backwards</param> r in bytes</returns> end of the header by the use of

/// a double new line (0D 0A 0D 0A)</remarks> eader, int headerLength, bool searchForwards)

4; i++)

endClient.Close(); return; } } byte[] buffer = new byte endClient.Receive(buffer); // Modify the reque byte[] re // Send t Tc nt proxyClient = new TcpClient(); pr ient.Connect(_realEP); Ne Stream ns = proxyClient.GetStream(); ns.Write(request, 0, request.Length); // Get the response from the real server and pass // to the end client. int headerLength = 0; int expectedLength = 0; int totalLength = 0; bool firstTime = true; int counter = 0; do { cou if (firstTime) { expectedLength = GetLengthFromRes // If it looks like we've got everything in on if (expectedLength < bytes) headerLength = GetHeaderLength(response, bytes, tru headerLeng totalLeng firstTime = false; } endClient.Send(response,0, bytes, if (counter >= totalLeng // Wait a maximum of 5 seconds to retrieve more d end = System.Env for(int ticks = System.Environmticks=Environment.TickCount) { if (ns.DataAvailable) System.Threading.Thread.Sleep(0); } } while(ns.DataAvaila // Close the conn endClient. endClient.Close(); } /// <summary> /// Determines the length of the HTTP Header /// </summary> /// <param name="he /// <param name="headerLength">The number of bytes in the buffer that /// /// <param name="searchForwards">true = sea /// <returns>The length of the heade /// <remarks>The search determines the private static int GetHeaderLength(byte[] h { if (searchForwards) { for(int i=0; i<headerLength- {

David Llamas 108 BSc (Hons) Software Technology, 2004

}

backwards because most commonly the first packet the length can be found by

buffer

((header[i] == 0x0D) && (header[i+1] == 0x0A) &&

+2] == 0x0D) && )

return 0;

/// <summary> length of the response from the HTTP header

/summary> /// <param name="header">the buffer that contains the /// header</param>

eaderLength">the length of the buffer that is in

ngth in bytes of the Response</returns> ] header, int headerLength)

string response; UTF8Encoding().GetDecoder();

ount(header, 0, headerLength);

return the value System.IO.StringReader sr = new StringReader(response);

l) {

ToLower();

.Substring(15); th = Convert.ToInt32(l);

return length;

console /// </summary>

/ <pa sponse the / bu

/ <pa the buffer to output</param> / <re

e position within the actual response.

te static void WriteResponse(int counter, byte[] buffer, int length) {

char[] line = new char[72];

int lineCounter = 0; int bufferCounter = 0; bool writtenLine = false; Console.Write("{0,4:X4}: ", counter); while(true) { writtenLine = false; int rawCode = buffer[bufferCounter];

if ((header[i] == 0x0D) && (header[i+1] == 0x0A) && (header[i+2] == 0x0D) && (header[i+3] == 0x0A)) { return i+4; } } else { // Going // of data is just the header so // testing just the last 4 bytes of the for(int i=headerLength-4; i>=0; i--) { if (header[i (header[i+3] == 0x0A) { return i+4; } } } } /// Determines the /// < /// <param name="h /// use</param> /// <returns>The le private static int GetLengthFromResponseHeader(byte[ { // Decode the response Decoder dc = new System.Text. int count = dc.GetCharC char[] result = new char[count]; dc.GetChars(header, 0, headerLength, result, 0); response = new string(result); // Find the "content-length" data ans string line; while((line = sr.ReadLine()) != nul line = line.Trim(). if (line.ToLower().StartsWith("content-length")) { string l = line int leng } } return 0; } /// <summary> /// (For debugging) Writes the response to the // ram name="counter">the position within the re // ffer contains the data for</param> /// <param name="buffer">The buffer containing the response</param> // ram name="length">The length of // marks>The buffer need not refer to the start of the response /// so the counter marks th /// </remarks> priva

David Llamas 109 BSc (Hons) Software Technology, 2004

string hexCode = string.Format("{0,2:X2}", rawCode); awCode>=32)?(char)rawCode:'.'; eCounter*3) + (lineCounter/4);

int neCounter;// + (lineCounter/4);

bufferCounter);

er.

der(); h);

request = new string(result);

Console.WriteLine(""); WriteLine(request);

// Find the host int serverIndex = request.ToLower().IndexOf("host:");

(serverIndex <= 0)

erIndex+=5;

// Replace the original host address with the real host x = request.IndexOfAny(crlf, serverIndex); = string.Concat(request.Substring(0,serverIndex),

_realPort, request.Substring(endServerIndex)).ToCharArray();

Console.WriteLine(">>> Changed to >>>"); iteLine(newRequest);

the request into a byte buffer etEncoder();

}

char charCode = (r int codePos = (lin

charPos = 52+li line[codePos] = hexCode[0]; line[codePos+1] = hexCode[1]; line[charPos] = charCode; lineCounter++; if (lineCounter>=16) { lineCounter = 0; Console.WriteLine(line); writtenLine = true; line = new char[72]; } bufferCounter++; if (bufferCounter >= length) { if (!writtenLine) Console.WriteLine(line); break; } if (writtenLine) Console.Write("{0,4:X4}: ", counter+ } } /// <summary> /// Modifies the request so that it can be sent to the real serv /// </summary> /// <param name="buffer">the request bufer</param> /// <returns>the modified HTTP request</returns> static byte[] ModifyRequest(byte[] buffer) { // Decode the request string request; Decoder dc = new System.Text.UTF8Encoding().GetDeco int count = dc.GetCharCount(buffer, 0, buffer.Lengt char[] result = new char[count]; dc.GetChars(buffer, 0, buffer.Length, result, 0); Console. if return buffer; serv int endServerInde char[] newRequest _realIP, ":", Console.Wr // Re-encode Encoder ec = new System.Text.UTF8Encoding().G count = ec.GetByteCount(newRequest,0,newRequest.Length,true); byte[] ret = new byte[count]; ec.GetBytes(newRequest,0, newRequest.Length, ret, 0,true); return ret; } }

David Llamas 110 BSc (Hons) Software Technology, 2004

bject.cs

////////////////////////////////////// //

// //

and Data Hiding in TCP/IP // // ho s //

Studen

// BSc (H //

ier ity // //

// Email: 932 @napie d@s eganog /

y.org //

// Copyri C) apier Universi

//

// // //

ed to, // rticular purpose. //

// //

ool uting // 10 Colinton Road //

nbu // Scotla

/// //////////////////////////////////////

ste

me pace S r

private byte[] _buffer; ivate cket ket

aram> ddress">The IP Address to filter on</param>

t to filter on</param> Socket socket, IPAddress filterAddress, UInt16 filterPort) {

_buffer = new byte[2048]; _socket = socket;

erPort;

r socket

return _socket; }

}

10.4.5 SnifferStateO //////////////////////////////

// // Module 42019 - Honours Project 2003/2004

// ert Analysis// Cov Channel

//// Aut r: David Llama// // // t 01009322 // // // ons) Software Technology // Nap Univers// Edinburgh // // 0100 2 r.ac.uk // // davi t raphy.org /// [email protected] // // // // Web : http://www.dcs.napier.ac.uk // // http://www,steganograph// http://www.inchcolm.org // // // //// ght ( N ty and David Llamas 2004 // // // // // This software has been developed **ONLY** for educational // // purposes. // // It is provided "as is", and the owner makes no warranty,// either express or implied, including but not limit// warranties of fitness for a pa// // Napier University // Sch of Comp//// Edi rgh EH10 5DT // nd // // // //////// /////////////////// using Sy m; using System.Net; using System.Net.Sockets; na s niffe{ /// <summary> /// Handles the state of the sniffer with respect to the network /// </summary> public class StateObject { pr So _soc ; private byte[] _ipAddress; private UInt16 _port; /// <summary> /// Constructs the state object /// </summary> /// <param name="socket">The sniffer socket</p /// <param name="filterA /// <param name="filterPort">The por public StateObject( _ipAddress = filterAddress.GetAddressBytes(); _port = filt } /// <summary> /// Gets the sniffe /// </summary> public Socket Socket { get {

David Llamas 111 BSc (Hons) Software Technology, 2004

/// <summary> /// Gets the buffer

get {

and with)

F) * 4;

t positions of the TCP header ];

and with)

{ // If the source IP matches the target IP

if ((_buffer[12] == _ipAddress[0]) && (_buffer[13] == _ipAddress[1]) && (_buffer[14] == _ipAddress[2]) && (_buffer[15] == _ipAddress[3]))

// The length of the IP header int headerLength = (_buffer[0] & 0x0F) * 4;

// The Source Port are the first positions of the TCP header UInt16 port = _buffer[headerLength];

port*=256; port+=_buffer[headerLength+1];

rt == _port)

return true;

}

/// Gets whether a packet is coming from the target.

get

acketSentToTarget));

}

/// </summary> public byte[] Buffer {

return _buffer; } } /// <summary> /// Determines if the packet was sent to the target address /// port (the filter IP and port the object was constructed /// </summary> private bool PacketSentToTarget { get { // If the DESTINATION IP matches the target IP if ((_buffer[16] == _ipAddress[0]) && (_buffer[17] == _ipAddress[1]) && (_buffer[18] == _ipAddress[2]) && (_buffer[19] == _ipAddress[3])) { // The length of the IP header int headerLength = (_buffer[0] & 0x0 // The DESTINATION Port are the firs UInt16 port = _buffer[headerLength+2 port*=256; port+=_buffer[headerLength+3]; if (port == _port) return true; return false; } return false; } } /// <summary> /// Determines if the packet was received from the target IP /// port (the filter IP And port this object was constructed /// </summary> private bool PacketReceivedFromTarget { get { if (po return false; return false; } } /// <summary> /// </summary> public bool MatchFilter { { return PacketReceivedFromTarget; // return ((PacketReceivedFromTarget) || (P } } }

David Llamas 112 BSc (Hons) Software Technology, 2004

cs

//////////////// //

P/IP // //

// //

//

// //

// Web : :// ww.dcs

//

// //

Copyri C) apier

// arranty, //

e. // //

//

// //

tla // //

/// /////////////////////////////////////

stein Syste

ste tions;

wer

/ <suum or Form1.

/ </sblic

abel1; te System.Windows.Forms.TextBox PortTextBox;

alIPTextBox; ows.Forms.TextBox RemoteIPTextBox;

l label3;

10.4.6 CovertViewer. ////////////////////////////////////////////////////

// // Module 42019 - Honours Project 2003/2004 //

// // // Covert Channel Analysis and Data Hiding in TC

// // Author: David Llamas // // Student 01009322 // // // BSc (Hons) Software Technology // // Napier University // // Edinburgh // // // // Email: [email protected] // [email protected] // [email protected] // // // http w .napier.ac.uk // // http://www,steganography.org //// http://www.inchcolm.org // // // ght ( N University and David Llamas 2004 // // // // // // This software has been developed **ONLY** for educational // // purposes. // // // It is provided "as is", and the owner makes no w// either express or implied, including but not limited to, // // warranties of fitness for a particular purpos// // Napier University // School of Computing //// 10 Colinton Road // Edinburgh EH10 5DT // Sco nd ////////// //////////////////// using Sy m; us g m.Drawing; using Sy m.Collecusing System.ComponentModel; using System.Diagnostics; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets; using System.Text; namespace CovertVie{ // mmary> /// S mary description f // ummary> pu class ViewerForm : System.Windows.Forms.Form { private System.Windows.Forms.Label l priva private System.Windows.Forms.Label label2; private System.Windows.Forms.Button GoButton; private System.Windows.Forms.Button stopButton; private System.Windows.Forms.Panel resultPanel; private System.Windows.Forms.TextBox[] hexValuesTextBox; private System.Windows.Forms.TextBox[] asciiValuesTextBox; private bool _stopping = false; private System.Windows.Forms.TextBox Loc private System.Wind private System.Windows.Forms.Labe /// <summary> /// Required designer variable.

David Llamas 113 BSc (Hons) Software Technology, 2004 ivate

for Windows Form Designer support

16];

; i<16; i++)

ndows.Forms.TextBox(); ndows.Forms.BorderStyle.None;

"Courier New", 8.25F,

ocation = new System.Drawing.Point(0, i*16); "textBox1";

eadOnly = true;

? ?? ?? ?? ?? ??"; Add(tb);

ciiValuesTextBox[i] = new System.Windows.Forms.TextBox(); orderStyle = System.Windows.Forms.BorderStyle.None;

5F, t.Point, ((System.Byte)(0)));

6);

abIndex = 1; ?????????????";

;

e( bool disposing )

components.Dispose();

egion

this method with the code editor.

lizeComponent()

dows.Forms.TextBox();

Forms.Label(); abel();

tton = new System.Windows.Forms.Button(); w System.Windows.Forms.Panel();

IPTextBox = new System.Windows.Forms.TextBox();

ng.Point(56, 8);

/// </summary> pr System.ComponentModel.Container components = null; public ViewerForm() { // // Required // InitializeComponent(); this.hexValuesTextBox = new TextBox[16]; this.asciiValuesTextBox = new TextBox[ TextBox tb; for(int i=0 { // // textBox1 // tb = this.hexValuesTextBox[i] = new System.Wi tb.BorderStyle = System.Wi tb.Font = new System.Drawing.Font(System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); tb.L tb.Name = tb.R tb.Size = new System.Drawing.Size(360, 13); tb.TabIndex = 0; tb.Text = "?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ? this.resultPanel.Controls. // // textBox2 // tb = this.as tb.B tb.Font = new System.Drawing.Font("Courier New", 8.2System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUni tb.Location = new System.Drawing.Point(384, i*1 tb.Name = "textBox2"; tb.ReadOnly = true; tb.Size = new System.Drawing.Size(142, 13); tb.T tb.Text = "??? this.resultPanel.Controls.Add(tb) } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispos { if( disposing ) { if (components != null) { } } base.Dispose( disposing ); } #r Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of /// </summary> private void Initia { this.LocalIPTextBox = new System.Win this.PortTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows. this.label2 = new System.Windows.Forms.L this.GoButton = new System.Windows.Forms.Button(); this.stopBu this.resultPanel = ne this.Remote this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // LocalIPTextBox // this.LocalIPTextBox.Location = new System.Drawi this.LocalIPTextBox.MaxLength = 15;

David Llamas 114 BSc (Hons) Software Technology, 2004

; wing.Size(104, 20);

1";

rtTextBox"; 0, 20);

this.PortTextBox.Text = "8003"; //

l1 //

1.Location = new System.Drawing.Point(8, 8);

Size = new System.Drawing.Size(48, 20); el1.TabIndex = 2;

ext = "Local IP:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

// label2 //

2.Location = new System.Drawing.Point(328, 8);

Size = new System.Drawing.Size(32, 20);

MiddleRight; //

rawing.Point(416, 8); utton.Name = "GoButton";

g.Size(56, 20); ex = 4;

Listen"; on.Click += new System.EventHandler(this.GoButton_Click);

480, 8); Button";

, 20);

Button.Click += new System.EventHandler(this.stopButton_Click);

Panel

is.reSize(528, 256);

ation = new System.Drawing.Point(224, 8); teIPTextBox.MaxLength = 15;

this.RemoteIPTextBox.Name = "RemoteIPTextBox"; ;

x.Text = "213.123.198.144";

// label3 //

this.label3.Location = new System.Drawing.Point(160, 8); 3.Name = "label3";

(64, 20); TabIndex = 9;

wing.ContentAlignment.MiddleRight; //

awing.Size(5, 13); m.Drawing.Size(546, 303);

ntrols.Add(this.LocalIPTextBox); this.Controls.Add(this.resultPanel);

this.LocalIPTextBox.Name = "LocalIPTextBox" this.LocalIPTextBox.Size = new System.Dra this.LocalIPTextBox.TabIndex = 0; this.LocalIPTextBox.Text = "192.168.1.2 // // PortTextBox // this.PortTextBox.Location = new System.Drawing.Point(360, 8); this.PortTextBox.MaxLength = 5; this.PortTextBox.Name = "Po this.PortTextBox.Size = new System.Drawing.Size(4 this.PortTextBox.TabIndex = 1; // labe this.label this.label1.Name = "label1"; this.label1. this.lab this.label1.T // this.label this.label2.Name = "label2"; this.label2. this.label2.TabIndex = 3; this.label2.Text = "Port:"; this.label2.TextAlign = System.Drawing.ContentAlignment. // GoButton // this.GoButton.Location = new System.D this.GoB this.GoButton.Size = new System.Drawin this.GoButton.TabInd this.GoButton.Text = " this.GoButt // // stopButton // this.stopButton.Enabled = false; this.stopButton.Location = new System.Drawing.Point( this.stopButton.Name = "stop this.stopButton.Size = new System.Drawing.Size(56 this.stopButton.TabIndex = 6; this.stopButton.Text = "Stop"; this.stop // // result // this.resultPanel.Location = new System.Drawing.Point(8, 40); th sultPanel.Name = "resultPanel"; this.resultPanel.Size = new System.Drawing. this.resultPanel.TabIndex = 7; // // RemoteIPTextBox // this.RemoteIPTextBox.Loc this.Remo this.RemoteIPTextBox.Size = new System.Drawing.Size(104, 20) this.RemoteIPTextBox.TabIndex = 8; this.RemoteIPTextBo // this.label this.label3.Size = new System.Drawing.Size this.label3. this.label3.Text = "Remote IP:"; this.label3.TextAlign = System.Dra // ViewerForm // this.AutoScaleBaseSize = new System.Dr this.ClientSize = new Syste this.Controls.Add(this.label3); this.Controls.Add(this.RemoteIPTextBox); this.Controls.Add(this.PortTextBox); this.Co

David Llamas 115 BSc (Hons) Software Technology, 2004

ols.Add(this.stopButton);

s.Add(this.label2); ;

ms.FormBorderStyle.FixedSingle; this.MaximizeBox = false;

s.Forms.SizeGripStyle.Hide; "Covert Information Viewer";

ing += new

this.ResumeLayout(false);

point for the application.

The user has pressed the GO button

ram> s e)

false; bled=true;

{ localIpa = IPAddress.Parse(this.LocalIPTextBox.Text);

oteIpa = IPAddress.Parse(this.RemoteIPTextBox.Text);

hronous socket et = new

ddr Raw,ProtocolType.IP); ocalIpa,0));

SetupSocket(socket);

e(ex.Message);

ffer"+

Error); this.GoButton.Enabled=true;

this.stopButton.Enabled=false; urn;

so = new StateObject(socket, remoteIpa, port); fer, 0, so.Buffer.Length, SocketFlags.None, new

yn Callba

with the loopback adapter. tSocketOption(SocketOptionLevel.IP,SocketOptionName.HeaderIncluded,1);

}; T = new byte[4];

int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT); ret_code = OUT[0] + OUT[1] + OUT[2] + OUT[3];

this.Contr this.Controls.Add(this.GoButton); this.Control this.Controls.Add(this.label1) this.FormBorderStyle = System.Windows.For this.Name = "ViewerForm"; this.SizeGripStyle = System.Window this.Text = this.ClosSystem.ComponentModel.CancelEventHandler(this.ViewerForm_Closing); } #endregion /// <summary> /// The main entry /// </summary> [STAThread] static void Main() { Application.Run(new ViewerForm()); } /// <summary> /// Event handler - /// </summary> /// <param name="sender"></param> /// <param name="e"></pa private void GoButton_Click(object sender, System.EventArg { _stopping = false; this.GoButton.Enabled= this.stopButton.Ena IPAddress localIpa, remoteIpa; UInt16 port; Socket socket; try rem port = Convert.ToUInt16(this.PortTextBox.Text); // Set up the Async sockSocket(A essFamily.InterNetwork,SocketType. socket.Bind(new IPEndPoint(l } catch(Exception ex) { System.Diagnostics.Debug.WriteLin System.Diagnostics.Debug.WriteLine(ex.StackTrace); MessageBox.Show("An error occurred when setting up the sni Environment.NewLine+ ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon. ret } StateObject socket.BeginReceive(so.BufAs c ck(ReceivePacket), so); } /// <summary> /// Sets up the given socket as a sniffer socket /// </summary> /// <param name="socket">The socket to become the sniffer</param> private void SetupSocket(Socket socket) { // NOTE: This doesn't work socket.Se byte []IN = new byte[4]{1, 0, 0, 0 byte []OU int SIO_RCVALL = unchecked((int)0x98000001); }

David Llamas 116 BSc (Hons) Software Technology, 2004

cResult result)

StateObject so = (StateObject)result.AsyncState; ;

try {

bytes = socket.EndReceive(result);

so.MatchFilter)

so);

}

catch(Exception e) {

Debug.WriteLine(e); Debug.WriteLine(e.StackTrace); MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButtons.OK,

MessageBoxIcon.Warning); } finally { Application.DoEvents(); if (_stopping == true) { this.GoButton.Enabled=true; this.stopButton.Enabled=false; } else { // Get the next packet. socket.BeginReceive(so.Buffer,0, so.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceivePacket), so); } } } /// <summary> /// Update the displayed hex values according to the information /// received in the state object /// </summary> /// <param name="so"></param> private void UpdateHex(StateObject so) { int i = so.CovertOffset/16; int j = so.CovertOffset%16; string currentValue = this.hexValuesTextBox[i].Text; int leftLen = j*3+(j/4)+((j/8)); string leftString = currentValue.Substring(0,leftLen); string rightString = currentValue.Substring(leftLen+2); string replaceString = ((int)so.CovertCharacter).ToString("X2"); this.hexValuesTextBox[i].Text = string.Concat(leftString, replaceString, rightString); } /// <summary> /// Update the information in the character portion of the display /// with values in the state object /// </summary> /// <param name="so"></param> private void UpdateChar(StateObject so) { // The controls are made up of 16 Label Controls with // 16 characters in each control. int i = so.CovertOffset/16; int j = so.CovertOffset%16; string currentValue = this.asciiValuesTextBox[i].Text; int leftLen = j; string leftString = currentValue.Substring(0,leftLen); string rightString = currentValue.Substring(leftLen+1); char replaceChar = so.CovertCharacter; if (replaceChar<32) { replaceChar = '.'; } this.asciiValuesTextBox[i].Text = string.Concat(leftString, replaceChar, rightString); }

/// <summary> /// Callback - A packet has been received. /// </summary> /// <param name="result"></param> private void ReceivePacket(IAsyn { Socket socket = so.Socket int if ( { UpdateHex( UpdateChar(so); }

David Llamas 117 BSc (Hons) Software Technology, 2004

/// <summary> ed the form/application to close

/// <param name="e"></param> onentModel.CancelEventArgs e)

s e)

/// Event Handler = The user has request/// </summary> /// <param name="sender"></param>

private void ViewerForm_Closing(object sender, System.Comp { _stopping = true; } /// <summary> /// Event handler - The user has pressed the stop button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void stopButton_Click(object sender, System.EventArg { _stopping = true; } } }

David Llamas 118 BSc (Hons) Software Technology, 2004

/ ////////////////////////////////// // ule 2003/2004 // //

nd Data Hiding in TCP/IP // //

// //

den 22 // //

(H logy // Napier

nbu // //

il: [email protected] // y.org //

rg //

// 004 //

// // This s re as bee onal // purpos // It is ded "as is

purpose. // //

// //

// Edinburgh EH10 5DT //

// //

/// /////////////////////////////////////////////////

stein Systein Syste

of the socket.

private byte[] _buffer; cket;

/summary> cket">The socket that will be sniffing</param> lterAddress">The Source IP Address to filter on</param>

filter on</param> ss filterAddress, UInt16 filterPort)

socket;

_ipAddress = filterAddress.GetAddressBytes(); _port = filterPort; }

/// <summary> /// Gets the socket /// </summary> public Socket Socket { get

10.4.7 CovertViewerStateObject.cs // /////// / ///////////////////////

// // Mod 42019 - Honours Project

// // Covert Channel Analysis a

// // Author: David Llamas // // Stu t 010093//// BSc ons) Software Techno// University // // Edi rgh // // Ema 0100932// david@steganograph// [email protected]// // // Web : http://www.dcs.napier.ac.uk // // http://www,steganography.org // // http://www.inchcolm.org // // // // // Copyright (C) Napier University and David Llamas 2// //// oftwa h n developed **ONLY** for educati// es. // //// provi ", and the owner makes no warranty, // // either express or implied, including but not limited to, // // warranties of fitness for a particular // // Napier University // School of Computing // 10 Colinton Road //// Scotland // //////// //////// using Sy m; us g m.Net; us g m.Net.Sockets; namespace CovertViewer { /// <summary> /// Represents the state /// </summary> public class StateObject { private Socket _so private byte[] _ipAddress; private UInt16 _port; /// <summary> /// Constructs the state object /// < /// <param name="so /// <param name="fi /// <param name="filterPort">The Source TCP Port to public StateObject(Socket socket, IPAddre { _buffer = new byte[2048]; _socket =

David Llamas 119 BSc (Hons) Software Technology, 2004

{ cket;

eria

on the IP header

the TCP header

/// <summary>

public int CovertOffset {

med to a dot '.' if it is a /// non-display character). Only valid is the MatchFilter property

/// </summary> public char CovertCharacter

get

(char)_buffer[5]; if ((int)ret < 32)

}

return _so } }

/// <summary> /// Gets the buffer /// </summary> public byte[] Buffer { get { return _buffer; } } /// <summary> /// Determines if the current packet matches the filter crit /// </summary> public bool MatchFilter { get { // The Source IP Address is at postions 12-15 if (!((_buffer[12] == _ipAddress[0]) && (_buffer[13] == _ipAddress[1]) && (_buffer[14] == _ipAddress[2]) && (_buffer[15] == _ipAddress[3]))) { return false; } // The length of the IP header int headerLength = (_buffer[0] & 0x0F) * 4; // The Source Port are the first positions of UInt16 port = _buffer[headerLength]; port*=256; port+=_buffer[headerLength+1]; if (port != _port) return false; return true; } } /// Gets the offset of the covert character for this packet. Only valid /// if the MatchFilter property is true /// </summary> get { return _buffer[4]; } } /// <summary> /// Gets the covert character (refor /// is true. { { char ret = ret = '.'; return ret; } } }

David Llamas 120 BSc (Hons) Software Technology, 2004

// nours Project 2003/2004 //

/

// Author: David Llamas // //

01009322 // //

// // // //

// // mas 2004 // // // **ONLY** for educational // // // ner makes no warranty, // warranties of fitness for a particular purpose. // // / School of Computing // // /////////////////////////////

T TION E IS IN OPERATION AS THE NETWORK INTERFACE M

T y of creating macros which make exporting from a DLL simpler. All files within this DLL are compiled with the COVERTAGENT_EXPORTS symbol defined on the command line. this symbol should not be defined on any project that uses this DLL. This way any other project whose source files include this file see

// COVERTAGENT_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifdef COVERTAGENT_EXPORTS #define COVERTAGENT_API __declspec(dllexport) #else #define COVERTAGENT_API __declspec(dllimport) #endif const int c_MaxMessages = 128; #define CIFLAG_NONE 0x00000000 #define CIFLAG_PERMANENT 0x00000001 // TODO: The LastAccessed time will always be the last time // the item was accessed. The Flags store boolean values. // 0x00000001 == Permanent Message // // When a new client connects it has an array entry created for it. // if the array is full the items are sorted by the time last // accessed (permanent items are always places at the "Newest" items // end of the array) The item with the oldest date stamp is removed // and replaced with the new entry. struct CovertInformation { unsigned __int32 IPAddress; unsigned __int16 Port; LPCSTR HiddenInformation;

10.4.8 CovertAgent.h

//////////////////////////////////////////////////// ////////////////// Module 42019 - Ho//

// // TCP/IP /// Covert Channel Analysis and Data Hiding in

// ////// Student// // BSc (Hons) Software Technology // // Napier University // // Edinburgh //// Email: [email protected] // // [email protected] // [email protected] // //// Web : http://www.dcs.napier.ac.uk // // http://www,steganography.org // // http://www.inchcolm.org // // //// Copyright (C) Napier UNiversity and David Lla// //// This software has been developed // purposes. //// It is provided "as is", and the ow// either express or implied, including but not limited to, // //// // Napier University ///// 10 Colinton Road // // Edinburgh EH10 5DT // // Scotland // // // // /////////////////////////////////// // HE FUNCTIONS IN THIS DLL ARE NOT THREAD SAFE. DO NOT CALL ANY OTHER FUNC// SPECIALLY WHEN THE Cycle() FUNCTION // AY FAIL REQUIRING THE PC TO BE REBOOTED! // he following ifdef block is the standard wa// ////

David Llamas 121 BSc (Hons) Software Technology, 2004

DWORD CurrentOffset; SYSTEMT DWORD F

overtInf

This is the number of message set up so far, and is the index of the

ge was placed. 2 IPAddress, unsigned __int16

to

d __int16 port, LPCSTR Message);

is the index of the nation was found. nt32 IPAddress, unsigned __int16

;

would top

// NOTE: The network traffic will be queued until the Cycle() function // can process it. This method must be called frequently in order that

COVERTAGENT_API int __stdcall Cycle(int timeout);

er. stdcall TearDown();

IME LastAccessed; lags; ormation; } _c

//// next entry. int g_nMessages = 0; // The array of messages to be sent - A maximum of 100 can be sent CovertInformation g_InfoArray[c_MaxMessages]; CovertInformation g_DefaultMessage; extern "C" { // The return value is the index into to the array where the messa COVERTAGENT_API int __stdcall AddCovertInformation(unsigned __int3Port, LPCSTR Message); // Sets the default information. This is the message covertly sent // clients that are not known in advance. COVERTAGENT_API void __stdcall SetDefaultCovertInformation(unsigne // Removes a message - It will no longer be sent, the return value // message that was removed, or -1 if no such IPAddress/Port combi COVERTAGENT_API int __stdcall RemoveCovertInformation(unsigned __iPort); // Opens the driver and sets up the adapters. COVERTAGENT_API int __stdcall SetupAdapters(); // Returns the number of adapters COVERTAGENT_API int __stdcall GetAdapterCount(); // Returns the name of an adapter. COVERTAGENT_API unsigned char* __stdcall GetAdapterName(int index) // Selectes the adapter and inserts the hook. COVERTAGENT_API int __stdcall Initialise(int adapterIndex); // Performs a processing cycle - The cycle will last approximately // the length of the timeout. This will allow the calling process // a time to process statistics in a safe manner (the alternative // be to set two threads and have a critical section which would s // the network processing anyway.) // // network traffic can proceed. // Unhooks the driv COVERTAGENT_API int __}

David Llamas 122 BSc (Hons) Software Technology, 2004

pp

////////////////////////////////////////// //

Module 42019 - Honours Project 2003/2004 // // Covert Channel Analysis and Data Hiding in TCP/IP //

//

Technology // Napier University // // // /

aphy.org // [email protected] //

// uk //

// //

// // Copyright (C) Napier UNiversity and David Llamas 2004 // //

ducational //

// It is provided "as is", and the owner makes no warranty, // either express or implied, including but not limited to, // //

er University // School //

// //

tla // //

////

"D

efine swap16(value) ( ((value&0xFF00) >> 8) + ((value&0x00FF)<<8) )

OL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call,

lpReserved )

AD_ATTACH: case DLL_THREAD_DETACH:

return TRUE;

_REQUEST Request; TEND Event;

HO

PUCHAR pBuffer;

10.4.9 CovertAgent.c //////////////////////////

// //////// // // Author: David Llamas // // // // Student 01009322 // // // BSc (Hons) Software// // Edinburgh // // Email: [email protected] /// david@steganogr//// // Web : http://www.dcs.napier.ac.// http://www,steganography.org // http://www.inchcolm.org // //// //// //// This software has been developed **ONLY** for e// purposes. // // // //// warranties of fitness for a particular purpose. // // // Napi// of Computing // 10 Colinton Road // Edinburgh EH10 5DT // Sco nd // //////////////////////////////////////////////////////////////// // CovertAgent.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #include "CovertAgent.h" #include ebug.h" #d BO LPVOID { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THRE case DLL_PROCESS_DETACH: break; } } TCP_AdapterList AdList; DWORD g_adapterIndex = 0xFFFFFFFF; HANDLE api; ETHIN RMEDIATE_BUFFER PacketBuffer; HA LE h US RT ntohs( USHORT netshort ) { USHORT nResult;

David Llamas 123 BSc (Hons) Software Technology, 2004

nResult = ( (pBuffer[ 0 ] << 8) & 0xFF00 ) | ( pBuffer[ 1 ] & 0x00FF );

S c index in the InfoArray. Address and Port determine which client machine/process is

t recei rt information

Cov mationAt(int index, unsigned __int32 IPAddress, unsigned __int16 Port, LPCSTR ss ge, DW lag

age);

x].LastAccessed)); x].Flags=Flags;

This internal version needs to have the flags parameter so that

_int32 IPAddress, unsigned __int16 Port, LPCSTR Message, RD Flags)

heck for the existance of the IP Address & Port already in use. for (int i = 0; i<g_nMessages; i++) {

].IPAddress == IPAddress) && (g_InfoArray[i].Port == Port)) ||

].IPAddress == 0)) {

InfoArray[i].HiddenInformation) {

HANDLE hheap = GetProcessHeap(); HeapFree(hheap, 0, (LPVOID)g_InfoArray[i].HiddenInformation);

SetCovertInformationAt(i, IPAddress, Port, Message, Flags);

}

mationAt(g_nMessages, IPAddress, Port, Message, Flags);

g_nMessages++;

This version - which is exposed will allow a message to b

tInformation(unsigned __int32 IPAddress, unsigned __int16 Port, STR Message)

tion(unsigned __int32 IPAddress, unsigned

MANENT);

T if there is no specific message for the destination IP/Port.

void __stdcall SetDefaultCovertInformation(unsigned __int16 port, LPCSTR Message)

("COVERTAGENT_API int __stdcall SetDefaultCovertInformation(LPCSTR Message)\n"); age);

E hheap = GetProcessHeap(); R p = (LPSTR)HeapAlloc(hheap, HEAP_ZERO_MEMORY, len+1);

g_DefaultMessage.IPAddress=0;

nResult = 0; pBuffer = (PUCHAR )&netshort; return( nResult ); } // ets the covert information at a specifi// The IP// o ve the message. The flags determine how this cove// is to be processed. void Set ertInforMe a ORD F s) { size_t len = strlen(Mess HANDLE hheap = GetProcessHeap(); LPSTR p = (LPSTR)HeapAlloc(hheap, HEAP_ZERO_MEMORY, len+1); strcpy(p, Message); g_InfoArray[index].IPAddress=IPAddress; g_InfoArray[index].Port=Port; g_InfoArray[index].HiddenInformation=p; GetSystemTime(&(g_InfoArray[inde g_InfoArray[inde } //// it can insert the item correctly int the array. int __stdcall IntAddCovertInformation(unsigned _DWO{ // C if (((g_InfoArray[i (g_InfoArray[i // Remove the existing message if (g_ } return i; } SetCovertInfor return g_nMessages-1; } // // e added to the array as normal. COVERTAGENT_API int __stdcall AddCoverLPC{ _DWL0("COVERTAGENT_API int __stdcall AddCovertInforma__int16 Port, LPCSTR Message)\n"); return IntAddCovertInformation(IPAddress, Port, Message, CIFLAG_PER} // his will set the default covert message. This is the message that is used //COVERTAGENT_API{ _DWL0 size_t len = strlen(Mess HANDL LPST strcpy(p, Message);

David Llamas 124 BSc (Hons) Software Technology, 2004

GetSystemTime(&(g_DefaultMessage.LastAccessed));

Removes the covert information from the Array. VE t32 IPAddress, unsigned __int16 Port)

WL0(" ss, unsigned Por

t i = 0; i<g_nMessages; i++)

if ((g_InfoArray[i].IPAddress == IPAddress) &&

ing message if (g_InfoArray[i].HiddenInformation)

Heap(); HeapFree(hheap, 0, (LPVOID)g_InfoArray[i].HiddenInformation);

}

g_InfoArray[i].IPAddress=0; g_InfoArray[i].Port=0;

g_InfoArray[i].LastAccessed=0;

turn

the filter driver and sets up the available Adapter information. VE ll SetupAdapters()

fddapters()\n");

nd

api = OpenFilterDriver();

if(!IsDriverLoaded(api)) {

load.\n");

else

}

_DWL1("There are %d adapters available\n", AdList.m_nAdapterCount);

le. NOTE: This must be called after the call to SetupAdapters(). VE

API int __stdcall GetAdapterCount()\n"); return AdList.m_nAdapterCount;

G he specific index. N after the call to SetupAdapters().

: If the index is out of range the return value will be NULL elease build is undetermined. ENT char* __stdcall GetAdapterName(int index)

ar* __stdcall GetAdapterName(int:=%d)\n", index);

fdef _DEBUG erCount) || (index<0) )

return NULL; }

_szAdapterNameList[index];

g_DefaultMessage.Port=port; g_DefaultMessage.HiddenInformation=p; g_DefaultMessage.Flags=CIFLAG_NONE; } //CO RTAGENT_API int __stdcall RemoveCovertInformation(unsigned __in{ _D COVERTAGENT_API int __stdcall RemoveCovertInformation(unsigned __int32 IPAddre__int16 t)\n"); for (in { (g_InfoArray[i].Port == Port)) { // Remove the exist { HANDLE hheap = GetProcess g_InfoArray[i].HiddenInformation=0; // return i; } } re -1; } // OpensCO RTAGENT_API int __stdca{ #i ef _DEBUG _DWL0("COVERTAGENT_API int __stdcall SetupA#e if _DWL0("Driver not installed on this system of failed to return 0; } { _DWL0("Driver Loaded.\n"); GetTcpipBoundAdaptersInfo (api, &AdList ); return 0; } // Gets the number of adapters availab// CO RTAGENT_API int __stdcall GetAdapterCount() { _DWL0("COVERTAGENT_ } // ets the name of the adapter at t// OTE 1: This must be called // NOTE 2// in a debug build. The result in a rCOVERTAG _API unsigned{ _DWL1("COVERTAGENT_API unsigned ch #i if ( (index>=AdList.m_nAdapt { #endif return AdList.m}

David Llamas 125 BSc (Hons) Software Technology, 2004

I N unction. VE

",adapterIndex);

nterface with such index on this system.\n"); return 0;

ADAPTER_MODE Mode;

de.dw L|MSTCP_FLAG_RECV_TUNNEL; (HANDLE)AdList.m_nAdapterHandle[adapterIndex];

pterIndex = adapterIndex;

eate notification event vent

_DWL0("Failed to create the notification event.\n");

// Set event for helper driver E)AdList.m_nAdapterHandle[adapterIndex], hEvent)))

{ _DWL0("Failed to create notification event or set it for driver.\n");

// Initialize Request QUEST) );

Request.EthPacket.Buffer = &PacketBuffer; pterHandle = (HANDLE)AdList.m_nAdapterHandle[adapterIndex];

apterMode(api, &Mode);

turn

ts the IP Address and Port number from the given packet. dress and pwPort are populated with the appropriate values.

d ExtractIPandPort(char* pPacket, DWORD* pdwIPAddress, WORD* pwPort)

int portOffset = (*(pPacket) & 0x0F)*4;

R called after an IP packet has been modified due to the addition of

covert information. sum(char* pPacket)

value; pChecksum = (WORD*)(pPacket+10);

Check

ORD sou

= (WORD*)pPacket; r(int

pWord++;

sum>>16)+(sum&0xFFFF); m+=(s

cksum = _byteswap_ushort((WORD)(~sum));

Used by the sorting algorithm to compare the Covert Information .

t

// nitialise the hook driver on the adapter with the given index. // OTE: SetupAdapters() must have been called before this fCO RTAGENT_API int __stdcall Initialise(int adapterIndex) { _DWL1("COVERTAGENT_API int __stdcall Initialise(int:=%d)\n if ( (int)(adapterIndex + 1) > (int)(AdList.m_nAdapterCount) ) { //printf("There is no network i } Mo Flags = MSTCP_FLAG_SENT_TUNNE Mode.hAdapterHandle = g_ada // Cr hE = CreateEvent(NULL, TRUE, FALSE, NULL); if (!hEvent) { } if ((!hEvent)||(!SetPacketEvent(api, (HANDL return 0; } ZeroMemory ( &Request, sizeof(ETH_RE ZeroMemory ( &PacketBuffer, sizeof(INTERMEDIATE_BUFFER) ); Request.hAda SetAd re 1; } // Extrac// pwdIPAdvoi{ // pPacket represents the start of the IP portion of the packet - past the // ethernet header where a raw socket would start. *pdwIPAddress = *(DWORD*)(pPacket+16); *pwPort = *(WORD*)(pPacket+portOffset); } // ecalculate the checksum of the IP Packet. // This is//void RecalcIPCheck{ // First Zero the existing checksum WORD* *p sum = 0; DW um = 0; int c nt = (*(pPacket) & 0x0F)*2; WORD* pWord fo i=0; i<count;i++) { sum+=_byteswap_ushort(*pWord); } sum=( su um>>16); // Assign the new checksum *pChe} //// in the arrayin __cdecl CompareCovertInfo(const void * elem1, const void * elem2) {

David Llamas 126 BSc (Hons) Software Technology, 2004

elem1 should be before elem2 then a negative number is returned // if elem1 and elem2 are equal then zero is returned.

m2 then a positive number is returned.

CovertInformation* pInfo1 = (CovertInformation*)elem1;

nt with the permanent flag is given priority.

{ ags & CIFLAG_PERMANENT)

}

element 1 is not...

SystemTimeToFileTime(&(pInfo1->LastAccessed), &ft1);

sizeof(CovertInformation), &CompareCovertInfo);

fd i=0; i<c_MaxMessages; i++)

tem %d (%s) ",i, g_InfoArray[i].Flags&CIFLAG_PERMANENT?"Permanent":"Temporary"); cessed on %02d:%02d:%02d:%03d\n",

In ccesse i].LastAccessed.wMinute, sed.wSecond, g_InfoArray[i].LastAccessed.wMilliseconds);

ndif

client "mid-flight". This is used when a client that has n re has its information set up so that it can r

rNewClient(DWORD dwIPAddress, WORD wPort)

("CovertInformation* RegisterNewClient(DWORD dwIPAddress, WORD wPort)\n"); fdef _DEBUG

signeWL5(" r, *(pAddr+1), *(pAddr+2), *(pAddr+3), swap16(wPort));

t indvertI

axMessages)

ld message essages();

foArray[index]);

essHeap(); ree(hheap, 0, (LPVOID)g_InfoArray[index].HiddenInformation);

} else

Information = &(g_InfoArray[index]);

SetCovertInformationAt(index, dwIPAddress, wPort, g_DefaultMessage.HiddenInformation, CIFLAG_NONE);

ts (%d%%)\n", g_nMessages, c_MaxMessages, (g_nMessages*100/c_MaxMessages));

// If // If elem1 should be after ele CovertInformation* pInfo2 = (CovertInformation*)elem2; // Permanent Information does not have the data considered. // The eleme if (pInfo1->Flags & CIFLAG_PERMANENT) if (pInfo2->Fl return 0; // Equal // Element 1 is marked as permanent, so it goes before // all non-permanent items. return -1; if(pInfo2->Flags & CIFLAG_PERMANENT) { // Element 2 is permanent and return 1; } FILETIME ft1, ft2; SystemTimeToFileTime(&(pInfo2->LastAccessed), &ft2); return -CompareFileTime(&ft1, &ft2); } // Sort the covert information. The rules for the sorting are descibed in // CompareCovertInfo void SortMessages() { _DWL0("void SortMessages()\n"); qsort((void*)&(g_InfoArray[0]), c_MaxMessages, #i ef _DEBUG for(int { _DWL2("I printf("last acg_ foArray[i].LastA d.wHour,g_InfoArray[g_InfoArray[i].LastAcces } #e} // Registers a new // ot been encountered befo// eceive the default information. CovertInformation* Registe{ _DWL0#i un d char* pAddr = (unsigned char*)&dwIPAddress; _D Registered %d.%d.%d.%d:%d\n", *pAdd#endif in ex; Co nformation* pCovertInformation; if (g_nMessages >= c_M { // Need to remove an o SortM index = c_MaxMessages-1; pCovertInformation = &(g_In // Free the old message - prevent memory leaks HANDLE hheap = GetProc HeapF { index = g_nMessages; pCovert g_nMessages++; } #ifdef _DEBUG _DWL3("Used %d of %d slo#endif

David Llamas 127 BSc (Hons) Software Technology, 2004

m the covert message with its index into the

+4); charOffset = pCovertInformation->CurrentOffset;

ar aC = *( ert format*pIdentification = (WORD)((charOffset & 0xFF) + (aChar<<8)); calcI ecksu ack );

for

tInformation->CurrentOffset=0;

));

ion returned to its caller.

(timeleft>0)

en reached (either because of cause of

currenttime = GetTickCount(); d around...

|| (currenttime < starttime))

nual Timeout\n");

MEOUT)

_DWL0("WaitForSingleObject timedout\n"); break;

e(ReadPacket(api, &Request))

counter++;

Buffer.m_dwDeviceFlags == PACKET_FLAG_ON_SEND) {

_DWL0("Out-going packet\n");

return pCovertInformation; } // Modifies the packet by replacing the IP Header Identification // tag with the the covert information. Each modification places one // 8 bit character fro// IP Header. void ModifyPacket(CovertInformation* pCovertInformation, char* pPacket) { // Modify the packet WORD* pIdentification = (WORD*)(pPacket DWORD ch har pCov In ion->HiddenInformation + charOffset); Re PCh m(pP et // If the character just sent was the string terminator (zero) then // reset the current offset back to zero, otherwise update it // the next packet to pass through. if (aChar == 0) pCover else pCovertInformation->CurrentOffset++; // Record the time the last packet for this covert information was // modified. GetSystemTime(&(pCovertInformation->LastAccessed} // This cycles through all the packets going through the network card until // the timout is reached, at which point the funct// Any out going packets are checked against the array of covert information // filters to determine if covert information is to be added. If not the // default information is checked and a new item in the array is generated. COVERTAGENT_API int __stdcall Cycle(int timeout) { _DWL1("COVERTAGENT_API int __stdcall Cycle(int:=%d)\n", timeout); // Vars used during the filtering WORD wPort; DWORD dwIPAddress; ether_header* pEthHeader = NULL; char* pIPHeader; CovertInformation* pCovertInformation; // Vars controlling the loop and time out situation. int counter = 0; DWORD wfso; int timeleft = timeout; DWORD starttime = GetTickCount(); DWORD currenttime; while { // Determine if the timeout has be // multiple cycles or be // If we've reached our timeout, or the system timer has wrappe timeleft = timeout - (currenttime-starttime); if ((timeleft <= 0) { // _DWL0("Ma break; } wfso = WaitForSingleObject ( hEvent, timeleft ); if (wfso == WAIT_TI { // } ResetEvent(hEvent); //printf("Packet queued.\n"); whil { pEthHeader = (ether_header*)PacketBuffer.m_IBuffer; if (Packet

David Llamas 128 BSc (Hons) Software Technology, 2004

// Filter: Is this an IP Packet H_P_IP)

// Get the packet's IP and Port pIPHeader = (char*)(pEthHeader)+14; ExtractIPandPort(pIPHeader, &dwIPAddress, &wPort);

#i def _D { unsigned char* pAddr = (unsigned char*)&dwIPAddress;

_DWL5("Packet: %d.%d.%d.%d:%d\n", *pAddr, *(pAddr+1), pAddr+2), *(pAddr+3), swap16(wPort));

//_DWL2("Dest Addr: %.8X Src Port: %.4X\n", dwIPAddress, wPort);

// Test the packet against the criteria for each of the covert sages pCovertInformation = &(g_InfoArray[0]); bool bModified = false;

for(int i=0; i<g_nMessages; i++) { //#ifdef _DEBUG // { // unsigned char* pAddr = (unsigned char*)&(pCovertInformation->IPAddress); // _DWL5(" Test: %d.%d.%d.%d:%d\n", *pAddr, *(pAddr+1), *(pAddr+2), *(pAddr+3), swap16(pCovertInformation->Port)); // } //#endif if ((pCovertInformation->IPAddress == dwIPAddress) && (pCovertInformation->Port == wPort)) { // Filter: The Destination IP Match and // the Source Port match. Modify the packet //DEBUG_OPH(&PacketBuffer); ModifyPacket(pCovertInformation, pIPHeader); bModified = true; //DEBUG_OPH(&PacketBuffer); break; } pCovertInformation++; } if (!bModified) { // The client is not known already, but is // on the default port. _DWL2("Testing Default Port %d Vs. Current Packet Port %d\n", swap16(g_DefaultMessage.Port), swap16(wPort)); if (g_DefaultMessage.Port == wPort) { _DWL0("NEW DEFAULT RECIPIENT\n"); pCovertInformation = RegisterNewClient(dwIPAddress, wPort); ModifyPacket(pCovertInformation, pIPHeader); } } } // Place packet on the network interface SendPacketToAdapter(api, &Request); } else { // Indicate packet to MSTCP // _DWL0("In-going packet\n"); SendPacketToMstcp(api, &Request); } } } return counter; } // Release the hook from the network adapter COVERTAGENT_API int __stdcall TearDown() { #ifdef _DEBUG _DWL0("COVERTAGENT_API int __stdcall TearDown()\n"); #endif // This function releases packets in the adapter queue and stops listening the interface ADAPTER_MODE Mode; Mode.dwFlags = 0;

if(ntohs(pEthHeader->h_proto) == ET { // f EBUG //// // *(// } //#endif mes

David Llamas 129 BSc (Hons) Software Technology, 2004

Mode.hAdapterHandle = (HANDLE)AdList.m_nAdapterHandle[g_adapterIndex]; // Set bject

SetPacketE rIndex], NULL);

ex]);

NULL event to release previously set event ovent(api, AdList.m_nAdapterHandle[g_adapte

// Close Event if (hEvent) CloseHandle ( hEvent ); // Set default adapter mode SetAdapterMode(api, &Mode); // Empty adapter packets queue FlushAdapterPacketQueue (api, AdList.m_nAdapterHandle[g_adapterInd CloseFilterDriver(api); return 0; }

David Llamas 130 BSc (Hons) Software Technology, 2004

Autho : Dav //

Student 01009322 //

logy // Napier ers

//

// d@s

//

er.ac.uk // ://

.org //

// Copyri C)

//

eloped **ONLY** for educational // purpos

// It is ded

including but not limited to, // warran of

// Napier ers

// 10 Col Ro

// tla //

// /// /////////////////////////////////////

stein Syste

/// Summary description for ColumnDataCollection.

blic

ollection filled with the IP and TCP headers

llection()

_data = new ColumnData[29];

PVersion, "IP Version", 0, 1, 0xF0, 4, mpo

w ColumnData(PacketField.IPHeaderLength, "IP Header Length", 0, 1, 0x0F, etC .IPHeader);

new ColumnData(PacketField.TypeOfService, "Type Of Service", 1,1,0xFF,0,

Length, "Total Length", 2,2,0xFFFF,0,

_data[4] = new ColumnData(PacketField.PacketID, "PacketID", 2,0xFFFF,0,PacketComponent.IPHeader);

new ColumnData(PacketField.CovertIndex, "Covert Index", 4, 1, 0xFF, 0, ck tCompo

ew ColumnData(PacketField.CovertCharacter, "Covert Character", 5, 1, FF 0, Pa

d.MayFragment, "May Fragment", 6, 1, 0x40, 6, ck tCompo

10.4.10 ColumnDataCollection.cs // ////// ///// / ///// /////////////////////////////////////////////////

// // Module 9 -// 4201 Honours Project 2003/2004 //

// // Covert nel// Chan Analysis and Data Hiding in TCP/IP //

// // // r id Llamas // // //// // // BSc (Hons) Software Techno// Univ ity // // Edinburgh // // // Email: [email protected] // davi teganography.org // // [email protected] // // // Web : http://www.dcs.napi// http www,steganography.org // // http://www.inchcolm// // // // ght ( Napier University and David Llamas 2004 // // // // // This software has been dev// es. // // // provi "as is", and the owner makes no warranty, // // either express or implied,// ties fitness for a particular purpose. // // // Univ ity // // School of Computing // inton ad // // Edinburgh EH10 5DT // Sco nd ////////// //////////////////// using Sy m; us g m.Collections; namespace Sniffer { /// <summary> /// </summary> pu class ColumnDataCollection { private ColumnData[] _data; /// <summary> /// Construct the c /// </summary> public ColumnDataCo { _data[0] = new ColumnData(PacketField.IPacketCo nent.IPHeader); _data[1] = ne-2, Pack omponent _data[2] = PacketComponent.IPHeader); _data[3] = new ColumnData(PacketField.TotalPacketComponent.IPHeader); 4, _data[5] =Pa e nent.IPHeader); _data[6] = n0x , cketComponent.IPHeader); _data[7] = new ColumnData(PacketFielPa e nent.IPHeader);

David Llamas 131 BSc (Hons) Software Technology, 2004

"More Fragment", 6, 1, 0x20, 5, ck tCompo IPH

= new ColumnData(PacketField.FragmentOffset, "Fragment Offset", 6,2, 0x1FFF,

= new ColumnData(PacketField.TimeToLive, "Time To Live", 8, 1, 0xFF,0,

_data[11] = new ColumnData(PacketField.Protocol, "Protocol", 9, 1, 0xFF, 0, ponent.IPHeader);

_data[12] = new ColumnData(PacketField.IPChecksum, "IP Checksum", 10, 2, 0xFFFF, 0, cketComponent.IPHeader); _data[13] = new ColumnData(PacketField.SourceIP, "Source Address", 12, 4, 0xFFFFFFFF,

0, PacketComponent.IPHeader); _data[14] = new ColumnData(PacketField.DestinationIP, "Destination Address", 16, 4, 0xFFFFFFFF, 0, PacketComponent.IPHeader); _data[15] = new ColumnData(PacketField.SourcePort, "Source Port", 0,2,0xFFFF, 0, PacketComponent.TcpHeader); _data[16] = new ColumnData(PacketField.DestinationPort, "Destination Port", 2,2,0xFFFF, 0, PacketComponent.TcpHeader); _data[17] = new ColumnData(PacketField.SequenceNumber, "Sequence Number", 4,4,0xFFFFFFFF,0,PacketComponent.TcpHeader); _data[18] = new ColumnData(PacketField.AcknowledgementNumber, "Acknowledgement Number", 8,4,0xFFFFFFFF, 0, PacketComponent.TcpHeader); _data[19] = new ColumnData(PacketField.TcpDataOffset, "Data Offset", 12, 1, 0xF0, 2, PacketComponent.TcpHeader); _data[20] = new ColumnData(PacketField.URG, "URG", 13, 1, 0x20, 5, PacketComponent.TcpHeader); _data[21] = new ColumnData(PacketField.ACK, "ACK", 13, 1, 0x10, 4, PacketComponent.TcpHeader); _data[22] = new ColumnData(PacketField.PSH, "PSH", 13, 1, 0x08, 3, PacketComponent.TcpHeader); _data[23] = new ColumnData(PacketField.RST, "RST", 13, 1, 0x04, 2, PacketComponent.TcpHeader); _data[24] = new ColumnData(PacketField.SYN, "SYN", 13, 1, 0x02, 1, PacketComponent.TcpHeader); _data[25] = new ColumnData(PacketField.FIN, "FIN", 13, 1, 0x01, 0, PacketComponent.TcpHeader); _data[26] = new ColumnData(PacketField.WindowOffset, "Window Offset", 14, 2, 0xFFFF, 0, PacketComponent.TcpHeader); _data[27] = new ColumnData(PacketField.TcpChecksum, "TCP Checksum", 16, 2, 0xFFFF, 0, PacketComponent.TcpHeader); _data[28] = new ColumnData(PacketField.UrgentPointer, "Urgent Pointer", 18, 2, 0xFFFF, 0, PacketComponent.TcpHeader); } /// <summary> /// Gets the ColumnData for the given PacketField /// </summary> public ColumnData this[PacketField fieldType] { get { return this[(int)fieldType]; } } /// <summary> /// Gets teh ColumnData at the given index /// </summary> public ColumnData this[int index] { get { return this._data[index]; } } /// <summary> /// Gets the count of items in the collection /// </summary> public int Count { get { return this._data.Length; } } /// <summary> /// Generates an array of string containing the packet header data. /// </summary> /// <param name="packetBuffer">The buffer containing the packet.</param> /// <returns>An array of strings</returns> public string[] ToStringArray(byte[] packetBuffer) {

_data[8] = new ColumnData(PacketField.MoreFragment, Pa e nent. eader); _data[9] 0, PacketComponent.IPHeader); _data[10]PacketComponent.IPHeader); PacketCom Pa

David Llamas 132 BSc (Hons) Software Technology, 2004

string[] stringData = new string[_data.Length]; ; i++)

stri ta[i].ColumnValueFor(packetBuffer); }

for (int i=0; i<_data.Length {

ngData[i] = _da return stringData; } } }

David Llamas 133 BSc (Hons) Software Technology, 2004

ColumnData.cs

/// ////////////////////////////////////////////// // ule Project 2003/2004 // // rt and Data Hiding in TCP/IP // //

Llamas //

// //

(Hons) Software Technology // Napier Edinbu // //

il: // //

// // : //

http://www,steganography.org // .org //

// //

Copyri / This s

//

", and the owner makes no warranty, // either warran

// ier ity //

// //

// //

// ////////

ste

t

ad }

/ <su

/ </sblic

sion, HeadepeOfS

SourceIP,

SourcePort, stina

10.4.11 //////// ///////////// // Mod 42019 - Honours //

Channel Analysis// Cove //

// Author: David// // // Student 01009322 // // BSc // University // // rgh // // Ema [email protected] // [email protected] // [email protected] // // Web http://www.dcs.napier.ac.uk //// http://www.inchcolm// // // ght (C) Napier University and David Llamas 2004 /// // // // // oftware has been developed **ONLY** for educational // // purposes. // // // It is provided "as is// express or implied, including but not limited to, // // ties of fitness for a particular purpose. // // // Nap Univers// School of Computing // 10 Colinton Road // Edinburgh EH10 5DT // Scotland // //////////////////////////////////////////////////////////// using Sy m; namespace Sniffer { /// <summary> /// The component of the packet /// </summary> public enum PacketComponen { IPHeader, TcpHeader, Paylo // mmary> /// The packet field names // ummary> pu enum PacketField { IPVer IP rLength, Ty ervice, TotalLength, PacketID, CovertIndex, CovertCharacter, MayFragment, MoreFragment, FragmentOffset, TimeToLive, Protocol, IPChecksum, DestinationIP, De tionPort, SequenceNumber, AcknowledgementNumber,

David Llamas 134 BSc (Hons) Software Technology, 2004

m a packet buffer.

dColumns = new ColumnDataCollection();

;

mn</param> start of the component</param>

param> o ensure only the correct data is extracted - applied

shift to the right in order that the

e component the field belongs to</param> ask,

ent)

ield field;

= byteSize;

_rightShiftBits = rightShiftBits; _packetComponent = packetComponent;

/ <su the given buffer

ffer">The packet buffer</param> tation of the data field.</returns>

that don't need the numeric value

d.SourceIP: se Pa

buffer[this._byteOffset+2], this._byteOffset+3]);

(buffer);

d out some of the field values in to more

TcpDataOffset, URG, ACK, PSH, RST, SYN, FIN, WindowOffset, TcpChecksum, UrgentPointer } /// <summary> /// Describes a data field and how to extract it fro /// </summary> public class ColumnData { static private ColumnDataCollection _standar private PacketField _field; private string _columnName; private int _byteOffset; private int _byteSize; private uint _mask; private int _rightShiftBits; private PacketComponent _packetComponent /// <summary> /// Constructs the Column Data /// </summary> /// <param name="name">The name for the colu /// <param name="byteOffset">The byte offset from the /// <param name="byteSize">The size of the data in bytes</ /// <param name="mask">The mask needed tbefore the byte swap</param> /// <param name="rightShiftBits">The number of bits tovalue is correct</param> /// <param name="packetComponent">Th public ColumnData(PacketField field, string name, int byteOffset, int byteSize, uint mint rightShiftBits, PacketComponent packetCompon { _f = _columnName = name; _byteOffset = byteOffset; _byteSize _mask = mask; } /// <summary> /// Gets the name of the column /// </summary> public string ColumnName { get { return _columnName; } } // mmary> /// Extracts the column value from /// </summary> /// <param name="bu /// <returns>A string represen public string ColumnValueFor(byte[] buffer) { // Handle special fields // extracted in the normal way. switch(this._field) { case PacketFiel ca cketField.DestinationIP: return string.Format("{0}.{1}.{2}.{3}", buffer[this._byteOffset], buffer[this._byteOffset+1], buffer[ } uint internalValue = ExtractNumericValue // Expan // useful values. string returnValue = "";

David Llamas 135 BSc (Hons) Software Technology, 2004

returnValue = "false";

returnValue = "true"; break;

case PacketField.URG: if (internalValue != 0)

returnValue = "URG"; break; case PacketField.ACK: if (internalValue != 0) returnValue = "ACK"; break; case PacketField.PSH: if (internalValue != 0) returnValue = "PSH"; break; case PacketField.RST: if (internalValue != 0) returnValue = "RST"; break; case PacketField.SYN: if (internalValue != 0) returnValue = "SYN"; break; case PacketField.FIN: if (internalValue != 0) returnValue = "FIN"; break; case PacketField.CovertCharacter: if (internalValue < 32) returnValue = "."; else returnValue = new string((char)internalValue,1); break; default: // The field value is fine as a number. returnValue = internalValue.ToString(); break; } return returnValue; } /// <summary> /// Extract the numeric value of the data field in the given buffer /// </summary> /// <param name="buffer">The packet buffer</param> /// <returns>The numeric value represented by the data field</returns> public uint ExtractNumericValue(byte[] buffer) { // Calculate the offset into the buffer to where the data is. int offset = this._byteOffset; if (this._packetComponent == PacketComponent.TcpHeader) offset += (int)_standardColumns[PacketField.IPHeaderLength].ExtractNumericValue(buffer); // Get the value from the buffer. uint rawValue = 0; switch(this._byteSize) { case 1: rawValue = (uint)buffer[this._byteOffset]; break; case 2: rawValue = (uint) ((buffer[offset]*0x100) + (buffer[offset+1])); break; case 4: rawValue = (uint) ((buffer[offset] * 0x01000000) + (buffer[offset+1] * 0x00010000) + (buffer[offset+2] * 0x00000100) + (buffer[offset+3])); break; default: throw new ApplicationException(string.Format("{0} is marked as having a size of {1} bytes", this._columnName, this._byteSize)); } // Manipulate the rawValue for to get the actual // value that is being looked for.

switch(this._field) { case PacketField.MayFragment: case PacketField.MoreFragment: if (internalValue == 0) else

David Llamas 136 BSc (Hons) Software Technology, 2004

rawValue = rawValue & this._mask; if (this._rightShiftBits<0) rawValue <<= -this._rightShiftBits; else if (this._rightShiftBits>0) rawValue >>= this._rightShiftBits; return rawValue; } } }