Cheatsheet

= ARP vs MAC Table =

= Fragmentation =


 * Before fragmentation:


 * After fragmentation:

= Headers =

Hardware type Protocol type Hardware address length Protocol address length Operation Source MAC Source IP Dest MAC Dest IP
 * ARP Header

Code Checksum Rest of Header
 * ICMP Header

= TCP =

MSS WSF SACK Permitted
 * Parameters determined during Handshake:


 * MTU vs MSS



- Sender starts with cwnd = 1 MSS, Size increases 1 MSS each time one Ack arrives, Increases the rate exponentially(1,2,4,8....) until a threshold is reached
 * Congestion Control
 * Slow Start - Exponential Increase


 * Congestion Avoidance - Additive Increase

- Increases the cwnd Additively, When a “window” is Ack cwnd is increased by 1, Window = No of segments transmitted during RTT - The increase is based on RTT, not on the number of arrived ACKs, Congestion window increases additively until congestion is detected


 * Congestion Detection - Multiplicative Decrease

- If congestion occurs, Window size must be decreased, Sender knows about congestion via RTO or 3 Dup Acks received, Size of Threshold is dropped to half

- If RTO occured, TCP Reacts Strongly - Reduces cwnd back to 1 Segment, starts the slow start phase again
 * Tahoe

- If 3 Duplicate ACKs are received, TCP has a Weaker Reaction - Starts the Congestion Avoidance phase - This is called fast transmission and fast recovery
 * Reno


 * Silly Window Syndrome: Sender creates data slowly or Receiver consumes slowly or both.

Syndrome due to Sender: - Nagle’s Algorithm: Send data initially, accumulate data in output buffer, Wait for Ack or till 1 MSS Data in Buffer

Syndrome due to Receiver: - Clark’s Solution: Announce window size 0 till 1) enough space for 1 MSS in Buffer or Half Receive buffer is empty - Delayed Acknowledgment: Segment not acknowledged immediately, Sender TCP does not slide its window, reduces traffic, sender may unnecessarily retransmit, Not delay more than 500 ms.

- If RTO has a larger value - If sender receives four acknowledgments with same value (three duplicates) - Segment expected by all of these Ack is resent immediately
 * Fast Retransmission


 * Persistence Timer

- Issue of Deadlock created by Lost Ack, used to reset Window size 0 advertized earlier, is resolved by this timer - Sending TCP sends a special segment(1 byte of new data) called Probe, causes the receiving TCP to resend Ack - If no reply, another probe is sent and value of persistence timer is doubled and reset - Sender continues sending probes, doubling, resetting value of persistence timer until it reaches a threshold(generally 60s) - After that the sender sends one probe segment every 60s until the window is reopened

= VPN Messages =

Cookie,Proposal List Cookie,Accepted Proposal DH Key,Nonce DH Key,Nonce ID,ID Hash ID,ID Hash
 * Phase 1 - Main Mode

ID,Proposal List,DH Key,Nonce ID,Accepted Proposal,DH Key,Nonce,ID Hash ID Hash Ph1 Hash,Message ID,Proposal List,Nonce, DH Key,Proxy-ID Ph1 Hash,Message ID,Accepted Proposal,Nonce,DH Key,Proxy-ID Ph1 Hash,Message ID,Nonce
 * Phase 1 - Aggressive Mode
 * Phase 2 - Quick Mode

=HTTP Error Codes=

= HTTP Request Methods= GET:      Retrieve Data HEAD:     Header only without Response Body POST:     Submits Data to DB, web forum, etc PUT:      Replaces target resource with the uploaded content DELETE:   Removes target resource given by URI CONNECT:  Used when the client wants to establish a transparent connection to a remote host, usually to facilitate SSL-encrypted communication (HTTPS) through an HTTP proxy OPTIONS:  Returns the HTTP methods that the server supports for the specified URL TRACE:    Performs a message loop back test to see what (if any) changes or additions have been made by intermediate servers PATCH:

= SSL Handshake =



= NetScaler =

Least Connection   = Service with fewest active connections Round Robin        = Rotates a list of services Least Response time(LRTM) = Fewest active connections & lowest average response time Least Bandwidth     = Service serving least amount of traffic measured in mbps Least Packets       = Service that received fewest packets Source IP Hash      = Destination IP Hash =
 * LB Methods:

