Total Pageviews

Search: This Blog, Linked From Here, The Web, My fav sites, My Blogroll

Translate

15 September 2015

inode

When the file system is first established, it comes with a set number of inodes. The inode is a data structure used to store file information. The information that every inode will store consists of
  • The file type
  • The file’s permissions
  • The file’s owner and group
  • The file’s size
  • The inode number
  • A timestamp indicating when the inode was last modified, when the file was created,and when the file was last accessed
  • A link count (the number of hard links that point at this file)
  • The location of the file (i.e., the device storing the file) and pointers to the individual file blocks (if this is a regular file)
these pointers break down into
  •  A set number of pointers that point directly to blocks
  •  A set number of pointers that point to indirect blocks; each indirect block contains pointers that point directly to blocks
  • A set number of pointers that point to doubly indirect blocks, which are blocks that have pointers that point to additional indirect blocks
  • A set number of pointers that point to triply indirect blocks, which are blocks that have pointers that point to additional doubly indirect blocks
Typically, an inode will contain 15 pointers broken down as follows:
  • 12 direct pointers
  • 1 indirect pointer
  • 1 double indirect pointer
  • 1 triply indirect pointer
An inode is illustrated in Figure (which contains 1 indirect pointer and 1 doubly indirect pointer but no triply indirect pointer because of a lack of space).

 Let us take a look at how to access a Linux file through the inode. We will make a few assumptions.
First, our Linux inode will store 12 direct pointers, 1 indirect pointer, 1 doubly indirect pointer, and 1 triply indirect pointer. Blocks of pointers will store 12 pointers no matter whether they are indirect, doubly indirect, or triply indirect blocks. We will assume that our file consists of 500 blocks, numbered 0 to 499, each block storing 8 KB (the typical disk block stores between 1 KB and 8 KB depending on the file system utilized).
Our example file then stores 500 * 8 KB = 4000 KB or 4 MB. Here is the breakdown of how we access the various blocks.
  • Blocks 0–11: direct pointers from the inode.
  • Blocks 12–23: pointers from an indirect block pointed to by the inode’s indirect pointer.
  • For the rest of the file, access is more complicated.
   • We follow the inode’s doubly indirect pointer to a doubly indirect block. This block contains 12 pointers to indirect blocks. Each indirect block contains 12 pointers to disk blocks.
−− The doubly indirect block’s first pointer points to an indirect block of 12 pointers, which point to blocks 24–35.
−− The doubly indirect block’s second pointer points to another indirect block of 12 pointers, which point to blocks 36–47.
−− …
−− The doubly indirect block’s last pointer points to an indirect block of 12 pointers, which point to blocks 156–167.
• We follow the inode’s triply indirect pointer to a triply indirect block. This block contains 12 pointers to doubly indirect blocks, each of which contains 12 pointers to indirect blocks, each of which contain 12 pointers to disk blocks. From the triply indirect block, we can reach blocks 168 through 499 (with room to increase the file to block 1895).

Earlier, we noted that the disk drive supports random access. The idea is that to track down a block, block i, we have a mechanism to locate it. This is done through the inode pointers as just described.
The above example is far from accurate. A disk block used to store an indirect, doubly indirect, or triply indirect block of pointers would be 8 KB in size. Such a sized block would store far more than 12 pointers. A pointer is usually 32 or 64 bits long (4 or 8 bytes). If we assume an 8 byte pointer and an 8 KB disk block, then an indirect, doubly indirect, or
triply indirect block would store 8 KB/8 B pointers = 1 K or 1024 pointers rather than 12.
When a file system is created, it comes with a set number of inodes. The actual number depends on the size of the file system and the size of a disk block. Typically, there is 1 inode for every 2–8 KB of file system space.
If we have a 1 TB file system (a common size for a hard disk today), we might have as many as 128 K (approximately 128 thousand) inodes. The remainder of the file system is made up of disk blocks dedicated to file storage and pointers. Unless nearly all of the files in the file system are very small, the number of inodes should be more than sufficient for any file system usage.


Linux Commands to Inspect inodes and Files

There are several tools available to inspect inodes. The following commands provide such information:
  • stat—provides details on specific file usage, the option –c %i displays the file’s inode number
  • ls –i displays the inodes of all entries in the directory
  • df –i this command provides information on the utilization of the file system, partition by partition. The -i option includes details on the number of inodes used.
The stat command itself will respond with the name of the file, the size of the file, the blocks used to store the file, the device storing the file (specified as a device number), the inode of the file, the number of hard links to the file, the file’s permissions, UID, GID in both name and
number, and the last access, modification, and change date and time for the file. The stat command has many options. The most significant are: 
  • -L : follow links to obtain inode information of files stored in other directories (without this, symbolic links in the given directory are ignored)
  • -f : used to obtain statistics on an entire file system rather than a file
  •  -c FORMAT : output only the requested information where FORMAT uses the characters listed in Table , additionally when used with -f (file system stats) there are other formatting characters available (see second half of Table )

Formatting Characters for -c, Bottom Half for -c -f
We use stat to provide for us the size of each file in blocks and bytes, the file name, the inode number of the file, and the time of last access. This command is given as:

$ stat   -c "%b %s %n %i %x" *
736 373337 firestarter-events.txt~ 1486 2010-04-28 14:37:10.843398916 +0300
472544 241938432 FreeBSD-10.2-RELEASE-amd64-bootonly.iso 285743 2015-09-10 20:01:12.310727882 +0300
119344 61098928 FreeBSD-10.2-RELEASE-amd64-bootonly.iso.xz 4349 2015-09-10 19:53:37.250723649 +0300

 we inspect devices from /dev  where we look at the file’s type (%F)  the device number, UID of the owner, number of hard links, inode
number, file name, and file type.
 
