iconv

converts the encoding of characters in the target file from one char set to another, and sends the result to stdout, unless otherwise specified.

iconv -l

list known character sets;

iconv -f CP1251 -t UTF8 msg.txt > msg2.txt

convert msg.txt from Windows 1251 to UTF8, write converted version to msg2.txt (initial file is not changed);

iconv -f UTF8 -t CP1251 -o info2.txt info.txt

convert info.txt from UTF8 to Windows 1251, write converted version to info2.txt;

iconv -f enc1 -t enc2 file

Options

--help    -V    --version    -v    --verbose

-c omit invalid characters from output;

-f enc, --from-code enc

convert from encoding enc;

-l, --list

list supported character sets;

-o file, --output file

write to file instead of stdout;

-s, --silent

suppress warnings;

-t enc, --to-code enc

convert to encoding enc;

id

shows real and effective user and group IDs for the specified user (for the current user, if user is omitted).

id

my uid, gid, name, groups, etc;

id -nG pro07

the names of all groups that user pro07 belongs to;

id -u

my effective user ID;

id -gn

my effective group name;

id -u oracle

effective user id of oracle;

id [options] [user]

Options

--help    --version

-G, --groups

show all group IDs;

-g, --group

show only the effective group ID;

-n, --name

show a name instead of a number;

-r, --real

show the real ID instead of the effective ID;

-u, --user

show the effective user ID only;

-Z, --context

show the security context only;

Options -n and -r are supposed to be used with -ugG.

ifconfig

Deprecated

configures network interfaces. See also TCP/IP protocols.

ifconfig

show the status of currently active interfaces;

ifconfig -a

show the status of all interfaces;

ifconfig eth0

show the status of eth0 interface;

ifconfig eth0 192.168.0.4 netmask 255.255.255.0 up

configure the first ethernet card (eth0), set IP 192.168.0.4, netmask 24-bit;

ifconfig eth0:0 192.168.0.5 netmask 255.255.255.0 up

configure an additional IP address (192.168.0.5) on eth0; netmask 24-bit;

ifconfig lo0 127.0.0.1 up

configure loopback interface;

ifconfig eth1 down

deactivate interface eth1;

ifconfig [iface]

ifconfig iface [addr_family] options

iface is a driver name + a unit number (eth0, eth1, eth2 for ethernet cards, lo0 for loopback interface);

addr_family specifies the address family: unix (UNIX Domain), inet (DARPA Internet; default), inet6 (IPv6), ddp (Appletalk DDP), ipx (Novell IPX), ax25 (AMPR AX.25 Packet Radio), netrom (AMPR NET/ROM), rose (AMPR ROSE), ec (Econet), ash (Ash), x25 (CCITT X.25).

Options

--help    --version

