Skip to content

raulmouzo/Pentesting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

218 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Linux and pentesting basics

Useful links

Basic linux commands

https://gist.github.com/jonathanmorley/9876546#file-linux-commands-md

1. SYSTEM

$ uname –a                          # Display linux system information
$ uname –r                          # Display kernel release information (refer uname command in detail)
$ hostname                          # Show system host name
$ hostname -i                       # Display the IP address of the host (all options hostname)
$ uptime                            # Show how long system running + load (learn uptime command)
$ last reboot                       # Show system reboot history (more examples last command)
$ cat /etc/redhat_release           # Show which version of redhat installed 
$ date                              # Show the current date and time (options of date command)
$ cal                               # Show this month calendar (what more in cal)
$ w                                 # Display who is online (learn more about w command)
$ whoami                            # Who you are logged in as (example + sreenshots)
$ finger user                       # Display information about user (many options of finger command)

2. Hardware

$ dmesg                             # Detected hardware and boot messages (dmesg many more options)
$ cat /proc/cpuinfo                 # CPU model
$ cat /proc/meminfo                 # Hardware memory
$ cat /proc/interrupts              # Lists the number of interrupts per CPU per I/O device
$ lshw                              # Displays information on hardware configuration of the system
$ lsblk                             # Displays block device related information in Linux (sudo yum install util-linux-ng)
$ free -m                           # Used and free memory (-m for MB) (free command in detail)
$ lspci -tv                         # Show PCI devices (very useful to find vendor ids)
$ lsusb -tv                         # Show USB devices (read more lsusb options)
$ lshal                             # Show a list of all devices with their properties 
$ dmidecode                         # Show hardware info from the BIOS (vendor details)
$ hdparm -i /dev/sda                # Show info about disk sda 
$ hdparm -tT /dev/sda               # Do a read speed test on disk sda
$ badblocks -s /dev/sda             # Test for unreadable blocks on disk sda

3. Statistics

$ top                               # Display and update the top cpu processes (30 example options)
$ mpstat 1                          # Display processors related statistics (learn mpstat command)
$ vmstat 2                          # Display virtual memory statistics (very useful performance tool)
$ iostat 2                          # Display I/O statistics (2sec Intervals) (more examples)
$ tail -n 500 /var/log/messages     # Last 10 kernel/syslog messages (everyday use tail options)
$ tcpdump -i eth1                   # Capture all packets flows on interface eth1 (useful to sort network issue)
$ tcpdump -i eth0 'port 80'         # Monitor all traffic on port 80 ( HTTP )
$ lsof                              # List all open files belonging to all active processes.(sysadmin favorite command)
$ lsof -u testuser                  # List files opened by specific user
$ free –m                           # Show amount of RAM (daily usage command)
$ watch df –h                       # Watch changeable data continuously(interesting linux command)

4. Users

$ id                                        # Show the active user id with login and group(with screenshot)
$ last                                      # Show last logins on the system (few more examples)
$ who                                       # Show who is logged on the system (real user who logged in)
$ groupadd   admin                          # Add group "admin" (force add existing group)
$ useradd -c "Sam Tomshi" -g admin -m sam   # Create user "sam" and add to group "admin" (here read all parameter)
$ userdel sam                               # Delete user sam (force,file removal)
$ adduser sam                               # Add user "sam" 
$ usermod                                   # Modify user information (mostly useful for linux system admins)

5. File Commands

$ ls –al                                # Display all information about files/ directories(20 examples)
$ pwd                                   # Show current directory path(simple but need every day)
$ mkdir directory-name                  # Create a directory(create mutiple directory)
$ rm file-name                          # Delete file(be careful of using rm command)
$ rm -r directory-name                  # Delete directory recursively 
$ rm -f file-name                       # Forcefully  remove file
$ rm -rf directory-name                 # Forcefully remove directory recursively
$ cp file1 file2                        # Copy file1 to file2 (15 cd command examples)
$ cp -r dir1 dir2                       # Copy dir1 to dir2, create dir2 if it doesn’t  exist
$ mv file1 file2                        # Move files from one place to another(with 10 examples)
$ ln –s  /path/to/file-name  link-name  # Create symbolic link to file-name (examples)
$ touch file                            # Create or update file (timestamp change)
$ cat > file                            # Place standard input into file (15 cat command examples)
$ more file                             # Output the contents of file (help display long tail files)
$ head file                             # Output the first 10 lines of file (with different parameters)
$ tail file                             # Output the last 10 lines of file (detailed article with tail options)
$ tail -f file                          # Output the contents of file as it grows starting with the last 10 lines
$ gpg -c file                           # Encrypt file (how to use gpg)
$ gpg file.gpg                          # Decrypt file