SOURCE IP = COOKIE Insert = Connections having same HTTP Cookie inserted by Set-Cookie directive from server belong to same persistence session. SSL Session   = Connections having same SSL session ID RULE           = All connection matching a user defined rule URL Passive   = requests having same server ID(Hexadecimal of Server IP & Port) of service to which request is to be fwded Dest IP       = SRC IP DST IP = CALL ID       = Same Caller ID in SIP Header
 * Persistence Methods:


 * What is Stateful & Stateless Persistence? Which one is more scalable/Efficient?

Stateless Session Persistence: Cookie inserted by ADC is more efficient because no need to create a table, NS will insert cookie & forget, with reply, it will read cookie value, decrypt it & fwd request. State-full Session Persistence: Server will insert cookie, NS will hash it & fwd based on Hash value but will need to keep a table in memory with all hashes & IP Addresses. Same is true for Source IP based Persistence, Also inefficient behind NAT Using Set-cookie-header = by Server - insert Name & Value Fields Client sends cookie in Cookie Header Who ever generates cookie, will be able to read it

= OSPF = Down Attempt Init 2-Way ExStart Exchange Loading Full
 * States

Type 1 - Router LSAs Type 2 - Network LSAs Type 3 - Network Summary LSA Type 4 - ASBR summary LSA Type 5 - AS external LSA Type 7 - NSSA External LSA Type 1 - Hello Type 2 - Database Description (DBD) Type 3 - Link-State request (LSR) Type 4 - LSU Type 5 - LSAck Same area Same authentication config Same subnet Same hello/dead interval Matching stub flags
 * LSA Type
 * Packet Types
 * Neighbor Requirements:




 * OSPF path selection: O > O*IA > O*E1 > O*E2.
 * “area range” summarize type 3 LSA’.
 * “summary-address” summarize type 5 & 7 LSA’s.
 * Auto-cost reference BW (Default = 100mb), formula = 100000000/Int-Bw.

= BGP =


 * Route Selection Criteria

Idle Active        Attempting to connect Connect       TCP session established OpenSent      Open message sent OpenConfirm   Response received Established   Adjacency established
 * BGP States

Open Update Keepalive      Sent every 60 seconds Notification   Always indicate something is wrong
 * BGP Messages

=VPN Monitor vs DPD vs IKE Heartbeat =

=SRX Architecture= Screens Static NAT | Dest NAT Route ==> Forwarding Lookup Zones Policy Reverse Static NAT | Source NAT Service ALG Session
 * First Path:

Screens TCP NAT Service ALG
 * Fast Path:

= ScreenOS = Sanity Check Screening Session lookup Route Lookup Policy lookup Session creation ARP lookup
 * ScreenOS Flow order

Policy Based Routing Source Interface Based Routing Source Routing Destination Routing Mapped IP Virtual IP  Policy Based NAT (NAT-Src & NAT-Dst) Interface Based NAT
 * Route preference order
 * NAT Preference order

= SYN Flood Protection = Threshold = Proxy connections above this limit If Syn-cookie is enabled, no sessions established between client & firewall or firewall & server directly Alarm Threshold = Alarm/Alert (to log) Queue Size = The number of proxied connections held in queue After this the firewall starts rejecting new connection requests Timeout Value is maximum time before a half-completed connection is dropped from the queue The range is 0–50s; default is 20s

= Linux =

Linux Booting
0 – halt 1 – Single user mode 2 – Multiuser, without NFS 3 – Full multiuser mode 4 – unused 5 – X11 6 – reboot
 * BIOS
 * MBR
 * GRUB
 * Kernel
 * Init
 * Runlevel programs

Manually Boot using Grub
grub> ls (hd0) (hd0,msdos5) (hd1) (hd1,msdos0)
 * Locate where the vmlinuz and initrd.* files are located:

grub> linux (hd1,msdos1)/install/vmlinuz root=/dev/sdb1 grub> initrd (hd1,msdos1)/install/initrd.gz grub> boot
 * Boot the system:

File system layout
/          – The Root Directory /bin       – Essential command binaries /boot      – Boot loader files /dev       – Device Files /etc       – Configuration Files /home      – Home Directory /lib       – Essential Libraries /lost+found – Recovering Files /media     – Removable Media Devices /mnt       – Temporarily mounted filesystems /opt       – Optional software packages /proc      – Kernel & Process Information /root      – Root Home Directory /sbin      – System binaries /selinux   – Security-Enhanced Linux /srv       – Service Data /sys       – virtual filesystem /tmp       – Temporary files /usr       – binaries, documentation, source code, libraries /var       – Variable Files