up activate interface (it's assumed by default when an address is assigned to the interface);

down

shutdown the specified interface;

[-]arp

enable / disable the use of arp protocol on this interface;

[-]promisc

enable / disable promiscuous mode on this interface;

[-]allmulti

enable / disable all-multicast mode on this interface;

metric n

set the interface metric;

mtu n

set interface MTU (Maximum Transfer Unit);

netmask xxxx

set IP network mask for this interface;

add addr/prefixlen

add IPv6 address to an interface;

del addr/prefixlen

remove IPv6 address from an interface;

tunnel aa.bb.cc.dd

create a new SIT (IPv6-in-IPv4) device, tunnelling to the given destination;

irq spec

set the interrupt line used by this device (if supported);

io_addr addr

set the start address in I/O space (if supported);

mem_start addr

set the start address for shared memory (if supported);

[-]broadcast [addr]

set the broadcast address for this interface (if addr is given); otherwise set/clear IFF_BROADCAST flag;

[-]pointtopoint [addr]

used to establish a direct link between 2 hosts; if addr is given, assign it to the other side of the link; otherwise set/clear IFF_POINTTOPOINT flag;

hw class addr

set the hardware address of this interface (must be supported by the driver and hardware); class may be one of the following (there are more):

loopLocal Loopback
slipSerial Line IP
cslipVJ Serial Line IP
slip66-bit Serial Line IP
cslip6VJ 6-bit Serial Line IP
adaptiveAdaptive Serial Line IP
etherEthernet
tr16/4 Mbps Token Ring
ax25AMPR AX.25
netromAMPR NET/ROM
roseAMPR ROSE
tunnelIPIP Tunnel
pppPoint-to-Point Protocol
hdlc(Cisco)-HDLC
lapbLAPB
dlciFrame Relay DLCI
fradFrame Relay Access Device
sitIPv6-in-IPv4
fddiFiber Distributed Data Interface
irdaIrLAP
x25generic X.25
infinibandInfiniBand

Desktop systems nowdays tend to minimize network config efforts due to use of DHCP, zero configuration networking (zeroconfig), and network management daemons (like NetworkManager). Servers, however, sometimes require manual job. For a quick temp config you can use ~, otherwise you should edit some system files. For example, Ubuntu dynamic IP address assignment requires the following lines in /etc/network/interfaces:

auto eth0
iface eth0 inet dhcp

To configure your system to use a static IP address assignment:

auto eth0
iface eth0 inet static
address 192.168.0.6
netmask 255.255.255.0
gateway 192.168.0.254

To assign several static IP addresses to a single NIC:

auto eth0
auto eth0:1
auto eth0:2

iface eth0 inet static
address 192.168.1.6
netmask 255.255.255.0
gateway 192.168.1.254

iface eth0:1 inet static
address 192.168.1.7
netmask 255.255.255.0
gateway 192.168.1.254

iface eth0:2 inet static
address 192.168.1.12
netmask 255.255.255.0
gateway 192.168.1.254
Files
/proc/net/socket  
/proc/net/dev  
/proc/net/if_inet6  
/etc/hosts hosts to be resolved locally
/etc/resolv.conf DNS servers for internet domain name resolution
/etc/nsswitch order of host name search (typical: local files first, then NIS, then DNS)
/etc/network/interfaces Ubuntu / Debian
/etc/sysconfig/network Red Hat / Fedora / CentOS
/etc/sysconfig/network-scripts/* Red Hat / Fedora / CentOS

info

reads doc in Info format. There is also pinfo - curses-based lynx-style info browser. Both use env var INFOPATH, but options are different.

info [option] ... [menu-item ...]

The first non-option arg, if present, is the menu entry to start from; it is searched for in all 'dir' files along INFOPATH. If it is not present, ~ merges all 'dir' files and shows the result. Any remaining args are treated as the names of menu items relative to the initial node visited.

info

show top-level dir menu;

info emacs

show emacs info starting at emacs node from top-level dir;

info emacs buffers

show emacs info starting at buffers node;

info --show-options emacs

show emacs’ command line options;

pinfo slocate

show info about slocate using pinfo;

pinfo -m slocate

similar to 'man slocate' cmd;

Options

-h    --help    --version

-d dir, --directory=dir

add dir to INFOPATH;

-f file, --file=file

specify Info file to visit;

-n name, --node=name

specify nodes in first visited Info file;

-o file, --output=file

output selected nodes to file;

-R, --raw-escapes

output "raw" ANSI escapes (default);

-O, --show-options

go to cmd line options node;

-w, --where, --location

physical location of Info file;

--apropos=str

look up str in all indices of all manuals;

--dribble=file

remember user keystrokes in file;

--index-search=str

go to node pointed by index entry str;

--no-raw-escapes

output escapes as literal text;

--restore=file

read initial keystrokes from file;

--subnodes

recursively output menu items;

--vi-keys

use vi-like and less-like key bindings;

init

is described here FYI only. It's not an app for users or administrators! It's a very important system daemon that runs all the time until the system is shut down.

Historicaly, in Unix-based operating systems, init ("initialization" or "initializer") is the first process started during system boot; it is direct or indirect ancestor of all processes in the system, and it auto adopts all orphaned processes. Unlike other daemons, init is started by the kernel using a hard-coded filename and has pid = 1.

FYI: pid = 0 is assigned to swapper (sched) which is not a separate program but a part of the kernel responsible for paging.

If kernel is unable to start init, it throws kernel panic.

One of the major drawbacks of the classical init is that it starts tasks serially, waiting for each task to finish loading before moving on to the next one. Modern Linux implementation of init (like systemd) try to improve performace by running tasks in parallel.

initctl

(Ubuntu/Debian, outdated) provides communication with the Upstart init daemon. When run as initctl (it can also be invoked through symlinks), the first non-option arg is the cmd. Global options may be specified before or after cmd. The standard symlinks are start, stop, status.

initctl list

output a list of all jobs and their states;

initctl --system list

output a list of all jobs and their states (non-root user);

initctl restart cron

restart cron daemon (send SIGTERM to that daemon);

initctl status logd

show the status of logd daemon;

status logd

show the status of logd daemon;

initctl emit --no-wait control-alt-delete

emit a signal event control-alt-delete (signal event: emitter does not care whether the signal is handled, or how long it takes to handle);

initctl emit unmounting-filesystems

umount -a

emit event unmounting-filesystems and wait while Upstart is starting or stopping any related services and runs the appropriate tasks; when it's finished, the second cmd is executed;

initctl help

show a list of ~ commands;

initctl list --help

show more info about list cmd;

Options

--system

instructs ~ to communicate with init daemon via the D-Bus rather than over the private socket (which is default, convenient, and fast, but available to root only); this option allows regular users to exec read-only cmds;

--dest

specifies the well-known name of the init daemon when using --system option; usually, it's unnecessary as the daemon uses the default com.ubuntu.Upstart name; however, it may be useful for debugging;

--no-wait

(only with start, stop, restart, emit) normally ~ waits for the cmd to finish before returning; this option causes it to only wait for the goal change or event to be queued;

--quiet

output errors only;

Commands

start job [key=value]

requests that a new instance of the named job be started, outputting the status of the job to stdout when cmd completes; key=value can be used to specify env vars to be passed to the starting job, and placed in its env; most jobs only permit a single instance; those that use the instance stanza in their config define a string expanded from env vars to name the instance; thus the env vars also serve to select which instance of job is to be acted upon; if the job is already running, this cmd will return an error;

stop job [key=value]

requests that an instance of job be stopped, outputting the status of the job to stdout when cmd completes;

status job [key=value]

requests the status an instance of job;

list

requests a list of the known jobs and instances;

emit event [key=value]

requests that the specified event be emitted, potentially causing jobs to be started and stopped depending on their use of the start on and stop on stanzas in their config; the optional key=value pairs specify env vars to be included with the event and thus exported into the environment of any jobs started and stopped by the event; env may also serve to specify which instance of multi-instance jobs should be started or stopped;

reload-configuration

requests that the init daemon reloads its config (usually not necessary since this daemon watches its config directories with inotify and auto reloads in cases of changes);

version

requests and outputs the version of the running init daemon;

log-priority [priority]

if called with priority, it requests that the init daemon log all messages with that priority or greater (may be used to both increase and decrease the volume of logged msgs); priority can be: debug, info, message, warn, error, fatal; without priority, it requests (and outputs to stdout) the current min msg priority that the init daemon will log;

ip

shows and manipulate routing, network devices, interfaces and tunnels.

ip [ OPTIONS ] OBJECT { COMMAND | help }

ip [ -force ] -batch filename

Note that ip is functionally organized on two layers of Networking Stack: Layer 2 (Link Layer) and Layer 3 (IP Layer) and does the work of all cmds from net-tools package.

The following commands use enp7s0 network interface name as an example (it's a built-in Ethernet device on an old ASUS motherboard). Your own network interface may have a different name!

ip a

ip addr

ip address

show addresses assigned to all network interfaces (enabled and disabled); similar to ifconfig, but output is not exactly the same;

ip -br a

like prev but very brief output:

lo          UNKNOWN      127.0.0.1/8 ::1/128
enp7s0      UP           192.168.10.101/24
                               fe80::3d5f:28ea:9721:76ea/64

ip a add 192.168.10.154 dev enp7s0

add new network interface;

ip a del 192.168.10.154 dev enp7s0

remove an existing network interface;

ip link set dev enp7s0 address 00:0c:29:33:4e:aa

add MAC address;

ip link set dev enp7s0 mtu 2000

set MTU value to 2000;

ip link set dev enp7s0 multicast on

ip link set dev enp7s0 multicast off

enable/disable multicast flag;

ip link set dev enp7s0 txqueuelen 1200

set the transmit queue length to 1200;

ip link set dev enp7s0 promisc on

ip link set dev enp7s0 promisc off

enable/disable promiscuous mode;

ip link set dev enp7s0 allmulti on

enable/disable all multicast mode;

ip link set enp7s0 up

ip link set enp7s0 down

enable/disable the specified interface;

ip link set dev enp7s0 arp on

ip link set dev enp7s0 arp off

enable/disable ARP for the specified interface;

ip n

ip neigh

ip neighbour

show the current neighbour table in kernel (similar to arp -a):

192.168.10.1 dev enp7s0 lladdr 00:14:d1:bd:ae:c5 REACHABLE
192.168.10.104 dev enp7s0 lladdr c0:4a:00:17:d8:24 STALE
192.168.10.103 dev enp7s0 lladdr 6c:71:d7:5b:71:9e STALE
192.168.10.102 dev enp7s0 lladdr f4:7b:5e:ae:c1:45 STALE

ip n f

ip n del

invalidate neighbour table entries (similar to arp -d, remove the ARP cache entries);

ip n del 192.168.100.11

invalidate neighbour entry for the specified host;

ip n del 192.168.100.11 dev enp7s0

invalidate ARP cache entry for host 192.168.100.11 on device enp7s0;

ip neighbor show dev enp7s0

show the ARP cache for interface enp7s0;

ip r

ip route

ip route show all

show kernel routing tables (similar to route or netstat -r):

default via 192.168.10.1 dev enp7s0 proto dhcp metric 100
169.254.0.0/16 dev enp7s0 scope link metric 1000
192.168.10.0/24 dev enp7s0 proto kernel scope
                link src 192.168.10.101 metric 100

ip route list cache

show routing info from the route cache (similar to netstat -C);

ip maddr

display multicast group membership info for IPv4 and IPv6 (similar to netstat -g);

ip -s link

display a table of all network interfaces (similar to netstat -I):

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue
        state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    RX: bytes  packets  errors  dropped overrun mcast
    757713923  1397260  0       0       0       0
    TX: bytes  packets  errors  dropped carrier collsns
    757713923  1397260  0       0       0       0
2: enp7s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
        fq_codel state UP mode DEFAULT group default qlen 1000
    link/ether 54:04:a6:7f:30:b1 brd ff:ff:ff:ff:ff:ff
    RX: bytes  packets  errors  dropped overrun mcast
    142884794755 105433976 0       0       0       672938
    TX: bytes  packets  errors  dropped carrier collsns
    38670413265 71936164 0       0       1       0

ip route add default via 192.168.100.1

set default gateway (route pkts through the specified IP addr);

ip route add 10.23.30.0/24 via 192.168.10.1

add static route to the specified net through the specified gateway;

ip route del 10.28.0.0/16 via 192.168.10.1 dev enp7s0

delete the specified route from the routing table;

Options
-0 (it's a zero) shortcut for -family link;
-4 shortcut for -family inet;
-6 shortcut for -family inet6;
-a execute the specified cmd over all objects; skip if cmd does not support this option (-all);
-B shortcut for -family bridge;
-b read cmds from the specified file or stdin and invoke them; first failure terminates ip exec (-batch filename);
-br show only basic info in a tabular format for better readability; this only works with ip addr show and ip link show cmds (-brief);
-c use color output (-color);
-D shortcut for -family decnet;
-d show more details (-details);
-f the protocol family to use: inet, inet6, bridge, ipx (Novell NetWare IPX, old stuff), dnet (DecNet, very old), mpls (RFC 4950, MPLS - ICMP Extensions for Multiprotocol Label Switching), link; without this option the protocol family is guessed from other arguments; if the cmdline does not allow to guess, the default one will be used (inet or any); note that link is a special family identifier meaning that no networking protocol is involved (-family prot_family);
-h output statistics using human readable values followed by suffix (-human);
-I shortcut for -family ipx;
-j output results in JavaScript Object Notation format (-json);
-l specify max num of loops the ip address flush logic will attempt before giving up; the default is 10, zero means loop until all addresses are removed (-loops count);
-M shortcut for -family mpls;
-n switch to the specified network namespace (-netns net_namespace);
-o output each record on a single line, replacing line feeds with the '\' char; this may be useful if you want to count records with wc or pipe to grep (-oneline);
-p output results in JSON format, add indentation for better raedability (-pretty);
-r use the system's name resolver to print DNS names instead of host addresses (-resolve);
-rc set the netlink socket receive buffer size; default is 1MB (-rcvbuf size);
-s output more info; if the option appears twice or more, there'll be even more info (-stats);
-t display current time when using monitor option (-timestamp);
-ts like prev (timestamp) but use shorter format (-tshort);
-V output utility version and exit (-Version);

-force

do not terminate on errors in batch mode; if there were any errors during execution of the commands, the application return code will be non zero;

-iec

print human readable rates in IEC units (e.g. 1KiB = 1024);

Commands

Command specifies the action to perform on the object. The set of possible actions depends on the object type. The typical cmds are add, delete, show (or list ) objects, but some objects do not allow all these operations or have some additional cmds. The help cmd is available for all objects, and shows a list of available cmds and arg syntax.

If cmd is not specified some default is assumed, usually list or help (if the objects of this class cannot be listed).

Objects

address - IPv4 or IPv6 address on a device;

addrlabel - label configuration for prot addr selection;

l2tp - tunnel ethernet over IP (L2TPv3);

link - network device;

maddress - multicast address;

monitor - watch for netlink messages;

mroute - multicast routing cache entry;

mrule - rule in multicast routing policy database;

neighbour - manage ARP or NDISC cache entries;

netns - manage network namespaces;

ntable - manage the neighbor cache's operation;

route - routing table entry;

rule - rule in routing policy database;

tcp_metrics/tcpmetrics - manage TCP Metrics;

token - manage tokenized interface identifiers;

tunnel - tunnel over IP;

tuntap - manage TUN/TAP devices;

xfrm - manage IPSec policies;

The names of objects may be written in full or abbreviated.

Exit status

Exit status is 0 if cmd was successful, and 1 if there was a syntax error. If an error was reported by the kernel exit status is 2.

ipcs

reports interprocess communication facilities status.

ipcs -m -l

display the shared memory limits;

ipcs -s -l

display the semaphore limits;

ipcs -u

display a short summary on all IPC facilities;

ipcs [options]

Without options ~ displays message queues, shared memory segments, semaphore sets that are currently active in the system. There are env variables that affect ~ execution: LANG, LC_ALL, LC_CTYPE, LC_MESSAGES, NLSPATH, TZ.

Options (resource specification)
-q show info about active message queues;
-m show info about active shared memory segments;
-s show info about active semaphore sets;
-a show all (default);
Options (output format specification)
-c show creator’s user/group names;
-l show info on max allowable sizes (limits): max num of bytes in message queue or size of shared mem segments or num of semaphores in each set;
-p show process number info (pid of the last process to send a msg and pid of the last process to receive a msg on message queues, pid of the creating process and pid of the last process to attach or detach on shared memory segments);
-t show time info: time of the last control operation that changed the access permissions for all facilities, time of the last msgsnd() and msgrcv() on message queues, time of the last shmat() and shmdt() on shared memory, time of the last semop() on semaphores;
-u print a short summary;

iptables

is a firewall config tool used by admins (and experienced users) to set/modify rules for packet filtering and NAT (Network Address Translation); iptables works with IPv4 only, ip6tables handles IPv6. See also:

In Linux, firewall (netfilter) is the part of the Linux kernel (a bunch of loadable modules). Technically, it's a stateful firewall of the type packet filter (there are also proxy-type firewalls, e.g., SQUID). Linux firewall has a modular struct and its functionality depends on the kernel config. Distro kernels usually provide a reasonable set of firewall features, but if you want something exotic, you may have to build your own kernel from source.

Examples

Note!

You must be a superuser to exec following cmds!

To see INPUT chain rules with line numbers:

iptables -L INPUT --line-numbers -n

iptables -L INPUT --line-numbers -n | more

In the above examples, -L (command) means 'list', -n (option) means 'do not resolve names', use IPs and numeric port specs (saves time). Remember: there are 5 kernel tables, and the filter table is default, you don't have to specify it explicitly; to select other/any table use -t option:

To list FORWARD chain rules with line numbers, interfaces, no name resolution:

iptables -L FORWARD --line-numbers -n -v

The -v (verbose) provides more info, including interfaces. Line numbers are useful because they are required to insert, replace, delete rule(s).

To flush FORWARD chain (to remove all rules):

iptables -F FORWARD

To reset all counters in FORWARD chain:

iptables -Z FORWARD

Creating a new user-defined chain in filter table; the name of this new chain will be 'allowed':

iptables -N allowed

To delete the user-defined chain 'allowed', you must first flush it:

iptables -F allowed

iptables -X allowed

The default policy in popular Linux distros is usually ACCEPT. This may be OK for OUTPUT chain but not for INPUT, because it practically defeats the purpose. To change this situation you must explicitly set the default policy like this:

iptables -P INPUT DROP

It means: drop all incoming packets. This default policy practically cuts you from network, but it's supposed to be suplemented with other, less restrictive, rules. Note that pkts that are supposed to be forwarded to another host/net do not traverse INPUT chain and go directly to FORWARD.

You must take care of FORWARD chain only if your system is actually forwarding something to somewhere. To be sure, check IP forwarding status; 0 means 'no forwarding'. It's normal for a desktop or laptop. But it would be reasonable to set the default policy DROP (just in case..):

iptables -P FORWARD DROP

For routing hosts/servers this is only the beginning [of the chain]. Of course, if you rely on some other firewall, the default forwarding policy can be ACCEPT, but .. I don't know..

Setting the following default policy for OUTPUT chain

iptables -P OUTPUT ACCEPT

may be redundant because most likely it is like this from the beginning (unless you changed it). To be exact, it means: let out all packets generated within this system (careless and irresponsible, but common).

Adding rules to the end of the chain (-A) is the most popular style of firewall setting (probably because it minimizes the quantity of errors). The following rule is added to the end of the INPUT chain to drop fragmented packets (second and further fragments):

iptables -A INPUT -f -j DROP

Next rule allows SSH connection requests from anywhere:

iptables -A INPUT -p tcp -m conntrack --ctstate NEW --dport 22 -j ACCEPT

About state: old style was

-m state --state st

and though it's still supported, you probably should use

-m conntrack --ctstate st

Here goes the most basic rule for INPUT and FORWARD chains when the default policy is DROP. It allows your firewall to accept any packets of existing (already established) connections, but it rejects connection requests from the outside world (unless you add some exceptions later). Thus your system can be made practically unaccessible from the network, but you will be able to access everything (assuming your OUTPUT policy is properly set):

iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

In fact, you should start your firewall config by setting default policies DROP for input and forwarding, then adding this rule, then allowing some types of ICMP pkts (see below) to make your system visible to ping, and then maybe .. nothing else, if you don't want anybody to connect to your system. You should put the above command as close as possible to the top of the list (i.e., to the beginning of the chain). Experts also advice to add:

iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

The following cmd means: add new rule to the end of the FORWARD chain allowing to transfer any HTTP connection requests arriving from the specified IP range and destined to anywhere:

iptables -A FORWARD -p tcp -m iprange --src-range 192.168.1.10-192.168.1.20 -m state --state NEW --dport 80 -j ACCEPT

Next cmd is adding new rule allowing to transfer TCP pkts arriving through network interface eth1, but only if they have SYN flag set, while RST and ACK are unset; other flags are not matched. It's a messy syntax and probably you should avoid it unless you know TCP/IP well enough. Available flags are ACK, FIN, PSH, RST, SYN, and URG; you can also use ALL (match every flag) and NONE (match none of those flags):

iptables -A FORWARD -p tcp -i eth1
--tcp-flags SYN,RST,ACK SYN -j DROP

If you want to save firewall-related events to file, add following rule:

iptables -A INPUT -p tcp -j LOG --log-prefix "INPUT packets"

This particular cmd is not good because it logs all TCP pkts traversing INPUT chain, and often it's too much. In most cases you should either invent more selective cmd or use it for a short period of time.

Inserting a rule in the middle of the chain (-I) may be usefull if you want to correct some config mistakes, or to try this and that, or when you administer heavily loaded server and need to change your filtering policy on the fly.

The following cmd inserts a new rule in the middle of the INPUT chain. The rule itself means: accept FTP requests from 192.168.0.0 network arriving through eth0. To be exact, this cmd puts new rule at line #15 and shifts down all other rules that follow it, i.e., the old #15 becomes #16, etc:

iptables -I INPUT 15 -p tcp -i eth0
-s 192.168.0.0/24 --dport 21 -j ACCEPT

When you remove (delete) rule at the specified position, the lower part of the table shifts up. You should remember that each successful insert and delete changes line numbers of rules that follow involved position.

To delete rule #6 in INPUT chain:

iptables -D INPUT 6

To delete rule #10 in FORWARD chain:

iptables -D FORWARD 10

Replace rule at the specified position:

Replace rule #5 in the INPUT chain:

iptables -R INPUT 5 -p tcp -s 0/0 -m state --state NEW --dport 22 -j ACCEPT

Replace rule #5 in the INPUT chain once again:

iptables -R INPUT 5 -p tcp -s 192.168.0.0/24 -m conntrack --ctstate NEW --dport 22 -j ACCEPT

Miscell rules for NAT:

Enable HTTP forwarding with address translation from inet (external IP = 213.110.24.250) to LAN host 192.168.10.5:

iptables -t nat -A PREROUTING -p tcp -i eth2
-d 213.110.24.250 --dport 80
-j DNAT --to-destination 192.168.10.5

Insert a new rule into PREROUTING chain: this rule translates external (internet) IP 62.33.47.106 to local (internal) IP 192.168.10.6 and translates TCP port 29814 to TCP port 80, providing access to internal (behind the proxy) HTTP server (192.168.10.6). External users should connect to it using http://62.33.47.106:29814 because IP 62.33.47.106 is also used to provide access to another web-server:

iptables -t nat -I PREROUTING 42 -p tcp -i eth0
-d 62.33.47.106 --dport 29814
-j DNAT --to-destination 192.168.10.6:80

Enable IP forwarding and network address translation (simple case):

iptables -t nat -A POSTROUTING -o eth2
-j SNAT --to-source 192.168.0.0

In the above example it's supposed that the host is a router connected to two or more different networks. The net interface eth2 is connected to an internal network (LAN), and there must be other net interfaces, one of them is probably connected to Internet.

In the following example we set mark 44 (random choice) to all packets with destination port 443/tcp;

iptables -t mangle -A PREROUTING --dport 443
-p tcp -j MARK --set-mark 44

A set of rules for a typical Home PC

These scripts were mentioned at the beginning of the chapter: iptabs_init.sh sets the rules for a typical Home PC (or any PC used as a workstation), iptabs_remove.sh removes those rules. Note that the last script would only work correctly for the rules created by the first script, if you add/remove some chains you must modify the second script.

With the rules configured by iptabs_init.sh, your computer would respond to ping, but would not accept any connection requests from the outside (except SSH, HTTP/HTTPS, DLNA, and some other protocols). Forwarding is totally blocked, output is not restricted.

In fact, such scripts are quite personal, i.e., some people want this, some people want that. So, the last part of the script is supposed to be modified according to your requirements. For example, you can (and should) comment out all lines from SSH (tcp/22) to the end of the script, unless you really need to connect from outside to SSHD on your comp, to web-server (some people want to have their own locally), to MiniDLNA (good service to watch on TV movies that you keep on your PC), etc.

You can run iptabs_init.sh [as root] once after system installation, and if it's good for you, save it using following cmds:

iptables-save > /etc/iptables.rules

ip6tables-save > /etc/ip6tables.rules

To configure auto restore of the saved rules after reboot, add the following lines to /etc/network/interfaces:

pre-up /sbin/iptables-restore < /etc/iptables.rules
pre-up /sbin/ip6tables-restore < /etc/ip6tables.rules

The above cmds are good for Ubuntu/Debian, but RedHat/Fedora store those rules by default in /etc/sysconfig/iptables, and handle all these things in a different way.

You can also configure auto saving of iptables rules, however it has sense only if the rules are often modified or if you want to save/restore packet counters (in the last case option -c should be added to both iptables-save and iptables-restore).

The script iptabs_remove.sh is supposed to be used in two cases:

You should modify iptabs_remove.sh only when you add/remove some user-defined chains; modification of rules does not affect it.

Commands

-A, --append

append rule(s) to the end of the selected chain;

-D, --delete

delete rule(s) from the selected chain (specify exactly the rule or its number; the first rule is #1);

-E old new, --rename-chain old new

rename a user-defined chain;

-F, --flush

flush the selected chain (all chains of the table, if not specified);

-I, --insert

insert rule(s) in the selected chain as the given rule numbers; if not specified, #1 is default;

-L, --list

list all rules in the selected chain (in all chains, if not specified); use -n to avoid reverse DNS lookup;

-N name, --new-chain name

create a new user-defined chain;

-P chain target, --policy chain target

set the policy for the chain to the given target; only built-in chains can have policies;

-R, --replace

replace a rule in the selected chain (if src and/or dest names resolve to multiple addresses, the cmd will fail);

-X name, --delete-chain name

delete a user-defined chain;

-Z, --zero

zero (reset) packet and byte counters in the specified chain (all chains, if not specified);

Some popular matches

--icmp-type [!] n

match by ICMP type, usually numeric, typically 8 and 11 (see TCP/IP);

--length n[:m]

match the packet length against a numeric value or range;

--limit rate

max average matching rate, where rate may be n/second, n/minute, n/hour, n/day (default is 3/hour);

--mac-source [!] addr

match src MAC address; appropriate only for pkts coming from Ethernet devices and entering INPUT, FORWARD, PREROUTING chains;

--source-ports lst

--destination-ports lst

--ports lst

multiport match (up to 15 ports can be specified); lst - comma-separated list of port numbers; should be used only with -p tcp or -p udp;

--pkt-type unicast|broadcast|multicast

match by the link-layer packet type;

--state st

--ctstate st

match by the connection state, see more about states;

--sport, --source-port [!] port[:port]

match by source port or port range; :1024 means 0:1024, 1024: means 1024:65535;

--dport, --destination-port [!] port[:port]

match by destination port or port range;

--tcp-flags [!] mask comp

match by TCP flags; the first arg is a comma separated list of flags that we examine, the second arg is a comma separated list of flags that must be set: SYN, ACK, FIN, RST, URG, PSH, ALL, NONE;

[!] --syn

match only TCP pkts with SYN flag set and ACK, RST unset; such pkts are used to request TCP connection initiation; it is equivalent to --tcp-flags SYN,ACK,RST SYN;

Options

-c pkts bytes, --set-counters pkts bytes

this allows to initialize packet and byte counters of a rule (usually during INSERT, UPDATE, REPLACE);

-d [!] addr[/mask], --dst [!] addr[/mask]

(also --destination..) dest specification; addr can be a hostname, network name, IP address; mask can be specified by its length in bits;

[!] -f, --fragment

the rule only refers to the second and further fragments of the fragmented packets; since there is no way to tell the src or dst ports (or ICMP type) of such a packet, it will not match any rules that specify src, dst, icmp type; with "!" the rule will only match head fragments, or unfragmented packets;

-i [!] iface, --in-interface [!] iface

the name of interface through which the packet was received; appropriate only for INPUT, FORWARD and PREROUTING; by default any interface name will match;

-j target, --jump target

specifies what to do if the packet matches the rule;

--line-numbers

add line numbers when listing rules;

-m module

load the specified extended pkt matching module (addrtype, ah, cluster, connbytes, connlimit, etc);

-n, --numeric

output IP addresses and port numbers instead of host/network names and services which is default;

-o [!] iface, --out-interface [!] iface

the name of interface through which the packet is going to be sent; appropriate only for OUTPUT, FORWARD, POSTROUTING; by default any interface name will match;

-p [!] prot, --protocol [!] prot

protocol spec, prot can be tcp, udp, udplite, icmp, esp, ah, sctp, all (default); also it can be specified by a num value (0 means all); ! inverts the test;

-s [!] addr[/mask], --source [!] addr[/mask]

source spec; addr can be a hostname, network name, IP; mask can be specified by its length in bits;

-t table

use the specified kernel table; by default it's filter;

-v verbose mode (to be used with -L);

-x, --exact

output exact values of the counters instead of rounded ones (that is, multiply by 1024, not 1000);

More about Linux firewall

When a packet arrives or is going to leave, it is matched against the rules in those chains one-by-one. If a match is found, the process jumps onto the target and performs the action associated with it. If a packet traveses the chain and is not matched anywhere, it's handled according to the default policy of this chain. The default policy is actually a target. By default, all chains have a default policy ACCEPT, i.e., "let it go".

Kernel tables

There are 5 independent kernel tables containing

  1. filter table is default - you don't have to specify it explicitly in your command. It contains INPUT, FORWARD, and OUTPUT (pre-defined) chains. An important thing (!) to remember: though pkts that are supposed to be routed are coming into the box, they're bypassing INPUT chain and go directly to FORWARD.
  2. nat is used when a packet that creates a new connection is encountered; there are following buil-in chains PREROUTING (for altering pkts as soon as they come in), OUTPUT (for altering locally-generated pkts), POSTROUTING (for altering pkts as they are about to go out).
  3. mangle is used for specialized packet alteration; it has following built-in chains PREROUTING (for altering incoming pkts before routing), OUTPUT (for altering locally-generated pkts before routing), INPUT (for pkts coming into the box itself), FORWARD (for altering pkts being routed through the box), POSTROUTING (for altering pkts as they are about to go out).
  4. raw table is used mainly to config exemptions from connection tracking in combination with the NOTRACK target. It registers at the netfilter hooks with higher priority and is thus called before ip_conntrack, or any other IP tables. It provides PREROUTING and OUTPUT chains
  5. security (not all kernel have it) table is used for Mandatory Access Control (MAC) networking rules, such as those enabled by the SECMARK and CONNSECMARK targets. MAC is implemented by Linux Security Modules such as SELinux. The security table is called after the filter table, allowing any Discretionary Access Control (DAC) rules in the filter table to take effect before MAC rules. This table provides INPUT, OUTPUT, and FORWARD built-in chains.
Chains

Each chain is a list of rules which can match a set of packets. Each rule specifies a target - what to do with a matched packet. If pkt doesn't match, the next rule in the chain is examined. There are also cmds without rules and targets.

There are five predefined chains with a default policy (usually it's ACCEPT or DROP):

Targets

A target is the action triggered when a packet meets the matching criteria of a rule. Terminating targets perform an action which terminates evaluation within the chain and returns control to the netfilter hook. Non-terminating targets perform an action and continue evaluation within the chain.

Note that some targets are applicable to specific chains only.

ACCEPT

(terminating target) let the packet trough; the rule is accepted and will not continue traversing the current chain or any other chain in this table; however, the pkt can still travel through chains within other tables, and could be dropped there;

DROP

(terminating target) drop the packet silently, right here, right now, and forget about it;

REJECT

(terminating target) just like DROP, but, unlike DROP, sends a response back; it's only valid in the INPUT, FORWARD, OUTPUT chains and user-defined chains called from these chains; the only option is

--reject-with type  

where type can be (not all are listed here):

tcp-reset
icmp-net-unreachable
icmp-host-unreacable
icmp-port-unreachable
icmp-proto-unreachable
 

RETURN

stop traversing this chain and resume at the next rule in the previous (calling) chain;

DNAT

(destination NAT) modify dest address of the packet and all future pkts in this connection; valid only in nat table, within PREROUTING and OUTPUT chains and within any chains called upon from these chains; the option:

--to-destination ip[-ip][:port-port]

specifies either a single new dest address, or a range; port range may be added for TCP and UDP protocols; port stays unchanged, if not specified;

SNAT

(source NAT) modify the src address of the packet and all future pkts in this connection; it is only valid in the nat table for the POSTROUTING chain; the option

--to-source ip[-ip][:port-port]  

new src address (or range); optionally port range (tcp, udp);

MASQUERADE

should only be used in the nat table POSTROUTING chain with dynamically assigned IPs (like DHCP or dialup inet connection); for static addresses use SNAT; the option

--to-ports port[-port]   src port (or range);

REDIRECT

alter the dest IP address to send the packet to the machine itself (locally-generated pkts are mapped to 127.0.0.1); should only be used in the nat table PREROUTING, OUTPUT and user-defined chains called from the first two; it takes one option:

--to-ports port[-port]   dest port (or range);

MARK

valid only in the mangle table; the mark value is not set within the actual packet, but is associated with the pkt within the kernel;

LOG

turn on kernel logging of matching packets; this is non-terminating target, so if you want to log refused packets, use two separate rules: first to log, second to drop; options are:

--log-level n typical value is 7; see syslog.conf;
--log-prefix str text str up to 29 char;
--log-tcp-sequence   log TCP seq numbers (unsafe);
--log-tcp-options log opts from TCP pkt header;
--log-ip-options log opts from IP pkt header;

The location of the log depends on the distro, usually it's /var/log/syslog or /var/log/messages.

ULOG

multicast the packet and pkt info through a netlink socket. One or more user-space processes may then subscribe to various multicast groups and receive the packet;

QUEUE

pass the packet to userspace;

States

Linux firewall provides "statefulness" with the help of conntrack module. Connections tracked by this module can be in one of the following states:

NEW

This state represents the very first packet of a connection.

ESTABLISHED

This state is used for packets that are part of an existing connection. To be in this state, a connection should have received a reply from the other host.

RELATED

This state is used for connections that are related to another ESTABLISHED connection, e.g., FTP data connection are "related" to the already "established" FTP control connection.

INVALID

This state means the packet doesn't have a proper state; the reasons may be diff, like the system running out of memory, etc.

UNTRACKED

Any packets exempted from connection tracking in the raw table with the NOTRACK target end up in this state.

DNAT

This is a virtual state used to represent pkts whose dest address was changed by rules in the nat table.

SNAT

Like prev, this state represents pkts whose source address was changed.

Limits

are useful in preventing DOS attacks and password cracking attempts. For example, to limit the number of ICMP packets allowed to pass through, you can use the following rule:

iptables -A INPUT -p icmp -m limit --limit 1/sec --limit-burst 1 -j ACCEPT

As long as pkts arrive at rate one (or less) packet per sec, they are accepted. If pkts start to come more often, they are treated according to the default policy which should be DROP.

Here is more selective rule. It limits connection attempts from any particular source address:

iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name SSHPKT --rsource

iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name SSHPKT --update --seconds 180 --hitcount 5 --name SSH --rsource -j DROP

A named module SSHPKT keeps track of pkts requesting connections to the port 22/tcp. The name can be different, if not specified, it will be DEFAULT. The first cmd adds each new src IP to the, list, or updates counter for this address if it's already in the list. The second cmd checks counters and drops excessive pkts. The limit is 5 requests within 180 sec from a particular src IP. Techincally, only 4 pkts will pass throuh, the fifth will be dropped.

The above example focuses on SSH, but you can use similar approach for other services too.

As relatively new kernels can handle param --mask, you can limit the flow of packets not just from a partular source address, but from the whole network. For example, with the following mask you can limit the flow from a class B network (254 nodes):

iptables ... -m recent ... --mask 255.255.255.0

iwconfig

configures a wireless network interface (similar to ifconfig, but sets net interface params specific to the wireless op).

iwconfig [iface]

iwconfig iface [params]

If params are not given, ~ displays params and stats.

iwconfig wlan0

display params and stats for iface wlan0;

iwconfig wlan0 essid any

set ESSID any for iface wlan0;

iwconfig wlan0 essid 'My home wifi'

set ESSID "My home wifi" for iface wlan0;

iwconfig wlan0 mode ad-hoc

set mode Ad-Hoc for iface wlan0;

iwconfig wlan0 channel auto

let the wireless device to pick up the appropriate channel;

iwconfig wlan0 ap 00:60:1D:01:23:45

force the card to register to the specified Access Point;

iwconfig wlan0 ap auto

force the card to reassociate with the currently best Access Point;

iwconfig wlan0 bit 54M

force the card to transmit at the speed 54 Mbit/sec;

iwconfig wlan0 retry lifetime 300m

set max retry time to 300 milliseonds;

Parameters

ap

force the card to register to the Access Point given by the address, if it is possible; the address is the cell identity of the AP, as reported by wireless scanning, which may be different from its network MAC address; if the wireless link is point to point, set the address of the other end of the link; if the link is ad-hoc, set the cell identity of the ad-hoc network; when the quality of the connection goes too low, the driver may revert back to automatic mode (the card selects the best AP in the range); off re-enables automatic mode without changing the current AP, any or auto force the card to reassociate with the currently best AP;

commit

forces the card to apply all pending changes; some cards may not apply changes done through Wireless Extensions immediately (they wait to aggregate changes or apply it only when the card is brought up via ifconfig); usually, you need not interfere, except for debugging purposes;

essid

ESSID (other names: Network Name, Domain ID ) is used to identify cells which are part of the same virtual network; while AP Address or NWID define a single cell, the ESSID defines a group of cells connected via repeaters or infrastructure, where the user may roam transparently; some cards allow to disable ESSID checking (ESSID promiscuous) with off or any, and reenable it with on; if network's ESSID coincides with the special keyword (off, on, any), you use -- to escape it;

frag [n]

sets max fragment size which is always lower than the max pkt size; fragmentation allows to split an IP pkt in a burst of smaller frags transmitted on the medium; it may add overhead, but in a very noisy env this reduces the error penalty and allow pkts to get through interference bursts; this param may also control Frame Bursting available on some cards - the ability to send multiple IP pkts together; this mechanism would be enabled if the fragment size is larger than the max pkt size; you can also set this param to auto, fixed or off;

freq/channel

operating frequency or channel; a value < 1000 indicates a channel, a value > 1000 means freq in Hz (K, M, G mean KHz, MHz, GHz); channel nums usually start at 1 (iwlist gives the total num of channels, available freqs, current freq as a channel); depending on regulations, some freqs/channels may not be available; when mode is "Managed", most APs set the channel, and you cannot set it with ~; in "Ad-Hoc" mode, the freq setting may only be used at initial cell creation, and may be ignored when joining an existing cell; use off or auto to let the card pick up the best channel (when supported);

key/enc [xxx]

to set the current encryption key, enter the key in hex digits; to set a key other than the current key, prepend or append [index] to the key itself (this won't change which is the active key); you can also enter the key as an ASCII str with s: prefix; to change the currently active key, enter [index] without any key value; off disables, on reenables encryption; the security mode may be open or restricted; with most cards, in open mode no auth is used and the card may accept non-encrypted sessions; in restricted mode only encrypted sessions are accepted and the card will use auth if available; to set multiple keys, or set a key and change the active key, use multiple key cmds;

mode

device operating mode, depends on the net topology; it can be "Ad-Hoc" (network composed of only one cell and without Access Point), "Managed" (node connects to a net composed of many Access Points, with roaming), "Master" (the node is the synchronisation master or acts as an Access Point), "Repeater" (forwards pkts between other wireless nodes), "Secondary" (acts as a backup master/repeater), "Monitor" (is not associated with any cell and passively monitor all pkts on the frequency), "Auto";

modu, modulation

forces the card to use a specific set of modulations (may be necessary to fix interoperability issues); usually, a card can support standard (802.11b, 802.11g, ...) and some proprietary modulations (use iwlist to find available); auto allows the driver to do its best;

nick, nickname

nickname (station name); some 802.11 products do define it, but this is not used as far as the protocols (MAC, IP, TCP) are concerned and completely useless for config; some wireless diag tools may use it;

nwid

(obsolete / use for pre-802.11 hw only) Network ID; this param is used to differentiate adjacent wireless networks and identify nodes belonging to the same cell (802.11 protocol uses the ESSID and AP Address for this function);

power

sets misc power management params and mode; period n sets period between wake-ups, timeout n sets timeout before going back to sleep; values are in sec, millisec (m), microsec (u); saving n sets the generic level of power saving; off disables, on reenables power management; mode can be all (receive all pkts), unicast (receive unicast pkts only), multicast (receive multicast and broadcast pkts only);

rate, bit, bitrate

set the bitrate in b/s (if supported); the bitrate is the speed at which bits are transmitted over the medium, the real speed of the link is lower due to medium sharing and misc overhead; k, M, G mean 103, 106, 109; values below 1000 are card specific, usually an index in the bitrate list; auto causes auto speed selection (fallback to lower rate on noisy channels), fixed reverts back to the fixed setting; if you specify a bitrate value + auto, the driver will use all rates lower or equal than this value;

retry

most cards have MAC retransmissions, and some allow to set the behaviour of the retry mechanism; to set max num of retries, enter limit value - some reasonable positive num; to set max length of time the MAC should retry, enter lifetime value; by default, it's in seconds, m or u are for milliseconds or microseconds respectively; you can also add the short, long, min and max modifiers; if the card supports auto mode, they define the bounds of the limit or lifetime; some cards define different values depending on pkt size;

rts [n]

sets the size of the smallest pkt for which the node sends RTS; a value equal to the max pkt size disables the mechanism; you may also set this param to auto, fixed or off; RTS/CTS adds a handshake before each pkt transmission to make sure that the channel is clear; this adds overhead, but increases performance in case of hidden nodes or a large number of active nodes;

sens

sensitivity threshold; positive value is assumed to be the raw value used by the hardware or a percentage, negative value is assumed to be dBm; depending on the hardware, this param may control various functions; on modern cards it usually controls handover/roaming threshold, the lowest signal level for which hw remains associated with the current AP; when the sig level goes below this threshold the card starts looking for a new/better AP; some cards may use the num of missed beacons to trigger this proc; for high density of APs, a higher threshold make sure the card is always associated with the best AP, for low density of APs, a lower threshold minimizes num of failed handoffs; on ancient cards this param usually controls the defer threshold - the lowest sig level for which hw considers the channel busy; sig levels above this threshold make hw to inhibit its own transmission, whereas signals weaker than this are ignored and hw is free to transmit; this is usually strongly linked to the receive threshold - the lowest sig level for which hw attempts pkt reception; proper setting of these thresholds prevents time waste on the background noise while still receiving weak transmissions; modern designs control those thresholds auto;

txpower

set transmit power in dBm (if card supports multiple transmit powers); the power in dBm is P = 30 + 10log(W), where W is the power in watt; on and off enable/disable the radio, auto and fixed enable/disable power control (if supported);

Displayed parameters

are mostly the same as described above. Note that '=' means that param is fixed and forced, while ':' means that param is auto and the current value is shown (and may change). An address like 00:00:00:00:00:00 means that the card failed to associate with an AP (most likely a config issue). The AP param will be shown as Cell in Ad-Hoc mode. Other parameters:

Link quality

overall quality of link, an aggregate value that depends on the driver and the hardware;

Signal level

received signal strength (RSSI); may be in arbitrary units or dBm; in Ad-Hoc mode may be undefined (use iwspy);

Noise level

background noise level (when no pkts transmit);

Rx invalid nwid

num of pkts received with a different NWID or ESSID; check config; (!) also an adjacent network on the same freq may be the cause;

Rx invalid crypt

num of pkts that the hardware was unable to decrypt; check encryption settings;

Rx invalid frag

num of pkts for which the hardware was not able to properly re-assemble the link layer fragments (most likely one was missing);

Tx excessive retries

most MAC protocols will retry the pkt a number of times before giving up;

Invalid misc

other pkts lost in relation with specific wireless operations;

Missed beacon

num of periodic beacons from the Cell or AP we have missed; beacons are sent at the regular intervals to maintain the cell coordination; failure to receive them usually means that the card is out of range;

See also /proc/net/wireless.

iwlist

displays all info from a wireless interface related to the category specified by param.

iwlist [iface] param

iwlist wlan0 scanning

start scanning on wlan0 (root priv is required);

iwlist wlan0 rate

display the bitrates supported on the specified device;

iwlist --help

iwlist --version

Parameters

ap, accesspoint, peers

(deprecated; try scanning) the list of Access Points in range, and optionally the quality of link to them;

auth

list the WPA auth params curently set;

event

list the wireless events supported by device;

freq, frequency, channel

the list of available frequencies and the number of defined channels; usually driver returns the total num of channels and only those freqs that are available in the present locale, i.e., there is no one-to-one mapping between freqs displayed and channel nums;

genie

list the Generic Information Elements set in the device (used for WPA support);

keys, enc, encryption

list the encryption key sizes supported and list all the enc keys set in the device;

modu, modulation

list modulations supported by the device, and those currently enabled;

power

list Power Management attribs/modes of the device;

rate, bitrate

show the bitrates supported;

retry

list transmit retry limits and retry lifetime on the device;

scan, scanning

(root only) the list of Access Points and Ad-Hoc cells in range, and optionally misc info about them (ESSID, Quality, Frequency, Mode, etc); the result depends on what card supports; the scope of scan depends on card and card settings; though this cmd takes optional args, most drivers ignore them; essid specifies a scan on a specific ESSID; with some cards/drivers, this allows to see hidden networks; regular users cannot trigger a scan, but option last allows them to read left-over scan results;

txpower

list Transmit Powers available on the device;

wpa, wpakeys

list all WPA encryption keys set in the device;

See also /proc/net/wireless.

iwspy

provides wireless stats on the link between your NIC and another wireless device on the network. Stats include quality of the link, signal strength and noise level. However, if you just exec:

iwspy wlan0

the answer may be something like "No statistics to collect". This means that you must first specify a target (this activates monitoring):

iwspy wlan0 192.168.1.5

Note that ~ works only for nodes within the current wireless cell, you cannot monitor Access Points you are not associated with and nodes in other cells. In Managed mode pkts are usually relayed by AP, and you will get the signal strength of AP in this case. Thus, this functionality is mostly useful in Ad-Hoc and Master modes.

When monitoring is on, both cmds shown above display the stats.

The stats is updated each time a new pkt arrives, so every address (you can specify up to 8) in the list adds some overhead. This means that you should deactivate proc when you need no more info. To switch monitoring off:

iwspy wlan0 off

In general, the syntax is:

iwspy iface [params]

The only option (besides params) is --version.

Parameters
+ add a new set of addresses at the end of the current list (instead of replacing it);

dnsname | ipaddr

set an IP address, or in some cases a DNS name; actually, ~ needs MAC and uses ARP to fetch it; ~ may fail if there is no corresponding MAC in ARP cache, in this case you can ping the target ipaddr (it puts an appropriate record in ARP cache), and then retry ~;

hwaddr

like previous, but sets MAC address directly, without ARP;

getthr

get current low and high signal strength thresholds for ~ event;

off remove the current list of addresses and disable spy functionality;

setthr

set low/high signal strength thresholds for ~ event (if drivers supports); each time the signal strength for any of the addresses monitored goes under or beyond the corresponding threshold, a Wireless Event is generated; this allows to monitor link outages without having to run ~ often;