Linux Guide
Linux Guide
Daniele Raffo
Version history
1st edition May 2013 9th edition January 2021
2nd edition September 2014
3rd edition July 2015
4th edition June 2016
5th edition September 2017
6th edition August 2018
7th edition May 2019
8th edition January 2020
Logical Volume Management (LVM) introduces an abstraction between physical and logical storage, allowing a more versatile
use of filesystems. LVM uses the Linux device mapper feature (/dev/mapper).
Disks, partitions, and RAID devices are made of Physical Volumes, which are grouped into a Volume Group.
A Volume Group is divided into small fixed-size chunks called Physical Extents, which are mapped 1-to-1 to Logical Extents.
Logical Extents are grouped into Logical Volumes, on which filesystems are created.
How to increase the size of a Logical Volume (operation possible only if the underlying filesystem allows it)
1. Add a new disk to the machine, to provide the extra disk space
2. pvcreate /dev/sdc Initialize the Physical Volume
3. vgextend myvg0 /dev/sdc Add the Physical Volume to an existing Volume Group
or
1. Increase the size of an existing disk (already initialized as PV)
2. partprobe Notify the kernel of the new disk size
3. pvresize /dev/sdc Accommodate the Physical Volume to the new size
Then:
4. lvextend -L 2048M /dev/myvg0/mylv
Extend the Logical Volume by 2 Gb
or lvresize -L+2048M /dev/myvg0/mylv
or lvresize -l+100%FREE /dev/myvg/mylv or extend the Logical Volume taking all free space
5. resize2fs /dev/myvg0/mylv (ext) Extend the filesystem.
xfs_growfs /dev/myvg0/mylv (XFS) Alternatively, use lvresize -r on the previous step
How to reduce the size of a Logical Volume (operation possible only if the underlying filesystem allows it)
1. resize2fs /dev/myvg0/mylv 900M Shrink the filesystem to 900 Mb
2. lvreduce -L 900M /dev/myvg0/mylv
Shrink the Logical Volume to 900 Mb
or lvresize -L 900M /dev/myvg0/mylv
Boot sequence
POST
Low-level check of PC hardware.
(Power-On Self Test)
BIOS
Detection of disks and hardware.
(Basic I/O System)
GRUB stage 1 is loaded from the MBR and executes GRUB stage 2 from filesystem.
GRUB chooses which OS to boot on.
The chain loader hands over to the boot sector of the partition on which resides the OS.
Chain loader The chain loader also mounts initrd, an initial ramdisk (typically a compressed ext2
GRUB
filesystem) to be used as the initial root device during kernel boot; this makes possible to
(GRand Unified
load kernel modules that recognize hard drives hardware and that are hence needed to
Bootloader)
mount the real root filesystem. Afterwards, the system runs /linuxrc with PID 1.
(From Linux 2.6.13 onwards, the system instead loads into memory initramfs, a cpio-
compressed image, and unpacks it into an instance of tmpfs in RAM. The kernel then
executes /init from within the image.)
Kernel execution.
Linux kernel
Detection of devices.
Modern systems use UEFI (Unified Extensible Firmware Interface) instead of BIOS. UEFI does not use the MBR boot code; it
has knowledge of partition table and filesystems, and stores its application files required for launch in an EFI System
Partition, mostly formatted as FAT32.
After the POST, the system loads the UEFI firmware which initializes the hardware required for booting, then reads its Boot
Manager data to determine which UEFI application to launch. The launched UEFI application may then launch another
application, e.g. the kernel and initramfs in case of a boot loader like GRUB.
Information about the boot process can be found in the manpages man 7 boot and man 7 bootup.
The last script to be run is S99local -> ../init.d/rc.local; therefore, an easy way to run a specific program upon
boot is to call it from this script file.
/etc/init.d/boot.local runs only at boot time, not when switching runlevel.
/etc/init.d/before.local (SUSE) runs only at boot time, before the scripts in the startup directories.
/etc/init.d/after.local (SUSE) runs only at boot time, after the scripts in the startup directories.
To add or remove services at boot sequence: update-rc.d service defaults chkconfig --add service
update-rc.d -f service remove chkconfig --del service
When adding or removing a service at boot, startup directories will be updated by creating or deleting symlinks for the
default runlevels: K symlinks for runlevels 0 1 6, and S symlinks for runlevels 2 3 4 5.
Service will be run via the xinetd super server.
Default runlevels and S/K symlinks values can also be specified as such:
# chkconfig: 2345 85 15
# description: Foo service
/etc/init/start-ttys.conf (Red Hat) Start the specified number of terminals at bootup via getty, which
manages physical or virtual terminals (TTYs)
/etc/sysconfig/init (Red Hat) Control appearance and functioning of the system during bootup
/etc/machine-id (Red Hat) Randomly-generated machine ID.
The machine ID can be safely regenerated by deleting this file and then
running the command systemd-machine-id-setup
/etc/securetty List of TTYs from which the root user is allowed to login
/etc/issue Message printed before the login prompt. Can contain these escape codes:
\b Baudrate of line \o Domain name
\d Date \r OS release number
\s System name and OS \t Time
\l Terminal device line \u Number of users logged in
\m Machine architecture identifier \U "n users" logged in
\n Nodename aka hostname \v OS version and build date
/etc/issue.net Message printed before the login prompt on a remote session
/etc/motd Message Of The Day, printed after a successful login, but before execution
of the login shell
/etc/nologin If this file exists, login and sshd deny login to all unprivileged users.
Useful when doing system maintenance
/etc/login.defs Definition of default values (UID and GID ranges, mail directory, account
validity, password encryption method, etc.) for user account creation
/var/log/secure (Red Hat) Logfile containing user logins (both successful and failed) and
/var/log/auth.log (Debian) authentication mechanisms
/var/log/pwdfail Logfile containing failed authentication attempts
To prevent a specific user to log in, their shell can be set either as:
/bin/false user is forced to exit immediately
/sbin/nologin user is prompted a message and forced to exit; the message is "This account is currently not available"
or the contents of file /etc/nologin.txt if it exists
last Print the list of users that logged in and out. Searches through the file /var/log/wtmp
lastb Print the list of bad login attempts. Searches through the file /var/log/btmp
fail2ban Temporarily ban IP addresses (via firewall rules) that have too many failed password logins.
This information is taken from authentication logs
pam_tally2 Deny access to users that have too many failed logins
Runlevel Target
Debian Red Hat
(SysV) (Systemd)
0 Shutdown
1 Single user / maintenance mode
Multi-user mode
2 Multi-user mode without network
(default)
shutdown Shut down the system securely: all logged in users are notified via a message to
their terminal, and login is disabled. Can only be run by the root user
shutdown -a Non-root users that are listed in /etc/shutdown.allow can use this command to
shut down the system
shutdown -h 16:00 message Schedule a shutdown for 4 PM and send a warning message to all logged in users
shutdown -f Skip fsck on reboot
shutdown -F Force fsck on reboot
shutdown -c Cancel a shutdown that has been already initiated
update-rc.d -f service \ Add a service on the default runlevels; creates S30 symlinks for
start 30 2 3 4 5 . stop 70 0 1 6 . starting the service and K70 symlinks for stopping it
chkconfig --list service Display current configuration of service (its status and the
runlevels in which it is active)
systemctl list-unit-files --type=service List all active services and their current configuration
systemctl List loaded and active units
systemctl --all List all units, including inactive ones
/etc/inittab describes which processes are started at bootup and during normal operation; it is read and executed by
init at bootup.
All its entries have the form id:runlevels:action:process.
Process is executed when power goes down and a UPS kicks in.
powerwait
init will wait for its termination
powerfailnow Process is executed when power is down and the UPS battery is almost empty
powerokwait Process is executed when power has been restored from UPS
ctrlaltdel Process is executed when init receives a SIGINT via CTRL ALT DEL
Directory Content
/bin Essential command binaries for all users
/boot Bootloader files (OS loader, kernel image, initrd, etc.)
/dev Virtual filesystem containing device nodes to devices and partitions
/etc System configuration files and scripts
/home Home directories for users
/lib Libraries for the binaries in /bin and /sbin, kernel modules
/lost+found Storage directory for recovered files in this partition
/media Mount points for removable media
/mnt Mount points for temporary filesystems
/net Access to directory tree on different external NFS servers
/opt Optional, large add-on application software packages
/proc Virtual filesystem providing kernel and processes information
/root Home directory for the root user
/run Runtime variable data; replaces /var/run
/sbin Essential system binaries, system administration commands
/srv Data for services provided by the system
/sys Virtual filesystem providing information about hotplug hardware devices
/tmp Temporary files; deleted at reboot
/usr User utilities and applications
/usr/bin Non-essential command binaries for all users
/usr/include C header files
/usr/lib Libraries for the binaries in /usr/bin and /usr/sbin
/usr/local Software installed locally
/usr/local/bin Local software binaries
/usr/local/games Local game binaries
/usr/local/include Local C header files
/usr/local/lib Local libraries for the binaries in /usr/local/bin and /usr/local/sbin
/usr/local/man Local man pages
/usr/local/sbin Local system binaries
/usr/local/share Local architecture-independent hierarchy
/usr/local/src Local source code
/usr/sbin Non-essential system binaries (daemons and services)
/usr/share Architecture-independent files (icons, fonts, documentation, etc.)
/usr/share/doc Package-specific documentation not included in man pages
/usr/share/man Man pages
/usr/share/info Documentation in Info format
/usr/src Source code for the current OS
/var Variable files (logs, caches, mail spools, etc.)
/var/log Logfiles
/var/opt Variable files for the application software installed in /opt
/var/spool Queued items to be processed (mail messages, cron jobs, print jobs, etc.)
/var/tmp Temporary files that need to be stored for a longer time; preserved between reboots
The manpage man hier contains information about filesystem hierarchy.
The superblock contains information relative to the filesystem e.g. filesystem type, size, status, metadata structures.
The Master Boot Record (MBR) is a 512-byte program located in the first sector of the hard disk; it contains information
about hard disk partitions and has the duty of loading the OS. On recent systems, the MBR has been replaced by the GUID
Partition Table (GPT).
Almost all modern filesystems use journaling; in a journaling filesystem, the journal logs changes before committing them
to the filesystem, which ensures faster recovery and less risk of corruption in case of a crash.
GPT does not differentiate between primary, extended, or logical partitions. Furthermore, it practically has no limits
concerning number and size of partitions.
FUSE (Filesystem in Userspace) is an interface for userspace programs to export a filesystem to the Linux kernel, and is
particularly useful for virtual file systems.
partprobe device Notify the OS about partition table changes. Otherwise, the changes will take place
hdparm -z device only after reboot
blockdev --getbsz /dev/sda1 Get the block size of the specified partition
The UUID (Universal Unique Identifier) of a partition is a 128-bit hash number, which is associated to the partition when
the partition is initialized.
findfs UUID=652b786e-b87f-49d2-af23-8087ced0c667 Print the name of the specified partition, given its UUID
findfs LABEL=/boot Print the name of the specified partition, given its label
umount /dev/fd0 Unmount a floppy disk that was mounted on /mnt (device must not be busy)
umount /mnt
umount -l /dev/fd0 Unmount the floppy disk as soon as it is not in use anymore
Partition types
0x00 Empty 0x4e QNX4.x 2nd part 0xa8 Darwin UFS
0x01 FAT12 0x4f QNX4.x 3rd part 0xa9 NetBSD
0x02 XENIX root 0x50 OnTrack DM 0xab Darwin boot
0x03 XENIX usr 0x51 OnTrack DM6 Aux1 0xaf HFS / HFS+
0x04 FAT16 <32M 0x52 CP/M 0xb7 BSDI fs
0x05 Extended 0x53 OnTrack DM6 Aux3 0xb8 BSDI swap
0x06 FAT16 0x54 OnTrackDM6 0xbb Boot Wizard hidden
0x07 HPFS / NTFS / exFAT 0x55 EZ-Drive 0xbe Solaris boot
0x08 AIX 0x56 Golden Bow 0xbf Solaris
0x09 AIX bootable 0x5c Priam Edisk 0xc1 DRDOS/sec (FAT-12)
0x0a OS/2 Boot Manager 0x61 SpeedStor 0xc4 DRDOS/sec (FAT-16 < 32Mb)
0x0b W95 FAT32 0x63 GNU HURD or SysV 0xc6 DRDOS/sec (FAT-16)
0x0c W95 FAT32 (LBA) 0x64 Novell Netware 286 0xc7 Syrinx
0x0e W95 FAT16 (LBA) 0x65 Novell Netware 386 0xda Non-FS data
0x0f W95 extended (LBA) 0x70 DiskSecure Multi-Boot 0xdb CP/M, CTOS, etc.
0x10 OPUS 0x75 PC/IX 0xde Dell Utility
0x11 Hidden FAT12 0x80 Old Minix 0xdf BootIt
0x12 Compaq diagnostics 0x81 Minix / old Linux 0xe1 DOS access
0x14 Hidden FAT16 <32Mb 0x82 Linux swap / Solaris 0xe3 DOS R/O
0x16 Hidden FAT16 0x83 Linux 0xe4 SpeedStor
0x17 Hidden HPFS/NTFS 0x84 OS/2 hidden C: drive 0xeb BeOS fs
0x18 AST SmartSleep 0x85 Linux extended 0xee GPT
0x1b Hidden W95 FAT32 0x86 NTFS volume set 0xef EFI (FAT-12/16/32)
0x1c Hidden W95 FAT32 (LBA) 0x87 NTFS volume set 0xf0 Linux/PA-RISC boot
0x1e Hidden W95 FAT16 (LBA) 0x88 Linux plaintext 0xf1 SpeedStor
0x24 NEC DOS 0x8e Linux LVM 0xf4 SpeedStor
0x27 Hidden NTFS WinRE 0x93 Amoeba 0xf2 DOS secondary
0x39 Plan 9 0x94 Amoeba BBT 0xfb VMware VMFS
0x3c PartitionMagic recovery 0x9f BSD/OS 0xfc VMware VMKCORE
0x40 Venix 80286 0xa0 IBM Thinkpad hibernation 0xfd Linux raid autodetect
0x41 PPC PReP Boot 0xa5 FreeBSD 0xfe LANstep
0x42 SFS 0xa6 OpenBSD 0xff BBT
0x4d QNX4.x 0xa7 NeXTSTEP
The command sfdisk -T prints the above list of partition IDs and names.
The swap space is an area on disk (a file or a partition) used as a RAM extension. When there is not enough free physical
RAM for a process, inactive pages in memory are temporarily swapped out of memory to disk, to later be swapped in to
memory when RAM resources are available again. If both RAM and swap space become nearly full, the system may get
clogged by spending all the time paging blocks of memory back and forth between RAM and swap (thrashing).
The amount of RAM plus the swap is defined as the virtual memory.
In Linux, a swap partition is usually preferred over a swap file. While a swap file can be resized more easily, it cannot be
used for hibernation; this because the system must first locate the swap file's header, but in order to do so the filesystem
containing the swap file must be mounted, and journaled filesystems such as ext3 or ext4 cannot be mounted during
resume from disk. Also, in older Linux versions a swap partition used to have faster disk access and less fragmentation than
a swap file, although the difference is negligible nowadays.
The swap partition is listed as filesystem type 0x82; however, it is not a filesystem, but a raw addressable memory space
with no structure. For this reason it does not appear in the output of mount or df commands.
A swap partition can be created via any partitioning tool e.g. fdisk.
swapon /swapfile Enable a swap file or partition, thus telling the kernel that it
can use it now
swapoff /swapfile Disable a swap file or partition
/etc/fstab contains information about filesystems, including all filesystems that must be automatically mounted at bootup.
filesystem Device or partition. The filesystem can be identified either by its name, label, or UUID
mount point Directory on which the partition will be mounted
type Filesystem type, or auto if detected automatically
defaults Use the default options. The default options depend on the filesystem type
and can be found via the command:
tune2fs -l device | grep "Default mount options"
Most common default options: rw, suid, dev, auto, nouser, exec, async
ro Mount read-only
rw Mount read-write (default)
suid Permit SUID and SGID bit operations (default)
nosuid Do not permit SUID and SGID bit operations
dev Interpret block special devices on the filesystem (default)
nodev Do not interpret block special devices on the filesystem
auto Mount automatically at bootup, or when command mount -a is given (default)
noauto Mount only if explicitly demanded
options user Partition can be mounted by any user
nouser Partition can be mounted only by the root user (default)
exec Binaries contained on the partition can be executed (default)
noexec Binaries contained on the partition cannot be executed
sync Write files immediately to the partition
async Buffer write operations and commit them at once later, or when device is
unmounted (default)
noatime Do not update atime (access time) information for the filesystem. This results
in a performance improvement because the system does not need anymore to
do filesystem writes for files which are just being read
acl Support ACLs on files contained in the partition
context="context" Apply a specific SELinux context to the mount
Other specific options apply to specific partition types (e.g. NFS or Samba)
dump Options for the dump backup utility. 0 = do not backup
pass Order in which the filesystem must be checked by fsck. 0 = do not check
du directory Report disk usage, as the size of each file contained in directory, in Kb
du -s directory Show the total sum of the sizes of all files contained in directory
du -h directory Report disk usage in human-readable output
du -hs * | sort -hr Print out all files and directories in the current directory, ordered by size
(the largest first), in human-readable output
du -a /path | sort -nr | head Print out the 10 biggest files and directories under path
find /path -type f -exec du -Sh {} + \ Print out the 10 biggest files under path
| sort -hr | head
chroot /path/to/newrootdir command Run a command in a chroot jail (i.e. in a new root directory). The
command process will be unable to access files outside the chroot jail
chroot /mnt/sysimage Start a shell with /mnt/sysimage as filesystem root.
Useful during system recovery when the machine has been booted from
a removable media; this device is defined as the filesystem root and
often needs to be changed to perform operations on the machine
multipath options device Detect and aggregate multiple I/O paths (SAN connections) to a device
blkdiscard options device Discard device sectors, wiping the data they contain. Useful for SSDs
Many hard drives feature the Self-Monitoring, Analysis and Reporting Technology (SMART) whose purpose is to
monitor the reliability of the drive, predict drive failures, and carry out different types of drive self-tests.
The smartd daemon attempts to poll this information from all drives every 30 minutes, logging all data to syslog.
smartctl -a /dev/sda Print SMART information for drive /dev/sda
smartctl -s off /dev/sda Disable SMART monitoring and log collection for drive /dev/sda
smartctl -t long /dev/sda Begin an extended SMART self-test on drive /dev/sda
mkisofs -r -o cdrom.img data/ Create a CD-ROM image from the contents of the target directory.
Enables Rock Ridge extension and sets all content on CD to be publicly
readable, instead of inheriting the permissions from the original files
CD-ROM filesystems
Filesystem Commands
ISO9660 mkisofs Create a ISO9660 filesystem
mkudffs Create a UDF filesystem
udffsck Check a UDF filesystem
UDF (Universal Disk Format)
wrudf Maintain a UDF filesystem
cdrwtool Manage CD-RW drives (e.g. disk format, read/write speed)
HFS (Hierarchical File System)
CD-ROM filesystem extensions
Rock Ridge Contains the original file information (e.g. permissions, filename) for MS Windows 8.3 filenames
MS Joliet Used to create more MS Windows friendly CD-ROMs
El Torito Used to create bootable CD-ROMs
AutoFS is a client-side service that allows automounting of filesystems, even for nonprivileged users.
AutoFS is composed of the autofs kernel module that monitors specific directories for attempts to access them; in this case,
the kernel module signals the automount userspace daemon, which mounts the directory when it needs to be accessed and
unmounts it when is no longer accessed.
Mounts managed by AutoFS should not be mounted/unmounted manually or via /etc/fstab, to avoid inconsistencies.
# dir filesystem
/mydir nfsserver1.foo.org:/myshare
/etc/auto.misc Indirect map file for automounting of directory /misc.
RAID levels
Level Description Storage capacity
RAID 0 Striping (data is written across all member disks). Sum of the capacity of member disks
High I/O but no redundancy
RAID 1 Mirroring (data is mirrored on all disks). Capacity of the smaller member disk
High redundancy but high cost
RAID 4 Parity on a single disk. Sum of the capacity of member disks,
I/O bottleneck unless coupled to write-back caching minus one
RAID 5 Parity distributed across all disks. Sum of the capacity of member disks,
Can sustain one disk crash minus one
RAID 6 Double parity distributed across all disks. Sum of the capacity of member disks,
Can sustain two disk crashes minus two
RAID 10 (1+0) Striping + mirroring. Capacity of the smaller member disk
High redundancy but high cost
Linear RAID Data written sequentially across all disks. Sum of the capacity of member disks
No redundancy
mdadm -C /dev/md0 -l 5 \ Create a RAID 5 array from three partitions and a spare.
-n 3 /dev/sdb1 /dev/sdc1 /dev/sdd1 \ Partitions type must be set to 0xFD.
-x 1 /dev/sde1 Once the RAID device has been created, it must be formatted e.g. via
mke2fs -j /dev/md0
Non-GRUB bootloaders
LILO Obsolete. Small bootloader that can be placed in the MBR or the boot sector of a partition.
(Linux Loader) The configuration file is /etc/lilo.conf (run /sbin/lilo afterwards to validate changes).
SYSLINUX Able to boot from FAT and NTFS filesystems e.g. floppy disks and USB drives.
Used for boot floppy disks, rescue floppy disks, and Live USBs.
ISOLINUX Able to boot from CD-ROM ISO 9660 filesystems.
Used for Live CDs and bootable install CDs.
PXELINUX Able to boot from PXE (Pre-boot eXecution Environment). PXE uses DHCP or BOOTP to enable
basic networking, then uses TFTP to download a bootstrap program that loads and configures
SYSLINUX the kernel.
Used for Linux installations from a central server or network boot of diskless workstations.
EXTLINUX General-purpose bootloader like LILO or GRUB. Now merged with SYSLINUX.
GRUB (Grand Unified Bootloader) is the standard boot manager on Linux distributions. The latest version is GRUB 2; the
older version is GRUB Legacy.
GRUB Stage 1 (446 bytes), as well as the partition table (64 bytes) and the boot signature (2 bytes), is stored in the 512-
byte MBR. It then accesses the GRUB configuration and commands available on the filesystem, usually on /boot/grub.
# Linux Debian
menuentry "Debian 2.6.36-experimental" {
set root=(hd0,1)
linux (hd0,1)/bzImage-2.6.36-experimental ro root=/dev/hda6
}
# MS Windows
menuentry "MS Windows" {
set root=(hd0,2)
chainloader +1
}
The GRUB 2 configuration file must not be edited manually. Instead, it is necessary to edit the files in /etc/grub.d/
(scripts that will be run in order) and the file /etc/default/grub (configuration file for menu display settings), then run
update-grub (Debian) or grub2-mkconfig (Red Hat) which will recreate this configuration file.
root= Specify the location of the filesystem root. This is a required parameter
ro Mount read-only on boot
quiet Disable non-critical kernel messages during boot
debug Enable kernel debugging
Common
splash Show splash image
kernel
parameters: single Boot in single-user mode (runlevel 1)
emergency Emergency mode: after the kernel is booted, run sulogin (single-user login)
which asks for the root password for system maintenance, then run a Bash shell.
Does not load init or any daemon or configuration setting
init=/bin/bash Run a Bash shell (may also be any other executable) instead of init
The GRUB menu, presented at startup, allows to choose the OS or kernel to boot:
ENTER Boot the currently selected GRUB entry
C Get a GRUB command line
E Edit the selected GRUB entry (e.g. to edit kernel parameters in order to boot in single-user emergency mode,
or to change IRQ or I/O port of a device driver compiled in the kernel)
B Boot the currently selected GRUB entry. This is usually done after finishing modifying the entry
P Bring up the GRUB password prompt. Necessary if a GRUB password has been set
grub2-set-default 1 Set GRUB to automatically boot the second entry in the GRUB menu
grub2-editenv list Display the current GRUB menu entry that is automatically booted
/boot/grub/device.map This file can be created to map Linux device filenames to BIOS drives
(fd0) /dev/fd0
(hd0) /dev/hda
dpkg is the low-level package manager for Debian. It uses the DEB package format, which is compressed with ar.
rpm is the low-level package manager for Red Hat. It uses the RPM package format, which is cpio-compressed.
yum is the high-level package manager for Red Hat up to RHEL 7. In RHEL 8, it is a front-end to dnf.
3. Transfer the directory /tmp/repo from the online machine to the offline machine
[local]
name=Local
baseurl=file:///tmp/repo
enabled=1
gpgcheck=0
protect=1
5. Install the package from the local repository yum install package
ddrescue Data recovery tool. Like dd, but with high tolerance for read errors
testdisk Data recovery tool. Recovers data from a deleted or corrupted partition
photorec Data recovery tool. Recovers graphical image and video files from media
such as digital cameras and CD-ROMs
extundelete Data recovery tool. Recovers data from a EXT3 or EXT4 partition
scalpel Data recovery tool. Recovers data from a disk image or a raw block
device
rsync Tool for local and remote file synchronization. For all copies after the
first, copies only the blocks that have changed, making it a very fast and
bandwidth-efficient backup solution
rsync -rzv /home /tmp/bak Synchronize the content of the home directory with the temporary
rsync -rzv /home/ /tmp/bak/home backup directory; use recursion, compression, and verbosity
rsync -avz /home [email protected]:/backup/ Synchronize the content of the home directory with the backup directory
on the remote server via SSH; use archive mode (operates recursively
and preserves owner, group, permissions, timestamps, and symlinks)
Tape libraries
/dev/st0 First SCSI tape device
Devices
/dev/nst0 First SCSI tape device (no-rewind device file)
Utility for magnetic tapes mt -f /dev/nst0 asf 3 Position the tape at the start of the 3rd file
mtx -f /dev/sg1 status Display status of tape library
mtx -f /dev/sg1 load 3 Load tape from slot 3 to drive 0
mtx -f /dev/sg1 unload Unload tape from drive 0 to original slot
Utility for tape libraries mtx -f /dev/sg1 transfer 3 4 Transfer tape from slot 3 to slot 4
mtx -f /dev/sg1 inventory Force robot to rescan all slots and drives
mtx -f /dev/sg1 inquiry Inquiry about SCSI media device
(Medium Changer = tape library)
mandb Generate or refresh the search database for manpage entries. This must be done after installing
new packages, in order to obtain results from apropos or man -k
apropos keyword Show the commands whose manpage's short description matches the keyword. Inverse of the
man -k keyword whatis command
apropos -r regex Show the commands whose manpage's short description matches the regex
man -k regex
man -K regex Show the commands whose manpage's full text matches the regex
yum whatprovides /usr/share/man/mann/command.n.gz (Red Hat) Find which package provides section n of the
command manpage
yum install man-pages (Red Hat) Install a large number of manpages from the
Linux Documentation Project
yum install man-db (Red Hat) Install various manpage commands and utilities
cat > file <<EOF Create a Here Document, storing the lines entered in input to file.
line 1 EOF can be any text
line 2
line 3
EOF
command <<< 'string' Create a Here String, passing string as input to command
cat -etv <<< 'string' Print string, showing all invisible characters
tac file Print or concatenate text files in opposite order line-wise, from last line to first line
rev file Print a text file with every line reversed character-wise, from last char to first char
join file1 file2 Join lines of two text files on a common field
paste file1 file2 Merge lines of text files
split -l 1 file Split a text file into 1-line files; these will be named xaa, xab, xac, etc.
uniq file Print the unique lines of a text file, omitting consecutive identical lines
sort file Sort alphabetically the lines of a text file
shuf file Shuffle randomly the lines of a text file
diff file1 file2 Compare two text files line by line and print the differences
cmp file1 file2 Compare two binary files byte by byte and print the differences
sed 's/foo/bar/' file Stream Editor: Replace the first occurrence on a line of "foo" with "bar"
in file, and print on stdout the result
sed -i 's/foo/bar/' file Replace "foo" with "bar", overwriting the results in file
sed 's/foo/bar/g' file Replace all occurrences of "foo" with "bar"
sed '0,/foo/s//bar/' file Replace only the first line match
sed -n '7,13p' file Print line 7 to 13 of a text file
sed "s/foo/$var/" file Replace "foo" with the value of variable $var.
The double quotes are necessary for variable expansion
tr a-z A-Z <file Translate characters: Convert all lowercase into uppercase in a text file
tr [:lower:] [:upper:] <file
tr -d 0-9 <file Delete all digits from a text file
tr -d [:digit:] <file
awk Interpreter for the AWK programming language, designed for text
processing and data extraction
stdbuf option command Run command with modified stdin, stdout, or stderr buffering
tidy Correct and tidy up the markup of HTML, XHTML, and XML files
tidy -asxml -xml -indent -wrap 2000 \ Strip out comments from an XML file
-quiet --hide-comments yes file.xml
strings file Show all printable character sequences at least 4-characters long that
are contained in file
The symbols above are used in POSIX EREs (Extended Regular Expressions).
In POSIX BREs (Basic Regular Expressions), the symbols ? + { | ( ) need to be escaped; this is done by adding a
backslash character \ in front of them.
pv file > file2 Copy a file, monitoring the progress of data through a pipe
rename str1 str2 file Rename a file, replacing in the filename the first occurrence of string str1 with str2
touch file Change access timestamp and modify timestamp of a file as now.
If the file does not exist, it is created
truncate -s size file Shrink or extend a file to the specified size. If the file is larger than the specified size, it is
truncated; if the file is shorter, the extra space is filled with zeros
fdupes dir Examine a directory for duplicate files in it. To consider files a duplicate, it first compares file
sizes and MD5 signatures, then file contents byte-by-byte
Brace expansion
cp foo.{txt,bak} Copy file "foo.txt" to "foo.bak"
touch foo_{a,b,c}
touch foo_{a..c} Create files "foo_a", "foo_b", "foo_c"
dirs Display the directory stack (i.e. the list of remembered directories)
pushd dir Add dir to the top of the directory stack and make it the current working directory
popd Remove the top directory from the directory stack and change to the new top directory
dirname file Output the directory path in which file is located, stripping any non-directory suffix from
the filename
fuser Show the name of processes using a specific file, directory, or socket
fuser -v file Show the name of the process using file
fuser -v -n tcp 443 Show the name of the process running on port 443
tmpwatch Remove files which have not been accessed for some time
hexdump options file Dump a file into hexadecimal (or octal, decimal, ASCII)
xxd options file Convert a file from binary to hexadecimal (i.e create a hex dump), or vice versa
uuencode file Encode a file using only printing ASCII characters. Used to transmit a binary file over a
medium that supports only ASCII data, e.g. e-mail
uuencode -m file Encode a file to Base64
uudecode file Decode a file
In Linux, everything is (displayed as) a file. File descriptors are automatically associated to any process launched.
File descriptors
# Name Type Default device Device file
0 Standard input (stdin) Input text stream Keyboard /dev/stdin
mail user@email < file Redirect file to the stdin of command mail (in this case, send via e-mail the contents of
file to the email address user@email).
Redirection is handled by the shell, not by the command invoked. The space after the
redirection operator is optional
ls > file Redirect the stdout of command ls to file (in this case, write on file the contents of the
ls 1> file current directory). This overwrites file if it already exists, unless the Bash noclobber
option is set (via set -o noclobber)
ls >| file Redirect the stdout of command ls to file, even if noclobber is set
ls >> file Append the stdout of command ls to file
ls 1>> file
ls 2> file Redirect the stderr of command ls to file (in this case, write any error encountered by
the command ls to file)
ls 2>> file Append the stderr of command ls to file
ls 2> /dev/null Silence any error coming from the command ls
cat <file1 >file2 Redirect file1 to the stdin and file2 to the stdout of the command cat (in this case, copy
<file1 cat >file2 file1 to file2).
<file1 >file2 cat cat >file2 <file1 also works but is not recommended, because it truncates file2 if for
some reason file1 cannot be opened
cat /etc/passwd | wc -l Pipe the stdout of command cat to the stdin of command wc (in this case, print the
number of accounts in the system).
Piped commands run concurrently
echo "$(sort file)" > file Sort the contents of file and write the output to the file itself.
echo "`sort file`" > file sort file > file would not produce the desired result, because the stdout destination
sort file | sponge file is created (and therefore the content of the preexisting file is deleted) before the sort
command is run
> file Create an empty file. If the file exists, its content will be deleted
ls | tee file tee reads from stdin and writes both to stdout and file (in this case, writes the contents
of the current directory to screen and to file at the same time)
ls | tee -a file tee reads from stdin and appends both to stdout and file
while read -r line Process a text file line by line, reading from file, and output the lines.
do If file is /dev/stdin, reads from standard input instead
echo "Hello $line"
done < file
while read line Process a text file containing multiple words in each line, and output the words
do
for word in $line
do
echo "Hello $word"
done
done < file
while IFS=$'\t' read -r -a array Process a text file containing three words per line separated by a tab, and
do output the words. Example of input file:
echo "${array[0]}"
echo "${array[1]}" aaaa bbb ccc
echo "${array[2]}" dd eeeee ff
done < file ggg hhh iiii
Any application, program, script, or service that runs on the system is a process. Processes whose parent is a shell are
called jobs.
Signals are used for inter-process communication. Each process has a unique PID (Process ID) and a PPID (Parent Process
ID); when a process spawns a child, the process PID is assigned to the child's PPID.
The /sbin/init process, run at bootup, has PID 1. It is the ancestor of all processes and becomes the parent of any
orphaned process. It is also unkillable; should it die, the kernel will panic.
When a child process dies, its status becomes EXIT_ZOMBIE and a SIGCHLD is sent to the parent. The parent should then
call the wait() system call to read the dead process' exit status and other information; until that moment, the child process
remains a zombie.
:(){ :|:& };: Fork bomb: starts a process that continually replicates itself, slowing down or crashing the
system because of resource starvation. Dangerous!
To each process is associated a niceness value: the higher the niceness, the lower the priority.
The niceness value ranges from -20 to 19, and a newly created process has a default niceness of 0.
Unprivileged users can modify a process' niceness only within the range from 1 to 19.
nice -n -5 command Start command with a niceness of -5. If niceness is omitted, a default value of 10 is used
renice -5 command Change the niceness of a running command to -5
snice Change the niceness of a process. Obsolete
nohup script.sh Prevent a process from terminating (receiving a SIGHUP) when its parent Bash dies.
When a Bash shell is terminated cleanly via exit, its jobs will become child of the Bash's
parent and will continue running. When a Bash shell is killed instead, it issues a SIGHUP to
its children which will terminate
strace command Trace the execution of command, intercepting and printing system calls called by a process
and signals received by a process
ipcs Show IPC facilities information (shared memory, message queues, and semaphores)
uptime Show how long the system has been up, how many users are connected, and the
system load averages for the past 1, 5, and 15 minutes
time command Execute command and, at its completion, write to stderr timing statistics about the run:
elapsed real time between invocation and termination, user CPU time, system CPU time
sysbench Multi-threaded benchmark tool able to monitor different OS parameters: file I/O,
scheduler, memory allocation, thread implementation, databases
inxi Debugging tool to rapidly and easily gather system information and configuration
- r w x r w x r w x .
user
user(owner)
(owner) group
group others
others
rr==read
read rr==read
read rr==read
read
ww==write
write ww==write
write ww==write
write
xx==execute
execute xx==execute
execute xx==execute
execute
ss==setUID
setUIDand
andexecute
execute ss==setGID
setGIDand
andexecute
execute tt==sticky
stickyand
andexecute
execute
SS==setUID
setUID andnot
and notexecute
execute SS==setGID
setGID andnot
and notexecute
execute TT==sticky
sticky andnot
and notexecute
execute
Read group: 40 chmod g+r Can open and read the file Can list directory content
others: 4 chmod o+r
chmod 711 file Set read, write, and execute permission to user; set execute permission to group and others
chmod u=rwx,go=x file
chmod u+wx file Add write and execute permission to user
chmod -x file Remove execute permission from everybody (user, group, and others)
chmod -R g+x /path Set the group execute bit recursively on path and every dir and file underneath
find /path -type d \ Set the group execute bit recursively on path and every dir, but not file, underneath
-exec chmod g+x {} \;
umask 022 Set the permission mask to 022, hence masking write permission for group and others.
Linux default permissions are 0666 for files and 0777 for directories. These base
permissions are ANDed with the inverted umask value to calculate the final permissions of a
new file or directory
- r w x r w x r w x .
--==regular ..==file
filewith
withSELinux
SELinuxcontext
regularfile
file context
dd==directory ++==file with ACL
file with ACL
directory
ll==symbolic
symboliclink
link
ss==Unix
Unixdomain
domainsocket
socket
pp==named
namedpipe
pipe
cc==character
characterdevice
devicefile
file
bb==block
blockdevice
devicefilefile
Attribute Effect
a File can only be opened in append mode for writing
A When file is accessed, its atime record is not modified. This reduces I/O operations
c File is automatically compressed on the fly on disk by the kernel. Reading it produces uncompressed data
C For filesystems which perform copy-on-write, file is not subject to copy-on-write updates
d File will not be backed up by the dump program
D When directory is modified, changes are written synchronously on disk. Equivalent to dirsync mount option
e File is using extents for mapping the blocks on disk
E Compression error on a compressed file. This attribute is used by experimental compression patches
h File stores its blocks in units of filesystem blocksize instead of in units of sectors. This means that the file is
(or was) larger than 2 Tb
i File is immutable i.e. cannot be deleted, modified, renamed, linked, or changed permissions
I Directory is being indexed using hashed trees
j All file data is written to the ext3 or ext4 journal before being written to the file itself
N File has data stored inline within the inode itself
s File will be securely wiped by zeroing when deleted
S When file is modified, changes are written synchronously on disk. Equivalent to the sync mount option
t For filesystems with support for tail-merging, file will not have EOF partial block fragment merged with other
files. This is necessary for some applications e.g. LILO
T Directory is the top of directory hierarchies for the purpose of the Orlov block allocator
u File can be undeleted after being deleted
X Raw contents of compressed file can be accessed directly. This attribute is used by experimental
compression patches
Z Compressed file is dirty. This attribute is used by experimental compression patches
chattr +attribute file Add a file or directory attribute
chattr -attribute file Remove a file or directory attribute
chattr =attribute file Set a file or directory attribute, removing all other attributes
lsattr file List file or directory attributes
ctime Time of last change to file contents or file metadata (owner, group, or permissions) ls -lc
The POSIX standard does not define a timestamp for file creation. Some filesystems (e.g. ext4, JFS, Btrfs) store this value,
but currently there is no Linux kernel API to access it.
Access Control Lists (ACLs) provide a fine-grained set of permissions that can be applied to files and directories.
An access ACL is set on an individual file or directory; a default ACL is set on a directory, and applies to all files and
subdirs created inside it that don't have an access ACL.
The final permissions are the intersection of the ACL with the chmod/umask value.
A partition must have been mounted with the acl option in order to support ACLs on files.
setfacl -m d:u:user:permissions dir Same as above, but set a default ACL instead of an access ACL.
setfacl -d -m u:user:permissions dir This applies to all commands above
getfacl file Display the access (and default, if any) ACL for a file
getfacl file1 | setfacl --set-file=- file2 Copy the ACL of file1 and apply it to file2
getfacl --access dir | setfacl -d -M- dir Copy the access ACL of a directory and set it as default ACL
An inode is a structure containing all file metadata: file type, permissions, owner, group, size, access/change/modification/
deletion times, number of links, attributes, ACLs, and address where the actual file content (data) is stored. However, an
inode does not contain the name of the file; this information is stored in the directory where the file is located (i.e.
referenced).
A directory contains a list of mappings between filenames and inodes.
In Linux, two types of links exist: hard links and symbolic links (aka soft links).
The link count of a file is the total number of hard links to that file (i.e. to that file's inode). By default, files have a link
count of 1, and directories have a link count of 2 (the directory itself, and the . link inside the directory). The link count of a
directory is increased by one for each subdirectory (because of the .. parent link inside the subdirectory). Once a file has
no hard links pointing to it, the file is deleted, provided that no process holds the file open for reading.
Link is still valid if the original file Yes (because the link still references the No (because the path now references a
is moved or deleted inode to which the original file pointed) non-existent file)
Can link to a file in another No (because inode numbers make sense
Yes
filesystem only within a determinate filesystem)
Can link to a directory No Yes
Reflect the original file's permissions,
Link permissions rwxrwxrwx
even when these are changed
Link attributes - (regular file) l (symbolic link)
ls -i Show a listing of the directory with the inode number for each file
ls -l Show a listing of the directory with the link count for each file
whereis command Locate the binary, source, and manpage files for a command
whereis -b command Locate the binary files for a command
whereis -s command Locate the source files for a command
whereis -m command Locate the manpage files for a command
file file Analyze the content of a file or directory, and display the kind
of file (e.g. executable, text file, program text, swap file)
Almost all Linux commands accept the option -v (verbose), and some commands also accept the options -vv or -vvv
(increasing levels of verbosity).
All Bash built-in commands, and all commands respecting the POSIX requirements, accept the flag -- which denotes the
end of options and the start of positional parameters:
grep -- -i file Search for the string "-i" in file
rm -- -rf Delete a file called "-rf"
Another way to operate on a file whose name begins with a special character is to specify the path:
rm ./-rf Delete a file called "-rf"
Shells
sh Thompson Shell The first Unix shell, now obsolete.
Simple command interpreter, not designed for scripting.
sh Bourne Shell Default shell for Version 7 Unix, now obsolete.
On current Linux systems, /bin/sh is a symlink to the default shell.
bash Bash (Bourne Again Shell) GNU replacement for the Bourne Shell.
Default shell for the majority of Linux distributions.
csh C shell Shell originally designed for BSD.
tcsh tcsh C shell with additional features.
ksh KornShell Shell based on the Bourne Shell, with improvements.
zsh Z shell Shell based on the Bourne Shell, with improvements.
ash Almquist shell Lightweight shell, was the default shell for BSD.
dash Debian Almquist shell Port of Almquist shell for Debian.
fish Friendly interactive shell Interactive, user-friendly shell.
The scope of variables is the current shell only, while environment variables are visible within the current shell as well as
within all subshells and Bash child processes spawned by the shell.
Environment variables are set in /etc/environment in the form variable=value.
Conventionally, variable names are lowercase while environment variable names are uppercase.
VAR=$((5 + 37)) Evaluate a numeric expression and assign the result to another variable
VAR=$[5 + 37]
VAR=$((VAR2 + 42))
VAR=`expr $VAR2 + 42`
VAR=`command` Command substitution. Assign to a variable the standard output resulting from command
VAR=$(command) (which is executed in a subshell)
for i in /path/* Loop and operate through all the output tokens (in this case, files in the path).
do The construct for i in $(ls /path/) must not be used, because filenames containing
echo "Filename: $i" particular characters (whitespaces, glob characters, hyphens etc.) will cause unintended
done
results
echo ${VAR:-message} If variable exists and is not null, print its value, otherwise print message
echo ${VAR:+message} If variable exists and is not null, print message, otherwise print nothing
echo ${VAR,,} Print a string variable in lowercase
TOKENS=($STRING) String tokenizer. Splits a string stored in the variable STRING into tokens, according to
the content of the shell variable $IFS, and stores them in the array TOKENS
echo ${TOKENS[n]} Print the token number n
echo ${TOKENS[*]} Print all tokens
There are three ways to run a script with a specific Bash option enabled:
- Run the script with bash -option script.sh
- Specify the shebang line in the script as #!/bin/bash -option
- Add the command set -option at the beginning of the script
shopt Display the list of all shell options with their current value (on or off)
shopt -s shelloption Set (enable) a specific shell option
shopt -u shelloption Unset (disable) a specific shell option
Bash shell scripts must start with the shebang line #!/bin/bash indicating the location of the script interpreter.
Script execution
source script.sh Script execution takes place in the same shell. Variables defined and
. script.sh exported in the script are seen by the shell when the script exits
bash script.sh
Script execution spawns a new shell
./script.sh (file must be executable)
function myfunc { commands } Define a function. A function must be defined before it can be used in a Bash script.
myfunc() { commands } Argument number n is accessed in the body of the function via $n.
An advantage of functions over aliases is that functions can be passed arguments
myfunc arg1 arg2 ... Call a function
readonly -f myfunc Mark an already defined function as read-only, preventing it to be redefined
typeset -f Show functions defined in the current Bash session
readonly -p -f Show functions which are read-only
zenity Display GTK+ graphical dialogs for user messages and input
getopts syntax
while getopts abc:d: OPT Definition of accepted options
do
case $OPT in
a) Matches option -a.
command_a Executes a command
exit 0
;;
b)
command_b
exit 0
;;
c) Matches option -c argument.
command_c $OPTARG Executes a command with argument
exit 0
;;
d)
command_d $OPTARG
exit 0
;;
*) Command to execute if none of above options applies
default_command
exit 1
;;
esac
done
expect Dialogue with interactive programs according to a script, analyzing what can be
expected from the interactive program and replying accordingly
cmdtest Tool for black box testing of Linux command line programs
busybox BusyBox, "the Swiss Army knife of Embedded Linux", an optimized multi-call binary
which contains many Linux commands and utilities.
Useful for system recovery if Bash built-ins or common commands have become
unusable or have been removed from the system
busybox applet arguments Execute applet, which operates as the homonym Linux command
xargs command Call command multiple times, one for each argument found on stdin
ls foo* | xargs cat Print via cat the content of every file whose name starts by "foo"
Test operators
Integer operators File operators
-eq value Equal to -e file or -a file Exists
-ne value Not equal to -f file Is a regular file
-lt value Less than -d file Is a directory
-le value Less than or equal to -b file Is a block special file
-gt value Greater than -c file Is a character special file
-ge value Greater than or equal to -r file Is readable
Numeric operators -w file Is writable
= value Equal to -x file Is executable
!= value Not equal to -k file Is sticky
< value Less than -u file Is SUID
<= value Less than or equal to -g file Is SGID
> value Greater than -O file Is owned by the Effective UID
>= value Greater than or equal to -G file Is owned by the Effective GID
Expression operators -p file Is a named pipe (aka FIFO)
expr1 -a expr2 Logical AND -S file Is a socket
expr1 -o expr2 Logical OR -h file or -L file Is a symbolic link
! expr Logical NOT -s file Is non-zero length
\( expr \) Priority -N file Was modified since last read
String operators file1 -nt file2 Is newer than
-z Is zero length file1 -ot file2 Is older than
-n or nothing Is non-zero length file1 -ef file2 Refer to same device and inode as
= string or == string Is equal to
!= string Is not equal to
< string Is alphabetically before
> string Is alphabetically after
substr string pos len Substring
index string chars Index of any chars in string
length string String length
string : regex
or String matches regex
match string regex
expr "$MYVAR" = "39 + 3" Evaluate an expression (in this case, assigns the value 42 to the variable)
expr string : regex Return the length of the substring matching the regex
expr string : \(regex\) Return the substring matching the regex
Operators
Mathematical operators Logical operators
+ Addition ! Logical negation
- Subtraction && Logical AND
* Multiplication || Logical OR
/ Division Bitwise operators
% Remainder ~ Bitwise negation
** Exponentiation & Bitwise AND
++ Pre/post increment | Bitwise OR
-- Pre/post decrement ^ Bitwise XOR
Assignment operators << Left bitwise shift
= Assignment >> Right bitwise shift
op= Operation and assignment
Tests
if [test 1] case $STRING in
then pattern1)
[command block 1] [command block 1]
elif [test 2] ;;
then pattern2)
[command block 2] [command block 2]
else ;;
[command block 3] *)
fi [command block default]
;;
esac
Loops
while [test] until [test] for item in [list]
do do do
[command block] [command block] [command block]
done done done
The command block executes The command block executes The command block executes
as long as test is true as long as test is false for each item in list
i=0 i=0 for i in 0 1 2 3 4 5 6 7
while [ $i -le 7 ] until [ $i -gt 7 ] do
do do echo $i
echo $i echo $i done
let i++ let i++
done done for i in {0..7}
do
echo $i
done
start=0
end=7
for i in $(seq $start $end)
do
echo $i
done
start=0
end=7
for ((i = start; i <= end; i++))
do
echo $i
done
Loop breaking
break continue
less +command file Open file for reading, applying command (see list above)
less +F --follow-name file Move forward, attempting periodically to reopen file by name; useful to keep reading
a logfile that is being rotated. Note that, by default, less continues to read the
original input file even if it has been renamed
Option Effect
ai Turn on auto indentation
all Display all options
ap Print a line after the commands d c J m :s t u
aw Automatic write on commands :n ! e# ^^ :rew ^} :tag
bf Discard control characters from input
dir=tmpdir Set tmpdir as directory for temporary files
eb Precede error messages with a bell
ht=8 Set terminal tab as 8 spaces
ic Ignore case when searching
lisp Modify brackets for Lisp compatibility
list Show tabs and EOL characters
set listchars=tab:>- Show tab as > for the first char and as - for the following chars
magic Allow pattern matching with special characters
mesg Enable UNIX terminal messaging
nu Show line numbers
opt Speed up output by eliminating automatic Return
para=LIlPLPPPQPbpP Set macro to start paragraphs for { } operators
prompt Prompt : for command input
re Simulate smart terminal on dumb terminal
remap Accept macros within macros
report Show the largest size of changes on status line
ro Make file readonly
scroll=12 Set screen size as 12 lines
shell=/bin/bash Set shell escape to /bin/bash
showmode Show current mode on status line
slow Postpone display updates during inserts
sm Show matching parentheses when typing
sw=8 Set shift width to 8 characters
tags=/usr/lib/tags Set path for files checked for tags
term Print terminal type
terse Print terse messages
timeout Eliminate 1-second time limit for macros
tl=3 Set significance of tags beyond 3 characters (0 = all)
ts=8 Set tab stops to 8 for text input
wa Inhibit normal checks before write commands
warn Display the warning message "No write since last change"
window=24 Set text window as 24 lines
wm=0 Set automatic wraparound 0 spaces from right margin
:set option turn on an option
:set nooption turn off an option
:set option ? show the current value of option
Options can also be permanently set by including them in ~/.exrc (Vi) or ~/.vimrc (Vim)
ALTER TABLE customers MODIFY city VARCHAR(32); Modify the type of a column
If no database has been selected for use, tables must be referenced by databasename.tablename.
SELECT * FROM customers WHERE firstname LIKE 'Trill%'; Select customers whose first name
matches the expression:
% any number of chars, even zero
_ a single char
SELECT * FROM customers WHERE firstname REGEXP '^Art.*r$'; Select customers whose first name
matches the regex
SELECT firstname, lastname FROM customers WHERE zipcode = 'L1 42HG' Select customers that satisfy any of
UNION the two requirements
SELECT firstname, lastname FROM customers WHERE cusid > 4242001;
SELECT firstname, lastname FROM customers WHERE zipcode = 'L1 42HG' Select customers that satisfy both of
INTERSECT the two requirements
SELECT firstname, lastname FROM customers WHERE cusid > 4242001;
SELECT firstname, lastname FROM customers WHERE zipcode = 'L1 42HG' Select customers that satisfy the first
EXCEPT requirement but not the second
SELECT firstname, lastname FROM customers WHERE cusid > 4242001;
MySQL is the most used open source RDBMS (Relational Database Management System). It runs on TCP port 3306.
On RHEL 7 and later it is replaced by its fork MariaDB, but the names of the client and of most tools remain unchanged.
mysql -u root -p Login to MySQL as root and prompt for the password
mysql -u root -ppassword Login to MySQL as root with the specified password
mysql -u root -p -h host -P port Login to the specified remote MySQL host and port
mysql -u root -p -eNB'SHOW DATABASES' Run an SQL command via MySQL. Flags are:
e Run in batch mode
N Do not print table header
B Do not print table decoration characters +-|
mysqldump -u root -p --all-databases > dump.sql Backup all databases to a dump file
mysqldump -u root -p db > dump.sql Backup a database to a dump file
mysqldump -u root -p --databases db1 db2 > dump.sql Backup multiple databases to a dump file
mysqldump -u root -p db table1 table2 > dump.sql Backup some tables of a database to a dump file
mysql -u root -p < dump.sql Restore all databases from a dump file (which contains
a complete dump of a MySQL server)
mysql -u root -p db < dump.sql Restore a specific database from a dump file (which
contains one database)
mysqltuner.pl Review the current MySQL installation configuration for performances and stability
dbs="$(mysql -uroot -ppassword -Bse'SHOW DATABASES;')" Perform an operation on each database name
for db in $dbs
do
[operation on $db]
done
SHOW WARNINGS; Print warnings, errors and notes resulting from the most recent
statement in the current session that generated messages
SHOW ERRORS; Print errors resulting from the most recent statement in the
current session that generated messages
SHOW TABLE STATUS; Print information about all tables of the current database e.g.
engine (InnoDB or MyISAM), rows, indexes, data length
SHOW ENGINE INNODB STATUS; Print statistics concerning the InnoDB engine
SELECT * FROM information_schema.processlist; Print the list of threads running in your local session; if run as
SHOW FULL PROCESSLIST; root, print the list of threads running on the system
SELECT * FROM information_schema.processlist Print the list of threads running in your local session and all your
WHERE user='you'; other logged in sessions
SHOW CREATE TABLE table; Print the CREATE statement that created table or view
SHOW CREATE VIEW view;
SELECT table_name AS "Name", Display data and index size of all tables of
ROUND(((data_length)/1024/1024),2) AS "Data size in Mb", database
ROUND(((index_length)/1024/1024),2) AS "Index size in Mb"
FROM information_schema.TABLES WHERE table_schema='database'
ORDER BY table_name;
SELECT SUM(data_length+index_length)/1024/1024 AS "InnoDB Mb" Display the amount of InnoDB data in all
FROM information_schema.tables WHERE engine='InnoDB'; databases
SELECT CHAR_LENGTH(field) AS Length, COUNT(*) AS Occurrences Display all different lengths of string field and
FROM table GROUP BY CHAR_LENGTH(field); the number of times they occur
SELECT MAX(CHAR_LENGTH(field)) FROM table; Display the longest string stored in field
SHOW FULL TABLES IN database WHERE table_type LIKE 'VIEW'; Display the list of views in database
SELECT "Table 1" AS `set`, t1.* FROM table1 t1 WHERE Display the differences between the contents
ROW(t1.col1, t1.col2, t1.col3) NOT IN (SELECT * FROM table2) of two tables table1 and table2 (assuming
UNION ALL the tables are composed of 3 columns each)
SELECT "Table 2" AS `set`, t2.* FROM table2 t2 WHERE
ROW(t2.col1, t2.col2, t2.col3) NOT IN (SELECT * FROM table1)
PostgreSQL (aka Postgres) is an open source object-relational database. By default it listens for connections on TCP port
5432.
\list
\l List all databases
\list+
\l+ List all databases, displaying database size and description
\connect database
\c database Connect to database
\q Quit
8. In PostgreSQL, grant the necessary GRANT ALL PRIVILEGES ON DATABASE database TO user;
privileges on database to user \q
The X Window System (aka X11 or X) is a windowing system for Linux and UNIX-like OSes, providing a basic framework
for GUI applications via a client-server model. A display manager provides a login screen to enter an X session and
introduces the user to the desktop environment (e.g. GNOME, KDE, CDE, Enlightenment).
The following lines in /etc/sysconfig/desktop define GNOME as the default Display Environment and Display Manager:
desktop="gde"
displaymanager="gdm"
xrandr Configuration utility for the RandR (Resize and Rotate) X extension
xrandr -q Show screen(s) size and resolution
xrandr --output eDP1 --right-of VGA1 Extend the screen on an additional VGA physical monitor situated to the
left
xosview Monitor able to display several system parameters (CPU usage, memory
usage, load average, page swapping, interrupts, battery level, etc.)
This table is derived from keysymdef.h which defines keysym codes (i.e. characters or functions associated with each key in
the X Window System) as XK_key and its hex value. The key can be passed as argument to the xdotool key command.
root:x:0:0:/root:/bin/bash
bin:x:1:1:/bin:/bin/bash
jdoe:x:500:100:John Doe,,555-1234,,:/home/jdoe:/bin/bash
1 2 3 4 5 6 7
1 Login name
2 Hashed password (obsolete), or x if password is in /etc/shadow
3 UID – User ID
4 GID – Default Group ID
5 GECOS field – Information about the user: Full name, Room number, Work phone, Home phone, Other
6 Home directory of the user
7 Login shell (if set to /sbin/nologin or /bin/false, user will be unable to log in)
root:$6$qk8JmJHf$X9GfOZ/i9LZP4Kldu6.D3cx2pXA:15537:0:99999:7:::
bin:*:15637:0:99999:7:::
jdoe:!$6$YOiH1otQ$KxeeUKHExK8e3jCUdw9Rxy3Wu53:15580:0:99999:7::15766:
1 2 a b c 3 4 5 6 7 8 9
1 Login name
2 Hashed password (* if account is disabled, ! or !! if no password is set, prefixed by ! if the account is locked).
Composed of the following subfields separated by $:
a Hashing algorithm: 1 = MD5, 2a = Blowfish, 5 = SHA256, 6 = SHA512 (recommended)
b Random salt, up to 16 chars long. This is to thwart password cracking attempts based on rainbow tables
c String obtained by hashing the user's plaintext password concatenated to the stored salt
3 Date of last password change (in number of days since 1 January 1970)
4 Days before password may be changed; if 0, user can change the password at any time
5 Days after which password must be changed
6 Days before password expiration that user is warned
7 Days after password expiration that account is disabled
8 Date of account disabling (in number of days since 1 January 1970)
9 Reserved field
/etc/shadow and /etc/gshadow are mode 000 and therefore readable only by the root user.
usermod -c "Name Surname" user Modify the GECOS field of a user account
usermod -L user Lock a user account
usermod -U user Unlock a user account
Most options for usermod and useradd are the same.
chage -E 2022-02-14 user Change the password expiration date; account will be locked at that date
chage -d 13111 user Change the date (in number of days since 1 January 1970) of last password change
chage -d 0 user Force the user to change password at their next login
chage -M 30 user Change the max number of days during which a password is valid
chage -m 7 user Change the min number of days between password changes
chage -W 15 user Change the number of days before password expiration that the user will be warned
chage -I 3 user Change the number of days after password expiration before the account is locked
chage -l user List password aging information for a user
chpasswd Tool for batch update of passwords. Reads from stdin a list of username:password
On a system, every user is identified by a numeric UID (User ID), and every group by a numeric GID (Group ID).
UID 0 is assigned to the superuser.
UIDs from 0 to 99 should* be reserved for static allocation by the system and not be created by applications.
UIDs from 100 to 499 should* be reserved for dynamic allocation by the superuser and post-install scripts.
UIDs for user accounts start from 500 (Red Hat) or 1000 (SUSE, Debian).
*
as recommended by the Linux Standard Base core specifications
id Print your real and effective UID and GID, and the groups of which you are a member
id user Print real and effective UID and GID, and group membership information, about user
id -u Print your effective UID
w Print the list of users logged into the system, and what they are doing
rwho Print information about currently logged in users for all hosts on the local network
rusers Print names of currently logged in users for all hosts on the local network
Sudo is a mechanism that allows running a command as another user. Sudo access rights are defined in the sudoers files
/etc/sudoers and /etc/sudoers.d/*; these files must be edited only via visudo.
Commands run by sudo users are logged via syslog on /var/log/auth.log (Debian) or /var/log/secure (Red Hat).
sudoedit /etc/passwd Edit safely a file (in this case, /etc/passwd) according to security policies. It is
sudo -e /etc/passwd recommended to have nonprivileged users run this command instead of sudoing text
editors as root on protected files, because the text editor might spawn a shell, causing
security issues
gksudo -u root command GUI front-ends to su and sudo used to run an X Window command or application as
gksu -u root -l root. Pops up a requester prompting the user for root's password
runuser -u user command Run command as user. Can be launched only by root
screen Screen manager that multiplexes a single virtual VT100/ANSI terminal between
multiple processes or shells.
When the connection to a terminal is lost (e.g. because the terminal is closed
manually, the user logs out, or the remote SSH session goes into timeout), a
SIGHUP is sent to the shell and from there to all running child processes which are
therefore terminated. The screen command starts an interactive shell screen
session, to which the user will be able to reattach later
screen -S sessionname Start a screen session with the specified session name
screen command Start the specified command in a screen session; session will end when the
command exits
screen -list Show the list of detached screen sessions
screen -r pid.tty.host Resume a detached screen session
screen -r owner/pid.tty.host
screen -R Resume the last detached screen session
screen -d -R sessionname Detach a remote screen session and reattach your current terminal to it
CTRL A Send a command to the window manager:
0 ... 9 Switch between screen sessions
c Create a new screen session
? Show help
How to detach an already running job that was not started in a screen session
(this procedure detaches the job from its parent shell, so that the job will not be killed when the terminal is closed)
1. CTRL Z Suspend the job
2. bg Send the job to background
3. jobs Show the number (let us assume is n) of the backgrounded job
4. disown -h %n Mark job n so it will not receive a SIGHUP from its parent shell
or
1. screen Start a new screen session
2. reptyr pid Attach the job with process ID pid to the new terminal (screen session)
talk user Open an interactive chat session with user (which must be logged in)
cron is a job scheduler, allowing repeated execution of commands specified in crontab files.
The crond daemon checks the crontab files every minute and runs the command as the specified user at the specified times.
It is not necessary to restart crond after the modification of a crontab file, as the changes will be reloaded automatically.
On Systemd-based distros, Systemd timers are an alternative to cron jobs.
If /etc/cron.allow exists, only users listed therein can access the service.
If /etc/cron.deny exists, all users except those listed therein can access the service.
If none of these files exist, all users can access the service.
/etc/crontab
# m h dom mon dow user command
25 6 * * 1 root /opt/script1.sh every Monday at 6:25 AM
*/5 16 * * * root /opt/script2.sh from 4:00 to 4:55 PM every 5 minutes every day
0,30 7 25 12 * jdoe /home/jdoe/foo.sh at 7:00 and 7:30 AM on 25th December
3 17 * * 1-5 root /bin/rm /tmp/abc.o at 5:03 PM every day, from Monday to Friday
m minutes
h hours
dom day of month (1-31)
mon month (1-12 or jan-dec)
dow day of week (0-7 or sun-sat; 0=7=Sunday)
user User as whom the command will be executed
command Command that will be executed at the specified times
The crond daemon also runs anacron jobs, which allow execution of periodic jobs on a machine that is not always powered
on, such as a laptop. Only the superuser can schedule anacron jobs, which have a granularity of one day (vs one minute for
cron jobs).
/var/spool/anacron/jobid Date of the last execution of the anacron job identified by jobid
/etc/anacrontab
# period delay job-identifier command
7 10 cron.weekly /opt/script3.sh If the job has not been run in the last 7 days,
wait 10 minutes and then execute the command
period period, in days, during which the command was not executed
delay delay to wait, in minutes, before execution of the command
job-identifier job identifier in anacron messages; should be unique for each anacron job
command command that will be executed
at is used for scheduled execution of commands that must run only once. Execution of these commands is the duty of the
atd daemon.
If /etc/at.allow exists, only users listed therein can access the service.
If /etc/at.deny exists, all users except those listed therein can access the service.
If none of these files exist, no user except the superuser can access the service.
at 5:00pm tomorrow script.sh Execute a command once at the specified time (absolute or relative)
at -f listofcommands.txt 5:00pm tomorrow
echo "rm file" | at now+2 minutes
at -l List the scheduled jobs
atq
at -d 3 Remove job number 3 from the list
atrm 3
batch Schedule execution of a command for when the system is not too
charged. Reads a command from stdin and runs it when the system's
load average falls below 0.8
datamash Perform numeric operations, apply statistical functions, or change formatting on tabular data
vd VisiData, an interactive tool to explore and operate on tabular data
jp Draw simple plots from CSV or JSON data
daff Compare tabular data and find the differences
in2csv Convert various tabular data formats into CSV. Part of the csvkit Python package
sql2csv Execute SQL queries on a database and output the result as CSV
csvclean Correct common syntax error on a CSV file
csvcut Filter data on a CSV file
csvgrep Find data in specific columns of a CSV file
csvjoin Join CSV tables (similarly to SQL JOIN)
csvsort Sort data on a CSV file
csvstack Stack up rows from CSV files
csvformat Convert a CSV file to another format
csvjson Convert a CSV file to JSON format
csvlook Render a CSV file in the terminal as a fixed width table (compatible with Markdown)
csvpy Load a CSV file into a Python CLI shell
csvsql Generate SQL queries from a CSV file and execute them on a database
csvstat Print statistics for all columns of a CSV file
make Utility for automatic compiling, re-compiling, and installation of multi-file programs.
It determines automatically which parts of a multi-file program need recompiling. The relationships about
these parts, and the commands that must be used to update them, are described in a makefile (./Makefile
by default).
shc Shell script compiler, used to prevent a shell script from inspection or modification.
It encrypts a shell script, generates C source code, and compiles the C code into a stripped binary executable
file.
locale-gen it_IT.UTF-8 Generate a locale (in this case IT) by compiling a list
of locale definition files
apt-get install manpages-it language-pack-it (Debian) Install a different locale (in this case IT); this affects
system messages and manpages
iconv -f ISO-8859-10 filein -t UTF-8 > fileout Convert a text file from a codeset to another
ISO/IEC-8859 is a standard for 8-bit encoding of printable characters. The first 256 characters in ISO/IEC-8859-1 (Latin-1)
are identical to those in Unicode.
UTF-8 encoding can represent every character in the Unicode set, and is the de facto standard for text containing characters
with diacritics (which do not fit in the ASCII 7-bit set). It was designed for backward compatibility with ASCII. UTF-8
encodes a Unicode character into 8, 16, 24, or 32 bits, whatever necessary; a UTF-8 file containing only ASCII characters is
identical to an ASCII file.
zdump GMT Show current date and time in the GMT timezone
The Network Time Protocol is used to keep a machine's clock in sync with Internet timeservers. It uses UDP port 123.
ntpd -nqg Start NTP as a non-daemon, force synchronization of the clock, and quit.
The NTP daemon must not be running when this command is launched
ntptrace Trace from where a NTP server gets its time, following the chain of NTP servers back to the
primary time source
/etc/syslog.conf
# facility.level action
*.info;mail.none;authpriv.none /var/log/messages
authpriv.* /var/log/secure
mail.* /var/log/maillog
*.alert root
*.emerg *
local5.* @10.7.7.7
local7.* /var/log/boot.log
† = deprecated
Facilities and levels are listed in the manpage man 3 syslog.
logger -p auth.info "Message" Send a message to syslog with facility "auth" and priority "info"
logrotate Rotate logs. It gzips, renames, and eventually deletes old logfiles according to the
configuration files /etc/logrotate.conf and /etc/logrotate.d/*. It is usually
scheduled as a daily cron job
e.g. Pine, Mutt e.g. Sendmail, Exim, qmail e.g. Procmail, SpamAssassin
~/.forward Mail address(es) to which forward the user's mail, or mail commands
/etc/aliases Aliases database for users on the local machine. Each line has syntax alias: user
/etc/mail/aliases
/var/spool/mail/user Inbox for user on the local machine
Mailbox formats
Each mail folder is a single file, storing multiple email messages.
mbox $HOME/Mail/folder
Advantages: universally supported; fast search inside a mail folder.
Disadvantages: issues with file locking; possible mailbox corruption.
Each mail folder is a directory, and contains the subdirectories /cur, /new, and /tmp.
Each email message is stored in its own file with a unique filename ID.
The process that delivers an email message writes it to a file in the tmp/ directory,
and then moves it to new/. The moving is commonly done by hard linking the file to
new/ and then unlinking the file from tmp/, which guarantees that a MUA will not see
Maildir a partially written message as it never looks in tmp/. $HOME/Mail/folder/
When the MUA finds mail messages in new/ it moves them to cur/.
SMTP commands
220 smtp.example.com ESMTP Postfix (server) HELO xyz.linux.org Initiate the conversation and
HELO xyz.linux.org (client) identify client host to server
250 Hello xyz.linux.org, glad to meet you
EHLO xyz.linux.org Like HELO, but tell server to use
MAIL FROM: [email protected]
250 Ok Extended SMTP
RCPT TO [email protected] MAIL FROM: [email protected] Specify mail sender
250 Ok
RCPT TO [email protected] RCPT TO: [email protected] Specify mail recipient
250 Ok
DATA DATA Specify data to send. Ended
354 End data with <CR><LF>.<CR><LF> with a dot on a single line
From: Alice <[email protected]>
QUIT Disconnect
To: Bob <[email protected]>
RSET
Cc: Carol <[email protected]>
Date: Wed, 13 August 2014 18:02:43 -0500 HELP List all available commands
Subject: Test message
NOOP Empty command
This is a test message.
VRFY [email protected] Verify the existence of an email
.
250 OK id=1OjReS-0005kT-Jj address (this command should
QUIT not be implemented, for
221 Bye security reasons)
EXPN [email protected] Tell the actual delivery address
of aliases and mailing lists
newaliases Update the aliases database. Must be run after any change to /etc/aliases
sendmail -bi
mailq Examine the mail queue
sendmail -bp
sendmail -bt Run Sendmail in test mode
sendmail -q Force a queue run
Postfix is a fast, secure, easy to configure, open source MTA intended as a replacement for Sendmail. It is implemented as
a set of small helper daemons, most of which run in a chroot jail with low privileges. The main ones are:
master Postfix master daemon, always running; starts the other daemons when necessary
nqmgr Queue manager for incoming and outgoing mail, always running
smtpd SMTP daemon for incoming mail
smtp SMTP daemon for outgoing mail
bounce Manager of bounce messages
cleanup Daemon that verifies the syntax of outgoing messages before they are handed to the queue manager
local Daemon that handles local mail delivery
virtual Daemon that handles mail delivery to virtual users
postmap dbtype:textfile Manage Postfix lookup tables, creating a hashed map file of database
type dbtype from textfile
postmap hash:/etc/postfix/transport Regenerate the transport database
Procmail is a regex-based MDA whose main purpose is to preprocess and sort incoming email messages.
It is able to work both with the standard mbox format and the Maildir format.
To have all email processed by Procmail, the ~/.forward file may be edited to contain:
"|exec /usr/local/bin/procmail || exit 75"
# Blacklisted by SpamAssassin
Flag: file locking not necessary because blackholing to /dev/null
:0
* ^X-Spam-Status: Yes Condition: match SpamAssassin's specific header
/dev/null Destination: delete the message
:0B:
* hacking Flag: match body of message instead of headers
$MAILDIR/Geekstuff
:0HB:
* hacking Flag: match either headers or body of message
$MAILDIR/Geekstuff
:0:
* > 256000 Condition: match messages larger than 256 Kb
| /root/myprogram Destination: pipe message through the specified program
:0fw
* ^From: .*@foobar\.org Flags: use the pipe as a filter (modifying the message), and have
| /root/myprogram Procmail wait that the filter finished processing the message
:0c
* ^Subject:.*administration
Flag: copy the message and proceed with next recipe
! [email protected]
Destination: forward to specified email address, and (this is
:0: ordered by the next recipe) save in the specified mailfolder
$MAILDIR/Forwarded
The Courier MTA provides modules for ESMTP, IMAP, POP3, webmail, and mailing list services in a single framework.
To use Courier, it is necessary first to launch the courier-authlib service, then launch the desired mail service e.g.
courier-imap for the IMAP service.
Dovecot is an open source, security-hardened, fast, and efficient IMAP and POP3 server.
It implements its own high-performance dbox mailbox format. By default, it uses PAM authentication.
The script mkcert.sh can be used to create self-signed SSL certificates.
FTP (File Transfer Protocol) is a client-server unencrypted protocol for file transfer. Secure alternatives are FTPS (FTP
secured with SSL/TLS) and SFTP (SSH File Transfer Protocol). FTP can operate either in active or in passive mode.
Passive mode (more protocol-compliant, because it is the client, not the server, that initiates the second connection)
1. Client connects to FTP server on port 21 and requests passive mode via the PASV command
2. Server acknowledges and sends unprivileged port number via the PORT command
3. Client connects to server's unprivileged port number
4. Server acknowledges
FTP servers
Very Secure FTP Hardened and high-performance FTP implementation. The vsftpd daemon operates with multiple
processes that run as a non-privileged user in a chrooted jail
Pure-FTP Free and easy-to-use FTP server
pure-ftpd Pure-FTP daemon
pure-ftpwho Show clients connected to the Pure-FTP server
pure-mrtginfo Show connections to the Pure-FTP server as a MRTG graph
pure-statsdecode Show Pure-FTP log data
pure-pw Manage Pure-FTP virtual accounts
pure-pwconvert Convert the system user database to a Pure-FTP virtual accounts database
pure-quotacheck Manage Pure-FTP quota database
pure-uploadscript Run a command on the Pure-FTP server to process an uploaded file
FTP clients
ftp Standard FTP client
ftp ftpserver.domain.com Connect to an FTP server
lftp Sophisticated FTP client with support for HTTP and BitTorrent
lftp ftpserver.domain.com Connect to an FTP server and try an anonymous login
In Linux, printers are managed by cupsd, the CUPS (Common Unix Printing System) daemon.
Printers are administered via a web interface on the URL http://localhost:631.
IPv4 addressing
Address range Prefix Number of addresses Reference
An IPv4 address is 32-bit long, and is represented divided in four octets (dotted-quad notation), e.g. 193.22.33.44.
IPv4 classful addressing is obsolete and has been replaced by CIDR (Classless Inter-Domain Routing).
IPv6 addressing
64-bit network prefix (>= 48-bit routing prefix + <= 16-bit subnet id) + 64-bit interface identifier
Unicast
A 48-bit MAC address is transformed into a 64-bit EUI-64 by inserting ff:fe in the middle.
A EUI-64 is then transformed into an IPv6 interface identifier by inverting the 7 th most significant bit.
An IPv6 address is 128-bit long, and is represented divided in eight 16-bit groups (4 hex digits).
Leading zeros in each group can be deleted. A single chunk of one or more adjacent 0000 groups can be deleted.
e.g. 2130:0000:0000:0000:0007:0040:15bc:235f which can also be written as 2130::7:40:15bc:235f.
The IANA (Internet Assigned Numbers Authority) manages the allocation of IPv4 and IPv6 addresses, assigning large blocks
to RIRs (Regional Internet Registries) which in turn allocate addresses to ISPs (Internet Service Providers) and other local
registries. These address blocks can be searched via a WHOIS query to the appropriate RIR, which is:
AFRINIC for Africa
ARIN for US, Canada, and Antarctica
APNIC for Asia and Oceania
LACNIC for Latin America
RIPE NCC for Europe, Middle East, and Russia
Each block of a column identifies a subnet, whose range of valid hosts addresses is [network address +1 — broadcast
address -1] inclusive.
The network address of the subnet is the number shown inside a block.
The broadcast address of the subnet is the network address of the block underneath -1 or, for the bottom block, .255.
Client Server
FIN (Seq = q)
WEP is insecure because of the short length of the IV, which leads to IV reuse;
furthermore, the WEP standard does not even require a different IV for each
packet. Key reuse in a stream cipher is bad practice and leads to weak
encryption. A weak IV may even allow to deduce the WEP pre-shared key. In
case of an IV collision, it is possible to reconstruct the RC4 key stream from
the IV and the packet's decrypted payload. Therefore, WEP does not provide
cryptographic integrity protection of a packet, and is now obsolete.
After PSK or 802.1X authentication, a shared secret key called PMK (Pairwise
Master Key) is generated, and is validated through a four-way handshake
between wireless client and Access Point:
1. AP sends a nonce to the client, which uses it to build the PTK (Pairwise
Transient Key)
2. The client sends a nonce and a MIC to the AP
3. The AP builds and sends the GTK (Group Temporal Key) with another
MIC to the client
4. The client acknowledges reception to the AP
Wireless encryption can be used in conjunction with other security measures such as SSID cloaking (security by obscurity)
and MAC address filtering (whitelisting), which however are not very effective.
hostnamectl (Red Hat) Get the hostname, OS, and other information
ethtool option device Query or control network driver and hardware settings
ethtool eth0 View hardware settings of eth0
rdisc Network router discovery daemon. Client for IRDP (ICMP Router Discover Protocol).
Runs at bootup to populate the network routing tables with default routes
xinetd Extended Internet services daemon. Many network services are run by it rather than
standalone; xinetd operates as a super server, listening on all service ports defined in its
configuration, and upon receiving a connection request it starts the appropriate service
/etc/nsswitch.conf Sources that must be used by various system library lookup functions
order hosts,bind
multi on
/etc/resolv.conf Domain names that must be appended to bare hostnames, and DNS servers that will be used for
name resolution
loopback 127.0.0.0
mylan 10.2.3.0
Red Hat
/etc/sysconfig/network Network configuration file
ADDRESS=10.2.3.4
NETMASK=255.255.255.0
GATEWAY=10.2.3.254
HOSTNAME=mylinuxbox.example.org
NETWORKING=yes
DEVICE=eth0
TYPE=Ethernet
HWADDR=AA:BB:CC:DD:EE:FF
BOOTPROTO=none
ONBOOT=yes
NM_CONTROLLED=no
IPADDR=10.2.3.4
NETMASK=255.255.255.0
GATEWAY=10.2.3.254
DNS1=8.8.8.8
DNS2=4.4.4.4
USERCTL=no
/etc/sysconfig/network-scripts/ifcfg-eth0:0 Multiple configuration files for a single eth0 interface, which allows
/etc/sysconfig/network-scripts/ifcfg-eth0:1 binding multiple IP addresses to a single NIC
/etc/sysconfig/network-scripts/ifcfg-eth0:2
Debian
/etc/network/interfaces List and configuration of all network interfaces
allow-hotplug eth0
iface eth0 inet static
address 10.2.3.4
netmask 255.255.255.0
gateway 10.2.3.254
dns-domain example.com
dns-nameservers 8.8.8.8 4.4.4.4
In RHEL7 and later the network configuration is managed by the NetworkManager daemon.
A connection is a network configuration that applies to a device (aka network interface). A device can be included in
multiple connections, but only one of them may be active at a time.
The configuration for connection is stored in the file /etc/sysconfig/network-scripts/ifcfg-connection. Although it is
possible to set up networking by editing these configuration files, it is much easier to use the command nmcli.
nmcli connection reload Reload any manual change made to the files
/etc/sysconfig/network-scripts/ifcfg-*
Network teaming allows binding together two or more network interfaces to increase throughput or provide redundancy.
RHEL7 and later implement network teaming via the teamd daemon.
teamdctl teamif state Show the state of the team interface teamif
teamnl teamif command Debug a team interface teamif
A network bridge emulates a hardware bridge, i.e. a Layer 2 device able to forward traffic between networks based on
MAC addresses.
brctl show brif Display information about the bridge interface brif
The manpage man teamd.conf contains examples of team configurations and runners.
The manpage man nmcli-examples contains examples of teaming and bridging configuration.
whois example.org Query the WHOIS service for an Internet resource (usually a domain name)
ping host Test if a remote host can be reached and measure the round-trip time to it.
This is done by sending an ICMP Echo Request datagram and awaiting an
ICMP Echo Response
ping -M do -s size host Ping a remote host using an ICMP packet of size size (default is 56 bytes)
and setting the DF (Don't Fragment) bit. This command can be used to find
what is the maximum frame size allowed on the network, by trying
increasingly higher values for size until it exceeds the MTU and the
datagram is unable to reach the destination host
fping -a host1 host2 host3 Ping multiple hosts in parallel and report which ones are alive
traceroute host Print the route, hop by hop, packets trace to a remote host. This is done by
sending a sequence of ICMP Echo Request datagrams with increasing TTL
values, starting with TTL=1, and expecting ICMP Time Exceeded datagrams
uucp srchost!path desthost!path Unix-to-Unix copy. Copies files between hosts, identified by a bang path.
Obsolete
stunnel TLS encryption wrapper. Can be used to secure any client-server protocol
socat Establish two bidirectional data stream and transfer data between them
socat TCP-LISTEN:80,fork TCP:host:80 Forward local HTTP port to remote host's HTTP port
socat TCP:timeserver:13 - Query a timeserver using the Daytime Protocol
curl Transfer data to or from a remote host via HTTP, HTTPS, FTP, FTPS, SCP,
SFTP, TFTP, DICT, TELNET, LDAP, or FILE
curl www.example.org/file -o myfile Download a file via HTTP and save it locally under another name
curl -u user:psw 'ftp://server/file' Download a file via FTP, after logging in to the server
curl -XPUT webserver -d'data' Send an HTTP PUT command with data to webserver
inetsim Simulate Internet services. This is useful when setting up a confined lab
for malware analysis
pktgen Network packet generator. Uses the DPDK (Data Plane Development Kit)
packet processing framework
iwgetid wlan0 option Print NWID, ESSID, AP/Cell address or other information about the wireless network
that is currently in use
iw dev wlan0 station dump On a wireless card configured in AP Mode, display information (e.g. MAC address, tx/rx,
bitrate, signal strength) about the clients
hostapd Daemon that allows a wireless card to function in Host AP Mode, i.e. perform all
functions of an Access Point
hcidump -i device Display raw HCI (Host Controller Interface) data exchanged with a Bluetooth device
arp-scan Scan all hosts on the current LAN. Uses ARP (Layer 2) packets; therefore it is able to also find hosts
configured to drop all IP or ICMP traffic, and it cannot scan hosts outside the LAN
tcptrace Tool for the analysis of TCP dump files such as those generated by tcpdump, snoop, etc.
Nmap is a network analyzer, auditing tool, and penetration testing tool. The GUI equivalent is Zenmap.
Port state
open An application is listening for connections on the port
closed No application is listening for connections on the port
filtered Port is not responding to probe due to a firewall blocking the port, so port may be open or closed
unfiltered Port is responding to probe, but it is impossible to tell whether port is open or closed
Tcpdump is a packet sniffer (aka packet analyzer) which uses the libpcap library for packet capture. The GUI equivalent of
tcpdump is Wireshark, originally called Ethereal.
tcpdump options expression Print the content of sniffed packets that match expression.
Options:
-v -vv Increasing levels of verbosity
-n Do not perform DNS resolution on host addresses
-nn Do not convert protocol and port numbers to names
tcpdump ip host 10.0.0.2 tcp port 25 Sniff network packets on TCP port 25 from and to 10.0.0.2
tcpdump ether host '45:67:89:ab:cd:ef' Sniff traffic from and to the network interface having MAC address
45:67:89:ab:cd:ef
tcpdump 'src host 10.0.0.2 and \ Sniff HTTP and HTTPS traffic having as source host 10.0.0.2
(tcp port 80 or tcp port 443)'
tcpdump -i eth0 not port 22 Sniff all traffic on eth0 except that belonging to a SSH connection
tcpdump ip host 10.0.0.2 and not 10.0.0.9 Sniff IP traffic between 10.0.0.2 and any other host except 10.0.0.9
!= < <= ||
ne Not equal to lt Less than le Less than or equal to or Logical OR
Netcat is "the Swiss Army knife of networking", a very flexible generic TCP/IP client/server.
Depending on the distribution, the binary is called nc, ncat (Red Hat), or netcat (SUSE).
nc 10.0.0.7 389 < file Push the content of file to port 389 on remote host 10.0.0.7
echo "GET / HTTP/1.0\r\n\r\n" | nc 10.0.0.7 80 Connect to web server 10.0.0.7 and issue a HTTP GET
while true; \ Start a minimal web server, serving the specified HTML page
do nc -l -p 80 -q 1 < page.html; done to clients
while true; \
do echo "<html><body>Hello</body></html>" \
| ncat -l -p 80; done
nc -v -n -z -w1 -r 10.0.0.7 1-1023 Run a TCP port scan against remote host 10.0.0.7.
Probes randomly all privileged ports with a 1-second timeout,
without resolving service names, and with verbose output
echo "" | nc -v -n -w1 10.0.0.7 1-1023 Retrieve the greeting banner of any network service that
might be running on remote host 10.0.0.7
hping3 is a packet crafting tool, able to send any custom TCP/IP packet to a remote host and display the reply.
It is an extension of hping2, and is command-line compatible with it while having extended capabilities for packet
generation.
hping3 options host Send a crafted packet to host. By default, it sends TCP headers to port 0 of remote host
with no TCP flag set and a window size of 64
hping3 options
-c n Send n packets
-p n Use port n
-a src Set src as a fake IP source address for sent packets
--spoof src
-1 Use the ICMP protocol. By default, hping3 uses TCP
--ICMP
-2 Use the UDP protocol
--UDP
-8 n1-n2 Operate in scan mode, scanning the port range from n1 to n2
--scan n1-n2
-9 signature Operate in listening mode, trying to intercept signature
--listen signature
-A Set the ACK flag in probe packets. An ACK scan can be used to check if the remote
host is alive, when it does not respond to ping packets
-S Set the SYN flag in probe packets
-F Set the FIN flag in probe packets
-P Set the PSH flag in probe packets
-U Set the URG flag in probe packets
-Q Collect all TCP sequence numbers generated by the remote host
--tcp-timestamp Attempt to guess the timestamp update frequency and uptime of the remote host
hping3 -S -p 25 -c 5 host Send 5 TCP packets, with the SYN flag set, to port 25 of remote host
hping3 --scan 1-1024 -S host Perform a SYN scan on ports 1 to 1024 against the remote host
hping3 --udp --rand-source --data 512 host Send UDP packets with random source address and a data body size
of 512 bytes
hping3 -S -p 80 --flood host Perform a TCP SYN flood DoS attack against a webserver
hping3 -A -p 25 host Verify if a mailserver is alive (if it is, it will reply with an RST)
The TCP Wrapper feature provides basic traffic filtering of incoming network connections. To use this feature, the service
binary must have been compiled with the libwrap.a library.
/etc/hosts.allow Host access control files used by the TCP Wrapper system.
/etc/hosts.deny
Each file contains zero or more daemon:client lines. The first matching line is considered.
- rejected route
network mask network mask to apply for the destination network
Genmask 255.255.255.255 destination host
0.0.0.0 default route
U route is up
G use gateway
H target is host
Flags ! rejected route
D dynamically installed by daemon
M modified from routing daemon
R reinstate route for dynamic routing
ip route add 10.2.0.1 dev eth0 Add a route for a host 10.2.0.1
ip route add 10.2.0.1 via 10.2.0.254
route add -host 10.2.0.1 gw 10.2.0.254
ip route add 10.2.0.0/16 via 10.2.0.254 Add a route for a network 10.2.0.0/16
route add -net 10.2.0.0 netmask 255.255.0.0 gw 10.2.0.254
ip route delete 10.2.0.1 dev eth0 Delete a route for a host 10.2.0.1
route del -host 10.2.0.1 gw 10.2.0.254
ip route flush all Delete the routing table for all interfaces
The Netfilter framework provides firewalling capabilities in Linux. It is implemented by the user-space application programs
iptables for IPv4 (which replaced ipchains, which itself replaced ipfwadm) and ip6tables for IPv6.
iptables is implemented in the kernel and therefore does not have a daemon process or a service.
The ability to track connection state is provided by the ip_conntrack kernel module.
In RHEL 6, the service iptables provides all firewall functionalities; the GUI frontend is system-config-firewall.
In RHEL 7, the firewall is managed by the firewalld daemon, which uses iptables as backend. It is possible, but
discouraged, to use iptables directly by disabling firewalld and installing the package iptables-services, which
provides systemd units for iptables.
In RHEL 8, the firewall is managed by firewalld, with nftables (a replacement for iptables) as backend.
In Ubuntu, firewall capabilities are provided by the ufw (Uncomplicated Firewall) service, with iptables as backend.
iptables-restore < file Load into iptables the firewall rules specified in the file
iptables-save > file Save into iptables the firewall rules specified in the file
Iptables uses tables containing sets of chains, which contain sets of rules. Each rule has a target (e.g. ACCEPT).
The "filter" table contains chains INPUT, FORWARD, OUTPUT (built-in chains); this is the default table to which all iptables
commands are applied, unless another table is specified via the -t option.
The "nat" table contains chains PREROUTING, OUTPUT, POSTROUTING.
The "mangle" table contains chains PREROUTING, OUTPUT.
When a packet enters the system, it is handed to the INPUT chain. If the destination is local, it is processed; if the
destination is not local and IP forwarding is enabled, the packet is handed to the FORWARD chain, otherwise it is dropped.
An outgoing packet generated by the system will go through the OUTPUT chain.
If NAT is in use, an incoming packet will pass at first through the PREROUTING chain, and an outgoing packet will pass last
through the POSTROUTING chain.
iptables -A INPUT -s 10.0.0.6 -j ACCEPT Add a rule to accept all packets from 10.0.0.6
iptables -A INPUT -s 10.0.0.7 -j REJECT Add a rule to reject all packets from 10.0.0.7 and send
back a ICMP response to the sender
iptables -A INPUT -s 10.0.0.8 -j DROP Add a rule to silently drop all packets from 10.0.0.8
iptables -A INPUT -s 10.0.0.9 -j LOG Add a rule to log (via syslog) all packets from 10.0.0.9
iptables -A OUTPUT -d 10.7.7.0/24 -j DROP Add a rule to drop all packets with destination 10.7.7.0/24
iptables -A FORWARD -i eth0 -o eth1 -j LOG Add a rule to log all packets entering the system via eth0
and exiting via eth1
iptables -A INPUT -p 17 -j DROP Add a rule to drop all incoming UDP traffic (protocol
iptables -A INPUT -p udp -j DROP numbers are defined in /etc/protocols)
iptables -A INPUT --sport 1024:65535 --dport 53 \ Add a rule to accept all packets coming from any
-j ACCEPT unprivileged port and with destination port 53
iptables -A INPUT -p icmp --icmp-type echo-request \ Add a rule to accept incoming pings through eth0 at a
-m limit --limit 1/s -i eth0 -j ACCEPT maximum rate of 1 ping/second
iptables -A INPUT -m state --state ESTABLISHED \ Load the module for stateful packet filtering, and add a
-j ACCEPT rule to accept all packets that are part of a
communication already tracked by the state module
iptables -A INPUT -m state --state NEW -j ACCEPT Add a rule to accept all packets that are not part of a
communication already tracked by the state module
iptables -A INPUT -m state --state RELATED -j ACCEPT Add a rule to accept all packets that are related (e.g.
ICMP responses to TCP or UDP traffic) to a communication
already tracked by the state module
iptables -A INPUT -m state --state INVALID -j ACCEPT Add a rule to accept all packets that do not match any of
the states above
In firewalld, a network interface (aka interface) or a subnet address (aka source) can be assigned to a specific zone.
To determine to which zone a packet belongs, first the zone of the source is analyzed, then the zone of the interface; if no
source or interface matches, the packet is associated to the default zone (which is "public", unless set otherwise).
If the zone is not specified (via --zone=zone), the command is applied to the default zone.
By default, commands are temporary; adding the --permanent option to a command sets it as permanent, or shows
permanent settings only.
Temporary commands are effective immediately but are canceled at reboot, firewall reload, or firewall restart.
Permanent commands are effective only after reboot, firewall reload, or firewall restart.
Firewalld zones
block Rejects incoming connections with an ICMP HOST_PROHIBITED; allows only established connections
dmz Used to expose services to the public; allows only specific incoming connections
drop Drops all incoming packets; allows only outgoing connections
external Used for routing and masquerading; allows only specific connections
home Allows only specific incoming connections
internal Used to define internal networks and allow only private network traffic
public Allows only specific incoming connections. Default zone
trusted Accepts all traffic
work Used to define internal networks and allow only private network traffic
The list of firewall zones can be obtained via the command firewall-cmd --get-zones.
firewall-cmd --reload Reload firewall configuration; this applies all permanent changes and
cancels all temporary changes. Current connections are not terminated
firewall-cmd --complete-reload Reload firewall configuration, stopping all current connections
firewall-cmd --runtime-to-permanent Transform all temporary changes to permanent
firewall-cmd --add-rich-rule='richrule' Set up a rich rule (for more complex and detailed
firewall configurations)
firewall-cmd --add-rich-rule='rule \ Set up a rich rule to allow tftp connections from
family=ipv4 source address=10.2.2.0/24 service name=tftp subnet 10.2.2.0/24 and log them via syslog at a
log prefix=tftp level=info limit value=3/m accept' rate of 3 per minute
firewall-cmd --list-rich-rules List all rich rules
The manpage man firewalld.richlanguage contains several examples of rich rules.
firewall-cmd --direct --add-rule directrule Set up a direct rule (in iptables format)
firewall-cmd --direct --add-rule \ Set up a direct rule to allow SSH connections
ipv4 filter INPUT 0 -p tcp --dport 22 -j ACCEPT
firewall-offline-cmd directrule Set up a direct rule when firewalld is not running
firewall-cmd --direct --get-all-rules Show all direct rules
User-defined direct rules are stored in /etc/firewalld/direct.xml.
The manpage man firewalld.direct documents the syntax of direct rules.
Secure Shell (SSH) is a protocol (not a shell) for encrypted secure communications. It is mostly used as a replacement to
Telnet to securely login to a remote server's terminal, but can be applied to any network protocol. Some of the most
common applications of SSH are e.g. Secure Copy (SCP) and SSH File Transfer Protocol (SFTP).
ssh user@host Connect to a remote host via SSH and login as user.
Options:
-v -vv -vvv Increasing levels of verbosity
-p n Use port n instead of standard port 22
ssh user@host command Execute a command on a remote host
sshpass -p password ssh user@host Connect to a remote host using the specified password
pssh -i -H "host1 host2 host3" command Execute a command in parallel on a group of remote hosts
ssh-keygen -t rsa -b 2048 Generate interactively a 2048-bit RSA key pair; will prompt for a
passphrase
ssh-keygen -t dsa Generate a DSA key pair
ssh-keygen -p -t rsa Change passphrase of the private key
ssh-keygen -q -t rsa -f keyfile -N '' -C '' Generate an RSA key with no passphrase (for non-interactive use)
and no comment
ssh-keygen -lf keyfile View key length and fingerprint of a public or private key
< keyfile.pub awk '{print $2}' \ View fingerprint of a key, calculated using hashfunction.
| base64 -d | openssl hashfunction RSA keys fingerprint use sha1 (deprecated) or md5
ssh-keyscan host >> ~/.ssh/known_hosts Get the public key of host and add it to the user's known hosts file
ssh-agent Echo to the terminal the environment variables that must be set in
order to use the SSH Agent
eval `ssh-agent` Start the SSH Agent daemon that caches decrypted private keys in
memory; also shows the PID of ssh-agent and sets the appropriate
environment variables.
Once ssh-agent is started, the keys to cache must be added via
the ssh-add command; cached keys will then be automatically
used by any SSH tool e.g. ssh, sftp, scp
ssh-agent bash -c 'ssh-add keyfile' Start ssh-agent and cache the specified key
ssh-copy-id user@host Use locally available keys to authorize, via public key
authentication, login of user on a remote host.
This is done by copying the user's local public key
~/.ssh/id_rsa.pub to ~/.ssh/authorized_keys on the remote
host
sshfs user@host:/dir/ mountpoint/ SSH tool that allows mounting a remote directory as an SSH
filesystem on a mountpoint on the local machine. Uses the
FUSE kernel module.
The filesystem can be unmounted via the command
fusermount -u mountpoint/
X11 Forwarding
ssh -X [email protected] Enable the local display to execute locally an X application
stored on a remote host login.foo.com
The X.509 standard defines the format of public key certificates and other related files. It includes cryptographic standards
and protocols such as SSL/TLS, PKCS7, PKCS12, and OCSP.
The Public Key Infrastructure X.509 (PKIX) is described in RFC 5280.
DER and PEM are also used as file extensions for different types of files (see below).
OpenSSL is an open source cryptographic library containing an implementation of the SSL (Secure Sockets Layer) and TLS
(Transport Layer Security) protocols, plus various cryptographic utilities.
openssl x509 -in cert.pem -outform DER -out cert.der Convert a certificate from PEM to DER
openssl pkcs12 -export -in cert.pem \ Convert a certificate from PEM to PKCS#12 including
-inkey cert.key -out cert.pfx -name friendlyname the private key
openssl pkcs12 -in cert.p12 -out cert.crt -clcerts \ Convert a certificate from PKCS#12 to PEM
-nokeys
openssl pkcs12 -in cert.p12 -out cert.key -nocerts \ Extract the private key from a PKCS#12 certificate
-nodes
openssl pkcs12 -in cert.p12 -out ca.crt -cacerts Extract the CA certificate from a PKCS#12 certificate
cat cert.crt cert.key > cert.pem Create a PEM certificate from CRT and private key
openssl dgst -hashfunction -out file.hash file Generate the digest (hash) of a file
openssl dgst -hashfunction file | cmp -b file.hash Check the hash of a file; no output means OK
openssl dgst -hashfunction -sign private.key \ Sign a file
-out file.sig file
openssl dgst -hashfunction -verify public.key \ Verify the signature of a file
-signature file.sig file
openssl enc -e -cipher -in file -out file.enc -salt Encrypt a file
openssl enc -d -cipher -in file.enc -out file Decrypt a file
openssl genpkey -algorithm RSA -cipher 3des \ Generate a 2048-bit RSA key pair protected by a
-pkeyopt rsa_keygen_bits:2048 -out keypair.pem TripleDES-encrypted passphrase
openssl pkey -text -in private.key -noout Examine a private key
openssl pkey -in old.key -out new.key -cipher Change the passphrase of a private key
openssl pkey -in old.key -out new.key Remove the passphrase from a private key
1. openssl s_client -connect www.site.com:443 > tmpfile Inspect an SSL certificate from a website
2. CTRL C CTRL-C
3. openssl x509 -in tmpfile -text
In symmetric cryptography, a symmetric cipher (i.e. cryptographic algorithm) is used with a shared secret key to
encrypt a message. The message can then be decrypted using the same key.
In asymmetric cryptography aka Public Key Cryptography, ciphers do not operate with a single key but with a key
pair, composed of a public key and a private key. Public and private key are created together at the same time using a
special algorithm and are strictly related to each other; however, deriving a private key from its public key is
computationally infeasible. A message is encrypted with a public key and can only be decrypted with the companion private
key. Similarly, a message is digitally signed with a private key and can only be verified with the companion public key.
Encryption guarantees confidentiality (only sender and receiver are able to know the contents of the message).
Digital signature guarantees authentication (the receiver can verify that the message originates from the intended sender),
integrity (the receiver can verify that the message was not modified since it was signed), and non-repudiation (the sender
cannot deny having signed the message).
In a block cipher, the input plaintext is split into blocks of fixed size, fed to the algorithm, and transformed according to
the key. If the input plaintext is shorter than the block length, padding is used.
In a stream cipher, the input plaintext is combined with a pseudorandom digit stream. The key is applied to each bit, one
at a time.
A hash function maps a bitstring of arbitrary length to another bitstring of fixed length, hence outputting a condensed
representative image of the bitstring fed in input. Changing just one bit of the input string results in a very different hash
value in output (avalanche effect).
A hash function must have the following properties:
- be one-way, i.e. given an output value it is computationally infeasible to find the matching input (preimage resistance)
- given a specific input, it is computationally infeasible to find another input that results in the same output (second
preimage resistance)
- it is computationally infeasible to find two different inputs which would result in the same output (collision resistance)
A Public Key Infrastructure (PKI) handles creation, management, distribution, use, and revocation of Digital Certificates.
It is composed of the following entities:
- Certification Authority (CA), which issues and verifies Digital Certificates
- Registration Authority (RA), which verifies the CA, verifies the subject, and ensures valid and correct registration
- Validation Authority (VA), which verifies the validity of a Digital Certificate
stegsnow Steganography tool for text files. The secret message is concealed in additional tab and whitespace
characters at the end of lines
steghide Steganography tool for image and audio files
shasum Print or check the digest of a file generated by the SHA hashing algorithm
sha1sum
sha224sum
sha256sum
sha384sum
sha512sum
md5sum Print or check the digest of a file generated by the MD5 hashing algorithm
Symmetric ciphers
DES Block cipher with a 64-bit block size. Uses DEA (Data Encryption Algorithm)
(Data Encryption Standard) with a 56-bit key. Obsolete and insecure.
3DES Cipher which uses a key bundle of three DES keys: K1, K2, and K3.
(Triple DES) The algorithm consists in applying DES three times: encrypt with K 1, decrypt
with K2, then encrypt with K3.
Key options are:
- K1, K2, and K3 are all different (most secure)
- K1 = K3
- K1 = K2 = K3 (fallback to DES, insecure)
AES Iterated block cipher with a 128-bit block size. NIST standard.
(Advanced Encryption Standard) Can use a 128-bit, 192-bit, or 256-bit key.
IDEA Block cipher with a 64-bit block size and a 128-bit key.
(International Data Encryption Intended as a replacement for DES, is now patent-free.
Algorithm)
RC4 Stream cipher with byte-oriented operations, based on the use of a random
(Rivest Cipher 4) permutation. Key size is variable. Patented by RSA Security.
aka ARC4 or ARCFOUR
RC5 Fast, parameterized block cipher with a 32-bit, 64-bit, or 128-bit block size.
(Rivest Cipher 5) Number of rounds can be up to 255, and key size can be up to 2040 bits.
Uses two 2-bit registers. Patented by RSA Security.
RC6 Block cipher derived from RC5, with the improvement of integer multiplication
(Rivest Cipher 6) and four 4-bit registers. Patented by RSA Security.
SEAL Stream cipher optimized for 32-bit machines. Patented by IBM.
(Software-optimized Encryption
Algorithm)
Blowfish 16-round Feistel block cipher with a 64-bit block size. Key size can be from 32
to 448 bits, and is expanded into a set of subkeys 4168 bytes long.
Designed by Bruce Schneier as a replacement for DES or IDEA.
Twofish Feistel block cipher with a 128-bit block size. Highly configurable.
Designed by Bruce Schneier et al.
Asymmetric ciphers
DSA NIST standard used in the Digital Signature Standard (DSS). Generates a
(Digital Signature Algorithm) 320-bit digital signature. Based on the algebraic properties of modular
exponentiation and the discrete logarithm problem.
RSA Cryptosystem for encryption and authentication. Based on modular arithmetic
(Rivest-Shamir-Adleman) and large prime numbers.
DH Cryptographic protocol for securely establishing a shared secret key over an
(Diffie-Hellman) insecure channel. Based on modular arithmetic, exponentiation, and large
prime numbers.
Strength and algorithm of key exchange are defined by groups:
- group 1 (768 bit)
- group 2 (1024 bit)
- group 5 (1536 bit)
- group 14 (2048 bit)
- group 19 (256 bit, elliptic curve)
- group 20 (384 bit, elliptic curve)
Hash functions
MD2 Takes in input a message which is a multiple of 512 bits (if not, padding is used) and
(Message Digest v2) has a maximum length of 264-1 bits, and generates a 128-bit hash. Supports 8-bit
machines (i.e. word size is 8 bits).
Broken, but still used in digital certificates together with RSA.
MD4 Same properties as MD2. Supports 32-bit machines.
(Message Digest v4) Proven severely insecure, thus obsolete.
MD5 Same properties as MD2. Supports 32-bit machines.
(Message Digest v5) This is the hash function of the MD family currently in use.
SHA-0 Original version of the SHA hash function.
(Secure Hash Algorithm v0) Vulnerable, thus not in use anymore.
SHA-1 Takes in input a message with a maximum length of 264-1 bits, and generates a
(Secure Hash Algorithm v1) 160-bit hash.
Vulnerable and therefore no longer approved for cryptographic use.
SHA-2 Family of hash functions:
(Secure Hash Algorithm v2) SHA-256 (for 32-bit machines, generates a 256-bit hash)
SHA-224 (for 32-bit machines, generates a 224-bit hash, truncated version)
SHA-512 (for 64-bit machines, generates a 512-bit hash)
SHA-384 (for 64-bit machines, generates a 384-bit hash, truncated version)
Max input message length is 2128-1 bits.
SHA-3 Family of hash functions:
(Secure Hash Algorithm v3) SHA3-256 (for 32-bit machines, generates a 256-bit hash)
SHA3-224 (for 32-bit machines, generates a 224-bit hash, truncated version)
SHA3-512 (for 64-bit machines, generates a 512-bit hash)
SHA3-384 (for 64-bit machines, generates a 384-bit hash, truncated version)
SHAKE128 (generates a hash of arbitrary length)
SHAKE256 (generates a hash of arbitrary length)
Max input message length is unlimited.
RIPEMD Family of hash functions:
(RACE Integrity Primitives RIPEMD (generates a 128-bit hash; insecure)
Evaluation Message Digest) RIPEMD-128 (generates a 128-bit hash; insecure)
RIPEMD-160 (generates a 160-bit hash; most commonly used)
RIPEMD-256 (generates a 256-bit hash)
RIPEMD-320 (generates a 320-bit hash)
Authentication systems
HMAC Message Authentication Code used to verify data integrity and sender authentication.
(Hash-based Message Uses a hash function in conjunction with a secret key.
Authentication Code)
PAP Password-based authentication protocol used by Point-to-Point Protocol (PPP) to
(Password authenticate remote clients. Uses a weak authentication scheme, vulnerable to
Authentication Protocol) attacks; passwords are transmitted in plaintext over the network. For this reason, is
not recommended and it is advised to use CHAP or EAP instead.
CHAP Authentication protocol used by Point-to-Point Protocol (PPP) to authenticate remote
(Challenge-Handshake clients. Client identity is verified via a three-way handshake. It uses an
Authentication Protocol) incrementally changing identifier and a variable challenge value in order to thwart
replay attacks.
EAP Authentication framework able to use different authentication systems (passwords,
(Extensible smart tokens, one-time passwords, Secure ID cards, digital certificates, public key
Authentication Protocol) cryptography protocols, etc.) via a challenge-response mechanism.
LEAP Cisco proprietary version of EAP, used for WEP. Uses either the MS-CHAP or the EAP-
(Lightweight Extensible FAST authentication protocol. Vulnerable and not recommended.
Authentication Protocol)
PEAP TLS-encapsulated secured version of EAP, used in WPA2.
(Protected Extensible
Authentication Protocol)
GPG (GNU Privacy Guard) aka GnuPG is a well-known implementation of the OpenPGP standard described in RFC 4880.
The OpenPGP standard derives from PGP (Pretty Good Privacy), the first tool for strong encryption available to the public.
It specifies a suite of algorithms: ElGamal, DSA, Triple DES, SHA-1, RSA, AES-128, CAST-128, IDEA, Camellia, ECC (Elliptic
Curve Cryptography) i.e. ECDSA and ECDH.
LUKS (Linux Unified Key Setup) is a platform-independent specification for the encryption of a block device. It uses
dm-crypt, a transparent disk encryption subsystem which is part of the device mapper, as a backend.
cryptsetup Frontend command for dm-crypt. Will prompt for a passphrase for
most operations on a LUKS-encrypted device
cryptsetup luksFormat device Initialize a LUKS partition, prompting for an encryption passphrase
cryptsetup luksOpen device name Open a LUKS device and set up a mapping name
cryptsetup luksClose name Close a LUKS device and remove the mapping name
cryptsetup luksSuspend name Suspend a LUKS device and wipe the encryption key from memory
cryptsetup luksHeaderBackup device --header-backup-file file Backup header and keyslot areas of a LUKS
device to a file
cryptsetup luksHeaderRestore device --header-backup-file file Restore header and keyslot areas of a LUKS
device from a file
OpenVPN is an open source software that implements a Virtual Private Network (VPN) between two endpoints. The
encrypted VPN tunnel uses UDP port 1194.
openvpn --genkey --secret keyfile Generate a shared secret keyfile for OpenVPN authentication.
The keyfile must be copied on both server and client
dev tun
ifconfig server_IP client_IP
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
secret keyfile
remote server_public_IP
dev tun
ifconfig client_IP server_IP
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
secret keyfile
CTRL ALT E Expand the Bash alias currently entered on the command line
CTRL ALT DEL Send a SIGINT to reboot the machine (same as shutdown -r now),
as specified in /etc/inittab and /etc/init/control-alt-delete
The Hardware Abstraction Layer (HAL) manages device files and provides plug-and-play facilities. The HAL daemon hald
maintains a persistent database of devices.
udev is the device manager for the Linux kernel. It dynamically generates the device nodes in /dev/ for devices present on
the system; it also provides persistent naming for storage devices in /dev/disk.
When a device is added, removed, or changes state, the kernel sends an uevent received by the udevd daemon which will
pass the uevent through a set of rules stored in /etc/udev/rules.d/*.rules and /lib/udev/rules.d/*.rules.
freeramdisk Free the memory used for the initrd image. This command
must be run directly after unmounting /initrd
mkinitrd initrd_image kernel_version (Red Hat) Create an initrd image file
mkinitramfs (Debian)
dracut Create initial ramdisk images for preloading modules
kexec -l kernel_image --append=options \ Load a kernel image file into memory and boot it. This allows
--initrd=initrd_image && kexec -e running a different kernel without rebooting the machine
The runtime loader ld.so loads the required shared libraries of the program into RAM, searching in this order:
1. LD_LIBRARY_PATH Environment variable specifying the list of dirs where libraries should be searched for first
2. /etc/ld.so.cache Cache file
3. /lib and /usr/lib Default locations for shared libraries
Shared library locations (other than the default ones /lib and /usr/lib) can be specified in the file /etc/ld.so.conf.
uname Print system information. Options to show the relevant piece of information are:
-s Kernel name
-n Network node hostname
-r Kernel release number X.Y.Z
-v Kernel version number
-m Machine hardware name
-p Processor type
-i Hardware platform
-o Operating system
-a All the above information, in that order
journalctl Display the Systemd journal, which contains the kernel logs
journalctl -n n Display the most recent n log lines (default is 10)
journalctl --since "1 hour ago" Display events happened in the last hour
journalctl -x Display events, adding explanations from the message catalog
journalctl -f Display the journal in real-time
journalctl -u crond.service Display the log entries created by the cron service
journalctl _SYSTEMD_UNIT=crond.service
mkdir -p /var/log/journal/ && \ Enable persistent storage of logs in /var/log/journal/
systemctl restart systemd-journald (by default, journalctl stores the logfiles in RAM only)
Kernel compile
Download the kernel source code linux-X.Y.Z.tar.bz2 from http://www.kernel.org
Download
to the base of the kernel source tree /usr/src/linux
make clean Delete most generated files
Clean make mrproper Delete all generated files and kernel configuration
make distclean Delete temporary files, patch leftovers, and similar files
make oldconfig Create a new configuration file, based on the options in the old
configuration file and in the source code
Configure
Components (e.g. device drivers) can be either:
- not compiled
- compiled into the kernel binary, for support of devices always used on the system or necessary for
the system to boot
- compiled as a kernel module, for optional devices
Modules install make modules_install Install the previously built modules present in /lib/modules/X.Y.Z
make install Install the kernel automatically
To install the kernel by hand:
1. Copy the new compiled kernel and other files into the boot partition:
Kernel install cp /usr/src/linux/arch/boot/bzImage /boot/vmlinuz-X.Y.Z (kernel)
cp /usr/src/linux/arch/boot/System.map-X.Y.Z /boot
cp /usr/src/linux/arch/boot/config-X.Y.Z /boot (config options used for this compile)
Kernel patching
Download Download and decompress the patch to /usr/src
patch -p1 < file.patch Apply the patch
Patch Remove (reverse) a patch.
patch -Rp1 < file.patch
Alternatively, applying the patch again reverses it
Build Build the patched kernel as explained above
Install Install the patched kernel as explained above
Kernel modules allow the kernel to access functions (symbols) for kernel services e.g. hardware drivers, network stack, or
filesystem abstraction.
lsmod List the modules that are currently loaded into the kernel
insmod module Insert a module into the kernel. If the module requires another module or if it does
not detect compatible hardware, insertion will fail
rmmod module Remove a module from the kernel. If the module is in use by another module, it is
necessary to remove the latter module first
depmod -a Probe all modules in the kernel modules directory and generate the file that lists
their dependencies
modprobe module option=value Insert a module into the running kernel, with the specified parameters.
Prerequisite modules will be inserted automatically
modprobe -a Insert all modules
modprobe -t directory Attempt to load all modules contained in the directory until a module succeeds.
This action probes the hardware by successive module-insertion attempts for a single
type of hardware, e.g. a network adapter
modprobe -r module Remove a module
modprobe -c module Display module configuration
modprobe -l List loaded modules
It is recommended to use modprobe instead of insmod and rmmod, because modprobe automatically handles prerequisites
when inserting modules, is more specific about errors, and accepts just the module name alone instead of requiring the full
pathname.
Device driver compiled Configure the device driver by passing a kernel parameter in the GRUB menu:
into the kernel kernel /vmlinuz ro root=/dev/vg0/root vga=0x33c
/proc is a pseudo filesystem that gives access to process data held in the kernel.
/proc/sys is the only writable branch of /proc and can be used to tune kernel parameters on the fly.
All changes are lost after system shutdown, unless applied via sysctl -p.
/dev contains the device files to access all devices in the system.
File Device
/dev/sda SCSI, PATA, or SATA hard drive
/dev/hda IDE hard drive
/dev/pda Parallel port IDE hard drive
/dev/vda Virtual disk for KVM-based virtual machines
/dev/sda, /dev/sdb, /dev/sdc ... First, second, third ... hard drive
/dev/sda1, /dev/sda2, /dev/sda3 ... First, second, third ... partition of the first hard drive
/dev/md0 Metadisk group, for use with RAID
/dev/sr0 SCSI CD-ROM
/dev/pcd0 Parallel port CD-ROM
/dev/cdrom CD-ROM. Usually symlinked to /dev/sr0
/dev/fd0 Floppy disk drive
/dev/ht0 IDE tape drive
/dev/pt0 Parallel port tape drive
/dev/sg0 Generic SCSI device
/dev/loop0 Loopback device
/dev/autofs AutoFS device
/dev/fuse FUSE device
/dev/dsp Digital Signal Processor device. Interfaces with the soundcard
/dev/fb0 Framebuffer device. Interfaces with the graphics hardware
/dev/lp0 Parallel port printer device
/dev/parport0 Raw parallel port device
/dev/mem Physical memory
/dev/kmem Kernel virtual memory
/dev/core Obsolete. Symlink to /proc/kcore
/dev/stdin Standard Input
/dev/stdout Standard Output
/dev/stderr Standard Error
/dev/null Null device, aka blackhole or bit bucket. Discards any received data
/dev/zero Zero device. Outputs an infinite stream of zero bytes (NUL) on reads
/dev/full "Always full" device. Similar to /dev/zero, and also returns an error "No
space left on device" (ENOSPC) on writes
/dev/random Non-deterministic random number generator. Gathers entropy from the
system to generate randomness; once the entropy pool is depleted, the
device blocks all reads until it can collect more entropy
/dev/urandom Pseudo random number generator. Faster but unsafe for cryptographic
purposes
/dev/console System console
/dev/tty Terminal for current process
/dev/tty0 Current virtual console
/dev/ttyS0 Serial port, usually used for modem connections
/dev/ptyp0 Pseudo-TTY master
/dev/ttyp0 Pseudo-TTY slave
If the kernel has been booted in emergency mode and init has not been run, some initial configuration is necessary e.g.
mount /proc
mount -o remount,rw /
mount -a
mknod /dev/sda
mknod /dev/sda1
fdisk -l /dev/sda
fsck -y /dev/sda1
mount -t ext3 /dev/sda1 /mnt/sysimage
chroot /mnt/sysimage
To install a package using an alternative root directory (useful if the system has been booted from a removable media):
Alternative method:
chroot /mnt/sysimage
grub-install /dev/sda
Run sync and unmount all filesystems before exiting the shell, to ensure that all changes have been written on disk.
3. Press CTRL X ; the system will boot on the initramfs switch_root prompt
8. Remount the filesystem as readonly (not strictly necessary) mount -o remount,ro /sysroot
Domain Name System (DNS) is a decentralized hierarchical naming system, mostly used to resolve domain names to IP
addresses. It uses TCP and UDP port 53.
DNS implementations
BIND Berkeley Internet Name Domain system, is the standard DNS server for UNIX
Unbound Standard DNS server in RHEL 7
dnsmasq Lightweight DNS, DHCP and TFTP server for a small network
djbdns Security-hardened DNS server that also includes DNS debugging tools
PowerDNS Alternative open-source DNS server
named -u named -g named Run BIND as user/group "named" (must be created if needed) instead of root
named -t /var/cache/bind Run BIND in a chroot jail /var/cache/bind
(actually it is the chroot command that starts the named server)
DNSSEC was designed to secure the DNS tree and hence prevent cache poisoning.
The TSIG (Transaction SIGnature) standard, which authenticates communications between two trusted systems, is used to
sign zone transfers and DDNS (Dynamic DNS) updates.
dnssec-keygen -a dsa -b 1024 \ Generate a TSIG key with DNSSEC algorithm nnn and key fingerprint fffff.
-n HOST dns1.example.org This will create two key files
Kdns1.example.org.+nnn+fffff.key
Kdns1.example.org.+nnn+fffff.private
which contain a key number that must be inserted both in /etc/named.conf and
/etc/rndc.conf
key "rndc-key" {
algorithm hmac-md5;
secret "vyZqL3tPHsqnA57e4LT0Ek==";
};
options {
default-key "rndc-key";
default-server 127.0.0.1;
default-port 953;
};
options {
directory "/var/named"; // Working directory
version "0.0"; // Hide version number by replacing it with 0.0
listen-on port 53 {10.7.0.1; 127.0.0.1;}; // Port and own IP addresses to listen on
blackhole {172.17.17.0/24;}; // IPs whose packets are to be ignored
allow-query {mynetwork;}; // IPs allowed to make iterative queries
allow-query-on {any;}; // Local IPs that can accept iterative queries
allow-query-cache {any;}; // IPs that can get an answer from cache
allow-recursion {mynetwork;}; // IPs to accept recursive queries from (typically
// own network's IPs). The DNS server does the full
// resolution process on behalf of these client IPs,
// and returns a referral for the other IPs
allow-recursion-on {mynetwork;}; // Local IPs that can accept recursive queries
allow-transfer {10.7.0.254;}; // Zone transfer is restricted to these IPs (slaves);
// on slave servers, this option should be disabled
allow-update {any;}; // IPs to accept DDNS updates from
recursive-clients 1000; // Max number of simultaneous recursive lookups
dnssec-enable yes; // Enable DNSSEC
dialup no; // Not a dialup connection: external zone maintenance
// (e.g. sending heartbeat packets, external zone transfers)
// is then permitted
forward first; // Site-wide cache: bypass the normal resolution
forwarders {10.7.0.252; 10.7.0.253;}; // method by querying first these central DNS
// servers if they are available
};
IN NS dns1.example.org.
IN NS dns2.example.org.
IN MX 10 mail1.example.org.
IN MX 20 mail2.example.org.
dns1 IN A 224.123.240.3
dns2 IN A 224.123.240.4
mail1 IN A 224.123.240.73
mail2 IN A 224.123.240.77
foo IN A 224.123.240.12
bar IN A 224.123.240.13
www IN A 224.123.240.19
baz IN CNAME bar
Resource Records
$TTL How long to cache a positive response
$ORIGIN Suffix appended to all names not ending with a dot.
Useful when defining multiple subdomains inside the same zone
SOA Start Of Authority for the example.org zone
serial Serial number. Must be increased after each edit of the zone file
refresh How frequently a slave server refreshes its copy of zone data from the master
retry How frequently a slave server retries connecting to the master
expire How long a slave server relies on its copy of zone data. After this time period expires,
the slave server is not authoritative anymore for the zone unless it can contact a master
negative TTL How long to cache a non-existent answer
A Address: maps names to IP addresses. Used for DNS lookups.
PTR Pointer: maps IP addresses to names. Used for reverse DNS lookups.
Each A record must have a matching PTR record
CNAME Canonical Name: specifies an alias for a host with an A record (even in a different zone).
Discouraged as it causes multiple lookups; it is better to use multiple A records instead
NS Name Service: specifies the authoritative name servers for the zone
MX Mailserver: specifies address and priority of the servers able to handle mail for the zone
Glue Records are not really part of the zone; they delegate authority for other zones, usually subdomains
Apache is an open source and widespread HTTP server, originally based on the NCSA HTTPd server.
/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/*.conf (Red Hat)
Apache configuration files
/etc/apache2/httpd.conf (Debian and SUSE)
The Apache webserver contains a number of MPMs (Multi-Processing Modules) which can operate following two methods:
prefork MPM A number of child processes is spawned in advance, with each child serving one connection.
Highly reliable due to Linux memory protection that isolates each child process.
worker MPM Multiple child processes spawn multiple threads, with each thread serving one connection.
More scalable but prone to deadlocks if third-party non-threadsafe modules are loaded.
HTTPS
HTTPS (i.e. HTTP over SSL/TLS) allows securing communications between the webserver and the client by encrypting
all communications end-to-end between the two. A webserver using HTTPS hands over its public key to the client
when the client connects to the server via port 443. The server's public key is signed by a CA (Certification
Authority), whose validity is ensured by the root certificates stored into the client's browser.
The openssl command and its user-friendly CA.pl script are the tools of the OpenSSL cryptographic library that can
be used to accomplish all public key crypto operations e.g. generate key pairs, Certificate Signing Requests, and self-
signed certificates. Another user-friendly tool is genkey.
Virtual hosting with HTTPS requires assigning a unique IP address for each virtual host; this because the SSL
handshake (during which the server sends its certificate to the client's browser) takes place before the client sends
the Host: header (which tells to which virtual host the client wants to talk).
A workaround for this is SNI (Server Name Indication) which makes the browser send the hostname in the first
message of the SSL handshake. Another workaround is to have all multiple name-based virtual hosts use the same
SSL certificate with a wildcard domain e.g. *.example.org.
MaxClients 256 (before v2.3.13) Max number of simultaneous requests that will be served; clients
MaxRequestWorkers 256 (v2.3.13 and later) above this limit will get an HTTP error 503 - Service Unavailable.
Prefork MPM: max number of child processes launched to serve
requests.
Worker MPM: max total number of threads available to serve
requests
ServerLimit 256 Prefork MPM: max configured value for MaxRequestWorkers.
Worker MPM: in conjunction with ThreadLimit, max configured
value for MaxRequestWorkers
ThreadsPerChild 25 Worker MPM: number of threads created by each child process
ThreadLimit 64 Worker MPM: max configured value for ThreadsPerChild
Logging directives
LogFormat "%h %l %u %t \"%r\" %>s %b" Specify the format of a log
LogFormat "%h %l %u %t \"%r\" %>s %b" common Specify a nickname for a log format.
In this case, specifies "common" for the CLF (Common Log Format)
which is defined as such:
%h IP address of the client host
%l Identity of client as determined by identd
%u User ID of client making the request
%t Timestamp the server completed the request
%r Request as done by the user
%s Status code sent by the server to the client
%b Size of the object returned, in bytes
CustomLog /var/log/httpd/access_log common Set up a log filename, with the format or (as in this case) the
nickname specified
TransferLog /var/log/httpd/access_log Set up a log filename, with format determined by the most recent
LogFormat directive which did not define a nickname
TransferLog "|rotatelogs access_log 86400" Set log rotation every 24 hours
HostnameLookups Off Disable DNS hostname lookup to save network traffic.
Hostnames can be resolved later by processing the log file:
logresolve <access_log >accessdns_log
Order Allow,Deny (deprecated) Control the evaluation order of Allow and Deny directives.
webserver
10.2.2.73:8080
webserver
LAN Apache
10.2.2.73:8080 Internet
10.1.1.0/24 forward proxy
A forward proxy provides proxy services, typically web content caching and/or filtering, for clients located in a LAN.
All outgoing requests from the clients, and the responses from the Internet, pass through the proxy.
The clients must be manually configured (e.g. in the browser's connection settings) to use the proxy.
Apache configuration file
Forward proxy
ProxyRequests On Enable forward proxy requests
ProxyVia On Add a Via: HTTP header line to every request and reply
<Proxy "*"> Serve only proxy requests coming from 10.1.1.0/24
Require ip 10.1.1
</Proxy>
http://site.example.com
webserver Apache https://site.example.com
10.2.2.73:8080 Internet
reverse proxy
A reverse proxy aka gateway allows to expose a single entry point for one or more webservers in a LAN. This improves
security and simplifies management, as features (e.g. load balancing, firewalling, automatic redirection from HTTP to HTTPS,
redirection on default ports) can be configured centrally.
It is necessary to create a DNS A record that maps site.example.com to the public IP address of the proxy.
Apache configuration file
Reverse proxy
<VirtualHost *:80> Virtual host for HTTP
ServerName site.example.com Define website name
RewriteEngine On Redirect all HTTP requests to HTTPS
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Alternatively:
Apache Tomcat is an open source Java Servlet Container implementing several Java EE specifications, originally part of the
Jakarta Project. It is composed of:
- Catalina, the core component and servlet container implementation;
- Coyote, an HTTP connector component, providing a pure Java webserver environment to run Java code;
- Jasper, a JSP (Java Server Pages) engine, which parses JSP files and compiles them into Java servlets.
Tomcat has been removed from RHEL 8; instead, it is suggested to use the JBoss Enterprise Application Platform, which
includes Apache and Tomcat.
Samba is a free-software, cross-platform implementation of SMB/CIFS. SMB (Server Message Block) is a Microsoft
proprietary protocol for file and printer sharing, while CIFS (Common Internet File System) is the public version of SMB.
smbd Server Message Block daemon. Provides SMB file and printer sharing, browser services, user authentication,
and resource lock. An extra copy of this daemon runs for each client connected to the server
nmbd NetBIOS Name Service daemon. Handles NetBIOS name lookups, WINS requests, list browsing and elections.
An extra copy of this daemon runs if Samba functions as a WINS server; another extra copy of this daemon
runs if DNS is used to translate NetBIOS names.
WINS (Windows Internet Name Service) is a name service used to translate NetBIOS names to IP addresses
testparm Check the Samba configuration file and report any error
cat msg.txt | smbclient -M client -U user Show a message popup on the client machine, using the
WinPopup protocol
User-level authentication
[global]
security = user Set up user-level authentication
guest account = nobody Map the guest account to the system user nobody (default)
map to guest = Never Specify how incoming requests are mapped to the guest account:
Bad User redirect from an invalid user to guest account on server
Bad Password redirect from an invalid password to guest account on server
Never reject unauthenticated users
Server-level authentication
[global]
security = server Set up server-level authentication
password server = srv1 srv2 Authenticate to server srv1, or to server srv2 if the first one is unavailable
Domain-level authentication
[global]
security = ADS Set up domain-level authentication as an Active Directory member server
realm = KRB_REALM Join the specified realm.
Kerberos must be installed and an administrator account must be created:
net ads join -U Administrator%password
Share-level authentication
[global]
security = share Set up share-level authentication
[foobar] Define a "foobar" share accessible to any user which can supply user's password.
path = /foobar The user must be created on the system:
username = user useradd -c "Foobar account" -d /tmp -m -s /sbin/nologin user
only user = yes
and added to the Samba password file:
smbpasswd -a user
Samba macros
%S Username These macros are applied only to configuration options
used once a connection has been established:
%U Session username i.e. the username that the client
requested, not necessarily the same as the one the
client obtained
%G Primary group of session username %S Name of the current service, if any
%h Samba server hostname %P Root directory of the current service, if any
%M Client hostname %u Username of the current service, if any
%L NetBIOS name of the server %g Primary group name of username
%m NetBIOS name of the client %H Home directory of username
%d Process ID of the current server process %N Name of the NIS home directory server as
obtained from the NIS auto.map entry.
%a Architecture of remote machine
Same as %L if Samba was not compiled with the
%I IP address of client machine --with-automount option
%i Local IP address to which a client connected %p Path of service's home directory as obtained from
the NIS auto.map entry.
%T Current date and time
The NIS auto.map entry is split up as %N:%p
%D Domain or workgroup of the current user
%w Winbind separator
%$(var) Value of the environment variable var
Samba setup
This procedure allows sharing on read-write the local directory /smbshare on server 10.1.1.1 to client 10.2.2.2.
Server setup:
1. Create the group for write access to the share groupadd -r geeks
2. Create the user and assign it to the group useradd -G geeks jdoe
6. Set the correct SELinux label to the share semanage fcontext -a -t samba_share_t '/smbshare'
restorecon -FR /smbshare
[smbshare]
path = /smbshare
hosts allow = 10.2.2.2
write list = @geeks
Client setup:
1. Add an entry to /etc/fstab to mount the Samba share device automatically:
A Network File System (NFS) server makes filesystems available to remote clients for mounting.
NFS requires the portmapper to map incoming TCP/IP connections to the appropriate NFS RPC calls. Some Linux
distributions use rpcbind instead of the portmapper.
For security reasons, the TCP Wrapper should be configured to limit access to the portmapper to NFS clients only:
file /etc/hosts.deny should contain portmap: ALL
file /etc/hosts.allow should contain portmap: IP_addresses_of_clients
NFS handles user permissions across systems by considering users with same UID and username as the same user.
Group permission is evaluated similarly, by GID and groupname.
mount -t nfs nfsserver:/share /usr Command to be run on a client to mount locally a remote NFS share.
NFS shares accessed frequently should be added to /etc/fstab e.g.
nfsserver:/share /usr nfs intr 0 0
showmount Show the remote client hosts currently having active mounts
showmount --directories Show the directories currently mounted by a remote client host
showmount --exports Show the filesystems currently exported i.e. the active export list
showmount --all Show both remote client hosts and directories
showmount -e nfsserver Show the shares a NFS server has available for mounting
rpcinfo -p nfsserver Probe the portmapper on a NFS server and display the list of all registered
RPC services there
rpcinfo -t nfsserver nfs Test a NFS connection by sending a null pseudo request (using TCP)
rpcinfo -u nfsserver nfs Test a NFS connection by sending a null pseudo request (using UDP)
both -n -r -nr
NFS setup
This procedure allows sharing on read-write the local directory /nfsshare on server 10.1.1.1 to client 10.2.2.2.
Server setup:
1. Ensure that the nfs-server service is running
2. Change ownership of the share chown nfsnobody /nfsshare
/nfsshare 10.2.2.2(rw)
4. Reload the exports file exportfs -r
Client setup:
1. Add an entry to /etc/fstab to mount the NFS share device automatically:
/nfsshare 10.2.2.2(sec=krb5p,rw)
5. Reload the exports file exportfs -r
Client setup:
1. Install the appropriate client keytab on /etc/krb5.keytab
2. Ensure that the nfs-secure service is running
iSCSI (Internet Small Computer System Interface) is a network protocol that allows emulating an SCSI local storage device
over a TCP/IP network. By default it uses TCP port 3260.
An iSCSI server can use a local block device (physical or virtual disk, disk partition, or Logical Volume), a file, a physical
SCSI device, or a ramdisk as the underlying storage resource (backstore) and make it available by assigning it a LUN
(Logical Unit Number). An iSCSI server provides one or more targets, each of which presents one or more LUNs and is able
to accept connections from an iSCSI client (initiator).
Targets and initiators are called nodes and are identified by a unique IQN (iSCSI Qualified Name) e.g.
iqn.2017-11.org.example.subdomain:foo:bar. The IP address and port of a node is called a portal.
A target accepts connections from an initiator via a TPG (Target Portal Group) i.e. its IP address and port. A TPG may have
in place an ACL so to accept connections only from a specific initiator's IQN.
targetcli Target configurator (server side). Can be used as a command line tool or as an interactive shell.
Configuration is saved to /etc/target/saveconfig.json
iSCSI setup
This procedure makes available the local disk /dev/sbd on server 10.1.1.1 to the client having IQN
iqn.2017-11.org.example:client.
InitiatorName=iqn.2017-11.org.example:client
The iSCSI device is now locally available and can be formatted and mounted. Node records remain after logout or
reboot; the system will login again to the target IQN automatically
5. Add an entry to /etc/fstab to mount the iSCSI device automatically:
DHCP (Dynamic Host Configuration Protocol) is a protocol for network management that automatically provides a requesting
host with an IP address and other network configuration parameters. It is based on BOOTP (Bootstrap Protocol).
A DHCP server listens for requests on UDP port 67 and answers to UDP port 68. The assignment of an IP address to a host
is done through a sequence of DHCP messages initiated by the client host, which is (for DHCPv4): DHCP Discover, DHCP
Offer, DHCP Request, and then DHCP ACK.
Because DHCP Discover messages are broadcast and therefore not routed outside a LAN, a DHCP relay agent is necessary
for those clients situated outside the DHCP server's LAN. The DHCP relay agent listens to DHCP Discover messages and
relays them in unicast to the DHCP server.
}
group { Definition of a group
option routers 10.0.17.252;
option broadcast-address 10.0.17.255;
netmask 255.255.255.0;
host linuxbox1 { Definition of different hosts to whom static IP addresses
hardware ethernet AA:BB:CC:DD:EE:FF; will be assigned to, depending on their MAC address
fixed-address 10.0.17.42;
option host-name "linuxbox1";
}
host linuxbox2 {
hardware ethernet 33:44:55:66:77:88;
fixed-address 10.0.17.66;
option host-name "linuxbox2";
}
PAM (Pluggable Authentication Modules) is an abstraction layer that allows applications to use authentication methods while
being implementation-agnostic.
/etc/pam.d/service
auth requisite pam_securetty.so
auth required pam_nologin.so
auth required pam_env.so
auth required pam_unix.so nullok
account required pam_unix.so
session required pam_unix.so
session optional pam_lastlog.so
password required pam_unix.so nullok obscure min=4 max=8
auth Authentication module to verify user identity and group membership
account Authorization module to determine user's right to access a resource (other than their identity)
type
password Module to update a user's authentication credentials
session Module (run at end and beginning of a user session) to set up the user environment
optional Module is not critical to the success or failure of service
sufficient If this module successes, and no previous module has failed, module stack processing ends
successfully. If this module fails, it is non-fatal and processing of the stack continues
control required If this module fails, processing of the stack continues until the end, and service fails
requisite If this module fails, service fails and control returns to the application that invoked service
include Include modules from another PAM service file
PAM module and its options, e.g.:
pam_unix.so Standard UNIX authentication module via /etc/passwd and /etc/shadow
pam_nis.so Module for authentication via NIS
pam_ldap.so Module for authentication via LDAP
module
pam_fshadow.so Module for authentication against an alternative shadow passwords file
pam_cracklib.so Module for password strength policies (e.g. length, case, max number of retries)
pam_limits.so Module for system policies and system resource usage limits
pam_listfile.so Module to deny or allow the service based on an arbitrary text file
LDAP (Lightweight Directory Access Protocol) is a simplified version of the X.500 standard and uses TCP port 389.
LDAP allows organizing hierarchically a database of entries, each one of which is identified by a unique DN (Distinguished
Name). Each DN has a set of attributes, and each attribute has a value; an attribute may appear multiple times.
Special attributes called objectClass define which attributes are allowed and which are required, and determine the
schema of the LDAP.
All the LDAP commands below accept the following arguments, plus some extra arguments which are command-dependent.
-H ldap://srv Connect to the specified LDAP server
-H ldapi:// Connect to the localhost LDAP server using IPC instead of a network socket
-D binddn Bind (authenticate) to the LDAP server as the specified DN
-w password Authenticate with the specified password
-W Prompt for authentication
-x Use simple authentication instead of SASL
-v Use verbose mode for output
ldapsearch args Query an LDAP server and return the output in LDIF
-b base Start searching from base
-z n Retrieve at maximum n entries as result
-LLL Terse output. Outputs the result in LDIFv1, does not print comments, and
omits the LDIF version number
filter Search filter. If not specified, uses the default filter (objectClass=*)
attributes Attributes to return. If not specified, returns all attributes
ldapsearch -H ldap://ldap.example.org -s base \ Query a LDAP server for entries in the OU "people"
-b "ou=people,dc=example,dc=com" "(sn=Doe)" \ whose surname is "Doe"; print common name,
cn sn telephoneNumber surname, and telephone number of the entries found
ldapmodify -b -r -f file.ldif Modify an entry according to the LDIF file specified
ldapadd -h ldap.example.org \ Authenticating as "Admin", add an entry by adding
-D "cn=Admin,dc=example,dc=org" -W -f file.ldif the content of the specified LDIF file to the directory
ldapdelete -h ldap.example.org \ Authenticating as "Admin", delete the user "jdoe"
-D "cn=Admin,dc=example,dc=org" -W \
"uid=jdoe,dc=example,dc=org"
ldappasswd -h ldap.example.org \ Authenticating as "Admin" on example.org, change
-D "cn=Admin,dc=example,dc=org" -W -x \ the password of user "jdoe" in the OU "IT Dept"
-S "uid=jdoe,ou=IT Dept,dc=example,dc=org"
OpenLDAP is an open source implementation of LDAP, and was initially developed together with the LDAP protocol. Its
related service is slapd, the Standalone OpenLDAP daemon.
sssd, the System Security Services Daemon, can be used to provide access to OpenLDAP as an authentication and identity
provider.
getent group groupname Get entries about groupname from NSS libraries
Security-Enhanced Linux (SELinux) is a Linux kernel security module that provides a mechanism for supporting access
control security policies.
SELinux implements a Mandatory Access Control framework that allows the definition of fine-grained permissions for how
subjects (i.e. processes) access objects (i.e. other processes, files, devices, ports, sockets); this improves security with
respect to the traditional Discretionary Access Control, which defines accesses based on users and groups.
Processes, files, and users have a security context structured as user:role:type:level e.g.
unconfined_u:object_r:user_home_t:s0. The third field defines a type for files or a domain for processes.
The decisions SELinux takes about allowing or disallowing access are stored in the AVC (Access Vector Cache).
SELinux creates a pseudo filesystem (SELinuxfs) containing commands used by the kernel for its operations; this filesystem
is usually mounted on /selinux/ or /sys/fs/selinux/.
tar --selinux otherargs Create or extract archives that retain the security context of the original files
star -xattr -H=exustar otherargs
semanage port -l List port numbers and their assigned SELinux type
definitions
semanage port -a -t portlabel -p tcp n Assign the SELinux portlabel to TCP port n
semanage port -a -t http_port_t -p tcp 8888 Allow a local webserver to serve content on port 8888
semanage port -d -t http_port_t -p tcp 8888 Remove the binding of http_port_t port label to TCP 8888
semanage port -m -t http_cache_port_t -p tcp 8888 Modify the port label bound to TCP 8888
chcon context file Change the security context of file to the specified context
chcon --reference=file0 file Change the security context of file to be the same as file0
restorecon -f file Restore the security context of file to the system default
/root/anaconda-ks.cfg Kickstart file describing the current system. This file is automatically generated
during the installation
ksverdiff -f RHEL6 -t RHEL7 Show the differences in the Kickstart syntax between RHEL 6 and RHEL 7
Red Hat Satellite is a system management software platform that allows provisioning and configuration of RHEL machines.
Repository content is provided via Red Hat Subscription Management (RHSM).
Satellite 5 was based on Spacewalk, an open source system management software for Linux machines. Satellite 6 is a
complete overhaul of it and is composed of:
- Foreman, an open source lifecycle management tool able to provision servers via Kickstart and Puppet;
- Katello, a tool that handles Red Hat repository management (via the Pulp service) and subscription management (via the
Candlepin service).
All these components above need a PostgreSQL database, except Pulp which needs a MongoDB database.
As a separate component, Capsule servers act as a proxy for many of the main Satellite functions e.g. repository storage.
A Capsule is also integrated in each Satellite server.
virt-who Agent for scanning and reporting virtual guest IDs and hypervisors to a Satellite
server
foreman-debug Collect Satellite configuration, log, and backend data for debug purposes
sosreport Collect diagnostic and configuration data for technical support
citellus.py sosreportfile Perform some automated checks for troubleshooting a system
KVM (Kernel-based Virtual Machine) is a virtualization infrastructure for the Linux kernel that allows it to function as a
hypervisor.
/etc/libvirt/qemu/ Directory containing the XML files that define VMs properties.
libvirtd must be restarted after modifying an XML file
/var/lib/libvirt/ Directory containing files related to the VMs
Git is an open source version control system with a small footprint and very high performances. A Git directory is a
complete repository with full history and version tracking abilities, independent of any remote repository.
Git commits are identified by a 40-hex-digits hash number, usually shortened to 7 digits, or even less if unambiguous.
git pull Pull the changes from the remote repository branch to the local branch
git add file Add file to the staging area (i.e. content staged for the next commit), hence
starting to track it
git add . Add all modified files to the staging area
git rm file Remove file from the content staged for the next commit
git status See the status (e.g. files changed but not yet staged) of the current branch
git commit -m "Message" Commit all staged files in the current branch
git commit -am "Message" Add all changed files to the staging area in the current branch, and commit them
git merge branch Merge changes made on branch to the master branch
git push Push the local commits from the current branch to the remote repository
git push origin branch Push the local commits from branch to the remote repository
git log --all -- file Show the commits which involved file, across all branches
git log -p --all -S 'string' Show the commits whose added or deleted lines contain a specific word
git log -p --all -G 'regex'
git grep string `git show-ref --heads` Search for string across all branches' heads (i.e. in the latest content only,
and not in all the previous commits)
git config --list Get all currently set options and their values in the Git configuration
git config option Get the value of option
Vagrant is an open source software that allows building and maintaining lightweight and portable virtual environments for
software development. It relies on an underlying virtualization solution e.g. VirtualBox.
vagrant init hashicorp/precise64 Initialize the current directory as a specific Vagrant environment (in this case,
Ubuntu 12.04 64-bit) by creating a Vagrantfile on it
vagrant up vmname Start a guest virtual machine and do a first provisioning according to the
Vagrantfile
vagrant destroy vmname Delete the virtual machine and free any resource allocated to it
vagrant status Print the status of the virtual machines currently managed by Vagrant
vagrant global-status Print the status of all Vagrant environments on the system, by reading cached
data. Completes quickly but results may be outdated
vagrant global-status --prune Print the status of all Vagrant environments on the system, after rebuilding
the environment information cache. Results are always correct but completion
takes longer
The directory containing the Vagrantfile on the host can be accessed on the guest via /vagrant.
Puppet is a software configuration management tool. It is based on a client-server architecture, where a Puppet agent
(client, running as root on each managed node) periodically gathers information (facts) about the local node state via the
Facter tool, then communicates this information to the Puppet master (server, running as the puppet user and listening
on TCP port 8140). The Puppet master then sends back to the Puppet agent a catalog containing the desired configuration
for that node. The Puppet agent applies the needed changes so that the node's configuration converges with the desired
configuration, and sends back a report to the Puppet master. Puppet changes are idempotent.
Puppet configurations are based on resources (e.g. "package", "service", "file", "user" ...). For each resource, a list of
attributes is specified, with the desired value for each attribute.
Each resource type is implemented through providers (e.g. yum, rpm, apt, opkg ... for the resource "package").
Resources managed together as a single unit can be grouped into classes; classes are contained in manifests which are
files with the .pp extension.
Modules are directories containing self-contained pieces of configuration and classes for a specific complex setting, e.g. an
Apache webserver or a MySQL server.
Ansible is an open source tool (provided by Red Hat) for configuration management, software provisioning, and application
deployment. It is agentless and connects to the managed machines via SSH pubkey authentication, requiring only OpenSSH
and Python to be installed on the managed nodes.
The configuration for a managed node is specified in a playbook, written in YAML. A playbook contains one or more plays
to be run in sequence, each of which lists a number of small specific tasks to be run in sequence. Each task calls a
module, which describes the desired state of the system and executes the operation to do so (e.g. start the Apache server,
copy a file, verify that a package is installed, rename a database table). A module should be idempotent i.e. it should set
the system always in the same state regardless of how many times it is run.
Handlers are tasks that are run only via a notification system, when a change is made on a machine.
The inventory lists and categorizes all hosts on which tasks have to be executed. It is also possible to define roles to
categorize hosts and automatically load variables, tasks, handlers, and other artifacts pertaining to that role.
When a playbook is run, first it collects system and environment information (facts) which is then stored in multiple
variables named ansible_varname.
Ansible uses the Jinja template engine to enable access to tests, filters, variables, and dynamic execution.
Also available is a set of plugins that expand Ansible's core functionalities.
Ansible Tower is a web console for user-friendly configuration and management of Ansible elements, and includes web
services and a REST API.
ansible hosts -m module -a options Run the module with the specific options on the hosts
ansible hosts -m ansible.builtin.copy \ Copy a file to the hosts
-a "src=/path/to/file dest=/tmp/"
ansible hosts -m ansible.builtin.yum \ Ensure that hosts have the httpd package installed and updated to
-a "name=httpd state=latest" the latest version
ansible hosts -a "/sbin/shutdown" Shutdown the hosts
ansible all -m ping Ping all hosts in the inventory (by executing the "ping" module)
ansible all -m ansible.builtin.setup Show all facts
ansible-pull Pull a remote copy of Ansible on each managed node and download
the playbooks from a source repository. This inverts the default push
architecture of Ansible into a pull architecture
Main playbook
lamp.yml
Playbook that deploys the whole LAMP stack on the site
---
- name: Apply common configuration to all nodes
hosts: all
remote_user: root
roles:
- common
roles:
- web
roles:
- db
Role: common
roles/common/handlers/main.yml roles/common/tasks/main.yml roles/common/templates/ntp.conf.j2
Handler for general notifications, General play run on all nodes Jinja template for NTP configuration file
called from other plays
Role: db
roles/db/handlers/main.yml roles/db/tasks/main.yml
Handler for DB tier notifications Install MySQL, then create database and database user
--- ---
- name: Restart MySQL - name: Install the MySQL package
service: yum:
name: mysqld name: "{{ item }}"
state: restarted state: installed
with_items:
- name: Restart iptables - mysql-server
service: - MySQL-python
name: iptables
state: restarted - name: Configure MySQL
template:
src: my.cnf.j2
dest: /etc/my.cnf
notify: Restart MySQL
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
symbolic-links=0
port={{ mysql_port }}
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
Role: web
roles/web/handlers/main.yml roles/web/tasks/main.yml Main task, calls the other two playbooks
Handler for web tier notifications
---
--- - include: install_httpd.yml
- name: Restart iptables - include: copy_website.yml
service:
name: iptables roles/web/tasks/copy_website.yml Copy the code from the git repository
state: restarted
---
- name: Copy website from repo
git:
repo: "{{ repository }}"
dest: /var/www/html/
---
- name: Install httpd packages
yum:
name: "{{ item }}"
state: present
with_items:
- httpd
- php
- php-mysql
- git
<html>
<head>
<title>LAMP stack and website deployed via Ansible</title>
</head>
<body>
<a href=http://{{ ansible_default_ipv4.address }}/index.html>Homepage</a></br>
<?php
echo "Hostname: " . exec('hostname') . "</br>";
echo "Database list: </br>";
{% for host in groups['dbservers'] %}
$link = mysqli_connect(
'{{ hostvars[host].ansible_default_ipv4.address }}',
'{{ hostvars[host].dbuser }}',
'{{ hostvars[host].dbpassword }}'
) or die(mysqli_connect_error($link));
{% endfor %}
while ($r = mysqli_fetch_assoc(mysqli_query($link, "SHOW DATABASES;"))) {echo $r['Database'] . "\n";}
?>
</body>
</html>
Tag Attributes
<h1> ... <h6> Heading align=left|center|right|justify Heading alignment †
† = deprecated
Tag Attributes
<i> Italic
<b> Bold
<s>
<strike> Strike-through Strike-through text †
<small> Smaller
<sub> Subscript
<sup> Superscript
<strong> Strong
<acronym> Acronym
† = deprecated
Tag Attributes
align=top|bottom|left|middle|right Image alignment with respect to surrounding text †
alt=alternatetext Description of the image for text-only browsers
border=npixels Border width around the image †
height=npixels|percent% Image height
hspace=npixels Blank space on the left and right side of image †
<img>
ismap=url URL for server-side image map
Image
longdesc=url URL containing a long description of the image
src=url URL of the image
usemap=url URL for client-side image map
vspace=npixels Blank space on top and bottom of image †
width=npixels|percent% Image width
† = deprecated
Tag Attributes
align=left|center|right Table alignment †
bgcolor=rgb(r,g,b)|#rrggbb|color Table background color †
border=npixels Border width
cellpadding=npixels|percent% Space around the content of each cell
cellspacing=npixels|percent% Space between cells
<table>
Table frame=void|above|below|
lhs|rhs|hsides|vsides|box|border Visibility of sides of the table border
† = deprecated
Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char
0 0 NUL Null 32 20 space 64 40 @ 96 60 `
8 8 BS Backspace 40 28 ( 72 48 H 104 68 h
15 F SI Shift in 47 2F / 79 4F O 111 6F o
showkey -a Prompt for pressing a key and display its ASCII value in decimal, octal, and hex
Confidentiality, Integrity, and Availability (aka the CIA triad) are the basic policies of Information Security.
Confidentiality ensures that access to information is limited to those with the correct rights, integrity ensures that
information has not been improperly modified, and availability ensures that a system is operable and functioning.
A threat is an entity, circumstance, or event with the potential to adversely impact a computer system through
unauthorized access, destruction, disclosure, modification of data, or Denial of Service.
A vulnerability is a weakness in a computer system that could be exploited by a threat source.
A risk is the probability that a particular security threat will exploit a system vulnerability, according to the risk equation:
risk = threat × vulnerability.
An attack is the attempt to gain unauthorized access to a computer system's services, resources, or information, or the
attempt to compromise a computer system's confidentiality, integrity, or availability.
Analyze and evaluate risks to determine possible incidents, their likelihood, their
consequences, and the tolerance of each critical asset for such events.
Risk assessment
The components of risk assessment are technical safeguards, organizational
safeguards, physical safeguards, and administrative safeguards
Remediation Reduce the severity of vulnerabilities (via action plans, patches, hotfixes, etc.)
Verification Verify all the previous phases (via scanners, reports, etc.)
Monitor Monitor regularly the system to maintain the required level of security
The Common Vulnerability Scoring System (CVSS) assessment consists of three metrics for measuring vulnerabilities:
base metrics, temporal metrics, and environmental metrics. Each metric sets a severity score from 1 to 10.
Common Vulnerabilities and Exposures (CVE) is a public list of identifiers for software vulnerabilities.
The Metasploit Framework is a well-known tool and the de facto standard for developing and exploiting security
vulnerabilities in systems and applications. The GUI equivalent is Armitage.
Metasploit has a modular architecture. Exploit modules are the basic modules used to encapsulate an exploit.
Payload modules can be singles (self-contained), stagers (modules that establish a network connection to the attacked
system), and stages (downloaded by stagers).
Auxiliary modules are used to perform one-time actions such as port scanning, DoS, or fuzzing.
NOP modules generate no-op instructions (0x90 for x86 microchips) used to keep the payload size consistent by padding
out buffers.
The steps for carrying out an attack are, in order: configuring an exploit, setting up the exploit options, selecting a target,
selecting a payload, and launching the exploit.
Base commands
help Show the list of Metasploit commands
help command Show detailed help about command
db_status Check database connection status
creds Display all credentials in the database
use module Load and use module
setg variable value Assign value to a global variable
getg variable Get the value of a global variable
unsetg variable Unset the value of a global variable
connect host port Connect to a remote host on port
sessions Display information about active sessions
threads Display information about background threads and manipulate them
banner Display a Metasploit banner
history Show Metasploit command history
Module commands
info See information about the currently loaded module
show payloads Show the list of compatible payloads for the currently loaded module
show options Show all options (variables) available for the module, along with their descriptions and set values
set variable value Assign value to a context-specific variable
get variable Get the value of a context-specific variable
unset variable Unset the value of a context-specific variable
check host Check if host is vulnerable
reload Reload the module
rexploit
rerun Reload and execute the module
exploit
run Execute the module
Meterpreter is an advanced and dynamically extensible payload for a Metasploit attack that provides the attacker with an
interactive shell (Meterpreter session) to the target remote machine. This session is obtained by running from Metasploit an
exploit with the appropriate payload e.g. php/meterpreter/reverse_tcp.
The payload is deployed using in-memory DLL injection.
Meterpreter commands
help Show a list of all Meterpreter commands
background Send the Meterpreter session to background and return to the MSF CLI
cat file Display the contents of file
edit file Edit a text file (via Vim)
ls List files on the target machine
ps Display processes on the target machine
download file Download file from the target machine
upload file path Upload file from the local machine to the path on the target machine
execute -f command Execute a command on the target machine
resource file Execute on the target machine the Meterpreter commands listed in the local file
shell Run an OS shell on the target machine
sysinfo Get information about the target machine: OS, machine name, etc.
ipconfig Display network configuration of the target machine
localtime Display date and time of the target machine
clearev On a MS Windows target machine, clear all Application, Security, and System logs
webcam_list List all operative webcams on the target machine
webcam_snap Take a snapshot from the webcam on the target machine
quit
exit End the Meterpreter session
aireplay-ng attack options Replay packets to perform an attack, where attack is one of:
-0 Deauthentication attack
-1 Fake authentication attack
-2 Interactive packet replay attack
-3 ARP Request replay attack
-4 Chopchop attack
-5 Fragmentation attack (against WEP)
-6 Caffe Latte attack
-7 Hirte attack
-8 WPA Migration Mode attack
-9 Injection test
The Firmware Mod Kit is a toolkit to extract, deconstruct, modify, rebuild, and flash firmware images for Linux-based
routers, IoT devices, embedded devices, and most other devices that use common firmware formats and filesystems such as
TRX/uImage and SquashFS/CramFS.
It can be used by an attacker after compromising a device, to maintain access.
macchanger Tool to perform MAC spoofing. Changes the NIC to a random MAC address
macof DoS tool for MAC flooding
hts HTTPTunnel server. Used in conjunction with the HTTPTunnel client htc to tunnel network connections
through pure HTTP traffic (GET and POST requests), hence bypassing restrictive firewalls or proxies
htc HTTPTunnel client
iodined Firewall evasion tool. Tunnels IPv4 traffic through a DNS server. Replaces the obsolete tcp-over-dns
iodine Client for iodined
loic Low Orbit Ion Cannon, a GUI tool for network stress testing and DoS/DDoS attacks
hoic High Orbit Ion Cannon, a GUI tool for network stress testing and DoS/DDoS attacks
zz Zombie Zapper, a countermeasure tool capable of stopping DDoS packet flooding attacks carried out by
Trin00, TFN, Stacheldraht, etc.
airfart GUI tool that detects Wi-Fi devices and displays their signal strength
cowpatty WPA-PSK key cracker via dictionary attack. Part of the coWPAtty package
genpmk WPA-PSK key cracker via precomputation attack
hackrf_info Tool that probes the HackRF One device and shows its configuration.
HackRF One is an open source SDR (Software Defined Radio) peripheral for testing RF systems. It
is able to transmit and receive radio signals in the 1 MHz - 6 GHz range and can be used to carry
out attacks such as replay, jamming, fuzzing, BlueBorne, etc.
Usually used with the Ubuntu, Gentoo, and Pentoo distros
svmap Scanner for discovering VoIP SIP devices. Part of the SIPVicious package
svwar Scanner for identifying active extensions on a PBX
svcrack Online password cracker for SIP PBX
svcrash Countermeasure for unauthorized svwar and svcrack scans
svreport SIP audit session manager and reports exporter
ike-scan Tool for discovering IKE hosts (IPsec VPN servers) and determine which IKE implementation they use
ddosim Layer 7 DDoS simulator. Simulates zombie hosts connecting to a specific application on the target host
fat Firmware Analysis Toolkit, a toolkit to find and analyze vulnerabilities in the firmware of IoT devices and
embedded devices
balbuzard Tool to extract patterns of interest (e.g. URLs, IP addresses, typical malware strings) from malicious files
bbcrack Tool to bruteforce typical malware obfuscation transforms (XOR, ROL, ADD, etc.) and discover the
algorithms and keys used. Based on patterns of interest
bbharvest Tool to extract all patterns of interest found when applying typical malware obfuscation transforms (XOR,
ROL, ADD, etc.) trying all possible keys
bbtrans Tool to apply any of the malware obfuscation transforms from bbcrack to a file
sqlninja Tool to exploit SQL injection vulnerabilities against web applications that use Microsoft SQL Server as
database backend
SQLiX Web crawler that attempts to find SQL injection vulnerabilities on explored websites
psad Port Scan Attack Detector. Uses iptables log messages to detect and block port scans and other
malicious network traffic
honeyd Honeypot daemon. It creates virtual hosts, and simulates their networking stack and any desired
network service
labrea Honeypot for incoming IP connections. Replies to unanswered ARP requests, creating a virtual host with
the related unused IP address, which then performs Layer 4 tarpitting
sshhipot SSH honeypot
artillery Honeypot with monitoring and alerting system
honeytrap Extensible toolkit for running and monitoring honeypots
kojoney Low-interaction honeypot that emulates an SSH server
honeypy Medium-interaction honeypot
cowrie High-interaction SSH and Telnet honeypot
pentbox Security suite including password crackers, honeypots, DoS tools, etc.
websploit Exploit framework containing reconnaissance and attack tools for various technologies
nexphisher Automated phishing toolkit featuring many social media websites
inspy LinkedIn enumerator. Attempts to find technologies and people at a specified target company
recon-ng Web reconnaissance framework
dog Recon Dog, an OSINT reconnaissance tool
maltego OSINT tool with GUI that visualizes discovered data in a graph format for link analysis
Social engineering Wide range of non-technical attacks consisting in deception and psychological
manipulation of the target individual into divulging confidential information or performing
unwarranted actions.
Pretexting Social engineering attack where the attacker invents an elaborate scenario (i.e. a
pretext) to engage the target individual under a fake identity and convince them to
divulge confidential information or perform unwarranted actions.
Phishing Social engineering attack aimed at obtaining sensitive information from people via a fake
but legitimately-looking website controlled by the attacker. Usually perpetrated via an
email message containing an obfuscated link to the malicious website.
Spear phishing Personalized phishing targeted at a specific individual.
Whaling Phishing targeted at a high-value individual (CEO, CISO, etc.).
Vishing Phishing via VoIP.
Smishing Phishing via SMS.
Tailgating Social engineering attack in which an attacker lacking proper authorization follows an
Piggybacking authenticated individual into the targeted restricted area.
Shoulder surfing Act of getting access to sensitive information by spying an individual entering the data.
USB drop attack Social engineering attack consisting in leaving a bulk of malware-infected USB flash
Baiting drives in public places for people to find and use.
Dumpster diving Act of searching through discarded paper documents left behind by the target
organization in order to find and exploit information.
Rubber hose cryptanalysis Euphemism for extracting cryptographic secrets from the target by means of coercion or
violence.
Black bag cryptanalysis Euphemism for obtaining cryptographic secrets from the target by breaking and entering
the premises, burglary, theft, etc. This term is also used for other non-cryptanalysis
methods such as keystroke logging, infection via virus or trojan horse, etc.
Ping of death A malformed or oversized ping packet which, when reassembled by the target host, causes a
buffer overflow, crashing or infecting with malicious code the target host. Obsolete; modern
TCP/IP stacks, firewalls, and IDSs easily identify and discard pings of death.
Ping flood DoS in which the attacker sends a large number of ICMP Echo Request packets to the target
ICMP flood host.
Smurf attack DRDoS in which the attacker sends a large number of ICMP Echo Request packets to a
network broadcast address using the target host's spoofed source IP address. Obsolete; by
default, ICMP requests to broadcast addresses are not forwarded anymore by routers.
Fraggle attack DRDoS in which the attacker sends a large amount of UDP traffic to ports 7 (Echo Protocol)
and 19 (CHARGEN) of multiple remote hosts, using the target host's spoofed source IP
address.
SYN flood DoS in which the attacker sends a a large number of TCP SYN packets to the target host but
never responds to its SYN/ACK, hence never completing the TCP three-way handshake. This
creates a large number of half-open connections which, until they time out, fill up the target
host's connection queue, preventing legitimate clients to connect to it.
Countermeasures: TCP Intercept (aka SYN Proxy or SYN cookies).
Teardrop DoS in which the attacker sends mangled IP fragments with overlapping and oversized
payloads to the target host, causing it to crash. Obsolete; fixed in the Linux kernel v2.1.63.
Fragmentation attack DoS performed by sending a large number of fragmented TCP or UDP packets to the target
host, which will consume resources in reassembling and inspecting them.
Shrew attack Low-rate DoS that exploits the retransmission timeout (RTO) mechanism of TCP. Performed
by sending out a burst of traffic to a bottleneck router at the same time the client sends a
request to the server. Hence, the router suspends the data transmission, packets are
dropped during the RTO, and after the RTO the client needs to resend the lost packets,
slowing down the transmission.
MAC spoofing Act of setting a spoofed MAC address in the NIC in order to divert communications to the host
controlled by the attacker.
Countermeasure: IP Source Guard (on switches) using the DHCP snooping binding table.
MAC flooding Dispatch of multiple Ethernet frames with different source MAC addresses to a switch. This
fills up a switch's CAM table and forces the switch to failover to hub mode (i.e. broadcasting
to all switch ports), allowing the attacker to sniff all network traffic in the LAN.
Countermeasure: port security with max one MAC address per interface (on switches).
ARP spoofing Dispatch of forged ARP messages into the LAN to associate the attacker's MAC address with
ARP cache poisoning another host's (often the gateway) IP address, diverting communications to the attacker.
ARP poisoning Often the first choice of attack for the purpose of sniffing, or in preparation to MitM attacks or
ARP poison routing session hijacking attacks.
Countermeasures: Dynamic ARP Inspection (on switches) using the DHCP snooping binding
table, disabling of gratuitous ARP, static IP addresses and ARP tables. On wireless networks,
Client Isolation (on the wireless router) which prevents wireless clients from communicating
between them.
Port stealing ARP spoofing aimed to associate the attacker's MAC address with another host's IP address
on a switch's CAM table, which will then forward packets through the wrong switch port.
IP spoofing Act of setting a spoofed IP address in the NIC so the attacker's host can appear to be some
other host.
Countermeasure: direct TTL probes (however, this works only if the attacker's host is in a
different subnet).
DNS spoofing Tampering with the name resolution mechanism of the target host so that a domain name
resolves to an incorrect IP address controlled by the attacker. Can be carried out either by
DNS hijacking, by deceiving the target host to use a rogue DNS server, or by tampering
with the hosts file of the target host. Can be done in preparation to a MitM attack,
although for a LAN an ARP spoofing would serve the same purpose and is easier to do.
Countermeasures: DNSSEC, restriction of DNS service, master-slave DNS setup with no
Internet access for the master, DNS anti-spoofing.
DNS hijacking Attack which consists in compromising a DNS server and changing the mapping settings to
redirect towards a rogue DNS server. This can also be done by stealing the domain name
upon the sponsoring domain name registrar accredited by the ICANN (which manages the
DNS root zone).
Countermeasure: at the registrar level, REGISTRAR-LOCK status code to prevent
unauthorized changes to the domain name.
Cybersquatting Registration of a domain name which is similar to a well-known domain, product, or entity,
in order to deceive users. Can be done in preparation to phishing attacks or scams.
Typosquatting Cybersquatting where the attacker relies on typos and other mistakes made by users when
they manually type a URL into a web browser.
Domain sniping Registration of a domain name that has just expired, with the purpose of reselling it to the
Domain snapping original owner at a higher price.
DNS cache poisoning Injection of forged DNS records in the DNS resolver's cache, causing the name server to
return an incorrect IP address for a domain name, hence redirecting traffic to the attacker.
Blind response forgery DNS cache poisoning attack carried out by guessing the transaction ID (birthday paradox).
Countermeasure: randomization of UDP source port.
DNS water torture DDoS done by performing a large number of DNS queries for nonexistent subdomains of a
target domain. Subdomains strings are randomly-generated by the attacker, hence the
queries bypass the DNS cache and hit the DNS Authoritative Servers of the target domain.
DNS amplification attack DRDoS in which the attacker sends a large amount of DNS queries to the target host's
DNS server, using the target host's spoofed source IP address. The recursive resolution of
queries ends up overwhelming the target host's DNS server.
DNS sinkhole attack Act of providing incorrect DNS information to systems so to redirect their communications
Blackhole DNS attack to a single destination. This can also be done for beneficial purposes, e.g. to block ads or
stop botnets from contacting their C&C (Command and Control) host.
DHCP spoofing Attack consisting in setting up a rogue DHCP server and use it to send forged DHCP
responses to hosts. Often done to replace the IP addresses of the default gateway and
DNS server, redirecting traffic to attacker-controlled nodes.
Countermeasure: DHCP snooping and Dynamic ARP Inspection (DAI) on routers.
DHCP starvation DoS in which the attacker floods a DHCP server with DHCP requests from spoofed MAC
addresses, depleting the server's IP address pool and making it unable to allocate them for
legitimate clients. Also done in preparation to the deployment of a rogue DHCP server.
IRDP spoofing Injection of forged IRDP Router Advertisements to add default route entries to a target
host, redirecting traffic to the attacker-controlled node.
Sinkhole attack Attempt to attract network traffic by advertising fake routing updates. Once traffic passes
through the malicious node, the attacker may alter the payload, launch a blackhole or
wormhole attack, or perform other disruptive activities.
Blackhole attack DoS attack where an attacker-controlled node discards packets instead of relaying them.
Packet drop attack This can be done partially and/or selectively (e.g. depending on the time of the day, the
source, the destination) in order to avoid detection.
Wormhole attack Attack (usually carried out on wireless networks) where the attacker records packets in
one location and then tunnels them to another location, selectively or as a whole.
Man-in-the-Cloud (MitC) MitM-like attack against cloud file synchronization services, carried out by stealing and
reusing a synchronization token from the target cloud user to obtain access to their files.
Countermeasure: hardened policies for token expiration.
Wardialing Reconnaissance technique consisting in automatically dialing every telephone number from
a list (usually in a local area code) searching for modems, BBS, or fax machines.
Obsolete, as dial-up Internet connections have practically disappeared.
Evil twin attack Attack consisting in setting up a legitimately-looking rogue Wi-Fi Access
Point to lure clients into connecting to it and then perform eavesdropping
or MitM attacks. To improve effectiveness, the rogue AP can even
transmit with a stronger signal.
Countermeasures: network management software (on the network
management side) with wired side inputs to detect devices connected to
the LAN and hence also rogue APs; WIPS.
KARMA attack Variant of the evil twin attack. Some vulnerable devices broadcast the
list of their preferred networks (i.e. the SSIDs of APs to which they have
already connected and are going to connect automatically). Upon
receiving this information, an attacker can set up a rogue AP with a SSID
from the list.
Client misassociation Attack similar to the evil twin attack, consisting in setting up a rogue AP
that duplicates the SSID and the MAC address of a legitimate AP.
Disassociation attack Availability attack carried out by sending deauthentication frames to the
Deauthentication attack AP to disconnect clients. This attack can be done against a specific client
(by using the target client's spoofed MAC address) or all clients.
Beacon flood attack Availability attack carried out by sending a large number of forged Wi-Fi
beacons to confuse wireless clients and make it harder for them to
connect to a legitimate AP.
Clear channel assessment attack Physical layer DoS attack that exploits the CSMA/CA Clear Channel
Queensland attack Assessment (CCA) to make the channel appear busy.
Fluhrer, Mantin, and Shamir attack (FMS) Attack which exploits a weakness in the RC4 key scheduling algorithm to
reconstruct the key from encrypted messages. This attack can be used
to recover a WEP key.
Chopchop attack Attack carried out against a WEP-encrypted wireless communication
which allows to recover the unencrypted payload. The attacker chops off
the last byte of data from a WEP-encrypted packet, replaces that byte,
recalculates the checksum, and sends the packet to the AP. The AP
discards the packet, until by trial and error the attacker eventually
replaces a valid checksum and the AP accepts it.
The same attack can be carried out against WPA-TKIP.
This attack does not recover the WEP key.
Key Reinstallation Attack (KRACK) Attack against the four-way handshake in the WPA2 authentication
protocol. The attacker captures and replays the message in step 3
(containing the AP's nonce) to force nonce reuse; this allows the attacker
to decrypt all traffic.
Countermeasures: update all wireless devices with latest security
patches, patch the AP's firmware, use HTTPS, enable 2FA.
Fragmentation attack [WEP] Attack consisting in extracting some keying information from a WEP
packet, then sending ARP and LLC packets to the AP which resends them
back, then extracting more keying information from the packets. This
cycle is repeated until the attacker gets 1500 bytes of the PRGA (Pseudo
Random Generator Algorithm) which can then be used to forge and
inject packets. This attack does not recover the WEP key.
Caffe Latte attack Attack allowing to recover a WEP key from a client by capturing an ARP
packet from the client, manipulating it, and sending it back to the client.
Hirte attack Extension to the Caffe Latte attack, performed using any ARP or IP
Client-oriented fragmentation attack packet.
Wardriving Detection and reconnaissance of WLANs by listening to SSID broadcasts
or by sending probe requests, usually done from a moving vehicle.
Warchalking Technique of advertising discovered WLANs in range by drawing specific
symbols with chalk in public places, usually on pavement or walls.
Bluejacking Sending of anonymous messages (e.g. spam) to a Bluetooth device, done by inserting the message
in the BT connection request. Uses the OBEX (Object Exchange) protocol.
Bluesnarfing Theft of information from a Bluetooth device. The attacker connects to the target BT device and
performs a GET operation for known or guessed filenames. Carried out by exploiting a vulnerability
in the OBEX protocol.
Bluebugging Unauthorized remote access and takeover of a Bluetooth device.
Blueprinting Footprinting performed against a Bluetooth device.
Bluesmacking Ping of death attack carried against a Bluetooth device.
BlueBorne Vulnerability in the Bluetooth implementation on multiple OSes that allows an attacker to take
control of the target device, even if the device is not paired or even set to discoverable mode. The
attacker gets the MAC address and performs OS fingerprinting on the device, then uses a BT exploit.
Network-level hijacking Interception of TCP or UDP packets during transmission between client and server.
This term is also used for the takeover of a legitimate TCP communication between two
hosts, done via IP spoofing and MitM, sometimes using source routed packets. The
attacker sniffs (or tries to predict) TCP Sequence and Acknowledgment numbers from
the client, sends forged TCP Sequence and Acknowledgment numbers to the server to
desynchronize the client, and finally inserts itself in the TCP session.
Application-level hijacking Takeover of an HTTP session, usually done by stealing an HTTP session token. This is
Session hijacking not network-level hijacking.
TCP/IP hijacking Network-level hijacking in which the attacker sniffs the communications between two
hosts to get the target host's Initial Sequence Number (ISN). The attacker then sends
a packet with the target host's spoofed source IP address using the captured ISN. The
other host receives the packet, increments its TCP Sequence number, and sends an
ACK to the target host which ignores it. The attacker continues to send spoofed
packets with forged TCP Sequence and Acknowledgment numbers, causing the target
host to have desynchronized values and making its connection hang. At this point, the
attacker inserts itself in the TCP session, replacing the target host.
Blind hijacking Network-level session hijacking in which the attacker tries to predict ISN and TCP
Sequence and Acknowledgment numbers, without being able to see the response. Can
be used to inject malicious data into the communication, and does not require source
routing. This is not considered a MitM attack.
RST hijacking Injection of an RST packet with spoofed source IP address within a legitimate TCP
TCP reset attack communication, to terminate the connection. May be done in preparation to TCP/IP
hijacking.
UDP hijacking Network-level hijacking where the attacker forges UDP replies from the server.
Source routing attack Network-level session hijacking that uses the source routing field in the IP header to
specify a packet route so to, with the help of a trusted host, divert packets towards the
attacker's node. Used in IP spoofing attacks. Obsolete; by default, network devices
nowadays discard source routed packets.
Session fixation Application-level session hijacking in which the attacker sets a session ID on behalf on
the target host. This can be done e.g. via a phishing email. This attack is effective
against e.g. web applications that do not change the session cookie after a successful
login and instead allow additional privileges to it.
Session prediction Application-level session hijacking in which the attacker predicts a session ID value.
The attacker needs beforehand to collect valid session ID values that identify
authenticated users, and to analyze and understand the session ID generation
algorithm.
Session brute-forcing Application-level session hijacking in which the attacker tries all possible session ID
values until they successfully get access to the application.
Session riding Application-level session hijacking obtained via Cross-Site Request Forgery.
Countermeasures: check the HTTP Referrer header, ignore URL parameters when
processing an HTTP POST command.
Session sidejacking Application-level session hijacking in which the attacker sniffs a session ID (session
Sidejacking cookie) from a legitimate session and then reuses it to impersonate the legitimate
Cookie stealing client.
HTTP response-splitting attack Attack which consists in adding header response data into an input field so
HTTP header injection that the webserver splits the HTTP response into two; these can either be
served to the attacker, served to a legitimate client, or discarded.
Countermeasure: validation of client input. In particular, CR (%0d, \r) and
LF (%0a, \n) characters should never be allowed in input.
HTTP request tampering Unauthorized access to a web application obtained either by tampering with
the URL query string, or by modifying the HTTP headers sent to the
webserver e.g. the Referer: header which in vulnerable applications is used
for access control.
HTTP Parameter Pollution (HPP) Evasion technique used to bypass WAF security filters which consists in
crafting an HTTP request containing multiple instances of a parameter with
the same name, hence splitting the attack vector.
HTTP Parameter Fragmentation (HPF) Evasion technique, often used along with HPP, which allows to reconstruct
the parameter string passed in the HTTP request.
Webcache poisoning Attack where the attacker uses a specially crafted request to force the
webserver's cache to flush its contents and insert a URL with infected
content in the cache, which is then served to legitimate clients accessing the
cache. Can be performed via an HTTP response-splitting attack.
Directory traversal Unauthorized access to directories outside the webserver's root directory,
done by using repeatedly the ../ sequence in URLs.
Unvalidated redirect Phishing in which the URL is that of a legitimate site but contains a redirect
to the malicious site.
Unvalidated forwarding Unauthorized access to a restricted webpage obtained fraudulently via an
embedded forward query on the URL.
CRIME Compression Ratio Info-leak Made Easy. Exploit against authentication web
cookies transmitted over compressed HTTPS and SPDY connections, which
results in session hijacking.
BREACH Browser Reconnaissance and Exfiltration via Adaptive Compression of
Hypertext. Session hijacking exploit analogous to CRIME, but performed
against HTTPS when using HTTP compression.
HTTPS Stripping MitM attack which consists in hijacking the connection establishment from
SSL Stripping the target host to a remote secure webserver, then transparently
downgrading all HTTPS traffic to HTTP. This attack works for webservers
with redirection from HTTP to HTTPS, and only if the initial request to the
webserver is sent as HTTP; then, if the client does not explicitly specify
HTTPS for links, the attacker intercepts all HTTP 302 redirections and sends
the client the requested content through HTTP.
Countermeasure: HSTS (however, browsers not accepting HSTS cookies will
still be vulnerable).
Forbidden attack Attack exploiting vulnerable implementations of the TLS protocol that
incorrectly reuse the same cryptographic nonce when data is encrypted.
This allows the attacker to sniff the HTTPS connection and inject content.
HTTP flood Layer-7 DDoS targeted at webservers. Carried out by sending a large
number of HTTP GET and POST requests towards the target webserver.
Slow HTTP attack Low-bandwidth DoS targeted at webservers. Carried out by keeping several
connections to the target webserver open as long as possible, depleting the
webserver's connection pool. This is done by exchanging HTTP traffic at an
extremely slow rate (1 byte/min or less), preventing the webserver from
going into timeout for idle connection.
Slow Post attack Slow HTTP attack carried out by sending correct HTTP requests and headers
at an extremely slow rate.
Slow Read attack Slow HTTP attack carried out by reading the webserver's response at an
extremely slow rate.
Slowloris Similar to the Slow Post attack, but carried out by sending partial HTTP
request and headers, while never completing the request.
R U Dead Yet (RUDY) Slow HTTP attack carried out by opening concurrent POST HTTP connections
and delaying sending the body of the POST request.
Cross-Site Scripting (XSS) Injection of malicious client-side scripts (e.g. via input textfields) in webpages,
which are then executed when the webpage is viewed by other clients. This
can lead to session hijacking, data theft, exploiting user privileges, etc.
Identification of entry points for user input is the first step for exploiting a
website.
Countermeasures: set the HttpOnly flag in session cookies, sanitize user input.
Non-persistent XSS XSS attack where the malicious data provided by the attacker is used
Reflected XSS immediately by server-side scripts to display results to the targeted user only.
Persistent XSS XSS attack where the malicious data provided by the attacker is saved by the
Stored XSS server and permanently displayed to all users visiting the website.
Server-side XSS XSS attack where the malicious data provided by the attacker is wholly
processed server-side. Historically, this was the first kind of XSS attack.
DOM-based XSS XSS attack where the malicious data provided by the attacker does not affect
the webserver but it is reflected fully client-side, where all the presentation
logic (often JavaScript) occurs.
Cross-Site Flashing (XSF) XSS-like attack where the malicious data provided by the attacker is used in
some specific video playing functions and variables by Flash scripts.
Cross-Site Tracing (XST) XSS attack, involving the use of the HTTP TRACE method, that allows stealing
cookies via Javascript.
Cross-Site Request Forgery (CSRF) Attack which consists in having the target client unknowingly submit a
One-click attack maliciously crafted web request to a webpage. Can be performed via specially
designed image tags, hidden forms, JavaScript functions, etc.
Countermeasure: random tokens in the web application.
Server-Side Request Forgery (SSRF) Attack which consists in inducing the server-side application to make HTTP
requests to an arbitrary domain. This results in unauthorized actions and
access to data, and may lead to arbitrary command execution.
URL parameter tampering Modification of parameters in the URL to exploit vulnerable applications that
Web parameter tampering use them, e.g. http://www.bank.com/account?id=345&amount=200000
Session poisoning Unauthorized access to a web application by exploiting (e.g. via URL
parameter tampering) weak user input validation. The same term may also
indicate the takeover of a session of a legitimate user e.g. by injecting
malicious content, or via cookie poisoning.
Cookie sniffing Unauthorized access to a web application by sniffing a cookie belonging to a
legitimate user and reusing it to bypass the authentication process, ending up
logged in as that user.
Countermeasure: SSL, setting the secure attribute on cookies (which will
therefore be sent only over HTTPS).
Cookie replay Replay attack in which the attacker captures a cookie belonging to a legitimate
logged in user, then reuses it to perform malicious activities on behalf of that
user. The attack persists until the user logs off.
Cookie poisoning Unauthorized access to a web application by crafting a cookie, or by sniffing
and modifying a cookie belonging to a legitimate user.
Countermeasures: cookie expiration, associate cookie's credentials to an IP
address.
Cookie parameter tampering Unauthorized access to a web application by tampering with the parameters of
a cookie and resubmitting it.
SSI injection Code injection technique consisting in injecting scripts in webpages via SSI.
SSIs (Server Side Includes) are directives present on web applications which
allow inserting dynamic content into an HTML page before it is loaded or
visualized.
CORS attack Attack exploiting the Cross-Origin Resource Sharing (CORS) mechanism.
CORS allows restricted resources on a webpage to be requested from another
domain outside the domain from which the first resource was served; this is
safer than allowing all cross-domain requests. It bypasses the Same-Origin
Policy (SOP) which forbids certain cross-domain requests (e.g. Ajax).
Connection String Parameter Pollution (CSPP) Injection of connection string parameters into other existing
parameters, often carried out by using a ; character. This can be
done e.g. in connection strings for backend databases.
Website defacement Unauthorized changes made to the website appearance and content, to show the
attacker's propaganda and/or infect legitimate clients with malware.
Pharming Attack intended to redirect legitimate traffic from a website to a fake one. Usually
carried out via DNS spoofing. Considered an advanced form of phishing.
Watering hole attack Attack in which the attacker identifies which websites the target users visit more often
and infects those websites with malware (e.g. via XSS).
Framing attack Insertion of a malicious webpage inside a legitimate webpage by using the <iframe>
(inline frame) HTML tag.
Clickjacking Deceptive technique consisting in tricking web users to click on a different element from
UI redress attack the one they think they are clicking. Usually done via a framing attack, by having an
UI redressing (UIR) invisible iframe with malicious content on top of a visible iframe with innocuous content.
Man-in-the-browser (MitB) Attack related to MitM where a Trojan horse infects a web browser in the target host,
and injects HTML code in the browser's requests and responses. The Trojan operates
between browser and OS API, allowing it to read data before encryption when it is sent
from the host, and read data after decryption when it is received by the host.
XML External Entity (XXE) SSRF attack consisting in passing malicious XML input, referencing an external entity
containing infected data, to an application with a weakly configured XML parser. This
may cause confidential data disclosure, DoS, remote code execution, etc.
XML DoS issues are a common SOA vulnerability.
Billion laughs attack Exponential entity expansion attack consisting in a specially crafted XML document
XML bomb where the root element contains a defined entity which contains e.g. 10 defined entities,
each of which contains e.g. 10 defined entities, and so on. This takes up a large amount
of memory and results in a DoS when the XML document is processed.
Countermeasures: capping the memory allocated for an individual XML parser, treating
entities symbolically and expanding them only when needed.
XML injection Insertion of specially crafted XML fields in SOAP requests for web services. This may
XML poisoning cause confidential data disclosure, DoS, remote code execution, etc.
XPath injection Code injection technique in which the attacker provides malicious parameters to
construct the wrong XPath query and access the wrong XML node.
XPath is a query language for selecting nodes from an XML document.
Wrapping attack [XML] Attack performed during the translation of a SOAP message in the TLS layer, by
intercepting the message, adding the body to the header, injecting a malicious payload in
the body, and sending the message to the server as a legitimate client. The server
therefore verifies the XML signature as valid.
Countermeasures: XML schema validation, authenticated encryption in the XML-Enc (XML
Encryption) specification.
SQL injection (SQLI) Code injection technique in which the attacker inserts malicious SQL statements into an
input field for execution. This is done by using single quotes (') and double quotes (").
Countermeasures: user input sanitization, avoiding constructing dynamic SQL with
concatenated user input values, keeping untrusted data separate from commands and
queries, using least privilege account types for connection to the database.
In-band SQL injection SQL injection where the attacker uses the same communication channel to send the
query and retrieve the result. Most common type of SQL injection. Can be:
Error-based: the attacker causes the database to throw an error, e.g. by forcing a
conversion type, and gains knowledge by analyzing the error message
Illegal query: the attacker sends a logically incorrect query and gains knowledge by
analyzing the error message
Union: the attacker uses the UNION operator to get the field values from other tables;
can be coupled to other operators e.g. ORDER BY to find the number of fields in a table
Tautology: the attacker inserts the OR operator with a tautology so that a WHERE
clause is always true, e.g. ' OR '1'='1
End-of-line comment: the attacker uses -- to insert an end-of-line comment to make
the database parser ignore the rest of the query
Inline comment: the attacker uses /* */ to insert an inline comment to bypass fields
Piggybacked query aka stacked queries: the attacker uses a ; character to insert
additional malicious queries to the original query
Stored procedure: the attacker input is fed to dynamic SQL statements
Second order: the attacker's input is saved in a database and used later when the
attacker submits a second query; requires knowledge of the application backend
Out-of-band SQL injection SQL injection where the attacker retrieves the result via a different channel e.g. email,
HTTP, or file I/O functions. More difficult to perform.
Blind SQL injection SQL injection attack used when the application does not show a useful error message
Inferential SQL injection and hence the attacker needs to assess whether the application might be vulnerable to
an SQL injection. This attack is time-intensive. Can be:
Time-based aka double blind: the attacker sends a query which may be true or false
embedded with sleep or benchmark functions, and gets information from the time delay
that occurs in the response
Boolean-based: the attacker sends a query which causes the application to return a
different result depending on whether the query returns true or false
Heavy query: the attacker sends a query that takes noticeable time to execute, e.g. a
SELECT COUNT(*) from multiple tables
ORM injection SQL injection attack against a data access object model generated by ORM (Object
Relational Mapping).
Buffer overflow Attack carried out by writing data to a buffer over the buffer's boundaries,
Buffer overrun overwriting the adjacent memory addresses. This allows the attacker to modify the
target process' address space to control process execution, crash the process, and
modify variables.
Countermeasure: buffer bounds checking.
Fork bomb DoS attack consisting in a process that recursively replicates itself ad infinitum,
depleting system resources and slowing down or crashing the system due to
resource starvation.
Code injection Attack in which the attacker inserts text in a data field that gets interpreted as code.
File injection Code injection technique in which the attacker exploits dynamic file include
mechanisms in vulnerable web applications (especially in PHP). The attacker
provides a URL pointing to the malicious file, which is used by the web application
instead of the intended local file.
LDAP injection Code injection technique in which the attacker inserts malicious LDAP user
parameters into an input field to get access to the LDAP database.
Countermeasure: user input sanitization.
Insecure deserialization attack Injection of malicious code into a serialized object; if the application uses a
vulnerable algorithm for deserialization, the code is executed when the object is
deserialized.
Serialization is the act of converting an object into a format (e.g. XML, JSON, YAML)
which can be written to disk, transmitted over the network, or sent to a stream
(e.g. stdout).
Cross-guest VM breach Side channel attack carried out by running a VM on the same physical host as the
target VM and taking advantage of shared physical resources (e.g. CPU cache) to
extract cryptographic secrets.
Shrink-wrap code attack Attack consisting in exploiting holes in unpatched or misconfigured software (e.g.
software with default insecure configuration options).
Logjam Vulnerability affecting Diffie-Hellman key exchanges with key size from 512 to 1024
bits, allowing an attacker to downgrade a TLS connection and read and modify the
exchanged data.
Shellshock Vulnerability in the Bash shell which allows an attacker to execute arbitrary
commands by exploiting the function export feature of Bash.
Heartbleed Buffer over-read vulnerability in the OpenSSL cryptography library. The attacker
client sends a heartbeat request specifying a length larger than the message
payload. The server replies filling up all the allocated buffer with the contents of the
active memory, which may include private data.
Spectre Vulnerability affecting the branch prediction mechanism (done to improve
performances) on microprocessors. An attacker can exploit the side effects of
speculative execution, and particularly branch misprediction, to access private data.
Meltdown Vulnerability affecting some Intel x86, IBM POWER, and ARM microprocessors. An
attacker can have a process, even without proper authorization, read any memory
location by exploiting a race condition between memory access and privilege check
during instruction processing.
Virus
A virus is a piece of self-replicating code that attaches copies of itself to other executable programs, infecting them.
File virus Infects an executable file, overwriting it.
Boot Sector virus Executes its code before the target machine boots. Moves the Master Boot Record to another
System virus location on the hard disk and copies itself to the original location of the MBR.
Multipart virus Acts both as a file virus and a Boot Sector virus.
Hybrid virus
FAT virus Infects the File Allocation Table in FAT filesystems.
Cluster virus Infects files without changing them, saving instead the virus code to the hard disk and
overwriting the pointer in the directory entry; in this way, the virus code is read instead of the
actual program.
Stealth virus Alters the service call interrupts while running, to hide from AV software.
Tunneling virus
Sparse infector virus Infects files only occasionally, upon satisfying certain conditions (time, size of the file to infect,
etc.) to minimize the risk of being detected by AV software.
Encryption virus Consists of a decryption module and an encrypted copy of the virus. Once the target machine
is infected, the decryption module decrypts and executes the virus. The virus then infects files
with a copy of the virus which is encrypted with a different key for each file. This is done to
thwart signature detection methods in AV software.
Polymorphic virus Reprograms itself, changing the malicious code at each infection. Consists of the encrypted
virus, a decryption routine, and a mutation engine; the virus code mutates with each infection
while the virus algorithm stays the same. Undetectable by AV software.
Metamorphic virus Reprograms itself, rewriting the code each time it infects a new file: it inserts dead code,
reorders instructions, and modifies the program control structure to avoid pattern recognition
by AV software. Stealthier than a polymorphic virus.
Cavity virus When infecting, overwrites empty spaces (nulls) in the original file so not to modify its size.
Camouflage virus Creates a companion file with a different file extension for each file to infect; the companion
Companion virus file is executed first and contains the malicious code.
Shell virus Wraps itself around the infected file, hosting the original program as its subroutine, so that the
virus code is executed first.
TSR virus Terminate and Stay Resident virus. Remains resident in memory after the infected program
has terminated execution.
Macro virus Written as a macro (often in VBA language), infects Microsoft Office files.
File extension virus Tries to hide itself by adding a fake safe file extension (e.g. TXT) to its executable file.
Logic bomb Virus that is triggered in response to a specific event.
Trojan
A Trojan is a malicious program packed and concealed, with the help of a wrapper, inside an innocuous program.
Remote Access Trojan (RAT) Provides full access to the infected host, including files, shell, screen capture, webcam,
microphone, etc.
Backdoor Trojan Allows bypassing the standard system authentication through IDSs and firewalls.
Botnet Trojan Infects a large number of hosts (which, once compromised, become bots aka zombies)
to create a botnet that can then be controlled via a Command&Control center to carry
out distributed attacks.
Rootkit Trojan Composed of a dropper, a loader, and a rootkit; the dropper runs the loader which
causes a buffer overflow, causing the rootkit to be loaded into memory.
Proxy server Trojan Allows an attacker to use the infected system as a proxy to connect to the Internet.
Covert channel Trojan Creates a covert channel in the data stream authorized by the network access control
system, allowing the attacker to tunnel malicious traffic undetected.
Rootkit
A rootkit is a malicious program used to gain full, administrator-level, persistent access to a system without detection.
Hardware/firmware rootkit Located in the firmware (hard disks, BIOS, etc.), creates a persistent malware image.
Bootloader-level rootkit Replaces the bootloader. Can activate itself before the OS starts.
Kernel-level rootkit Runs at kernel level in Ring 0 with the highest OS privileges. This is the most difficult
type of rootkit to detect.
Hypervisor-level rootkit Runs in Ring 1, hosting the OS of the target machine as a VM and intercepting all
hardware calls made by the target OS.
Library-level rootkit Patches, hooks, or replaces OS system calls with backdoored versions.
Application-level rootkit Replaces application files and modifies process' behaviour by injecting malicious code.
Other malware
Worm Standalone malicious program that replicates itself and executes through network connections.
Usually it does not infect files, and uses just the CPU and RAM of the infected host.
Keylogger Program that covertly intercepts and records all keys pressed on the keyboard. May also be
hardware. The best location for it to be placed is the keyboard hardware or the OS.
Ransomware Malware that encrypts files in the infected system, blocking the legitimate user from accessing them,
and asks for a ransom to be paid online.
A firewall monitors incoming and outgoing network traffic, allowing or discarding it based on custom security rules.
Firewall architectures:
Bastion host Defends the LAN from outside attacks. Has one public interface connected to the Internet, and
one private interface connected to the LAN.
Screened subnet Has one public interface connected to the Internet, one private interface connected to the LAN,
and one interface connected to the DMZ. Designed to host servers that offer public services.
Multi-homed firewall Composed of multiple firewalls, or one firewall with at least three NICs, which allows the
protection of multiple network segments.
Firewall technologies:
Packet filtering Filters packets according to source and destination IP address, source and
destination TCP/UDP port, TCP flags, etc.
Circuit-level gateway Forwards data between networks, making traffic appear to have originated
from the gateway.
Application-level filtering Filters traffic depending on the protocol.
Stateful multilayer inspection Combines packet filtering, circuit-level gateway, and application-level filtering
to remember the state of previous packets and determine whether session
packets are legitimate.
Application proxy Provides protection by preventing direct connections between systems on
either side of the firewall, and hence by avoiding exposure of the proxied
service. A client connects to the proxy firewall (stateful) which then initiates a
new network connection on behalf of the request.
Virtual Private Network (VPN) Using traffic encryption and encapsulation, provides secure access to a private
network through a WAN.
Network Address Translation (NAT) The same as in routers, remaps LAN's private IP addresses to Internet-routable
public IP addresses.
An IDS (Intrusion Detection System) monitors, detects, and alerts about possible intrusions (passive mode). An IPS
(Intrusion Prevention System) also blocks them (active mode). An IDS can be network-based (NIDS) or host-based (HIDS).
A WIDS (Wireless Intrusion Detection System) or WIPS (Wireless Intrusion Prevention System) monitors the radio spectrum
to detect, block, and alert about possible intrusions in a wireless network.
A honeypot is a part of a computer and network system set up as a bait for attackers. It looks like a legitimate part of the
site and appears to contain information or resources valuable to attackers, but in fact it is isolated and heavily monitored.
It is used to identify attackers and their techniques, as well as to deflect attacks.
Types of honeypots:
Low-interaction honeypot Emulates a limited number of services and applications, and provides limited
interaction with the attacker. Used to collect information about attack vectors such as
network probes and worm infections.
Medium-interaction honeypot Emulates a real OS with services and applications, but can only respond to
preconfigured commands so the attacker might notice that its functioning is limited.
Allows gathering more detailed data about an attack.
High-interaction honeypot Not an emulation, but a real system actually running services and applications, or a
whole network architecture of systems (honeynet). As such, it may be compromised
or infected by an attacker. All intrusion activities are logged, so it allows collecting a
large amount of data about the attacker. A honeywall gateway allows the attacker to
interact with the honeynet while limiting outbound traffic via IDS technologies, to
control the attacker and preventing harm to computers outside the honeynet.
Production honeypot Emulates a real production system of an organization. Used to lure attackers to
trigger alerts and hence get early warnings about an attack.
Research honeypot High-interaction honeypot deployed in research, military, or government
organizations to get detailed information about cyberattacks in order to study exploits
and vulnerabilities.
Characteristics and methods used by honeypots (which can be used to identify them):
Layer 2 tarpit A tarpit is a service purposely used to delay incoming connections. A Layer 2 tarpit is
used to block network penetration of an attacker, but can be detected by the use of
the MAC address 00:00:0f:ff:ff:ff which acts as a blackhole for Layer 2 connections.
Layer 4 tarpit In a Layer 4 tarpit, the honeypot server receives the initial SYN packet from the
attacker and replies with a SYN/ACK, but then does not open a socket and forgets
everything about the connection. The attacker sends an ACK, believes the TCP three-
way handshake to be completed, and starts sending data which never reaches its
destination. The attacker does not receive acknowledgment for the sent packets and
retransmits them; the connection eventually times out.
Layer 4 tarpitting can also be done by setting a TCP Window Size of 0 to block the
attacker from sending further data, while keeping the connection open.
Layer 7 tarpit Layer 7 tarpits are implemented by having services with a very high latency, e.g. a
SMTP server which sends useless replies and waits a long time (15 secs or more)
between lines.
SYN Proxy As a protection against SYN flood attacks, a host applying SYN Proxy to a TCP
connection responds to the initial SYN packet from the attacker with a specially
crafted SYN/ACK, then waits for the ACK in response before forwarding the
connection request to the server. The lack of SYN/ACK retransmissions may indicate
the presence of a honeypot, especially honeyd.
Bait and switch Technique consisting in redirecting all network communications to a honeypot once an
intrusion attempt is detected. Attacker-side, this can be identified by the change in
TCP/IP parameters (RTT, TTL, TCP timestamps, etc.)
Fake Access Points Honeypots may create fake Wi-Fi APs. These APs have random SSIDs and send
beacon frames but no other traffic.
User-mode Linux (UML) User-mode Linux allows multiple virtual Linux kernel-based guest OSes to run as an
application within a host Linux system. It is often used for honeypots, so references
to UML in /proc subdirectories may indicate that the attacked system is a honeypot.