> For the complete documentation index, see [llms.txt](https://666isildur.gitbook.io/ethical-hacking/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://666isildur.gitbook.io/ethical-hacking/ctf-oscp-methodology/fundamentals/linux/basics.md).

# Basics

https\://linuxjourney.com/

### 1. The Shell

#### Navigating

`pwd` → Print working directory

`cd` → Change directory (Ex: `cd /home/isildur/Documents` change to Documents directory)

`cd ..` → Change directory to parent directory

`cd ~` → Change directory to your home directory

`cd -` → Go back to previous directory

#### Looking at files

`ls` → List files in directory

`ls -la` → Shows a detailed list of files in long format (`-l`) and lists all hidden files (`-a`)

`file` → Shows info about a file (what type of file it is) and a description of the file's contents

`cat` → Output the content of a file

`less` → Output the content of a file in a page manner, so you can navigate through a text file page by page

`more` → Output the file but hust a little bit at a time, similar to `less`

#### Working with files

`touch` → Create a new file

`cp` → Copy

`mv` → Move files and also renames them

`mkdir` → Make a directory

`mkdir -p new/thisonetoo/and/this/one` → Make entire directory structure

`rm` → Remove file

`rm -rf ./directory` → Remove recursively and its content. Very dangerous!

`rmdir` → Remove empty directory

#### General

`history` → Show commands history

`sudo` → Used before commands to execute this commands as root

`sudo -l` → List what rights the sudo user has

`cat /etc/sudoers` → Find which users have sudo rights

#### Finding Files

`find` → Slower command to locate files but a lot more thorough. You can search for files recursively and with regex and lof of more features

`find /home -name picture.jpg` → Find if there is a file named picture.jpg in the home directory

`find /home -type d -name MyFolder` → Find a directory (`-type d`) named `MyFolder` in the home directory

`find / -name file 2>/dev/null` → Send all permisions denied outputs to `dev/null`

`locate` → Locates files or directories really fast on an internal database

`sudo updatedb` → Updates database in order to run the `locate` command

`which` → Outputs the path of the binary that you are looking for, searching through the directories that are defined in you $PATH variable

### 2. String manipulation

#### stdout (Standard Out)

`echo Hello World > new.txt` → Adds "Hello World" to the `new.txt` file, overwritting it

`echo Hello World >> new.txt` → Adds "Hello World" to the `new.txt` file without overwritting it (appends)

#### stdin (Standard In)

`cat < new.txt > other.txt` → Redirects `new.txt` content as stdin to the `other.txt` file (`<` used for stdin redirection)

#### stderr (Standard Error)

`ls /fake/directory 2> new.txt` → Redirect stderr to the `new.txt` file

`ls /fake/directory > new.txt 2>&1` → Redirect stderr and stdout to the `new.txt` file

#### Pipe and tee

`ls -la /etc | less` → Pipe `less` with the `ls -la` command

`ls | tee new.txt` → Displays the content of `ls` in the screen and inside the `new.txt` file

#### env (Environment)

`echo $HOME` → Path to your home directory

`echo $USER` → Returns username

`env` → Returns information about the environment variables

`echo $PATH` → Returns a list of paths separated by a colon that the system searches when it runs a command

#### Editing Text

`sed "1d"` → Removes first line of file/stream

`cut -c 5 new.txt` → Outputs the 5th character in each line of the `new.txt` file

`cut -f 2 new.txt` → Extract contents by a field, by default everything separated by a TAB is a field.

`cut -f 1 -d ";" new.txt` → Extract first field separated by `;`

`head` → Outputs the first 10 lines of a file

`head -n 15` → Outputs the first 15 lines of a file

`tail` → Outputs the last 10 lines of a file

`tail -n 15` → Outputs the last 15 lines of a file

`join file1.txt file2.tx` → Joing `file1.txt` and `file2.txt`

`sort new.txt` → Sort `new.txt` in alphabetic order

`sort -r new.txt` → Sort `new.txt` in reverse alphabetic order

`sort -n new.txt` → Sort `new.txt` by numerical value

`tr a-z A-Z` → Translate all lower case character to uppercase characters

`cat new.txt | tr -d "."` → Remove all dots

`cat new.txt | tr "." "_"` → Remove all dots and replace them with underscores

`uniq new.txt` → Remove all adjacent duplicates in `new.txt`

`uniq -c new.txt` → Get the count of how many occurences are on a line

`uniq -u new.txt` → Gets only unique values

`uniq -d new.txt` → Gets only duplicate values

`sort new.txt | uniq` → Remove all duplicates in `new.txt` even if they are no adjacent

`wc /etc/passwd` → Shows the toal count of words in a file

`nl new.txt` → Check the count of lines on a file

`grep pattern new.txt` → Finds "pattern" inside the `new.txt` file

`grep -i pattern new.txt` → Finds case insensitive "pattern" in the `new.txt` file

`ls /somedir | grep '.txt$'` → Returns all files ending with `.txt` in somedir

`awk '{print}' filename` → Prints every line of a file

`awk '/192.16.40.10/' error.log` → Filters out specific IP address

`awk '/172.16.40.10.81/ {print $4}' error.log` → Print out the forth column of a file

`awk '{print $2,$5;}' error.txt` → Prints out columns 2 and 5

`awk -F ':' '{print $1}' test.txt` → Prints first column of `test.txt` with `:` as a delimiter

### 3. User management

`su` → Opens a root shell

`adduser NameOfUser` → Add a new user

`useradd NameOfUser` → Another way to add a new user

`adduser NameOfUser sudo` → Add user to sudo-group

`echo "username ALL=(ALL) ALL" >> /etc/sudoers` → On some machines we might not be able to adit the sudoers file because we don't have an interactive shell, in this case we can just redirect the text into the file

`cat /etc/group | grep sudo` → Check which users are in the sudo group

`su NameOfUser` → Switch user in terminal

`sudo userdel NameOfUser` → Remove/delete user

### 4. Permissions

`ls -la` → Show all the files and directories and their permission settings

`chmod +x` → Give executable permissions to all users

`chmod -x` → Remove executable permissions to all users

`chmod 777 file` → Give read, write and execute permissions to all users on that file

`sudo chown myfile` → Give ownership of `myfile` to all users

`passwd` → Change password of current user

`sudo chmod u+s myfile` → Modify SUID permissions to grant read, write and execyte to all users

### 5. Processes

`ps` → list all running processes

`ps aux` → Displays a detailed list of all processes running that don't have TTY associated with.

`top` → monitor processes at real time

`kill PID-number` → Kill process running on the PID number

`kill -9 PID-number` → Another way to kill the process

`ls /proc` → List process information stored in the filesystem

### 6. Packages

#### Install package

`sudo apt install` → Install something with apt

`sudo dpkg -i` → Install .deb file

####

#### Remove packages

`dpkg --list` → Find package

`dpkg -r something.deb` → Remove debian package

`sudo apt --purge remove nameOfProgram` → Remove program

`sido apt autoremove` → Remove dependecies left behind

####

#### Organizing $PATH variable

`source /etc/environment && export PATH` → Define the path

If using zhs:

```
sudo vim /etc/zsh/zshenv
source /etc/environment #add this to the file
```

####

#### Adding a path

`export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin` → Non-presistent way to add binaries to the path

#### tar and gzip

`gzip myfile` → Compress a file with gzip

`gunzip myfile.gz` → Decompress a file ith gzip

`tar cvd myfile.tar myfile1 myfile2` → Create and add files to a tar archive

`tar xvf myfile.tar` → Unpacking archives with tar

`tar vzf myfile.tar.gz` → Create a compressed tar file with tar and gzip

`tar xzf myfile.tar` → Uncompress and unpack tar file with tar and gzip

### 7. Cronjobs

There are two ways to configure cronjobs. The first one is by putting scripts in the following folders.

```
/etc/cron.daily
/etc/cron.hourly
/etc/cron.weekly
/etc/cron.monthly
```

The second way is to write the command in the crontab

```
# list cronjobs
crontab -l

# Edit or create new cronjobs
crontab -e
```

###

### 8. Devices

`fdisk -l` → List all devices

### 9. The Filesystem

####

#### Difference between sbin and bin

`sbin` → System Binaries

`bin` → Normal Binaries

Onry root and users with sudo privileges have access to `sbin` Binaries.

#### Mount

Everything on the linux-filesystem belongs to some part of the filesystem-tree. So if we plug in some device we need to mount it to the filesystem. That pretty much means that we need to connect it to the filesystem. Mount is like another word for connect.

`mount /dev/usb /media/usb` → Mount usb device to be able to browse its content

`umount /media/usb` → Umount usb device

### 10. Controlling Services

#### Systemctl

Systemctl can be used to enable and disable various services on your linux machine.

`netstat -apnt` → Verify services listening for connection

`systemctl start` → Start service

`systemctl status` → See service's status

`systemctl stop` → Stop service

`systemctl enable` → Enable service start upon boot

#### Init.d

nit.d is just a wrapper around Systemctl.

```
/etc/init.d/cron status
/etc/init.d/cron start
/etc/init.d/cron stop
```

###

### 11. Kernel

The Kernel is responsible for talking between the hardware and the software, and to manage the systems resources.

The Linux Kernel differs from Windows in that it contains drivers by default. So you don't have to go around looking for drivers like you do on windows when you want to install a printer, or something like that.

`sudo apt update` → Update system

`sudo apt upgrade` → Upgrade system

`sudo apt dist-upgrade` → Upgrade system to the lates Linux kernel

### 14. Logging

Logs can be viewed on `/var/log/` in debian distributions

### 16. Network basics

#### Network interfaces

`ifconfig` → Display network interfaces

`ifconfig eth0 192.168.2.1 netmask 255.255.255.0 up` → Create an interface and bring it up

`ifup eth0` → Bring interface up

`ifdown eth0` → Bring interface down

`ip link show` → Show interface information for all interfaces

`ip -s link show eth0` → Show the statistics of an interface

`ip address show` → Show ip addresses allocated to interfaces

`ip link set eth0 up` → Bring interface up

`ip link set eth0 down` → Bring interface down

`ip address add 192.168.1.1/24 dev eth0` → Add an ip address to an interface

#### Route

`sudo route add -net 192.168.2.1/23 gw 10.11.12.3` → Add a new route

`sudo route del -net 192.168.2.1/23` → Delete a route

`ip route add 192.168.2.1/23 via 10.11.12.3` → Add route with ip command

`ip route delete 192.168.2.1/23` → Delete route with ip command

#### dhclient

`sudo dhclient` → Obtain a fresh ip

#### arp

`arp` → View arp cache

`ip neighbour show` → View arp cache with ip command

#### Troubleshooting

`ping -c 3 [www.google.com](<http://www.google.com>)` → Test whether or not a packet can reach a host and stop sending echo request packets after the count (`3`) has been reached

`traceroute [google.com](<http://google.com>)` → See how packets are getting routed

`sudo tcpdump -i wlan0` → Capture packet data on an interface

`netstat -anpt` → Find out what services are listening for connection on the machine

`sudo service network-manager restart` → Restart the network manager

`rfkill list` → List wifi to see if its blocked or not

`rfkill block 0` → Block wifi interface

`rfkill unblock 0` → Unblock wifi interface

#### DNS

`nslookup [www.google.com](<http://www.google.com>)` → Query name servers to find information about resource records

`dig [www.google.com](<http://www.google.com>)` → Getting information about DNS name servers

### 16.1 Iptables

Iptables is a firewall tool in linux. A firewall is basically a tool that scans incoming and/or outgoing traffic. You can add rules to the iptables to filter for certain traffic.

#### Types of chains

So you can filter traffic in three different ways **input**, **forward**, and **output**. These are called three different chains.

INPUT **→** This is for incoming connections. If someone wants to ssh into your machine. Or a web-server responds to your request.

FORWARD **→** This chain is used for traffic that is not aimed at your machine. A router for example usually just passes information on. Most connections are just passing through.

OUTPUT **→**&#x54;his chain is used for outgoing traffic.

#### Active rules

`iptables -L` → View active rules

Return iptables to default settings:

```
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP
```

`iptables -A INPUT -s 192.168.1.30 -j DROP` → Block an ip address (`-A` for append and `-s` for source)

`iptables -A INPUT -s 192.168.1.0/24 -j DROP` → Block an entire range

`iptables -L -v --line-numbers` → Output the rules with line-numbers

`iptables -D INPUT 2` → Remove on specific rule

`iptables -F` → Remove all rules

`sudo /sbin/iptables-save` → Save changes made to iptables

#### Measuring bandwidth usage

`iptables -L -v` → List the rules with some verbosity

`iptables -Z` → Restart iptables count

`iptables -F` → Remove all the rules and FLUSH them

`iptables -I INPUT 1 -p tcp -j ACCEPT` → Add another rule