ProcFS

 * Procfs or /proc is a special FS under Linux used to present process information and kernel processes.
 * Much of the information for kernel level of 2.6 & above have been moved to "sysfs" generally mounted under /sys.
 * /proc is stored in memory.

"siblings" = (HT per CPU package) * (# of cores per CPU package) "cpu cores" = (# of cores per CPU package)
 * On multi-core CPUs, /proc/cpuinfo contains the fields for "siblings" and "cpu cores":


 * A CPU package means physical CPU which can have multiple cores (single core for one, dual core for two, quad core for four).
 * This allows a distinction between hyper-threading and dual-core, i.e. the number of hyper-threads per CPU package can be calculated by siblings / CPU cores.
 * If both values for a CPU package are the same, then hyper-threading is not supported.
 * For instance, a CPU package with siblings=2 and "cpu cores"=2 is a dual-core CPU but does not support hyper-threading.

/proc/cmdline      – Kernel command line information. /proc/consoles     – Information about current consoles including tty. /proc/crypto	   – list of available cryptographic modules /proc/devices      – Device drivers currently configured for the running kernel. /proc/diskstats    – /proc/dma          – Info about current DMA channels. /proc/fb           – Framebuffer devices. /proc/filesystems  – Current filesystems supported by the kernel. /proc/iomem        – Current system memory map for devices. /proc/ioports      – Registered port regions for input output communication with device. /proc/kmsg	    – holding messages output by the kernel /proc/loadavg      – System load average. /proc/locks        – Files currently locked by kernel. /proc/meminfo      – Summary of how the kernel is managing its memory. /proc/misc         – Miscellaneous drivers registered for miscellaneous major device. /proc/modules      – Currently loaded kernel modules. /proc/mounts       – List of all mounts in use by system. /proc/partitions   – Detailed info about partitions available to the system. /proc/pci          – Information about every PCI device. /proc/scsi	    – Information about any devices connected via a SCSI or RAID controller /proc/stat         – Record or various statistics kept from last reboot. /proc/swap         – Information about swap space. /proc/tty	    – Information about the current terminals /proc/uptime       – Uptime information (in seconds). /proc/version      – Kernel version, gcc version, and Linux distribution installed.

/proc/PID/cmdline  – Command line arguments. /proc/PID/cpu      – Current and last cpu in which it was executed. /proc/PID/cwd	    – Link to the current working directory. /proc/PID/environ  – Values of environment variables. /proc/PID/exe	    – Link to the executable of this process. /proc/PID/fd	    – Directory, which contains all file descriptors. /proc/PID/maps	    – Memory maps to executables and library files. /proc/PID/mem	    – Memory held by this process. /proc/PID/root	    – Link to the root directory of this process. /proc/PID/stat	    – Process status. /proc/PID/statm    – Process memory status information. /proc/PID/status   – Process status in human readable form (eg: GID, UID, etc) /proc/PID/limits   – Contains information about the limits of the process

Usage: ls -l /proc/$(pgrep -n python)/exe

Inode Number
Source: linoxide.com


 * Inode is entry in inode table containing metadata about a regular file and directory.
 * An inode is a data structure on a traditional Unix-style file system such as ext3 or ext4.
 * Linux extended filesystems such as ext2 or ext3 maintain an array of these inodes: the inode table.
 * This table contains list of all files in that filesystem.
 * The individual inodes in inode table have a unique number (unique to that filesystem) - the inode number.
 * There are some data about files, such as their size, ownership, permissions, timestamp etc.
 * This meta-data about a file is managed with a data structure known as an inode (index node).


 * There is no entry for file name in the Inode, file name is kept as a separate entry parallel to Inode number.
 * This is for maintaining hard-links to files.


 * Copy file: cp allocates a free inode number and placing a new entry in inode table.
 * Move or Rename a file: if destination is same filesystem as the source, Has no impact on inode number, it only changes the time stamps in inode table.
 * Delete a file: Deleting a file in Linux decrements the link count and freeing the inode number to be reused.


 * A Directory cannot hold two files with same name because it cannot map one name with two different inode numbers.
 * The inode number of / directory is fixed, and is always 2.


 * There exists an algorithm which is used to create number of Inodes in a file system.
 * This algorithm takes into consideration the size of the file system and average file size.
 * The user can tweak the number of Inodes while creating the file system.


 * Inode number (or index number) consists following attributes:

File type:                Regular file, directory, pipe etc. Permissions:               Read, write, execute Link count:               The number of hard link relative to an inode User ID:                  Owner of file Group ID:                 Group owner Size of file:             or major/minor number in case of some special files Time stamp:               Access time, modification time and (inode) change time Attributes:               Immutable' for example Access control list:      Permissions for special users/groups Link to location of file Other metadata about the file

df -i                               ==> Inodes on Filesystem df -i /dev/vda1                     ==> Inodes on Filesystem ls -il myfile.txt                   ==> Show inode no of file find /home/rahul -inum 1150561      ==> Find file using inode no stat unetbootin.bin                  ==> Show all details of file stat --format=%i unetbootin.bin     ==> Shows only inode no
 * Check info:

List the contents of the filesystem superblock tune2fs -l /dev/sda6 | grep inode
 * Manipulate the filesystem meta data

Make sure files on the file system are not being accessed: mount -o remount /yourfilesystem

debugfs /dev/sda1                   ==> Manipulate FS here

You can use debugfs to undelete a file by using its inode and indicating a file

In the case of inodes are full, You need to remove unused files from the filesystem to make Inode free. There is no option to increase/decrease inodes on disk. Its only created during the creation of filesystem on any disk.
 * Free Inodes on Filesystem

Sort links vs Hard link
drwxr-xr-x 6 aman aman    4096 Mar 30 11:50  Documents drwxr-xr-x 3 aman aman    4096 Sep 15 19:11  Downloads ^
 * Links and index number in Linux
 * In the output of ls -l, the column following the permissions and before owner is the link count.
 * Link count is the number of Hard Links to a file.
 * A link is a pointer to another file.
 * There are two types of links:

ln -s /home/bob/sync.sh filesync
 * Symbolic links (or Soft Links)
 * A separate file whose contents point to the linked-to file.
 * When creating a Sym link, first refer to the name of the original file and then to the name of the link:


 * Editing Sym link is like directly edit the original file.
 * If we delete or move the original file, the link will be broken and our filesync file will not be longer available.

ls -l filesync lrwxrwxrwx 1 root root 20 Apr 7 06:08 filesync -> /home/bobbin/sync.sh
 * The ls -l command shows that the resulting file is a symbolic link:


 * The contents of a symbolic link are the name of target file only.
 * The permissions on the symbolic link are completely open.
 * This is because the permissions are not managed
 * The original file is just a name that is connected directly to the inode, and the symbolic link refers to the name.
 * The size of the symbolic link is the number of bytes in the name of the file it refers to, because no other information is available in the symbolic link.


 * Hard links


 * The identity of a file is its inode number, not its name.
 * A hard link is a name that references an inode.
 * It means that if file1 has a hard link named file2, then both of these files refer to same inode.
 * So, when you create a hard link for a file, all you really do is add a new name to an inode.
 * there is no difference between the original file and the link: they are just two names connected to the same inode.

ln /home/bob/sync.sh synchro
 * Create a Hard link:

ls -il /home/bob/sync.sh synchro 517333 -rw-r- 2 root root 5 Apr 7 06:09 /home/bob/sync.sh 517333 -rw-r- 2 root root 5 Apr 7 06:09 synchro
 * Compare:


 * The directories cannot be hard linked as Linux does not permit this to maintain the acyclic tree structure of directories.
 * A hard link cannot be created across filesystems. Both the files must be on the same filesystems, because different filesystems have different independent inode tables (two files on different filesystems, but with same inode number will be different).

/home/bob/sync.sh /root/synchro
 * How to find hard link in Linux
 * 1) find / -inum 517333


 * Remove files
 * When rm command is issued, first it checks the link count of the file.
 * If the link count is greater than 1, then it removes that directory entry and decreases the link count.
 * Still, data is present, nor is the inode affected.
 * And when link count is 1, the inode is deleted from the inode table, inode number becomes free, and the data blocks that this file was occupying are added to the free data block list.