6. Process Related

$ ps                                # Display your currently active processes (many parameters to learn)
$ ps aux | grep 'telnet'            # Find all process id related to telnet process
$ pmap                              # Memory map of process (kernel,user memory etc)
$ top                               # Display all running processes (30 examples)
$ kill pid                          # Kill process with mentioned pid id (types of signals)
$ killall proc                      # Kill all processes named proc
$ pkill processname                 # Send signal to a process with its name
$ bg                                # Resumes suspended jobs without bringing them to foreground (bg and fg command)
$ fg                                # Brings the most recent job to foreground
$ fg n                              # Brings job n to the foreground

7. File Permission Related

$ chmod octal file-name                     # Change the permissions of file to octal , which can be found separately for user, group and world
                                            # Octal value (more examples)
                                            # 4 - read
                                            # 2 – write
                                            # 1 – execute
# Example 
$ chmod 777 /data/test.c                    # Set rwx permission for owner , rwx  permission for group, rwx permission for world
$ chmod 755 /data/test.c                    # Set rwx permission for owner,rx for group and world
$ chown owner-user file                     # Change owner of the file (chown more examples)
$ chown owner-user:owner-group  file-name   # Change owner and group owner of the file
$ chown owner-user:owner-group directory    # Change owner and group owner of the directory
# Example 
$ chown bobbin:linoxide test.txt
$ ls -l test.txt                            # -rw-r--r-- 1 bobbin linoxide 0 Mar 04 08:56 test.txt

8. Network

$ ifconfig –a                           # Display all network ports and ip address (set mtu and other all options)
$ ifconfig eth0                         # Display specific  ethernet port ip address and details
$ ip addr show                          # Display all network interfaces and ip address (available in iproute2 package, more powerful than ifconfig)
$ ip address add 192.168.0.1 dev eth0   # Set ip address
$ ethtool eth0                          # Linux tool to show ethernet status (set full duplex , pause parameter)
$ mii-tool  eth0                        # Linux tool to show  ethernet status (more or like ethtool)
$ ping host                             # Send echo request to test connection (learn sing enhanced ping tool)
$ whois domain                          # Get who is information for domain
$ dig domain                            # Get DNS information for domain (screenshots with other available parameters)
$ dig  -x host                          # Reverse lookup host 
$ host google.com                       # Lookup DNS ip address for the name (8 examples of host command)
$ hostname –i                           # Lookup local ip address (set hostname too)
$ wget file                             # Download file (very useful other option)
$ netstat  -tupl                        # Listing all active listening ports(tcp,udp,pid) (13 examples)

9. Compression / Archives

$ tar cf home.tar  home             # Create tar named home.tar containing home/ (11 tar examples)
$ tar xf file.tar                   # Extract the files from file.tar
$ tar czf  file.tar.gz  files       # Create a tar with gzip compression
$ gzip file                         # Compress file and renames it to file.gz (untar gzip file)

10. Install Package

$ rpm -i pkgname.rpm                # Install rpm based package (Installing, Uninstalling, Updating, Querying, Verifying)
$ rpm -e pkgname                    # Remove package
# Install from source
$ ./configure
$ make
$ make install (what it is)

11. Search

$ grep pattern files                # Search for pattern in files (you will this command often)
$ grep  -r pattern dir              # Search recursively for pattern in dir
$ locate file                       # Find all instances of file
$ find /home/tom -name 'index*'     # Find files names that start with "index"(10 find examples)
$ find /home -size +10000k          # Find files larger than 10000k in /home

12. Login (ssh and telnet)

$ ssh user@host                     # Connect to host as user (secure data communication command)
$ ssh  -p port user@host            # Connect to host using specific port
$ telnet host                       # Connect to the system using  telnet port

13. File Transfer