$ stat   -c "%d %u %h %i %n %F" /dev/*
5 0 1 4695 /dev/adsp character special file
5 0 1 4699 /dev/audio character special file
5 0 2 1901 /dev/block directory
5 0 2 2342 /dev/bsg directory
5 0 3 1801 /dev/bus directory
5 0 1 4001 /dev/cdrom symbolic link
5 0 2 2001 /dev/char directory
5 0 1 1592 /dev/console character special file
5 0 1 3249 /dev/core symbolic link
5 0 1 1834 /dev/cpu_dma_latency character special file
5 0 5 2377 /dev/disk directory
5 0 1 4698 /dev/dsp character special file
5 0 1 4004 /dev/dvd symbolic link
5 0 1 1585 /dev/ecryptfs character special file
5 0 1 2382 /dev/fb0 character special file
5 0 1 3250 /dev/fd symbolic link
5 0 1 1233 /dev/full character special file
5 0 1 1586 /dev/fuse character special file
5 0 1 2392 /dev/hidraw0 character special file
5 0 1 1662 /dev/hpet character special file
5 0 4 1811 /dev/input directory
5 0 1 1236 /dev/kmsg character special file
5 0 1 4784 /dev/log socket
5 0 1 1716 /dev/loop0 block special file
5 0 1 1719 /dev/loop1 block special file
5 0 1 1722 /dev/loop2 block special file
5 0 1 1725 /dev/loop3 block special file
5 0 1 1728 /dev/loop4 block special file
5 0 1 1731 /dev/loop5 block special file
5 0 1 1734 /dev/loop6 block special file
5 0 1 1737 /dev/loop7 block special file
5 0 2 1819 /dev/mapper directory
5 0 1 1575 /dev/mcelog character special file
5 0 1 1229 /dev/mem character special file
5 0 1 4702 /dev/mixer character special file
5 0 2 1744 /dev/net directory
5 0 1 1835 /dev/network_latency character special file
5 0 1 1836 /dev/network_throughput character special file
5 0 1 1230 /dev/null character special file
5 0 1 5256 /dev/nvidia0 character special file
5 0 1 5255 /dev/nvidiactl character special file
5 0 1 1237 /dev/oldmem character special file
5 0 2 1741 /dev/pktcdvd directory
5 0 1 1231 /dev/port character special file
5 0 1 1743 /dev/ppp character special file
5 0 1 1814 /dev/psaux character special file
5 0 1 1661 /dev/ptmx character special file
12 0 2 1 /dev/pts directory
5 0 1 1668 /dev/ram0 block special file
5 0 1 1671 /dev/ram1 block special file
5 0 1 1698 /dev/ram10 block special file
5 0 1 1701 /dev/ram11 block special file
5 0 1 1704 /dev/ram12 block special file
5 0 1 1707 /dev/ram13 block special file
5 0 1 1710 /dev/ram14 block special file
5 0 1 1713 /dev/ram15 block special file
5 0 1 1674 /dev/ram2 block special file
5 0 1 1677 /dev/ram3 block special file
5 0 1 1680 /dev/ram4 block special file
5 0 1 1683 /dev/ram5 block special file
5 0 1 1686 /dev/ram6 block special file
5 0 1 1689 /dev/ram7 block special file
5 0 1 1692 /dev/ram8 block special file
5 0 1 1695 /dev/ram9 block special file
5 0 1 1234 /dev/random character special file
5 0 1 397 /dev/rfkill character special file
5 0 1 4497 /dev/root symbolic link
5 0 1 2177 /dev/rtc symbolic link
5 0 1 1818 /dev/rtc0 character special file
5 0 1 2374 /dev/scd0 symbolic link
5 0 1 2344 /dev/sda block special file
5 0 1 2345 /dev/sda1 block special file
5 0 1 2346 /dev/sda2 block special file
5 0 1 2347 /dev/sda3 block special file
5 0 1 2348 /dev/sda4 block special file
5 0 1 2349 /dev/sda5 block special file
5 0 1 2350 /dev/sda6 block special file
5 0 1 2351 /dev/sda7 block special file
5 0 1 2352 /dev/sda8 block special file
5 0 1 2353 /dev/sda9 block special file
5 0 1 4371 /dev/sequencer character special file
5 0 1 4375 /dev/sequencer2 character special file
5 0 1 2341 /dev/sg0 character special file
5 0 1 2364 /dev/sg1 character special file
16 0 2 3261 /dev/shm directory
5 0 1 1576 /dev/snapshot character special file
5 0 3 4314 /dev/snd directory
5 0 1 3252 /dev/sndstat symbolic link
5 0 1 2361 /dev/sr0 block special file
5 0 1 3253 /dev/stderr symbolic link
5 0 1 3254 /dev/stdin symbolic link
5 0 1 3255 /dev/stdout symbolic link
5 0 1 1591 /dev/tty character special file
5 0 1 1593 /dev/tty0 character special file
5 0 1 1598 /dev/tty1 character special file
5 0 1 1607 /dev/tty10 character special file
5 0 1 1608 /dev/tty11 character special file
5 0 1 1609 /dev/tty12 character special file
5 0 1 1610 /dev/tty13 character special file
5 0 1 1611 /dev/tty14 character special file
5 0 1 1612 /dev/tty15 character special file
5 0 1 1613 /dev/tty16 character special file
5 0 1 1614 /dev/tty17 character special file
5 0 1 1615 /dev/tty18 character special file
5 0 1 1616 /dev/tty19 character special file
5 0 1 1599 /dev/tty2 character special file
5 0 1 1617 /dev/tty20 character special file
5 0 1 1618 /dev/tty21 character special file
5 0 1 1619 /dev/tty22 character special file
5 0 1 1620 /dev/tty23 character special file
5 0 1 1621 /dev/tty24 character special file
5 0 1 1622 /dev/tty25 character special file
5 0 1 1623 /dev/tty26 character special file
5 0 1 1624 /dev/tty27 character special file
5 0 1 1625 /dev/tty28 character special file
5 0 1 1626 /dev/tty29 character special file
5 0 1 1600 /dev/tty3 character special file
5 0 1 1627 /dev/tty30 character special file
5 0 1 1628 /dev/tty31 character special file
5 0 1 1629 /dev/tty32 character special file
5 0 1 1630 /dev/tty33 character special file
5 0 1 1631 /dev/tty34 character special file
5 0 1 1632 /dev/tty35 character special file
5 0 1 1633 /dev/tty36 character special file
5 0 1 1634 /dev/tty37 character special file
5 0 1 1635 /dev/tty38 character special file
5 0 1 1636 /dev/tty39 character special file
5 0 1 1601 /dev/tty4 character special file
5 0 1 1637 /dev/tty40 character special file
5 0 1 1638 /dev/tty41 character special file
5 0 1 1639 /dev/tty42 character special file
5 0 1 1640 /dev/tty43 character special file
5 0 1 1641 /dev/tty44 character special file
5 0 1 1642 /dev/tty45 character special file
5 0 1 1643 /dev/tty46 character special file
5 0 1 1644 /dev/tty47 character special file
5 0 1 1645 /dev/tty48 character special file
5 0 1 1646 /dev/tty49 character special file
5 0 1 1602 /dev/tty5 character special file
5 0 1 1647 /dev/tty50 character special file
5 0 1 1648 /dev/tty51 character special file
5 0 1 1649 /dev/tty52 character special file
5 0 1 1650 /dev/tty53 character special file
5 0 1 1651 /dev/tty54 character special file
5 0 1 1652 /dev/tty55 character special file
5 0 1 1653 /dev/tty56 character special file
5 0 1 1654 /dev/tty57 character special file
5 0 1 1655 /dev/tty58 character special file
5 0 1 1656 /dev/tty59 character special file
5 0 1 1603 /dev/tty6 character special file
5 0 1 1657 /dev/tty60 character special file
5 0 1 1658 /dev/tty61 character special file
5 0 1 1659 /dev/tty62 character special file
5 0 1 1660 /dev/tty63 character special file
5 0 1 1604 /dev/tty7 character special file
5 0 1 1605 /dev/tty8 character special file
5 0 1 1606 /dev/tty9 character special file
5 0 1 1667 /dev/ttyS0 character special file
5 0 1 1664 /dev/ttyS1 character special file
5 0 1 1665 /dev/ttyS2 character special file
5 0 1 1666 /dev/ttyS3 character special file
5 0 1 1235 /dev/urandom character special file
5 0 1 1749 /dev/usbmon0 character special file
5 0 1 1753 /dev/usbmon1 character special file
5 0 1 1808 /dev/usbmon2 character special file
5 0 1 7508 /dev/vboxdrv character special file
5 0 1 7512 /dev/vboxdrvu character special file
5 0 1 7561 /dev/vboxnetctl character special file
5 0 2 7754 /dev/vboxusb directory
5 0 1 1594 /dev/vcs character special file
5 0 1 1596 /dev/vcs1 character special file
5 0 1 2609 /dev/vcs2 character special file
5 0 1 2618 /dev/vcs3 character special file
5 0 1 2627 /dev/vcs4 character special file
5 0 1 2636 /dev/vcs5 character special file
5 0 1 2645 /dev/vcs6 character special file
5 0 1 2662 /dev/vcs7 character special file
5 0 1 1595 /dev/vcsa character special file
5 0 1 1597 /dev/vcsa1 character special file
5 0 1 2610 /dev/vcsa2 character special file
5 0 1 2619 /dev/vcsa3 character special file
5 0 1 2628 /dev/vcsa4 character special file
5 0 1 2637 /dev/vcsa5 character special file
5 0 1 2646 /dev/vcsa6 character special file
5 0 1 2663 /dev/vcsa7 character special file
5 0 1 387 /dev/vga_arbiter character special file
5 0 1 1232 /dev/zero character special file

Some considerations :
All except pts are located on device number 5.
All are owned by user 0 (root);
Most of the items have only one hard link, found in /dev. Both input and pts are directories and have more than one hard link. The inode numbers vary from 1 to 7754.
The file type demonstrates that “files” can make up a wide variety of entities from block or character files (devices) to symbolic links to directories to domain sockets. This last field varies in length from one word (directory) to three words (character special file, block special file).
Each new file is given the next inode available. As your file system is used, you will find newer files have higher inode numbers although deleted files return their inodes.

Whenever any file is used in Linux, it must first be opened. The opening of a file requires a special designator known as the file descriptor. The file descriptor is an integer assigned to the file while it is open. In Linux, three file descriptors are always made available:
  • 0  stdin
  • 1  stdout
  • 2  stderr
 Any remaining files that are utilized during Linux command or program execution need to be opened and have a file descriptor given to that file.

When a file is to be opened, the operating system kernel gets involved.
  1. First, it determines if the user has adequate access rights to the file.
  2.  If so, it then generates a file descriptor. 
  3. It then creates an entry in the system’s file table, a data structure that stores file pointers for every open file. The location of this pointer in the file table is equal to the file descriptor generated. For instance, if the file is given the descriptor 185, then the file’s pointer will be the 185th entry in the file table. 
  4. The pointer itself will point to an inode for the given file.
As devices are treated as files, file descriptors will also exist for every device, entities such as the keyboard, terminal windows, the monitor, the network interface(s), the disk drives, as well as the open files.
You can view the file descriptors of a given process by looking at the fd subdirectory of the process’ entry in the /proc directory (e.g., /proc/16531/fd). There will always be entries labeled 0, 1, and 2 for STDIN, STDOUT, and STDERR, respectively. Other devices and files in use will require additional entries. Alternatively, the lsof command will list any open files.

FILES

In the Linux operating system, everything is treated as a file except for the process.
What does this mean? Among other things, Linux file commands can be issued on entities that are not traditional files. The entities treated like files include
  • directories, 
  • physical devices,
  • named pipes, 
  • file system links.
Aside from physical devices, there are also some special-purpose programs that are treated like files (for instance, a random number generator).


Files versus Directories

The directory it's a named entity that contains files and sub-directories (or devices, links, etc.). The directory offers the user the ability to organize their files in some reasonable manner, giving the file space a hierarchical structure. 
Directories can be created just about anywhere in the file system and can contain just about anything from empty directories to directories that themselves contain directories.

The directory differs from the file in a few significant ways. 
  1. we expect directories to be executable. Without that permission, no one (including the owner) can cd into the directory. 
  2. the directory does not store content like a file; instead it merely stores other items. That is, whereas the file ultimately is a collection of blocks of data, the directory contains a list of pointers to files. 
  3. there are some commands that operate on directories and not files (e.g., cd, pwd, mkdir) and some commands that operate on files but not directories (e.g., wc, diff, less, more). We do find that most Linux file commands will operate on directories themselves, including for instance cp, mv, rm (using the recursive version), and wildcards apply to both files and directories.
  

Nonfile File Types

Many devices are treated as files in Linux. These devices are listed under the /dev directory. We categorize these devices into two subcategories: 
  • character devices  : Character devices are those that input or output streams of characters a char at a time ; like the keyboard, the mouse, a terminal (as in terminal window), and serial devices such as older MODEMs and printers.
  • block devices : Block devices communicate via blocks of data. The term “block” is traditionally applied to disk drives where the files are broken into fixed-sized blocks. However, here, block is applied to any device that communicates by transmitting chunks of data at a time (as opposed to the previously mentioned character type)

Aside from the quantity of data movement, another differentiating characteristic between character and block devices is how input and output are handled. 
  • For a character device, a program executing a file command must wait until the character is transferred before resuming. 
  • For a block device, blocks are buffered in memory so that the program can continue once the instruction has been issued. Further, as blocks are only portions of entire files, it is typically the case that a file command can request one portion of a file. This is often known as random access. The idea is that we do not have to request block 1 before obtaining block 2. Having to read blocks in order is known as sequential access. But in random access, we can obtain any block desired and it should take no longer to access block j than block i.
Another type of file construct is the domain socket (or  local socket) This is not to be confused with a network socket.
The domain socket is used to open communication between two local processes. This permits interprocess communication (IPC) so that the two processes can share data.
We might, for instance, want to use IPC when one process is producing data that another process is to consume. This would be the case when some application software is going to print a file. The application software produces the data to be printed, and the printer’s device driver consumes the data.
The IPC is also used to create a rendezvous between two processes where process B must wait for some event from process A.

There are several distinctions between a network and domain socket. 
  • The network socket is not treated as a file (although the network itself is a device that can interact via file system commands) while the domain socket is. 
  • The network socket is created by the operating system to maintain communication with a remote computer while domain sockets are created by users or running software. Network sockets provide communication lines between computers rather than between processes.
Yet another type of file entity is the named pipe. The named pipe  differs from the pipe in that it exists beyond the single usage that occurs when we place a pipe between two Linux commands.
To create a named pipe, you define it through the mkfifo operation. The expression FIFO is short for “first-in-first-out.” FIFO is often used to describe a queue (waiting line) as queues are generally serviced in a first-in, first-out manner. In this case, mkfifo creates a FIFO, or a named pipe. Once the pipe exists, you can assign it to be used between any two processes.
Unlike an ordinary pipe that must be used between two Linux processes in a single command, the named pipe can be used in separate instructions.
Let us examine the usage of a named pipe. First, we define our pipe:

mkfifo a_pipe
This creates a file entity called a_pipe. As with any file or directory, a_pipe has permissions, user and group owner, creation/modification date, and a size (of 0). Now that the pipe exists, we might use the pipe in some operation:

ps aux  > a_pipe

Unlike performing ps aux, or even ps aux | more, this instruction does not seem to do anything when executed. In fact, our terminal window seems to hang as there is no output but neither is the cursor returned to us. What we have done is opened one end of the pipe(in writing). But until also the other end of the pipe is open, there is nowhere for the ps aux instruction’s output to “flow.”
To open the other end of the pipe, we might apply an operation (in a different terminal window since we do not have a prompt in the original window) like:

cat a_pipe

Now, the contents “flow” from the ps aux command through the pipe to the cat command. The output appears in the second terminal window and when done, the command line prompt returns in the original window.

You might ask why use a named pipe? In fact, the pipe is being used much like an ordinary pipe. Additionally, the named pipe does roughly the same thing as a domain socket— it is a go between for IPC. There are differences between the named pipe and pipe.
The named pipe remains in existence. We can call upon the named pipe numerous times. Notice here that the source program is immaterial. We can use a_pipe no matter what the source program is.
Additionally, the mkfifo instruction allows us to fine tune the pipe’s performance. Specifically, we can assign permissions to the result of the pipe. This is done using the option –M mode where mode is a set of permissions such as –M 600 or –M u=rwx,g=r,o=r.
The difference between the named pipe and the domain socket is a little more obscure.
The named pipe always transfers one byte (character) at a time. The domain socket is not limited to byte transfers but could conceivably transfer more data at a time.


Links as File Types

The link is a file type. There are two forms of links:
  • hard links : A hard link is stored in a directory to represent a file. It stores the file’s name and the inode number. When creating a new hard link, it duplicates the original hard link, storing the new link in a different directory.
  • soft (or symbolic) links (or symlinks) : The symbolic link instead merely creates a pointer to point at the original hard link.
The difference between the two types of links is subtle but important. If you were to create a symbolic link and then attempt to access a file through the symbolic link rather than the original link, you are causing an extra level of indirect access.
The operating system must first access the symbolic link, which is a pointer. The pointer then provides access to the original file link. This file link then provides access to the file’s inode, which then provides access to the file’s disk blocks.
Hard link's drawbacks are:
  1. hard links cannot link files together that exist on separate partitions. 
  2. hard links can only link together files whereas symbolic links can link directories and other file system entities together.
On the positive side for hard links, they are always up to date. If you move the original object, all of the hard links are modified at the same time. If you delete or move a file that is linked by a symbolic link, the file’s (hard) link is modified but not the symbolic link; thus you may have an out-of-date symbolic link. This can lead to errors at a later time.

In either case, a link is used so that you can refer to a file that is stored in some other location than the current directory. This can be useful when you do not want to add the file’s location to your PATH variable.
For instance, imagine that user zappaf has created a program called my_program, which is stored in ~zappaf. You want to run the program and are you in your home directory. The symbolic link instead merely creates a pointer to point at the original hard link(and zappaf was nice enough to set its permissions to 755). Rather than adding /home/zappaf to your PATH, or use an absolute pathname you create a symbolic link from your home directory to ~zappaf/my_program. Now you can issue the my_program command from your home directory.
You can determine the number of hard links that exist for a single file when you perform an ls –l. The integer value after the permissions is the number of hard links.

$ ls -l
drwxr-xr-x  5 harrykar harrykar    4096 2011-05-05 23:31 perl5
This number will never be less than 1 because with no hard links, the file will not exist. However, the number could be far larger than 1. Deleting any of the hard links will reduce this number. If the number becomes 0, then the file’s inode is returned to the file system for reuse, and thus access to the file is lost with its disk space available for reuse.
If you have a symbolic link in a directory, you will be able to note this by its type and name when viewing the results of an ls –l command. First, the file type is indicated by an ‘l’ (state for link) and the file name will contain the symbolic link’s name, an arrow (->) and the location of the file being linked.

$ ls -l
lrwxrwxrwx  1 harrykar harrykar      22 2012-04-16 16:17 squeak -> /home/harrykar/.squeak
Unfortunately, unlike the hard link usage, if you were to use ls –l on the original file, you will not see any indication that it is linked to by symbolic links.


Collectively, all of the special types of entities are treated like files in the following ways:
  • Each item is listed when you do an ls.
  • Each item can be operated upon by file commands such as mv, cp, rm and we can apply redirection operators on them.
  • Each item is represented in the directory by means of an inode.
You can determine a file’s type by using ls -l (long listing). The first character of the 10-character permissions is the file’s type. In Linux, the seven types are denoted by the characters in Table .

file type identifiers in ls -l


Every file (no matter the type, e.g., regular file, character type, block type, named pipe) is stored in a directory. The directory maintains the entities stored in it through a list. The listing is a collection of hard and soft links. A hard link of a file stores the file’s name and the inode number dedicated to that file. The symbolic link is a pointer to a hard link stored elsewhere.

As the user modifies the contents of the directory, this list is modified. New files require new hard links pointing to newly allocated inodes. The deletion of a file causes the hard link to be removed and the numeric entry of hard links to a file to be decremented. The inode itself remains allocated to the given file unless the hard link count becomes 0.




Resources


Linux with Operating System Concepts by Richard Fox
isbn:9781482235906, goodreads:20792170

File Space



STORAGE ACCESS


A collection of storage devices present a file space. This file space exists at two levels:
  • a logical level defined by partitions, directories, and files, and 
  • a physical level defined by file systems, disk blocks, and pointers.
The users and system administrators primarily view the file space at the logical level. The physical level is one that the operating system handles for us based on our commands (requests).

The devices(disk, usb, optical, solid state ecc drives) that make up the file space collectively provide us with storage access, where we store executable programs and data files.
We generally perform one of two operations on this storage space:
  • we read from a file (load the file into main memory, or input from file)
  • and we write to a file (store/save information from main memory to a file, or output to file).

Disk Storage and Blocks

As hard disk storage is the most common implementation of a file system, although some of the concepts apply to other forms of storage as well. 
To store a file on disk, the file is decomposed into fixed-sized units called blocks. Figure illustrates a small file (six blocks) and the physical locations of those blocks. Notice that the last block may not fill up the entire disk block space, so it leaves behind a small fragment.

The operating system must be able to manage this distribution of files to blocks in three ways:
  1. given a file and block, the operating system must map that block number into a physical location on some disk surface. 
  2. the operating system must be able to direct the disk drive to access that particular block through a movement of both the disk and the drive’s read/write head. 
  3. the operating system must be able to maintain free file space (available blocks), including the return of file blocks once a file has  been deleted.
All of these operations are hidden from the user and system administrator.

Let us consider how a disk file might be broken into blocks. 
The files are distributed across all of the disk’s surfaces (a hard disk drive will contain multiple disk platters and each platter has two surfaces, a top and bottom). Given a new file to store, the file is broken into blocks.
The first block is placed at the first available free block on disk.
Where should the next disk block be placed? If the next block after the first is available, we could place the block there, giving us two blocks of contiguous storage. This may or may not be desirable. The disk drive spins the disks very rapidly. If we want to read two blocks, we read the first block and transfer it into a buffer in the disk drive. Then, that data are transferred to memory. However, during that transfer, the disk  continues to spin.
When we are ready to read the second disk block, it is likely that this block has spun past the read/write head and now the disk drive must wait to finish a full disk revolution before reading again. Distributing disk blocks so that they are not contiguous will get around this problem.
In Figure , you will see that the first three disk blocks are located near each other but not in a contiguous block. Instead, the first block lies at location 3018, the second at 3020, and the third at 3022.

Whether initial blocks are contiguous or distributed, we will find that further disk blocks may have to be placed elsewhere because we have reached the end of the available disk blocks in this locality. With the deletion of files and saving of other files, we will eventually find disk blocks of one file scattered around the disk surfaces. This may lead to some inefficiency in access in that we have to move from one location of the disk to another to read consecutive blocks and so the seek time and rotational latency are lengthened.
Back to Figure we might assume that the next available block after 3022 is at 5813 and so as the file continues to grow, its next block lies at 5813 followed by 5815. As the next block, according to the figure, lies at 683, we might surmise that 683 was picked up as free space because a file was deleted.


Block Indexing Using a File Allocation Table

That is, block i’s successor location is stored at location i
How do we locate a particular block of a disk? File systems use an indexing scheme. MS DOS and earlier Windows systems used a file allocation table (FAT).
For every disk block in the file system, the next block’s location is stored in the table under the current block number.
The FAT is loaded from disk into main memory at the time the file system is mounted (e.g., at system initialization time). 
In Figure , a partial listing of a FAT is provided. Here, assume a file  starts at block 151. Its next block is 153 followed by 156, which is the end of the file (denoted by “EOF”).
To find the file’s third block, the operating system will examine the FAT starting at location 151 to find 153 (the file’s second block) and then look at location 153 to find 156, the file’s third block.
Another file might start at block 154. Its second block is at location 732. The entry “Bad” indicates a bad sector that should not be used.

Other Disk File Details

Aside from determining the indexing strategy and the use/reuse of blocks, the file system must also specify a number of other details. These will include naming schemes for file entries (files, directories, links). Nowadays It is common  for names to permit just about any character, including blank spaces; however, older file systems had limitations such as eight-character names and names consisting only of letters and digits (and perhaps a few types of punctuation marks such as the hyphen, underscore, and period). Some file systems do not differentiate between uppercase and lowercase characters while others do. Most file systems permit but do not require file name extensions.

File systems will also maintain information about the entries, often called metadata. This will include the creation, last modification and last access date/time, owner (and group in many cases), and permissions or access control list. The access control list enumerates for each user of the system the permissions granted to that user so that there can be several levels of permissions over the Linux user/group/other approach.

Many different file system types have been developed over the years. Many early mainframes had their own, unique file systems. Today, operating systems tend to share file systems or provide compatibility so that a different file system can still be accessed by many different types of operating systems. Aside from the previously mentioned FAT and NTFS file systems, some of the more common file systems are the extended file system family (ext, ext2, ext3, ext4, derived originally from the Minix OS file system) used in Linux. NFS (the network file system) is also available in Linux. Files-11, which is a descendant of the
file system developed for DEC PDP mainframes, and the Vax VMS operating system (and itself a precursor of NTFS) are also available. While these multitudes of file systems are available, most Linux systems primarily use the ext family as the default file system type.



Resources


Linux with Operating System Concepts by Richard Fox
isbn:9781482235906, goodreads:20792170

07 September 2015

System Administrator's duties

The Linux operating system provides for two classes of users :
  1. normal users
  2. superusers 
  3. software accounts
The term superuser is commonly used in many operating systems although in Linux, we call such a user root. The root user (or users) has access to all system commands and so can access all system resources through those commands.
Normal users have greatly restricted access in that they can execute public programs, access public files and access their own file space.

The role of root is to properly administer the computer system. Operating systems divide accessibility into two or more categories, the ordinary user and the administrator (sometimes called privileged mode). Some operating systems have intermediate categories between the two extremes where a user is given more privileges(e.g. through the sudo command) but not full administrator privileges.
The reason for the division between normal user and administrator modes is to ensure that normal users can not impact other users.
In a work environment, keeping data secure becomes even more important. Different users would have access to different types of data (financial, personnel, management, research), based on their identified role within the organization. Performing administrator duties (creating accounts, scheduling backups, installing software, etc.), if performed by the wrong person, can cause disastrous results if the person does not do things correctly. E.g. imagine that when installing new software, the person unknowingly wipes out the boot sector of the disk. Upon reboot, the computer no longer functions correctly.
And so we have a unique account in all operating systems that is capable of full system access. It is through this account that all (or most) administrative functions will be performed.
What does a system administrator do? The role of the administrator will vary based on the number of users of the computer system(s), the complexity of the computer system(s), the types of software made available, and more significantly, the size of the organization.
A small organization with just a few employees might employ a single system administrator who is also in charge of network administration, computer security, and user training.
In a large organization, there may be several system administrators, several network administrators, a few people specifically in charge of all aspects of security, and another group in charge of training.

The following list is common to many system administrators:
  • Install the operating system
  • Update the operating system when needed
  • Configure the operating system to fit the needs of the users in the organization
  • Secure the operating system
  • Configure and maintain network communication
  • Install, configure, and maintain application software
  • Create and manage user accounts and ensure the use of strong passwords
  • Install and troubleshoot hardware connected to computers directly or through a network
  • Manage the file system including partitioning the disk drives and performing backups
  • Schedule operations as needed such as backing up file systems, mounting and unmounting file systems, updating the operating system and other application software, examining log files for troubleshooting and suspicious activity
  • Define (for your organization’s management) computer usage policies and disaster recovery plans
  • Create documentation and training materials for users
  • Make recommendations for system upgrades to management
System administrators may not be responsible for all of the above duties. Other forms of administration (e.g., network administration, webserver administration, database administration, DNS administration, and computer security specialist) may take on some of the duties or have overlapping duties with the system administrator(s).
For instance, a network administrator would be in charge of installing, configuring, and securing the network but the system administrator may also be involved by configuring each individual workstation to the network. A webserver administrator would be in charge of configuring, maintaining, and troubleshooting the webserver but the system administrator may be in charge of installing it and setting up a special account for the webserver administrator so that he/she can access some system files.



Resources


Linux with Operating System Concepts by Richard Fox
isbn:9781482235906, goodreads:20792170

UNIX AND LINUX a short history

Unix is an old operating system, dating back to 1969. Its earliest incarnation, known as MULTICS, was developed for a single platform. It was developed by AT&T Bell Labs. Two of the employees, Dennis Ritchie and Ken Thompson, wanted to revise MULTICS to run as a platform-independent operating system. They called their new system Unics, with its first version being written in the assembly language of the DEC PDP-11 computer so that it was not platform-independent.
They rewrote the operating system in the C programming language (which Ritchie developed in part for Unix) to make it platform independent. This version they named Unix.
Numerous versions of Unix were released between 1972 -- early 1980's including a version that would run on Intel 8086-based computers such as the early IBM PC and PC-compatible computers.
Unix was not a free operating system. In spite of it being implemented as a platform-independent operating system, it was not available for all hardware platforms.
In 1983, Richard Stallman of MIT began the GNU Project, an effort to complete a Unix-like operating system that was both free and open source. GNU stands for GNU’s Not Unix, an indication that GNU would be a Unix-like operating system but separate from Unix. His goal was to have anyone and everyone contribute to the project. He received help from programmers around the world who freely contributed to the GNU operating system, which they wrote from scratch. Although a completed version of GNU was never released, the approach taken was to lead to what we now call the open source community.
Stallman formed the Free Software Foundation (FSF) and defined the GNUs General Public License (GPL).
At around the same time as the initiation of the GNU Project, researchers at the University of California Berkeley developed their own version of Unix, which was given the name BSD (Berkeley Standard Distribution) Unix. This version includes networking code to support TCP/IP so that these Unix computers could easily access the growing Internet.
In time, BSD 4.2 would become one of the most widely distributed versions of Unix.
The result of several competing forms of Unix led to what some have called the “Unix Wars.” The war itself was not restricted to fighting over greater distribution. In 1992, Unix System Laboratories (USL) filed a lawsuit against Berkeley Software Design, Inc and the Regents of the University of California. The lawsuit claimed that BSD Unix was built, at least partially, on source code from AT&T’s Unix, in violation of a software license that UC Berkeley had been given when they acquired the software from AT&T. The case was settled out of court in 1993.
By 1990, the Open Software Foundation (OSF), members of the open source community had developed standardized versions of Unix based on BSD Unix.
Today, there are still many different distributions of Unix available which run on mainframe, minicomputers, and servers.

In 1991, a student from Finland, Linus Torvalds, was dissatisfied with an experimental operating system that was made available through an operating systems textbook of Andrew Tanenbaum. The operating system was called Minix. It was a scaled down Unix-like operating system that was used for educational purposes. Torvalds decided to build his own operating system kernel and provide it as source code for others to play with and build upon(Torvalds has claimed that had the GNU project kernel been available, he would not have written his own). Early on, his intention was just to explore operating systems. Surprisingly, many programmers were intrigued with the beginnings of this operating system, and through the open source community, the operating system grew and grew.
The development of Linux in many ways accomplished what Stallman set out to do with the GNU project. Stallman and many in the FSF refer to Linux as GNU/Linux as they claim that much of Linux was built on top of the GNU project code that had been developed years earlier. According to some surveys, roughly 75% of Linux has been developed by programmers who work for companies that are investing in Linux. The GPL causes many of these programmers to publish their code rather than keeping the code proprietary for the companies they work for. Additionally, 18% of the code is developed strictly by volunteers who are eager to see Linux grow.
Today, Linux stands on its own as a different operating system from Unix. Linux is freely available in source code and the open source community continues to contribute to it. And like Unix, there are many distributions(many many more than Unix distros really).
Unlike Unix, however, Linux’s popularity is far greater because, while Unix can run on personal computers, Linux is geared to run on any platform and is very effective on personal computers.
Although there are dozens of dialects of Unix, there are hundreds of different Linux distributions. Navigating between the available dialects can be challenging. Nearly all of the dialects can be categorized into one of four ancestor paths.
  • Debian: This branch includes the very popular Ubuntu which itself has spawned dozens of subdialects. Another popular spin-off of Debian is Knoppix.
  • Red Hat: There are as many or more subdialects of Red Hat as Debian. The most popular subdialect is Fedora. Another popular descendant is Mandrake and another is CentOS. Another distribution that is increasing in popularity is Scientific Linux, produced by Fermi National Accelerator Laboratory and CERN.
  • SLS/Slackware: This branch was first produced by a German company which led to SuSE Linux. Although there are dozens of spin-offs of SLS/Slackware, it is far less popular than either Debian or Red Hat.
  • Miscellany: There are dozens of dialects that either led nowhere or have few successors.
Linux and Unix operating systems are partially or completely POSIX conforming. POSIX is the Portable Operating System Interface, a set of standards that operating system developers might attempt to target when they implement their systems. POSIX defines an Application Programming Interface (API) so that programmers know what functions, data structures, and variables they should define or utilize to implement the code they are developing for the operating system.
In the development of Linux, the POSIX API has been used to generate a standard called the Linux Standard Base (LSB).
Anyone implementing a dialect of Linux who wishes to include this standard knows what is expected by reading the LSB. The LSB, among other things, defines the top-level directory structure of Linux and the location of significant  Linux files such as libraries, executables, and configuration files, a base set of Linux commands and utilities to be implemented, and implementations for such programs as gcc, the Gnu's C compiler.
Thus, underlying most dialects of Linux, you will find commonalities. In this way, learning one version of Linux is made easier once you have learned any other version of Linux.



Resources


Linux with Operating System Concepts by Richard Fox
isbn:9781482235906, goodreads:20792170

VIRTUAL MACHINES

A Virtual Machine(VM) is an extension to an older idea known as software emulation. Through emulation, a computer could emulate another type of computer. More specifically, the emulator would translate the instructions of some piece of incompatible software into instructions native to the computer. This would allow a user to run programs compiled for another computer with the right emulator.

The VM is a related idea to the emulator. The VM, as the name implies, creates an illusionary computer in your physical computer. The physical computer is set up to run a specific operating system and specific software. However, through emulation, the VM then can provide the user with a different operating system running different software.
One form of VM that you might be familiar with is the Java Virtual Machine (JVM),which is built into web browsers. Through the JVM, most web browsers can execute Java Applets. The JVM takes each Java Applet instruction, stored in an intermediate form called byte code, decodes the instruction into the machine language of the host computer, and executes it. Thus, the JVM is an interpreter rather than a compiler. The JVM became so successful that other forms of interpreters are now commonly available in a variety of software so that you can run, for instance, Java or Ruby code. Today, just about all web browsers contain a JVM.
Today’s VMs are a combination of :
  • software :  is a program that can perform emulation
  • data       :  consist of the operating system, applications software, and data files that the user uses in the virtual environment.

With VM software, you install an operating system. This creates a new VM. You run your VM software and boot to a specific VM from within. This gives you access to a non-native operating system, and any software you wish to install inside of it. Interacting with the VM is like interacting with a computer running that particular operating system. In this way, a Windows-based machine could run the Mac OS X or a Macintosh could run Windows 7.
Commonly, VMs are set up to run some version of Linux. Therefore, as a Linux user, you can access both your physical machine’s operating system (e.g., Windows) and also Linux without having to reboot the computer.
The cost of a VM is as follows:
  • The VM software itself—although some are free, VM software is typically commercially marketed and can be expensive.
  • The operating system(s)—if you want to place Windows 7 in a VM, you will have to purchase a Windows 7 installation CD to have a license to use it. Fortunately, mostly  versions of Linux are free and easily installed in a VM.
  • The load on the computer—a VM requires a great deal of  computational and memory overhead, however modern multicore processors are more than capable of handling the load.
  • The size of the VM on hard disk—the image of the VM must be stored on hard disk and the size of the VM will be similar in size to that of the real operating system, so for instance, 8 GBytes is reasonable for a Linux image and 30 GBytes for a Windows 7 image.
 You could create a Linux VM, a Windows VM, even a mainframe’s operating system, all accessible from your computer. Your computer could literally be several or dozens of different computers.
Each VM could have its own operating system, its own software, and its own file system space. Or, you could run several VMs where each VM is the same operating system and the same software, but each VM has different data files giving you a means of experimentation.
VM software is now available to run on Windows computers, Mac OS X, and Linux/Unix computers. VM software titles include vSphere Client and Server, VMware Workstation, VMware Player, Virtual Box, CoLinux, Windows Virtual PC, Parallels Desktop, VM from IBM, Virtual Iron, QEMU, and Xen. The latter two titles are open source and many of these titles have free versions available.

With VM software readily available, we can expand on its capabilities by implementing virtualization.
With virtualization, an organization hosts a number of VMs through one or more VM servers. The servers operate in a client–server networking model where a client runs a VM program on the user machine and requests access to one of the stored VMs.
The VM servers typically store the VMs on a storage area network (SAN). The collection of VM servers, the SAN, and the data that make up individual VMs can be called a VM Farm.
Now, accessibility to your VM is one of starting your VM client software and logging into the VM server. You select your VM from a list of choices, log into it, and the VM server then runs (emulates) the VM for you. Your client operates as an input/output device while the processing and storage take place on the VM server. As you make modifications to your VM, they are saved in the SAN.

There are numerous advantages to virtualization.
  1. First is accessibility. You are able to access your VM from any computer that has Internet access and runs the proper VM client software. 
  2. Second is cost savings. If your company is small and you cannot afford all of the hardware needed for your employees, you can lease or purchase time and space in a VM farm where the VM servers and SAN become the hardware that you use.
  3. You can also rely on the company hosting your VMs to handle security and backups alleviating some of the IT needs from your own organization. 
Today, more and more organizations are taking advantage of virtualization to improve their efficiency and lower costs.

Reasons to Use Virtualization



















Resources


Linux with Operating System Concepts by Richard Fox
isbn:9781482235906, goodreads:20792170

06 August 2015

Cisco Certified Network Associate (CCNA)


Cisco Network Architectures 

The role of the network has changed from a data-only network to a system that enables the connections of people, devices, and information in a media-rich, converged network environment.
In order for networks to function efficiently and grow, the network must be built upon a standard architecture. The network architecture refers to the devices, connections, and products that are integrated to support the necessary technologies and applications.
A well-planned network technology architecture
  • helps to ensure that any device can be connected across any combination of network 
  • increases cost efficiency by integrating network security and management
  • and improves business processes

With the constant evolution of networks, Cisco has updated its enterprise architectures and frameworks and has created the following three enterprise architectures to address the new network trends:

  • Borderless networks architecture
  • Collaboration architecture
  • Data center and virtualization architecture
These three enterprise technology architectures can be implemented separately, or combined.

CCNA 

The three Cisco architectures  are built on an infrastructure of scalable and resilient hardware and
software. Components of the architectures come together to build network systems that span your organization from network access to the cloud, and provide organizations with the services they need.
At the foundation of all three of these architectures, and in fact, at the foundation of the Internet itself, are routers and switches.
Routers and switches transport data, voice, and video communications, allow for wireless access, and provide for security.
After a basic network infrastructure with routing and switching is built, organizations can grow their network over time, adding features and functionality in an integrated solution.

As the use of these integrated, expanding networks increases, so does the need for training for individuals who implement and manage network solutions. This training must begin with the routing and switching foundation. 
Achieving Cisco Certified Network Associate (CCNA) certification is the first step in helping an individual prepare for a career in networking.
CCNA certification validates an individual’s ability to install, configure, operate, and troubleshoot medium-size routed and switched networks, including implementation and verification of connections to remote sites in a WAN. 
This CCNA curriculum includes lessons that address the basic mitigation of security threats, introduction to wireless networking concepts and terminology, and performance-based skills. This CCNA curriculum also includes the use of various protocols, such as Internet Protocol (IP), Open Shortest Path First (OSPF), Serial Line Interface Protocol (SLIP), Frame Relay, VLANs, Ethernet, access control lists (ACLs), and others.
This course helps set the stage for networking concepts and basic routing and switching configurations and is a start on your path for CCNA certification.

11 October 2011

File Transfer trough Netcat

under revision...

The flexibility and simple operation allows Netcat to fill a niche when it comes to moving a file or files in a quick and easy fashion. Encryption is provided via several different avenues including integrated support on some of the more modern Netcat variants, tunneling via third-party tools, or operating system integrated IPsec policies. After the file is transferred, any of several hash-generating programs can be used to verify the integrity of the file you received. Instead of being a specialized tool, like FTP, Netcat is a general-purpose tool, much like the Swiss army knife it is so often compared to. As a general purpose tool, the uses for Netcat are often more limited by your imagination than by Netcat’s functionality.

FT Using Netcat (the long story)


Netcat's Cons
Security Concerns
An area of concern is that of user and rights management. If you want to strictly control user access and user rights to the transferred files and the upload directories, Netcat is probably a poor choice.
Netcat itself offers no way to control who can send what to whom. 
  1. In order to exercise tight control over file uploads you would be forced to configure your permissions using the file system itself, which could be administratively burdensome in a complex environment. 
  2. Additionally, such configurations also increase the likelihood of introducing human error. 
    1. If i.e. you decide to grant the rights to maintain these permissions to another person, doing so may entail granting them more access to the underlying file system than you had in mind.
A product designed to give you granular control over user access rights such as a good FTP server, would make this task much easier, and probably be a better choice.
Another area where security can become a concern is the fact that some programs are more easily used by an attacker to compromise security on the host system.
  • In other words, it is true that an FTP server can be used against you by an attacker, however, the configuration of the FTP server is probably much more closely guarded. 
    • The configuration files are probably well secured and logging might notice attempts to manipulate the software’s normal configuration.
Netcat is a tool hackers are extremely familiar with. Simply having it on a host where it could possibly be leveraged by an attacker is an increased risk.
High security hosts will often have policies expressly prohibiting such programs from even being on the system. Of course Netcat can be secured appropriately,
it simply represents an increased risk over some of the less easily abused file transfer services.


Complex environments issues
If you will be using Windows hosts as either the client or server for your file transfers, this means you will have to “install” the appropriate Netcat version. Understandably, the “installation” may be as simple as copying a file onto the system, but even this process could be slowed by bureaucracy and cause problems on some mission-critical servers.

Sometimes simply getting permission to install non-Microsoft software can be challenging. Considering this, in some environments the simple fact that FTP clients are installed on all modern Microsoft operating systems, as well as being supported in Internet Explorer browsers, Netcat might not be the best option.

Even after the installation is complete, there is the matter of configuring the transfer. You may be wondering what there is to configure; you enter a single line at each end and off you go. It might be that simple, especially for a one-off transfer, but if you want something to be run regularly and programmatically it will probably take more time than this.
You might need to configure some type of wrapper script to handle errors or problems, as well as something to verify the file integrity and permissions.
  • How do you handle a corrupted file? 
  • How do you deal with an interrupted download?
Starting over might not be a good choice if the file is very large. How do you allow transfers from multiple users with differing security requirements?

If you can get Netcat installed where you need it without issues, there are still roadblocks. If all you need is a simple no-frills file transfer, configuring any needed scripts should be pretty trivial. If you need to configure some more complex routing to handle and rotate logs, interact with syslog, or deal with directories and rights, it could take some time.

The point here is that even if the bureaucratic process doesn’t slow you down, the developmental one might. Testing and troubleshooting file transfer scripts can easily end up taking more time than you have. All of these things collectively mean you might end up spending more time troubleshooting the simple Netcat transfer, when an alternate solution could have been implemented more quickly.



Netcat's Pros
There are still many circumstances where Netcat is not only a viable choice for moving data, but a preferable one.


Speedy Gonzales
Let’s suppose you need to move a file over from one host to another and it needs to be done quickly. Setting up an FTP or Trivial File Transfer Protocol (TFTP) server and creating users and setting up access rights, while not difficult, seems like a lot of work to just move one file.

Perhaps one host is a Linux host and one is a Windows host. To make matter worse, let’s say that Windows file sharing is not permitted on the network and the file you need to send it is too large for the e-mail system. Sounds like a real hassle; however, this scenario is fairly common in many corporate settings. You might find yourself in a position where preparing for the file transfer is going to take far longer than the actual transfer itself.

Here's when Netcat comes to the rescue. With the cross-platform support, you can run the client or server from your pen drive and have your file moved in less time than it takes to even locate the form required for setting up the appropriate service.
Netcat’s simplicity means those one-off file transfers can be accomplished very rapidly and with the minimal amount of fuss.

Sometimes you may not have the privileges required to create an FTP server or enable file sharing, but more often than not you will be able to start up Netcat on some high-numbered port. Even a user with minimal privileges can successfully move a file with Netcat. This single feature, rapid deployment, is reason enough to keep Netcat in your networking toolbox.


Stealth
It could be a matter of policy, a penetration testing exercise, or other grey hat endeavors, however, the ability to stealthily send data across the port of your choosing can be invaluable. Netcat not only grants you the ability to send data, but also allows you to push the data in either direction, irrespective of the direction the session was initiated from.

While many of the more sophisticated file transfer protocols are limited to a standard set of ports, Netcat has no such limitations. If the only port open is User Datagram Protocol (UDP)/Domain Name Service (DNS) port 53, you can certainly connect outbound over port 53 and then pull data back into your client system.

Even if the port you choose is being closely monitored for content, FTP and other such protocols contain easily identifiable characteristics that your Netcat file transfer may lack, potentially making a Netcat session harder to detect. This becomes even more true when you introduce simple and painless encryption to your Netcat session. (See the Cryptcat, OpenSSH, OpenSSL, IPsec) Of course there are some solutions that can hide the data even better, such as a Hypertext Transfer Protocol Secure (HTTPS) proxy, but typically these take a little more time and effort to configure and get working.
If you combine a client script with “port knocking,” you have the recipe for some seriously stealthy data transfers. See portknocking.org if you are not familiar with the powerful security benefits of port knocking


Small Footprint
Here're environments where production servers could not have software installed or removed except during pre-defined maintenance windows. Some company policies, however, will allow for simple portable applications that require no registry changes or file system access changes to be run on an as-needed basis. Some change management policies will allow the use of Netcat while other will not. You will need to determine what is appropriate in your environment. Even if you do not have the luxury of being able to start up Netcat without prior approval, Netcat offers a very small footprint, with the original version weighing in around 60KB. This, and the open source nature of many Netcat variants, may allow you to implement Netcat when some other “heavier” solution would have been problematic. Given Netcat’s small size and minimal system impact, it can find a special niche when such traits are important.


Simple Operation
The relatively simple operation of Netcat means it can be run with very little  training. Setting up an FTP server on the other hand, takes a little more know how, especially if firewalls are involved. Explaining to the person at the other end how to specify passive FTP in place of active FTP can be challenging and frustrating, even if you are using a GUI.

If you manage to overcome that hurdle, you could still find yourself troubleshooting user rights. Do you have access to the local file system? Is granting access feasible or permitted? Netcat’s options are simple enough. An e-mail with the attached executable would probably be all it took to get a file transferred with no more than a neophyte at the other end for help. The nearly identical operation between operating systems also means that familiarity with Linux Netcat pretty much means familiarity with Windows Netcat.

Overall, Netcat fills a special role when it comes to file transfers. When you need a way to move a file and need it done yesterday, Netcat may be the single fastest solution available. The lack of security features makes Netcat unsuitable for some tasks, but also ideal for others. You must evaluate the pros and cons of your particular circumstances. The right balance must be found between features and ease of use.
Your comfort level with implementing a given solution is also a consideration. If you know Secure file CoPy (SCP) inside and out, maybe that is easier than using Netcat. Netcat’s simplicity and ease of use could mean the difference between getting the job done “on time,” and getting it done “too late.”

Note:
Before setting out to use a particular flavor of Netcat, consider your intended application. Not all of the Netcat varieties will run on both Windows and *nix systems.
  1. The original Netcat, GNU Netcat, cryptcat, and SBD all have both Windows and UNIX/Linux versions. 
  2. The Socat offer *nix versions only, with no Windows support as of this writing.
If you are in a mixed Windows/ *nix environment, standardizing on a version which you can use on either type of host may be wise. This will make things easier because the various options and nuances of operation will be consistent.



Performing Basic File Transfers

Not all environments require high security, and not all file transfers will contain confidential or otherwise sensitive information. In some cases, your needs will be simple. To accommodate this we will start by looking at file transfers using Netcat in it’s most basic format. While not very robust, it serves its purpose and gets the job done.



Transferring Files with the Hobbie's Netcat
On the server side you will need to:
  1. specify that Netcat should be listening for inbound connections with the –l option, and 
  2. specify which port to listen on via the –p option.
  3. You also need to specify the file to direct the output to. 
This can be accomplished with the following command:
$ nc -l -p 4444 > /test/outfile.txt

This command would tell Netcat to listen on port 4444 (over TCP by default), and send the output from the connection to /test/infile.txt.

On the client side, the format is similar. All you need is:
  1. a destination IP address and port number, as well as 
  2. the file you wish to redirect to the network socket.
$ nc 192.168.1.99 4444 < C:\test\infile.txt

or
$ cat /test/infile.txt | nc 192.168.1.99 4444


On *nix systems you can use the cat command to read the file into Netcat or the </> redirection. Here we will use the </> format because they will work on Windows or Linux.


This would connect to the host at 192.168.1.99 over port 4444 and send the C:\test\outfile.txt over the socket thus created. That is all it takes to move a file.
  1. The file in question does not have to have the same name at each end, though it can. 
  2. The direction of the file transfer is from the client to the server in this example and all examples used here. 
  3. You can also “push” a file from the server to the client just as easily, by reversing the direction of the </> symbols. 

The –p option specifying the port will work with or without a space between the –p and the port number.

You can use the –u option to use Netcat over UDP instead of TCP, though for file transfers this is rarely needed or advisable.

Warning:
When using the redirect option to transfer a file, you will receive no warning or error if you attempt to overwrite an existing file.
You can use a >> to output to a file instead of > , and the file will be appended to instead of overwritten. 
Beyond these simple steps, it is left to the user to ensure that old data is not inadvertently overwritten via Netcat’s redirection capabilities. If this is a concern, see some of the Netcat variants that offer more control over how files are handled.



Closing Netcat When the Transfer is Completed
One of the first things you will notice as you play with Netcat, is that the file never seems to finish. At least it gives no indication that the file transfer is complete. Unfortunately, it will sit there indefinitely. If you break out (normally CTRL+C), you will find that the file is there in it’s entirety, assuming you allowed enough time to complete the transfer. This raises the question of how do I make the socket close when the file transfer is complete?

If you use the –w option, it will allow you to specify the delay in seconds after the end of the file is reached before Netcat will close the connection.
On Windows systems, the –w option can be used on the server or the client with identical results.
Both of these commands would result in the connection closing five seconds after the file transfer is completed. Here are commands for:
Windows server side:
$ nc –l –w5 –p 4444 > /test/infile.txt

and Windows client side:
$ nc –w5 192.168.1.99 4444 < C:\test\outfile.txt

The behavior of the –w option is a little different on Linux. On Linux, the –w option used on the Netcat server specifies how long to wait for a connection before closing. This can be useful if you want to only keep the port open for a short time before closing it, perhaps to increase security. The –w option used on the client side will act as a timeout before the connection closes, but after the file transfer, the same as on Windows systems.
This means the –w option behaves differently depending on which end of the connection you use it on (as the help output describes). This will cause the listening server to wait five seconds for a connection to be made before shutting down the listening port. If –w is used only on the server, the connection will not close by itself and will instead stay open when the file transfer is completed.
$ nc –l –w5 –p4444 > /test/infile.txt

This will cause the client to send the file specified, and then wait five seconds after the file is transferred before shutting itself down.
$ nc –w5 192.168.1.99 4444 < C:\test\outfile.txt


When you are mixing Linux and Windows Netcat servers and clients, you get the above behavior based on who is the client and who is the server.
In other words, because the –w option as an initial connection timeout is a server-based option, it will act as a connection timeout if Linux is the server. If it is a windows server, it will act as an end-of-file timeout.Either system will honor the end of file (EOF) timeout as a client option.


Other Options and Considerations
The –L option is specific to the Windows version of Netcat when used in server mode. This tells Netcat to continue listening on the indicated port even after the client disconnects. This is a departure from the standard behavior, which is to shut down the server side when the client disconnects. This option could be useful:
  1. if you want to send data to the server from multiple clients, or
  2. if you want to send multiple files to the server over different sessions to be appended to the same output file.
From a scripting perspective, it is worth pointing out that on Windows the file you
are using for redirection will be locked by the file system. This means an attempted move or renaming of the redirected file while Netcat is still running will result in an error.

Linux does not share this behavior, and will happily let you rename the file out from under Netcat. The file locking behavior may sometimes work to your advantage. Suppose you are sending a Windows host some type of log, perhaps from a custom written script. You can have an automated batch file loop and attempt to rename the file with the current date, for example, and you will not have to worry about figuring out if the Netcat portion of the script is completed or not. If Netcat has not closed, you will not be able to rename the file.

The –q option is only available on Linux and has no effect when run on the server, at least as far as file transfers are concerned. When used on a Linux client for a file transfer, it has the effect of closing the connection as soon as the file transfer is completed regardless of the number you specify, much the same as using –w1 on the client would (using zero seconds for the wait time will result in an error). This behavior is a little odd, but considering the option it is intended to be used with, stdin, it really isn’t that surprising.


Timing Transfers, Throughput, etc...
An additional option that could be of benefit when scripting file transfers, is the –v (for verbose) option. This tells Netcat to give you more feedback on the connection process. With a single –v, Netcat will tell you the IP and port being used. With an additional v, Netcat will also tell you the amount of data transferred in bits, similar to the following:
> F:\netcat>nc -v -l -p4444 > F:\small.txt
listening on [any] 4444
...
connect to [192.168.1.99] from (UNKNOWN) [192.168.1.112] 53442: NO_DATA

> F:\netcat>nc -vv -l -p4444 > F:\small.txt
listening on [any] 4444 
...
connect to [192.168.1.99] from (UNKNOWN) [192.168.1.112] 53492: NO_DATA
sent 0, rcvd 147

Note the final line that is added with the second v. This can be particularly handy if you want to grab the file size after the transfer. If necessary, you could script the timestamp before and after the transfer, and combined with the file size and a little math you could determine the throughput, much like an FTP file transfer.

The  Windows 2000 resource kit (and likely others) includes timethis.exe, which will accept another command as an argument and time how long it takes to complete the command. As an example, timethis.exe produces the following output for a netcat file transfer:
> timethis “nc 192.168.1.99 4444 < C:\test.txt”
timeThis :    Command Line     :     nc 192.168.1.112 4444 < F:\test.txt
timeThis :    
timeThis :    
Start Time     :     Tue Apr 01 17:50:21 2008
End Time     :     Tue Apr 01 17:50:24 2008
timeThis :    Elapsed Time     :     00:00:02.021

Remember that you will need to time the transfer on the client host. 
If you are planning on the server continuing to listen after the file is transferred, timethis would never see the command “complete” and know to stop the timer. Even if you are allowing the server to close after the transfer is completed, there would still be the extra time recorded while the server was listening, but before the client connected. This additional time would skew your total time and alter any calculations for throughput you might do.

Linux also offers the(pipe viewer) pv utility. If you do not already have it installed, it has some very cool options for monitoring the performance of a pipe. You can use the 
  • –b option to display the amount of bytes transferred, and 
  • the –t option to show the elapsed time.
This allows you to get both time and byte counts in a single tool. The following line would provide both the time elapsed and the bytes transferred:
$ cat test.txt | pv –bt | nc 192.168.1.99 4444 
177MB 0:00:19


Tunneling a Transfer Through an Intermediary
Another option is to use a host in between your client and server to bounce the Netcat session off. This could be helpful if you need to change the port you are using somewhere in the middle of the data path. While not supported natively, you can accomplish this by piping Netcat into Netcat on the intermediary system as follows:
$ nc -l -p4444 | nc 192.168.1.99 6666

This uses the same syntax you are familiar with, but sends the output of the listening Netcat into the client session as input. The creative uses you can put this type of simple redirection too are nearly endless. Netcat has what it takes to move a file easily from one system to another without too much fuss. While not sophisticated in it’s capabilities, it can still get the job done.

Of course, these simple file transfers are only the tip of the iceberg. You may still need to find ways to handle file integrity, because Netcat does not verify your data was transferred without errors. You will also want to ensure that the data you are transferring is protected from authorized viewing via encryption. Both of these options will be discussed later here. The next step is to examine some of
the Netcat variants and what options they offer when it comes to transferring files.



Using Netcat Variants

The original Netcat was created over a decade and half ago. As fast as technology moves, that makes it practically ancient by modern standards, and it is a credit to its creator that Netcat is still in wide use today. Despite this, there have been many other talented people who wanted some feature or function that Netcat could not offer. In other instances, popular *nix distributions have continued to develop their own version of the original Netcat, with new features and functionality. For these reasons many alternate versions of Netcat have been developed.

Some are extremely close to the original, offering only a single new feature such as cryptcat, while others introduce a host of options such as Socat. We will explore the file transfer capabilities these variants provide and discuss any caveats to performing file transfers that may exist.


Cryptcat
Cryptcat is a Netcat variant that is very close to the original; in fact the help screens are nearly identical.
The only differences from an options perspective are that cryptcat does not offer the –t option or the –q option. 
  • The –t option tells Netcat to use Telnet negotiation, making Netcat a Telnet client, and 
  • the –q option is used as an stdin timeout.
Cryptcat does add new functionality over the original Netcat. As one might guess, this new functionality is the integrated support for encryption. This feature is just as important for keeping file transfers confidential as it is for an interactive session.
The –k option is used to specify a shared secret password. Cryptcat with then use this password as the key for encrypting the data stream using B. Schneier's twofish encryption.

Cryptcat is available for *nix and Windows. Unfortunately they do not offer a pre-compiled executable on the cryptcat home page. If you don’t mind downloading a pre-compiled version from another source, there are many available on the Internet such as the one from www.security
forest.com/downloads/cryptcat.exe.

The operation of cryptcat is simple, following the same syntax and format as Netcat. Traffic through cryptcat will be encrypted even if you do not specify the –k option, though in this case it will use a default key of “metallica.” Otherwise, you can specify the same key on the client and server as follows:
Server:
$ cryptcat –l –k secretkey –p4444


client:
$ cryptcat –k secretkey 192.168.1.99 4444

The following output from tcpdump demonstrates why encryption might be a good idea. The first is the hex output of the packet from Netcat (minus the header data), while the second is the hex output from the same test data “this is a test string,” using the default key with cryptcat.
0x0000: 4500 004a 9806 4000 4006 1e77 c0a8 0170  E..J..@@..w...p
0x0010: c0a8 0170 adc0 115c 355d bdd7 3503 712f  ...p...5]..5.q/
0x0020: 8018 0101 846d 0000 0101 080a 00e2 2a35  ...p...5]..5.q/
0x0030: 00e2 25d2 7468 6973 2069 7320 6120 7465  ..%.this.is.a.te
0x0040: 7374 2073 7472 696e 670a                 st.string.

0x0000:  4500 0044 bf71 4000 4006 f711 c0a8 0170  E..D.q@.......p
0x0010:  c0a8 0170 adc1 115c 3625 8ca7 368c b1d5  ...p...6%..6...
0x0020:  8018 0101 8467 0000 0101 080a 00e2 37d6  ....g........7.
0x0030:  00e2 37d6 9b4c 4768 3576 71ed f564 bea4  ..7..LGh5vq..d..
0x0040:  6760 8e1d                                         

Just like Telnet, anyone who was able to capture your Netcat session would be able to see everything that was sent over the link. Cryptcat also supports the –L option on the Windows version. On Windows, the cryptcat executable can even be renamed to nc.exe if you wanted to “upgrade” current Netcat scripts to include encryption. If you need a quick way to move files while still protecting the data from prying eyes, cryptcat might fit the bill nicely.
Default Encryption Keys
As is always the case with any encryption mechanism, avoid using the default encryption keys for anything other than testing functionality. Much the same as the default passwords to common accounts are well known and exploited, so too are default encryption keys. If an attacker stumbled upon your encrypted Netcat stream, he/she could capture it and decrypt it using the default key of “metallica.” This attack does require some skill and opportunity, which may not always be practical, but it simply isn’t worth the risk. Always specify a high quality shared secret key for cryptcat. Another tip is to remember that if you are going to script a repeating process, be sure and take into account the fact that you will need to change the encryption key regularly.


GNU Netcat
The GNU Netcat is a completely rewritten version of the original Netcat licensed under the GNU general public license. Currently GNU Netcat is available for *nix operating systems only, though hopefully it is only a matter of time before someone creates a Windows port.

One of the objectives of the project is compatibility with the original Netcat. In addition to this there are some new features that have been added. Overall, the changes from the original Netcat are minimal.
  • The –q (stdin timeout) option has been changed to the –c option, but otherwise behaves the same. 
  • The –L option used in the Windows Netcat now serves a different purpose for the GNU Netcat. While there are a few more changes to the GNU Netcat options, –L option is the only new option of note when it comes to file transfers. The –L option is used to tunnel a connection using Netcat. 
For example, if you wanted a host to listen for an inbound Netcat connection on port 4444 and then send it out to host 192.168.1.99 on port 6666, you could use either of the following commands:
$ nc –L 192.168.1.99:6666 –p4444
 
$ nc -l -p4444 | nc 192.168.1.99 6666

The first of the two examples uses the GNU Netcat tunneling feature. The –p
option specifies the listening port as usual, and the –L option specifies the host and port to forward to.

The second example accomplishes the same thing by piping the input of one instance of Netcat into the output of another instance. This second example will
work with virtually any version of Netcat. This capability could be advantageous when you need to transfer a file, but there is more than one set of firewalls between the source and destination. The tunneling feature could allow you to change the port you use in the middle, increasing the odds you could make the connection successfully.


SBD
Shadowinteger’s Backdoor (SBD) is another Netcat variant, with all of the features of the original Netcat plus some new ones. SBD is available for both Windows and *nix, with pre-compiled binaries included in the single g-zipped file from http://security.cycom.se/dl/sbd. This feature alone makes SBD a good candidate to settle on as your Netcat-like utility of choice. If that is not enough reason, it offers encryption like cryptcat, and a respawn option, providing the –L functionality for both Windows and *nix hosts.

You can put a wrapper script around any version of Netcat to cause it to restart on *nix, but with SBD providing that functionality built-in, there is little need for such effort. While the basic operation of SBD remains much the same as the other Netcat-like tools, there are a couple of additional options that could be useful for transferring files.
  1. SBD allows you to specify the source port via the –p option if you are running in client mode (in server mode, –p specifies the listening port as usual). This feature could allow you to get through a firewall by making the SBD session look like a reply to a friendly protocol such as DNS. Of course, this trick is not going to fool a statefull firewall, but having this increased control never hurts.
  2. The –r option allows you to tell SBD to re-spawn after a client disconnect instead of the default Netcat behavior, which is to shut down the server.You can also configure a delay in seconds before re-spawning, this delay could be useful to help slow down any attempts to brute force your listening process. The Windows version of Netcat provides the same functionality via the –L option, while the original *nix version offers no such option. The delay can be set to zero seconds which provides identical behavior to the Windows Netcat –L option.
  3. With cryptcat, encryption is enabled by default, even if you do not specify a shared secret key. SBD takes the same approach except encryption can be disabled completely via the –c option (–c off disables encryption, –c on is the default). 
  4. Similar to cryptcat, the –k option is used to specify the shared secret key. 
  5. Another interesting option is –P, which is used to specify a prefix for incoming data. The original intent seems to be to facilitate SBD as a primitive chat client; however, it could also be useful to provide a sort of data “tag” for the server to log. Take for example, a scenario where you have two or more systems running a custom script you created. You want each system to log a status message so you know the process completed successfully. You could program in a custom message on each host, or grab a variable from the environment, or you could also have SBD add the “tag.” 
  6. The only other consideration to be aware of concerns SBD’s behavior after a file transfer is completed. Unlike the original Netcat, SBD closes the connection after the file transfer is completed. This behavior makes the use of the –w option obsolete.
 

Socat

Socat (short for socket cat) is by far the most advanced Netcat variant covered. 

Socat comes with an extensive number of options (try “Socat -???” for a list). There is currently also a Windows version available, but the impressive list of features could bring socat to the forefront when you are selecting a Netcat-like tool to use. The number of options is far too great for us to explore them all, so we will limit the discussion to those options that are most useful for transferring files. You can download socat from www.dest-unreach.org/Socat/download/. There is also a manual(in html). The examples at the bottom of the page are particularly valuable, though they could stand a little elaboration.


Socat Basics
While basic connectivity with Netcat has been covered extensively by this point, Socat is different enough to justify starting with the absolute basics. To open a simple TCP client connection, you would use the following command:
$ socat tcp:192.168.1.99:4444 stdin

At the server side you would use the following;
$ socat tcp-listen:4444 stdin

The above commands would create a session that would behave the same as a standard Netcat session. As you can see, Socat uses a format of Socat at all times. Basically, Socat acts as the bridge to link the two data channels together. Netcat behaves much the same way, except that Netcat assumes stdin as one of the communication channels. Socat makes no such assumptions, and if you fail to explicitly configure both communication channels, Socat will generate an error.


Transferring Files with Socat
The following commands can be used for a basic file transfer.
On the client:
$ socat tcp:192.168.1.99:4444 open:/test.file

On the server:
$ socat tcp-listen:4444 gopen:/newtest.file

These commands will behave similarly to Netcat. For example, using the above commands, the socat instance will close when the file transfer is complete. The open and gopen options have some subtle differences, however.
Using gopen (generic open) if the file does not exist it will be created. If the file does exist, the new data transferred would be appended to the existing file. Using open on the other hand, will generate an error if the file doesn’t exist. You can avoid this and cause open to create a file that doesn’t exist if you also use the creat option. The default behavior of open is to overwrite a pre-existing file unless you use the append option. 

The benefit of using the open option instead of gopen is that you can toggle the append behavior off or on as you like. If you put all of this together it means that for the server instance, both of these commands will operate the same.

$ socat tcp-listen:4444 gopen:/newtest.file

$ socat tcp-listen:4444 open:/newtest.file,creat,append

If you want to ensure that data cannot accidentally be sent back over a given connection in the wrong direction, socat also lets you control that as well. You can invoke Socat in unidirectional mode to ensure that a given data channel is used for reading and the other for writing. The following command would ensure that test.file would be sent from the client, and opened read-only for added security.
On the client:
$ socat –U tcp:192.168.1.99:4444 open:/test.file

On the server:
$ socat –u tcp-listen:4444 gopen:/newtest.file

On the server, the newtest.file would be opened write only and would not be read
from. The –U option specifies that the first channel is for writing, while the second channel is for reading data. The –u option does the same thing, but reverses which channel is for read and which one is for writing.

Socat also offers extensive logging capabilities and is the only Netcat variant which supports syslog natively. The –ly option will cause Socat to generate system messages with a default facility of “ daemon,” though you can specify the facility after the –ly option (–ly[] ).
 


Encryption
With all of these powerful features you might be wondering where and how socat
can provide encryption. Socat supports encryption of the data stream but it does not do so natively.

Socat does not have encryption capabilities built into it like cryptcat and SBD. Socat uses third-party tools, in this case OpenSSL, to provide encryption functionality. If you do not have OpenSSL installed on your host, the encryption options of socat will not work. 
To use socat to create an encrypted communication channel via OpenSSL, you would use the following commands.
On the client:

$ socat openssl:192.168.1.99:4444,cert=file.pem,cafile=file.crt stdin

On the server:
$ socat openssl-listen:4444,cert=file.pem,cafile=file.crt stdin

Transferring a file securely is just as easy; simply replace the stdin channel with the previously demonstrated open or gopen channels. These examples assume you have OpenSSL installed and configured correctly. If you do not have the certificates and key files generated, see the section on configuring universal SSL tunnel (Stunnel) later, for instructions on creating those files.
 

If you need to use Socat to act as a tunnel or port redirector, it is actually more intuitive than most other Netcat variants, because of the dual data channel command format. If you wanted to allow inbound connections on port 4444 and redirect them to a host at 192.168.1.99 over port 6666, you could use the following Socat command.
$ socat TCP-LISTEN:4444 TCP:192.168.1.99:6666

Adding a –v before the first data channel will allow the intermediary redirecting host to see all the data that flows through the socket. This will also include a date and time for each line of input. This can be particularly useful if you wish to perform extensive logging on this host. Such detailed logging would be ideal if this redirector was in a DMZ acting as a sort of proxy for the socat session.

The final consideration is socat’s default behavior of shutting down the socket after the file transfer is completed. If you wanted to be able to send data and append multiple files to a single file on the server, you need to use the fork option on the server.
$ socat tcp-listen:4444,fork open:test.file,creat,append

This command would allow the server to listen for inbound connections on port 4444. When a connection is made, the data would be written to a file called  test.file. When the client disconnects, socat would continue listening on port 4444. Future data would be appended to test.file indefinitely.


Mixing and Matching
Keep in mind that while the examples made use of only the Netcat variant being discussed, at the core they are simple network socket enablers. You can certainly mix and match one version of Netcat running on the host and another running on the server, with a third variant acting as a port redirector in between. In most cases, this should work without problems. You will only have access to any special options on that host, and in some cases a few options may interact in unusual ways. Test the versions you are using together extensively and all should be well.

Because of the large number of Netcat variants and the options they support, I have include a brief feature matrix in Table. This highlights the major file transfer points of interest for each variant, and includes a couple additional notes as well.



Ensuring File Confidentiality

The following is a short summary of the various encryption options for use with
Netcat.
  • SSL SSL is probably the simplest to implement. It does require a TCP-based Netcat and you must point to the preconfigured local listening SSL port. Stunnel may or may not need to be installed on your particular distribution. OpenSSL is often installed by default.
  • SSH In almost all Linux systems SSH will be included in the default install. Like SSL, it does require a TCP-based connection. 
    • The biggest disadvantage is that SSH is intended for interactive session and requires authentication (i.e., a password) at the time the SSH tunnel is established.
  • IPsec IPsec is both the most functional and flexible encryption option, as well as the most complicated. You need to match various security  association settings on both systems and multiple files have to be configured in order for it to work. 
    • IPsec’s primary strengths are the high degree of flexibility in how it is configured and that 
    • it is protocol independent. You can implement IPsec without making any changes to your specific application or scripts, because the encryption decisions are made by the operating system. This means that IPsec encryption can happen transparently to the application you are encrypting, such as Netcat.
    Bear in mind that this is a very minimalist IPsec configuration. The objective is only to secure your Netcat traffic over a single port. Configuration can become much more complex, particularly if you need to configure different IPsec policies for multiple systems. Refer to www.ipsec-howto.org for some very good documents that walk you through the process in a little more detail. We would also recommend reading the man page for syslog-ng, syslog-ng.conf, setkey, racoon, and racoon.conf.

Keeping the files you transfer confidential generally means encryption. If the data
you are sending is not sensitive, encryption might not be a consideration. If confidentiality is a concern, however, an encrypted Netcat-like solution might be just what you need to secure files you send with your home-brewed script or process.

Considering some Netcat variants offer encryption natively, you might wonder why you would want to use a different encryption mechanism. In many cases you may not need anything other than the integrated encryption offered by cryptcat or SBD, but what if those utilities are not a viable choice?
In some environments, using software that is not part of the native distribution is problematic, involving an extensive testing and approval process. Management or security might frown upon adding new software on top of what the distribution originally came with, particularly for mission-critical servers. In these circumstances, it might be easier to just make use of the software that is already installed.

On Windows hosts, the only software that is likely to already be installed is Internet Protocol Security (IPsec) support, because no version of Windows comes with Netcat. Most flavors of Linux, on the other hand, already come with some version of Netcat or a similar product, and frequently some options for encryption.If you find yourself in this situation there are a few options available to you. IPsec, Secure Sockets Layer (SSL), or Secure Shell (SSH) are all viable options for implementing encryption using software that is probably already installed on the hosts in question. Of course in the Windows world, you are probably only going to have IPSec available without resorting to installing additional software.

IPsec also has the advantage that it can encrypt UDP (or Internet Control Message Protocol [ICMP] for that matter) traffic while the other two options can encrypt TCP traffic only.

We will explain how to configure all three of these common solutions. We will
review configuring IPsec on both a Windows host as well as a Linux host.



Using OpenSSH
OpenSSH is an open source implementation of the SSH protocol. Originally it was intended as a secure alternative to other clear text protocols for remote administration, such as Telnet or rshell.

SSH includes a port-forwarding option that enables it to function similarly to Stunnel. There are advantages to using OpenSSH over Stunnel, such as the fact that you might already have OpenSSH installed to provide remote access.

In those cases, it would be one less piece of software that you needed to install and configure.Virtually every Linux implementation will come with OpenSSH
installed by default, so you are more likely to already have SSH on your Linux host than you are


SSH
Installing and Configuring Secure Shell SSH requires both an SSH client and an SSH server component.
SSH is the industry standard for remote command line access and most systems come with it as part of the default install. Windows systems are one of the few that do not. 
There are a variety of products available to bring SSH functionality to Windows, both commercial and free.

There is also a GUI front end for OpenSSH, called PuTTY. Cygwin (is a port of many UNIX tools for Windows and included in this package is an
SSH server). To add even more options, SSHWindows is a free package that installs only the minimum components of the Cygwin package to use SSH, SCP, and Secured File Transfer Protocol (SFTP).

Because the server components and client component operate differently, we will
first walk through setting up the server on a Windows XP system and ensuring that it can successfully accept SSH connections. After the basic functionality of SSH has been verified, we will cover configuring the port forwarding option to tunnel other protocols over the SSH connection.

The SSHWindows package includes both the SSH client files and the SSH server files.
  1. Download SSHWindows from http://sshwindows.sourceforge.net/ on the client and the server.
  2. Unzip the file and run the setup utility. Answer the standard prompts and then click Finish.
  3. At this point the SSH client is ready to be used without the need for any additional configuration. Before you can use the SSH server, however, you must create and edit the \OpenSSH\etc\passwd and \group files.
  4. If desired, create a separate group on the system to hold users who will have access to SSH, and add the local user accounts to the group for anyone you wish to have access to connect to the SSH server. At the console navigate to the directory where you installed \OpenSSH\bin\.
  5. Enter the following command on the server to specify which groups can
    connect via SSH mkgroup –l >>..\etc\group. This will give all local (–l)
    groups permission to connect via SSH.You should open the group file and
    edit out the lines corresponding to any groups you do not wish to have access.
  6. Enter the following command on the server to specify any individual accounts that are authorized to connect via SSH mkpasswd –l –u<accountname> >> ..\etc\passwd. You must perform both of these last two steps for SSH to work. If you do not specify the –u <accountname>, all local users will be added to the passwd file.
  7. Edit the Banner.txt file located in \etc\ to match the banner specified by your
    IP security policy.
Once this is completed you can start and use the SSH server via the Services applet of the Microsoft Management Console (MMC) or by entering net start “openssh server” at the command prompt. Output from a successful SSH connection is shown below.
I:\OpenSSH\bin>ssh sshuser@192.168.1.101
************ WARNING BANNER HERE ************
sshuser@192.168.1.101’s password:
Last login: Sat Jun 24 20:05:22 2006 from 192.168.1.99
Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.
C:\OpenSSH>ipconfig
Windows 2000 IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . 
:  rr.com
IP Address. . . . . . . . . . . .  :  192.168.1.101
Subnet Mask . . . . . . . . . . .  :  255.255.255.0
Default Gateway . . . . . . . . .  :  192.168.1.1

This is the sample output from sending a file to a host at 192.168.1.101 via SCP.
I:\Internet\OpenSSH\bin>scp sample.txt sshuser@192.168.1.101:/
************ WARNING BANNER HERE ************
sshuser@192.168.1.101’s password:
Could not chdir to home directory /home/SSHuser: No such file or directory
sample.txt   100% 1735  1.7KB/s  00:00

While the SSH port in SSHWindows uses standard CMD.exe syntax, the SCP command and SFTP command both use UNIX-style paths. Also of note is that unless it is configured differently, the SSH connection will assume that the directory you installed OpenSSH into is the starting root for client connections.
If you get an error of segid: Invalid Argument, this typically means that the permissions are incorrect in the passwd file. The logon account on Windows systems should be 544 instead of 514. The latest installation didn’t seem to have this issue, but it’s not uncommon. A console window should open and the configured logon banner will be displayed. If all is working well, you should then have access to the command prompt on the remote system. With basic SSH working properly and tested, it’s time to move to the port forwarding task.


Configuring OpenSSH Port Forwarding
Working under the assumption that you already have OpenSSH installed and working properly to provide remote command-line access, OpenSSH port forwarding is used much like Stunnel. The SSH client establishes a connection to the SSH server and then listens to local traffic destined for a port you specify. When it receives it, it will send the encrypted data out to an OpenSSH server, which in turn decrypts the data and passes it to the local port the service is listening on. In practical terms this means to set up port forwarding using OpenSSH, perform the following steps.
  1. On the Linux host, run the following command: ssh user@192.168.1.99 –L 5140:192.168.1.99:7140.
  2. Use Netcat to connect to the server over port 7140.
Although much of the operation of SSH port forwarding is the same as the SSL tunnel that Stunnel creates, there are a couple of differences. By default, the SSH port forwarding is just that. It is the forwarding of a port on an established SSH tunnel. So the encrypted SSH tunnel is established first, using the normal SSH TCP port of 22, unless you specify a different port. This tunnel is set up exactly the same as if you were going to connect for remote command-line access. In addition, SSH will listen for and forward connections on the additional port you have specified.

The primary disadvantage of using SSH for port forwarding is there is no command line means to specify the password. This is an intentional design choice on the part of the SSH developers, in order to increase security. They specifically did not wish to provide a simple means of including passwords in scripts and batch files. This requirement for user interaction makes SSH a better candidate for interactive sessions, rather than service-based connections. As you can see, however, it is very easy to set up on a system that already has SSH configured properly.




Using SSL
SSL can provide a very well documented and simple-to-implement encryption solution for almost any TCP-based communication. SSL is the same well-tested encryption that is commonly used to encrypt Web pages. Stunnel is open-source software, can tunnel TCP communications through an SSL-encrypted session with a minimum of configuration complexity. The end result is the capability to forward a TCP connection through an encrypted tunnel.


Configuring Stunnel
Stunnel is perhaps the most widely used tool for encapsulating arbitrary data in an encrypted tunnel.
Stunnel doesn’t contain any cryptographic code, but instead uses external libraries to perform the encryption. 
In this case, OpenSSL is used to create an encrypted tunnel. To demonstrate the operation of Stunnel on both Windows and Linux, we will be using
  1. a Linux host as the Netcat client and 
  2. a Windows host as the Netcat server.
This should give you a feel for the operation of Stunnel on both operating systems. Follow these steps to configure Stunnel on the Linux host.
  1. If Stunnel does not come pre-installed on your Linux distribution, then download and install Stunnel from www.stunnel.org.
  2. If OpenSSL is not already installed on your system, download and install OpenSSL. The source files (to be used on Linux) can be downloaded from www.openssl.org/source/. Pre-compiled binary files (for use on Windows) can be downloaded from www.slproweb.com/products/Win32OpenSSL.html.
  3. Create a Stunnel configuration file called /etc/stunnel/stunnel.conf. Add the following text to the file and save the file:
    1. client = yes
      [netcat_client]
      accept = 127.0.0.1:5140
      connect = 192.168.1.99:6140 
  4. This configures Stunnel in client mode (the default is server mode), and tells Stunnel to listen on port 5140 and send the data back out to 192.168.1.99 on port 6140.
  5. Open a terminal window and start stunnel by typing stunnel. Now you need to configure the server side of the SSL tunnel. Follow these steps to configure Stunnel on the server host. 
  6. Download and install Stunnel from www.stunnel.org.
  7. Navigate to the directory where you installed Stunnel and edit the stunnel.conf file. Add the following at the end of stunnel.conf and save the changes.
    1. [netcat_server]
      accept = 6140
      connect = 7140
    2. Stunnel will be in server mode by default, and the accept and connect lines simply tell Stunnel to listen on port 6140, and when a connection is made, send the data out to port 7140 on the local host. By not specifying an IP address in our configuration file, Stunnel assumes the local host.
  8. Navigate to Start > Programs > Stunnel > Run Stunnel.
    You should now be able to use Netcat on the client side with the following command;
    nc 127.0.0.1 5140
    This will tell Netcat to connect to the local host. Stunnel is listening on port 5140 and will redirect the socket across its encrypted tunnel to the recipient. After you start Stunnel, it will place an icon in the system tray. Right-clicking on this icon will open a very small menu. If you select Log on this menu, you can see a running log of the connections that Stunnel has accepted. Because the communication path can be a little confusing, Figure 6.1 shows a graphical representation of the data flow using Stunnel.


After you have verified that you can send and receive your Netcat session over the encrypted Stunnel link, you have only completed the testing phase of the Stunnel implementation. You still need to generate a new server certificate and private key to replace the default key you are using now. Stunnel requires a server certificate and private encryption key for the SSL encryption to function. The installation files come with a default certificate and key, combined into a single file called stunnel.pem.

Because the same certificate is distributed with all of the installation files, using this certificate in a production environment would be insecure because everyone would have your key. You need to generate a new certificate and key file for use on the server (you do not need to do this on the client host). The simplest way of generating the new certificate and key is by using the OpenSSL package.
  1. OpenSSL should already be installed and working or you wouldn’t have been able to get this far. Use these commands to generate a new server certificate: openssl genrsa –des3 –out server.key 1024. You will be prompted for a pass phrase and it will then generate an initial server key.
  2. Enter openssl req -new -key server.key -out server.csr to generate a certificate signing request. You will be required to enter the previously assigned pass phrase and answer several prompts with regional information such as your state, country, and company name.
  3. Enter openssl rsa -in server.key -out server.key to remove the pass phrase from the server key. You will be required to enter the pass phrase to complete this step.
  4. Enter openssl x509 -req -in server.csr -signkey server.key -out server.crt to generate the server certificate. 
  5. Finally, combine the certificate and key file into a single .pem file that stunnel will use by entering the following command: copy server.crt+server.
    key stunnel.pem
    (for linux cp server.crt stunnel.pem then cat server.key >> stunnel.pem will also work, the files are both plain text files).
  6. Replace the original stunnel.pem with the newly created stunnel.pem certificate in the Stunnel directory.
  7. Restart Stunnel on the server and verify that everything is still working properly.
Now that you are successfully encrypting your file transfers using stunnel, you might notice that all of the file transfers appear to be sourced from 127.0.0.1, which is the local host. This is because technically, that is who sent the message. This could be a scenario where the –P option of SBD would be handy if you wanted to pre-pend your data with the source IP or hostname. Of course you could also build this into whatever process is performing the file transfer instead. Stunnel enables you to encrypt virtually any TCP-based connection, not just Netcat. You could use Stunnel to encrypt a Telnet session, for example, or even a custom TCP-based application. After you have the Stunnel software installed and the basic configuration set up, adding additional tunnels is as simple as defining additional services in the stunnel.conf configuration file.
The primary downside to using Stunnel is the static nature of the configuration. Because services must be defined in both the client and server stunnel.conf file, you lose the dynamic ability to connect with a single command line.
You must pre-configure the tunnel on the hosts you wish to communicate between ahead of time, before the session can be secured with stunnel.



Using IPsec
Although a little more complicated to configure, IPsec is the industry standard when it comes to setting up Virtual Private Networks (VPNs), which is just another form of encrypted tunnel.
IPSec also has a major advantage in that it is protocol independent. IPsec can encrypt TCP, UDP, and even ICMP, basically anything that runs over IP with a few caveats.
In the case of encrypting your Netcat session, we only need traffic over that single port encrypted, but IPsec can be used to encrypt all communications between a given host and destination.
The primary downside to using IPsec over one of the previously mentioned solutions is of course the configuration complexity.
Additionally, the out-of-box support for modern Windows systems (Windows 2000,
Windows XP, and Windows Server 2003) is better (easier to configure) than that of a Linux host. Although Linux supports IPsec natively, the task of configuring it is made much simpler with the assistance of some third-party configuration utilities. We will demonstrate how to set up IPsec on hosts running Windows XP and Linux.


Configuring IPSec on Windows
For starters, let’s cover some basic Windows IPsec terminology.
  • IPsec settings are controlled on a Windows system via the IPsec policy. Only one policy can be applied to a given host at a time. 
  • The policy is defined using IPsec rules.  
  • A rule defines what types of traffic to act on and whether the traffic is 
    • permitted, 
    • blocked, or 
    • encrypted. 
  • The rules also determine how to authenticate the IPsec peer and other encryption settings.  
  • Filters are used to identify what types of traffic should be processed by the IPSec policy. On some systems this is referred to as defining interesting traffic. 
  • Security methods are used to define the encryption and hashing algorithms to be used.
Follow these steps to configure IPsec on the Windows client and server.
  1. Open the MMC and add the IP Security Policies snap-in to your console if it is not already present.
  2. Right-click IP Security Policies on Local Computer in the left pane and select Manage IP Filter lists and filter actions.
  3. On the Manage IP Filter Lists tab, click Add at the bottom. This will bring up the IP Filter List window.
  4. Enter a name for the filter; in this case we used Netcat.
  5. Enter a description for the filter. 
  6. Ensure that the Use Add Wizard check box is checked and click Add.
  7. Click Next on the IP Filter Wizard welcome screen.
  8. Enter a description of the filter and ensure that the Mirrored option is
    checked (it should be by default) and click Next.
  9. On the next window, leave the source address at the default of My IP
    Address
    and click Next.
  10. On the next window, for Destination address, select a specific IP
    address
    , enter the IP address of the Netcat server, and then click Next.
  11. For Select a protocol type, select TCP and click Next.
  12. For Set the IP protocol port, leave From any port selected and select
    To this port.
  13. Enter 4444 (4444 was only selected as an example, you can use a different
    port) in the Port box and click Next.
  14. Click Finish, which will take you back to the IP Filter List window. There
    should be a new IP Filter in the bottom section of this window. This filter will match against any outbound TCP traffic with a destination IP of the Netcat server and a destination port of 4444.
  15. Click OK to go back to the Manage IP filter lists and filter actions
    window. Click Close. We now have our filter defined, which will tell the system what traffic should be processed by the IPsec policy. We now must create that policy.
  16. Right-click IP Security Policies on Local Computer in the left-hand pane and select Create IP Security Policy.
  17. Click Next to begin the wizard.
  18. Enter a Name (e.g., Outbound_Netcat) and a Description and click Next.
  19. In Requests for Secure Communications, leave Activate the default response rule checked and click Next.
  20. Choose your Authentication method for the default response rule. Active directory is the default and will be the best choice in most circumstances. However, some systems, such as DMZ hosts, may not have domain connectivity, and instead may be standalone servers. In those cases you will need to use certificates or a pre-shared key. A pre-shared key is basically a password and is the weakest of the options available; however, it is also the simplest to i­mplement. For this example, we will use a pre-shared key of “password,” which is not secure but will serve for testing purposes. After making your selection click Next.
  21. Leave the check box checked to Edit Properties and click Next.
  22. On the Rules tab, ensure that the Use Add Wizard is not checked and click Add to add an IP filter.
  23. In the list of pre-made filters you should see the Netcat filter you created earlier. Select the radio button for the filter you created earlier.
  24. Select the Filter Action tab and select Require Security.
  25. Click the Authentication Methods tab and click Edit.
  26. Select the radio button for the authentication method you want to use, and
    then click OK.
  27. On the New Rule Properties, click Apply and then OK.
  28. You will be back at the Security Rules screen; click OK.
  29. Your Policy should now appear in the list in the right pane of the MMC
    window. Right-click this new policy and select Assign. After the policy is
    assigned, now all that is left is to configure the IPsec policy on the Netcat server. On the server side, you need to perform a similar configuration; however, there are some implementation details to consider before settling on your configuration. For example, 
    1. if all the systems connecting to the server will be using IPsec, you can configure the policy on the server to require IPsec, instead of requesting it. 
    2. If you will have a mixture, with some systems using IPSec secured traffic and some systems using unencrypted communications (internal trusted systems, for example), then the most secure option would be to require security from the individual systems that will be using IPsec, based on their IP address or IP segment.
  30. In the MMC of the client (not the server), select IP security policies on
    local computer
    in the left pane.
  31. Right-click and select All Tasks > Export Policies.
  32. Choose a name and location to save the policies and click Save.
  33. Open the MMC of the server, and if it isn’t already added, add the IP Security Policies snap-in.
  34. Right-click IP Security Policies on local computer in the left pane, and then select All Tasks > Import Policies....
  35. Browse to the policies you exported previously and click Open. This will import the exact policy that was configured on the client. 
    1. We will need to make some adjustments to use it on the server, but this process still saves us some time.
  36. You should see the Netcat policy in the list of policies in the right-hand pane. At this time is should list No under the Policy Assigned column.
  37. Right-click the Netcat policy and select assign.
Now when you open your Netcat session it will negotiate an IPsec tunnel. You can verify that the tunnel was established by opening the IP Security Monitor ­snap-in in your MMC. Simply select IP Security Monitor on the left pane and click to expand the tree under your server name. Then select Main Mode, and finally select Security Associations.Your SA listing should appear


Configuring IPSec on Linux
Because IPsec is an industry standard, specifically designed for interoperability between different vendor systems, it is a very popular choice for implementing encryption.
Current Linux kernels have IPsec support built in, and there are other packages that provide their own implementation of IPsec as well. 
For these examples we will assume you are using the Linux kernel native IPsec support. Follow these steps to configure IPsec on a Linux host.
  1. If they are not already installed, download and install the IPsec Tools. These tools provide a simplified interface to configure the various IPsec settings.
  2. Edit the /etc/racoon/psk.txt file. This file holds the pre-shared (aka “secret”) keys. You should use a high-quality password for a production environment. The format of the file is . In our example we would add the following line to the file and save the new file. 192.168.1.99 password If you wish to change the pre-shared key on the Windows server, edit the IPsec policy by following these steps:
  3. Open the MMC and select IP Security Policies on Local Computer in the left pane.
  4. Double-click the Inbound_Netcat policy in the right pane.
  5. Double-click the TCP Syslog security rule and select the Authentication Methods tab.
  6. Click Edit to change the pre-shared key, and enter the new key. 
  7. Click OK, OK, Apply, and OK to accept the changes and exit the policy configuration windows. The next step is to configure the IPsec policy on the Linux host. With the IPsec tools loaded, this can be done using the setkey utility. The utility can display the current security associations and perform several other configuration changes to your IPsec policy. By creating a setkey configuration file, we will define the security parameters to use. The entire contents of the configuration file are shown in 8.1.
  8. Create a configuration file (you could name it /etc/racoon/setkey.conf ) and
    enter the information shown below:
    1. # Configuration for 192.168.1.105
      # Flush the SAD and SPD
      flush;
      spdflush;
      #### ESP SAs using 192 bit long keys (168 + 24 parity) ####
      add 192.168.1.105 192.168.1.99 esp 1001
      -E 3des-cbc 0x7aeaca3f87d060a12f4a4487d5a5c3355920fae69a96c831;
      add 192.168.1.99 192.168.1.105 esp 1001
      -E 3des-cbc 0x7aeaca3f87d060a12f4a4487d5a5c3355920fae69a96c831;
      #### Security policies ####
      spdadd 192.168.1.105 192.168.1.99 any -P out ipsec
      esp/transport//require;
      spdadd 192.168.1.99 192.168.1.105 any -P in ipsec
      esp/transport//require;
    All lines beginning with # are comments and ignored by setkey. The flush and spdflush tells setkey to wipe out the previous configuration. This enables us to start clean and ensures that we are using only what is contained in this configuration file. The next section (#ESP SAs) defines the Encapsulating Security Payload (ESP) parameters(look http://en.wikipedia.org/wiki/IPsec#Encapsulating_Security_Payload). The first line states that traffic from 192.168.1.105 (the Netcat client) to 192.168.1.99 (the Netcat server) should use ESP and Triple Data Encryption Standard (3DES) for encryption. The long string beginning with 0x is a key. This is just a sample key used for testing. You should generate your own key for increased security. The following section serves the same purpose for traffic coming from 192.168.1.99 to 192.168.1.105. In this example we used the same key for both, but you certainly don’t have to. The final section (# Security Policies) defines the IPsec modes to be used. We are configuring transport mode and requiring that traffic matching the policy be encrypted. The line is duplicated with the IP addresses reversed so that our policy will apply to traffic in both directions.
  9. Apply the settings in your IPsec policy by entering setkey –f /etc/racoon/setkey.conf.
  10. Edit your racoon configuration file /etc/racoon/racoon.conf. Racoon is the daemon on Linux that handles your Internet Key Exchange (IKE) functionality. If invoked from the command line with no options, it will automatically be run in daemon mode. For initial testing and setup, we would recommend running it in the foreground, so that you can see the output for troubleshooting purposes. Executing racoon –F will run in the foreground, and adding –d (for debug) will increase the verbosity level to provide even more information. 10.1 shows the complete racoon.conf contents.
    1. # Racoon IKE daemon configuration file.
      # See 'man racoon.conf' for a description of the format and entries.
      path include "/etc/racoon";
      path pre_shared_key "/etc/racoon/psk.txt";
      path certificate "/etc/racoon/certs";
      ##### IKE PHASE 1
      remote 192.168.1.99 {
      exchange_mode main;
      proposal {
      encryption_algorithm 3des;
      hash_algorithm sha1;
      authentication_method pre_shared_key;
      dh_group 2;
      }
      }
      ##### IKE PHASE 2
      sainfo anonymous
      {
      lifetime time 1 hour ;
      encryption_algorithm 3des, des ;
      authentication_algorithm hmac_sha1, hmac_md5 ;
      compression_algorithm deflate ;
      }
    The first few path lines are unedited from the defaults and tell racoon where to find the pre-shared key file and any certificates you want to use. The functioning of this configuration file is pretty straightforward. The remote entry says that when speaking to 192.168.1.99 we will use main mode and attempt to use 3DES, with Secure Hash Algorithm Version 1.0 (SHA1), and a pre-shared key. The second section contains security association information that should be applied to all hosts (due to the anonymous entry). You could instead define different parameters to be used when communicating with different hosts if desired, by creating multiple entries in the format sainfo <host> instead of using anonymous. 545 
  11. At a terminal prompt, start racoon using racoon –F or racoon –F –d.
You should now be able to receive your encrypted Netcat session on TCP port
4444. Because IPsec is not protocol dependent, this same type of configuration can easily enable you to encrypt Netcat sessions over TCP or UDP from your Linux system to a Windows system as well. To do this, simply substitute the configuration options of TCP 4444 or UDP 4444, for another port of your choice.
When you first apply all the IPsec settings, you will probably not see traffic immediately. In most cases there will be a short delay while the initial IPsec connection is being established. This time is being spent agreeing on the encryption parameters and exchanging key information prior to the secure communications being able to take place.

Ensuring File Integrity

Of course after you transfer a file, you want to make sure that the file you received is identical to the file which was sent. For very small files any corruption might be obvious, but a visual inspection of a large binary file simply will not do. In these cases you need an automated way to compare the file before and after the transfer. The simplest way to do this is to generate a hash of the file and send that with (before or after) the original file. There are many software packages that can generate a variety of hashes for you, and odds are good you already have at least one of them installed already.

A hash is the result of a mathematical computation performed on a set of data. This result, called a hash, hash value, or message digest, is (ideally) unique and reproducible for a given input. In practical terms, this is similar to a digital fingerprint for a set of data. If you were to generate a hash using the entire book “War and Peace” as input, you would get a particular hash value. Anyone else who used the same hash algorithm with “War and Peace” as input would also generate the same hash value.

If any single character were altered in the entire book, such as a period being changed to a comma, the hash value would be different. A hash function is a one-way ­computation, meaning there is no way to derive the original input from a known hash value. In the case of a file transfer, if the hash that was generated with the file before it was sent matches the hash that is generated with the received file, the two files are identical.



Hashing Tools
There are many utilities for generating a hash value and many different algorithms that are widely used. Some algorithms are more “secure,” in that the odds of two different inputs producing the same hash value are smaller. SHA and Message Digest 5 (MD5) are commonly used algorithms that are considered to be secure enough for most uses. There are many utilities available; we will review a few of the most popular ones below. If you are generating hashes on a Windows server, an excellent utility is fsum from SlavaSoft. Fsum is freeware and can be purchased for commercial use. The license agreement allows fsum to be run on only one computer at a time. We would recommend, as with all free products, that you review and understand the license agreement yourself. Fsum will run on Windows 9x, NT, 2000, and XP and can generate 13 different types of hashes.

If you are using Linux you are likely to
  1. have md5, md5sum, or sha1sum already installed. Both md5sum and sha1sum are special-purpose programs that only generate hash values using their respective algorithms.
  2. You can also use the OpenSSL suite to generate message digests using a wider variety of algorithms. OpenSSL can generate the following hash types: 
    1. MD2, MD4, MD5, 
    2. rmd160, SHA, and 
    3. SHA1.
The simple and straightforward operation of these hashing utilities makes them ideal for automated scripting. After generating the hash for the source file, you could send a second file with the same <name >.hash. On the server side, the hash can be recalculated and the two hash files compared. If the hash is identical then the file was transferred without any changes occurring and the integrity of the file has been maintained.

The “diff ” utility is found on almost all *nix systems, and modern Windows systems include the compare (comp.exe) utility to do the same thing. There are many different applications to compare two files to choose from if either of these two are not what you are looking for


Using Netcat for Testing

In addition to using Netcat to transfer data for the simple purpose of moving data, it can also be used for troubleshooting and testing. Netcat’s lightweight nature and low overhead means it can serve several useful purposes for network troubleshooting. In a similar fashion to transferring a file, there are more sophisticated troubleshooting tools available. Netcat however is probably more readily available, it’s free, and it has a very small footprint. If you combine these features with a little scripting, Netcat can be a useful tool for troubleshooting and testing your network.


Testing Bandwidth
There are times when you need to push a lot of data over a connection for testing purposes. One of the classic tools for doing this is FTP. FTP is a good choice because it is a simple and efficient protocol. Efficient here means that there is little overhead.
This allows FTP to consume a large portion of the available bandwidth. Without any controls, FTP will consume as much of it as possible given the current network conditions. The only downside is you need an FTP client at one end, and an FTP server at the other end to test with. Of course virtually every operating system comes with an FTP client, but a server isn’t always available. If you are testing to the Internet finding an FTP server is trivial, but if you are testing internal links you might not have one available.
The same features that make FTP a good protocol to test with also make Netcat an equally good choice. Netcat is just as lightweight as FTP, possibly even more so. Netcat also has the benefit of being easier to use and in most cases a smaller footprint if you need to “install” Netcat before testing. Given FTP’s reputation as being bandwidth hungry, I ran a test to compare. The results were nearly identical. Both FTP and Netcat utilized 60 percent of my 100Mb Ethernet connection when using redirection at both ends. When I piped the file into Netcat on the linux client using the cat utility, utilization shot up to 98 percent of the available bandwidth. This tells me that Netcat is at least as efficient for testing load on a link as FTP is.


Testing Connectivity
Netcat offers some additional benefits when it comes to testing. Basic  connectivity testing is often performed with ICMP’s ping functionality. While adequate in most cases, it does have limitations:
  1. you cannot test arbitrary ports. Because ping is ICMP based, 
  2. you cannot even test TCP or UDP functionality for that matter. 
  3. You can test layers one through three with pings but no more.
Netcat on the other hand will allow you to perform testing at layer four. An example of this is when you want to test ports through a firewall. You could do it with nmap, and that would certainly be easier if you need to test a large number of ports, but for checking a single port, Netcat might be easier. Telnet is often used, but because Telnet includes some Telnet-specific protocol data, it can corrupt the particular strings you wish to send.
  1. The fact that Telnet adds Telnet-specific data to the data stream is exactly what makes Netcat a more suitable tool when it comes to interactively testing and probing a given port. With Netcat you can be sure that you will only be sending the data you want to. 
  2. You also cannot transfer most binary files using Telnet. This is because Telnet will interpret some of the binary data as Telnet command strings. 
  3. Telnet also has the major limitation that it is only a client tool. If the server is not running at the far end, but you want to test the firewall rules anyway, Telnet will not help you. Netcat has the option of running as a server as well as a client, so you can run Netcat at both ends and thus test that the firewall is allowing the port through.

Sometimes you know the connection works but you need to test Network Address Translation (NAT) rules. You want to know what IP you are showing up as
when you go through the firewall. If the destination is the Internet, there are many sites to show you your IP, so that part is easy. But if you want to test through some internal NAT or Port Address Translation (PAT) rules, Netcat can be a fast way to do that as well. By increasing the verbosity (–v), Netcat will tell you the IP and port that is being used to connect. Of course the need for these types of testing will probably not arise every day. When they do, however, Netcat is a small, fast tool that can do a lot when put to creative uses.

Resources