Commands
netstat -s netstat -anp netstat -ant
 * netstat


 * ps

ps -aux ps -ant ps -anp

us - user cpu time (or) % CPU time spent in user space sy - system cpu time (or) % CPU time spent in kernel space ni - user nice cpu time (or) % CPU time spent on low priority processes id - idle cpu time (or) % CPU time spent idle wa - io wait cpu time (or) % CPU time spent in wait (on disk) hi - hardware irq (or) % CPU time spent servicing/handling hardware interrupts si - software irq (or) % CPU time spent servicing/handling software interrupts st - steal time % CPU time in involuntary wait by virtual cpu while hypervisor is servicing another processor (or) % CPU time stolen from a virtual machine
 * top

Append a character to each file name indicating the file type:
 * ls

ls -F or ls --classify

*  Executable files /  Directories @  Symbolic links |  FIFOs =  Sockets >  Doors Nothing for Regular Files

List Symoblic Links:

ls -la lrwxrwxrwx  1 root       root                    11 Sep 13 14:57 mounts -> self/mounts dr-xr-xr-x  3 root       root                     0 Sep 13 14:57 mpt -rw-r--r--  1 root       root                     0 Sep 13 14:57 mtrr


 * free


 * du


 * df


 * curl


 * wget


 * smem


 * nslookup


 * dig


 * mtr


 * Misc

Find Sym Links: find. -type l -ls ls -la | grep "\->"

CPU Info: lscpu nproc grep 'model name' /proc/cpuinfo | wc -l

Obtain the PID with a utility: pgrep -n python pidof chrome              - return all PIDs pidof -s chrome           - return only 1 PID ps -C chrome -o pid=      - C = CMD

= Flows =


 * Complete Flow of PC opening a Website:


 * 1) Check NW config
 * 2) DHCP if not configured
 * 3) Check Domain name in Browser Cache
 * 4) Check Domain name in OS Cache
 * 5) Check if an entry exists in Hosts File
 * 6) If not Found in any cache, Prepare to send UDP DNS query to DNS Server
 * 7) If DNS Server configured is in same Network Check MAC address in ARP Table
 * 8) If not found, send ARP for MAC Address
 * 9) Forward DNS Query to DNS Server and wait for reply containing IP address of Website
 * 10) If DNS server configured is not in same subnet, check Gateway config(IP & MAC address)
 * 11) If MAC address not found in ARP Table, send ARP request
 * 12) After getting reply, fwd the DNS query to gateway
 * 13) After getting DNS response, start TCP 3-way handshake S-SA-A.
 * 14) Start SSL Handshake if SSL/TLS configured
 * 15) Send GET Request
 * 16) Client sends ACK & Body containing HTML Data
 * 17) If HTTP 1.0, Server sends FIN & CLoses connection
 * 18) Client send FIN-ACK
 * 19) Server sends Ack


 * Complete Flow of DNS Traffic


 * 1) Check NW config
 * 2) DHCP if not configured
 * 3) Check Domain name in Browser Cache
 * 4) Check Domain name in OS Cache
 * 5) Check if an entry exists in Hosts File
 * 6) If not Found in any cache, Prepare to send UDP DNS query to DNS Server
 * 7) If DNS Server configured is in same Network Check MAC address in ARP Table
 * 8) If not found, send ARP for MAC Address
 * 9) Forward DNS Query to DNS Server and wait for reply containing IP address of Website
 * 10) If DNS server configured is not in same subnet, check Gateway config(IP & MAC address)
 * 11) If MAC address not found in ARP Table, send ARP request
 * 12) After getting reply, fwd the DNS query to gateway
 * 13) DNS Server ??
 * 14) DNS Server ?? Iterative? Recursive? TLD? Authoritative
 * 15) DNS Server ??
 * 16) After getting DNS response, start TCP 3-way handshake S-SA-A.

[PC1]-[Hub]-[Switch]-[Router]--[Router]--[PC2]
 * Complete Flow of Traffic passing through below scenario:


 * 1) Check NW config
 * 2) DHCP if not configured
 * 3) Check if PC2 in same Subnet(not in this scenario as routers present)
 * 4) If in Same Subnet, check if MAC address is there in ARP Table
 * 5) Else send ARP Request
 * 6) Once MAC address is known, directly send Packet to PC2
 * 7) If PC2 is in Different Subnet(True for above scenario), Check Gateway IP address & MAC address
 * 8) If MAC address is not known, send an ARP request.
 * 9) Hub is directly connected, will receive & Flood packet on all Ports.
 * 10) Switch will receive packet and check its CAM Table for the MAC to Port bindings
 * 11) If MAC entry is not found in CAM table, Switch will Flood the ARP packet on all ports.
 * 12) Other destinations will drop the ARP Request packet as they do not have the IP address requested in ARP Header.
 * 13) Only Router will accept the packet as it has the requested IP address matching its own MAC address.
 * 14) It will reply with an ARP Reply message.
 * 15) Switch will add an entry of this MAC address & port number in its CAM Table once the reply packet pass through it.
 * 16) Hub will flood the packet through all ports.
 * 17) ARP Reply will reach PC1, it will add entry to its ARP Table
 * 18) Then send a packet destined to PC2 with destintion MAC address as Router's Interface's MAC address received in ARP reply.