scp
$ scp file.txt   server2:/tmp                           # Secure copy file.txt to remote host  /tmp folder
$ scp nixsavy@server2:/www/*.html   /www/tmp            # Copy *.html files from remote host to current system /www/tmp folder
$ scp -r nixsavy@server2:/www   /www/tmp                # Copy all files and folders recursively from remote server to the current system /www/tmp folder
rsync
$ rsync -a /home/apps /backup/                          # Synchronize source to destination
$ rsync -avz /home/apps linoxide@192.168.10.1:/backup   # Synchronize files/directories between the local and remote system with compression enabled

14. Disk Usage

$ df –h                             # Show free space on mounted filesystems(commonly used command)
$ df -i	                            # Show free inodes on mounted filesystems
$ fdisk -l	                        # Show disks partitions sizes and types(fdisk command output)
$ du -ah                            # Display disk usage in human readable form (command variations)
$ du -sh                            # Display total disk usage on the current directory
$ findmnt                           # Displays target mount point for all filesystem (refer type,list,evaluate output)
$ mount device-path mount-point     # Mount a device 

15. Directory Traverse

$ cd /test                          # Change to /test directory
$ cd ..                             # To go up one level of the directory tree(simple & most needed)
$ cd	                            # Go to $HOME directory

File Permissions

https://github.com/krishnaprasadkv/Linux-Commands/blob/master/filepermissions.md

Types of Files:

Symbol Type of File
- Normal file
d Directory
l Link file (shortcut)
b Block file (Harddisk, Floppy disk)
c Character file (Keyboard, Mouse)

Permissions are applied on three levels

  • Owner or User level
  • Group level
  • Others level

Access modes are of three types

  • r read only
  • w write/edit/delete/append
  • x execute/run a command

Access modes are different on file and directory

Permissions Files Directory
r Open the file 'ls' the contents of dir
w Write, edit, append, delete file Add/Del/Rename contents of dir
x To run a command/shell script To enter into dir using 'cd'

Some usefull commands

  • chgrp: change group ownership
  • chown: change file owner and group
  • usermod -a -G : add a new group to user
  • passwd: change user password

Exceptional file permissions

In Linux, file permissions determine the access rights for files and directories. The basic file permissions are read (r), write (w), and execute (x), which can be assigned to three different user categories: the owner (u), the group (g), and others (o).

Additionally, there are some exceptional file permissions that provide special access rights. These exceptional permissions include:

  • Set User ID (SUID): When the SUID permission is set on an executable file, it allows the user who executes the file to temporarily assume the owner's privileges for that file during the execution.
  • Set Group ID (SGID): Similar to SUID, the SGID permission allows the user to temporarily assume the group's privileges for the file during the execution.
  • Sticky Bit (SBIT): When the sticky bit is set on a directory, it restricts the deletion or renaming of files within that directory to the file's owner, the directory owner, or the superuser. It is commonly used for shared directories where multiple users have write access.

To represent these exceptional permissions in numerical format, the following values are added to the basic permissions:

  • SUID: 4
  • SGID: 2
  • SBIT: 1

For example, if an executable file has the SUID permission, its numerical permission value would be 4 + 1 = 5.

Exceptional file permissions can be displayed using the ls command with the -l option, which shows the file details along with their permissions.

https://gist.github.com/nicolaschan/8496337c603575a16ab1ffe2e3da127f

setuid (s) setgid (s) sticky (t)
Directory ignored New subfiles inherit group Only owner of subfile can (re)move it*
File Executes as file owner Executes as group ignored

Sticky bit can be set with chmod as the first of four digits, or using {+,-}s (for setuid/setgid) and {+,-}t (for sticky). For example, to enable setuid,

chmod u+s $FILE  # Add setuid to a file
chmod 4755 $FILE # Possible permissions of /bin/ping

Permissions displayed as an {s,S,t,T} in the third character of each permission section. For example,

-rwsr-xr-x 1 root root 68520 Aug 29 01:25 /bin/ping*
  • Since the setuid/setgid/sticky bit character is written in the same place as the execute bit, lowercase indicates execute bit is set and uppercase means execute bit is not set.

  • Root and owner of the directory can also (re)move subfiles. Commonly used in /tmp

How can we find suid permissions? find / -type f -perm 4000 2>/dev/nulll

Control Attributes

There are two commands lsattr and chattr that are used for attribute management.

Attribute Description
a can only be appended
A prevents updating the access time
c automatically compressed
D changes on directory are written synchronously to disk
e file uses extents for mapping the block on disk
i file cannot be changed, renamed or deleted
S changes in a file are written synchronously to disk

Linux directory structure

https://www.makeuseof.com/linux-directory-structure-explained/ http://www.dba-oracle.com/linux/important_files_directories.htm

  • / (root): stores all the directories in Linux.

  • /boot: contains important files needed by the boot loader.

  • /dev: contains special, virtual files representing hardware components.

  • /etc: contains vital system configuration files such as startup scripts, networking files, user account-related files, etc.

    • /etc/bashrc: contains global defaults and aliases used by the bash shell
    • /etc/crontab: a parent shell script to run commands periodically. It invokes hourly, daily, weekly, and monthly scripts.
    • /etc/group: holds information regarding security group definitions.
    • /etc/grub.conf: the grub boot loader configuration file.
    • /etc/hosts: contains host names and their corresponding IP addresses used for name resolution whenever a DNS server is unavailable.
    • /etc/passwd: contains information regarding registered system users. Passwords are typically kept in a shadow file for better security.
    • /etc/resolv.conf: a list of domain name servers (DNS) used by the local machine
    • /etc/shadow: stores encrypted password hashes for user accounts, ensuring added security. The file includes username, encrypted password hash, and other account-related details.
  • /home: stores an individual user's home directory.

  • /bin: contains system commands and other executable programs.

  • /opt: contains optional software packages to facilitate better compatibility of certain applications. When you install a third-party application that is not available in the official distribution repository, its software code gets stored in the /opt directory.

  • /proc: is a pseudo-filesystem containing information about processes and kernel parameters. It is populated with data during boot-up and is cleaned when you shut down your Linux machine.

  • /tmp: is used by the system and its applications to store temporary files. You can also store temporary data in this folder, but remember that the data will be deleted upon rebooting your system.

  • /root: is the home folder of the root user.

  • /usr: contains most of the files, libraries, programs, and system utilities.

  • /var: is the storage space for system-generated variable files, and it includes logs, caches, and spool files

  • /media: contains mount points for removable media devices such as USB drives, external hard drives, CD/DVD drives, and network shares.

  • /mnt: is used to mount storage devices in the system temporarily.

  • /lib: serves as the storage space for all libraries needed by the binaries in the /bin directory.

  • /sys: contains information about the various system components and drivers.

  • /run: directory logs system information since boot time.

-> More information about /etc/passwd:

username:password:userID:groupID:comment:homeDirectory:shell

Field Description
username The username for the account.
password Historically, an "x" is stored in this field, indicating that the encrypted password is stored in the "/etc/shadow" file or an authentication mechanism like LDAP is used. The actual encrypted password is not shown in the "/etc/passwd" file.
userID A unique numerical identifier (UID) for the user.
groupID The group ID (GID) of the user's primary group.
comment Optional additional information or a comment associated with the account.
homeDirectory The user's home directory, which typically contains their personal files.
shell The user's default shell, which determines the command interpreter used when the user logs in.

Linux Enviroment Variables

https://github.com/carlospolop/hacktricks/blob/master/linux-hardening/linux-environment-variables.md

Common variables

From: https://geek-university.com/linux/common-environment-variables/

  • DISPLAY – the display used by X. This variable is usually set to :0.0, which means the first display on the current computer.
  • EDITOR – the user’s preferred text editor.
  • HISTFILESIZE – the maximum number of lines contained in the history file.
  • HISTSIZE - Number of lines added to the history file when the user finish his session
  • HOME – your home directory.
  • HOSTNAME – the hostname of the computer.
  • LANG – your current language.
  • MAIL – the location of the user’s mail spool. Usually /var/spool/mail/USER.
  • MANPATH – the list of directories to search for manual pages.
  • OSTYPE – the type of operating system.
  • PS1 – the default prompt in bash.
  • PATH - stores the path of all the directories which holds binary files you want to execute just by specifying the name of the file and not by relative or absolute path.
  • PWD – the current working directory.
  • SHELL – the path to the current command shell (for example, /bin/bash).
  • TERM – the current terminal type (for example, xterm).
  • TZ – your time zone.
  • USER – your current username.

Interesting variables for hacking

HISTFILESIZE

Change the value of this variable to 0, so when you end your session the history file (~/.bash_history) will be deleted.

export HISTFILESIZE=0

HISTSIZE

Change the value of this variable to 0, so when you end your session any command will be added to the history file (~/.bash_history).

export HISTSIZE=0

http_proxy & https_proxy

The processes will use the proxy declared here to connect to internet through http or https.

export http_proxy="http://10.10.10.10:8080"
export https_proxy="http://10.10.10.10:8080"

SSL_CERT_FILE & SSL_CERT_DIR

The processes will trust the certificates indicated in these env variables.

export SSL_CERT_FILE=/path/to/ca-bundle.pem
export SSL_CERT_DIR=/path/to/ca-certificates

Bash Redirections Cheat Sheet

https://github.com/pkrumins/bash-redirections-cheat-sheet

Redirection Description
cmd > file Redirect the standard output (stdout) of cmd to a file.
cmd 1> file Same as cmd > file. 1 is the default file descriptor (fd) for stdout.
cmd 2> file Redirect the standard error (stderr) of cmd to a file. 2 is the default fd for stderr.
cmd >> file Append stdout of cmd to a file.
cmd 2>> file Append stderr of cmd to a file.
cmd &> file Redirect stdout and stderr of cmd to a file.
cmd > file 2>&1 Another way to redirect both stdout and stderr of cmd to a file. This is not the same as cmd 2>&1 > file. Redirection order matters!
cmd > /dev/null Discard stdout of cmd.
cmd 2> /dev/null Discard stderr of cmd.
cmd &> /dev/null Discard stdout and stderr of cmd.
cmd < file Redirect the contents of the file to the standard input (stdin) of cmd.
cmd << EOL Redirect a bunch of lines to the stdin. If 'EOL' is quoted, text is treated literally. This is called a here-document.
cmd <<- EOL Redirect a bunch of lines to the stdin and strip the leading tabs.
cmd <<< "string" Redirect a single line of text to the stdin of cmd. This is called a here-string.
exec 2> file Redirect stderr of all commands to a file forever.
exec 3< file Open a file for reading using a custom file descriptor.
exec 3> file Open a file for writing using a custom file descriptor.
exec 3<> file Open a file for reading and writing using a custom file descriptor.
exec 3>&- Close a file descriptor.
exec 4>&3 Make file descriptor 4 to be a copy of file descriptor 3. (Copy fd 3 to 4.)
exec 4>&3- Copy file descriptor 3 to 4 and close file descriptor 3.
echo "foo" >&3 Write to a custom file descriptor.
cat <&3 Read from a custom file descriptor.
(cmd1; cmd2) > file Redirect stdout from multiple commands to a file (using a sub-shell).
{ cmd1; cmd2; } > file Redirect stdout from multiple commands to a file (faster; not using a sub-shell).
exec 3<> /dev/tcp/host/port Open a TCP connection to host:port. (This is a bash feature, not a Linux feature).
exec 3<> /dev/udp/host/port Open a UDP connection to host:port. (This is a bash feature, not a Linux feature).

Linux Capabilities

Basic Commands:

  1. getcap: Displays the capabilities assigned to an executable file.
getcap /path/to/executable_file
  1. setcap: Assigns capabilities to an executable file.
sudo setcap <capability> <executable_file>
  1. getpcaps: Shows the effective, permitted, and inheritable capabilities of a running process.
getpcaps <process_ID>

Fundamental Capabilities:

  1. CAP_CHOWN: Allows changing the ownership of files and directories.

  2. CAP_DAC_OVERRIDE: Allows bypassing file access (DAC) permissions when reading, writing, or executing files.

  3. CAP_DAC_READ_SEARCH: Allows bypassing file access (DAC) permissions when reading or searching (accessing directories).

  4. CAP_FOWNER: Allows performing operations with owner privileges, such as changing file permissions even on system-protected files.

  5. CAP_SETUID: Allows changing the user ID (UID), including the ability to elevate privileges through the execution of SUID programs.

  6. CAP_SETGID: Allows changing the group ID (GID), including the ability to elevate privileges through the execution of SGID programs.

  7. CAP_NET_BIND_SERVICE: Allows binding sockets to low-numbered TCP or UDP ports (typically reserved for the system or superuser).

  8. CAP_SYS_CHROOT: Allows using the chroot command, which changes the root directory for a process and restricts its access to the filesystem.

  9. CAP_KILL: Allows sending signals to other processes, including signals that can terminate them.

About

Linux and pentesting basics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors