Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Monday, July 18, 2022

How to Encrypt Your File System with LUKS

 

Security and privacy are two very important subjects, and everyone of us, in a way or another, has sensitive data stored on his computer. While you can consider pretty safe your data on a home computer, on a laptop the situation is a lot different. You carry the notebook with you (that’s it’s purpose after all) and you don’t want to loose all your precious data in case it got stolen or lost for example. Here is where system encryption comes in. In this article i will show you how to full encrypt your system using two linux native tools: lvm (for partitioning) and luks (for the actual encryption). At this point you could ask why to use the command line to create this kind of setup when most of the distros installer could do it for us. Well that’s not completely true because usually the graphical installers don’t allow you to fine tune your settings (for example the type of cipher or key size you want to use), plus they don’t let you encrypt your raw disk without creating a partition table on it. Even if you don’t have these needs, it’s anyhow interesting to know how things works under the hood.  (LINUX.COM)

Prerequisites

  • Linux Server
  • Package "cryptsetup.x86_64" should be install on the server
yum install cryptsetup.x86_64 
  • Separate disk disk for Encryption 










Procedure

Step 01: Format Partition with Luks Format

cryptsetup luksFormat /dev/sdb1



 







Note: You must to put strong password 

Step 02: Open Luks Drive

cryptsetup luksOpen /dev/sdb1 sec-drive

Step 03: Make a directory to mount encrypted file system

mkdir /secure

Step 04: Format Luks drive with Ext4. (Note: You can use any File System)

mkfs.ext4 /dev/mapper/sec-drive















Step 05: Generate a Key for encryption

dd if=/dev/urandom of=/root/secure.key bs=4096 count=1










Step 06: Add generated key to luks partition

cryptsetup luksAddKey /dev/sdb1 ./secure.key

Step 07: Add fstab entry

echo "/dev/mapper/sec-drive       /secure     ext4    defaults 0 0" >> /etc/fstab

Step 08: Add crypttab entry

echo "sec-drive /dev/sdb1 /root/secure.key" >> /etc/crypttab

Verify

Execute mount -a




Friday, July 15, 2022

How to Secure SSH Service

 

Secure Shell

The Secure Shell Protocol is a cryptographic network protocol for operating network services securely over an unsecured network. Its most notable applications are remote login and command-line execution. SSH applications are based on a client–server architecture, connecting an SSH client instance with an SSH server. Wikipedia

With advancements in the technology world, hackers are becoming more sophisticated every day. Even your SSH connection is not secure if you are using the traditional or default installation settings. Therefore, it has become necessary to secure your SSH server from unwanted data breaches and malicious attacks by taking some crucial precautions.

In this article, we will introduce you to some important security practices which will help you in considerably increasing the level of SSH server security.

Use Strong Passwords and Apply Password Policy

First thing first, we mush use complex password for ssh logins. Password should contain Upper case, lower case, numbers and special characters. Also we must consider length of the password. It should be at least 8 characters. Another main thing is change the password every month. Will user follow this? We can enable all of these using password policy.

Enable Password Policy

In Red Hat Enterprise Linux 7 and 8 default configuration file for password complexity is /etc/security/pwquality.conf.

Set these parameters in this file.

  • Minimum length of the password
            minlen = 8 
  • Minimum number of uppercase characters
            ucredit = 2
  • Minimum number of lowercase characters
            lcredit = 2
  • Minimum number of other characters
            ocredit = 2

Disable Empty Passwords

Linux allows users to create empty passwords and allowing empty password login to the server will expose your server to vulnerable cyber attacks. So make sure you disable empty passwords.

Open the "/etc/ssh/sshd_config" file. Find PermitEmptyPasswords and and set it to no.

vi /etc/ssh/sshd_config
PermitEmptyPasswords no
systemctl restart sshd




Avoid Using Port 22

Port 22 is a default port for SSH connections and every hacker trying to access your SSH server will first attack this port. Therefore changing the port will add an extra security layer to your SSH Connection and it will prevent automated attacks on the SSH server. Changing the port will also keep you off from hacking radars. But still hackers can run a port scan on attack server and identify the ssh port. So, best option is allow ssh access for known source IPs. You can apply IP table rules to address this.

Change SSH Port

Open the ssh configuration file under "/etc/ssh/sshd_config" and put the port number you want. 

vi /etc/ssh/sshd_config
Port 3322
systemctl restart sshd





Restart the SSH service






IPTABLE Rules

iptables -I INPUT -p TCP -s 192.168.20.100/32 --dport 3322 -j ACCEPT
iptables -A INPUT -p TCP --dport 3322 -j DROP

Disable the Root Logins

Allowing direct login with root through SSH is most dangerous security breach. Attacker can listen to the commutation channel and  steel the root password. Therefore it is recommended to disable root user login and use non-root user access instead for security purposes. You can use the ‘su-’ command to access the root privileges after disabling root logins.

Open the  /etc/ssh/sshd_config file and set PermitRootLogin to "no". Then restart the service.

vi /etc/ssh/sshd_config
PermitRootLogin no
systemctl restart sshd







Maintain SSH Allow List

This allow us to permit access to SSH for specific users which are specified under AllowUsers parameter. Other users can't login. Once you apply restart the ssh service.

vi /etc/ssh/sshd_config
AllowUsers viduranga
systemctl restart sshd






Set an Idle Timeout Value

If there is an established SSH connection to your computer, and there has been no activity on it for a period of time, it could pose a security risk. There is a chance that the user has left their desk and is busy elsewhere. Anyone else who passes by their desk can sit down and start using their computer and, via SSH, your computer.

To avoid this we can set ClientAliveInterval parameter under /etc/ssh/sshd_config. 

vi /etc/ssh/sshd_config
ClientAliveInterval 60
systemctl restart sshd






Set a Limit For Password Attempts

Defining a limit on the number of authentication attempts can help thwart password guessing and brute-force attacks. After the designated number of authentication requests, the user will be disconnected from the SSH server. By default, there is no limit. But that is quickly remedied.

You can address this by editing "/etc/ssh/sshd_config". Set MaxAuthTries 3.

vi /etc/ssh/sshd_config
MaxAuthTries 3
systemctl restart sshd






Only Use SSH Protocol 2

SSH has two protocols that it can use. Protocol 1 is older and is less secure. Protocol 2 is what you should be using to harden your security. If you are looking for your server to become PCI compliant, then you must disable protocol 1.

Open your "/etc/ssh/sshd_config" file and set Protocol 2.

vi /etc/ssh/sshd_config
Protocol 2
systemctl restart sshd







Set Login Grace Time

The LoginGraceTime parameter specifies the time allowed for successful authentication to the SSH server. The longer the Grace period is the more open unauthenticated connections can exist. Like other session controls in this session the Grace Period should be limited to appropriate organizational limits to ensure the service is available for needed access.

vi /etc/ssh/sshd_config
LoginGraceTime 60 
systemctl restart sshd






Disable GSS API Authentication

GSSAPI authentication is used to provide additional authentication mechanisms to applications. Allowing GSSAPI authentication through SSH exposes the system's GSSAPI to remote hosts, increasing the attack surface of the system.

To disable this you have to edit "/etc/ssh/sshd_config" and set GSSAPIAuthentication to no.

vi /etc/ssh/sshd_config
GSSAPIAuthentication no 
systemctl restart sshd




Disable Weak Key Exchange and Weak Encryption Algorithm

Explicitly set key exchange and encryption algorithm in "/etc/ssh/sshd_config".  One you set, you must restart ssh service.

vi /etc/ssh/sshd_config

Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com

KexAlgorithms diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,curve25519-sha256,curve25519-sha256@libssh.org,sntrup4591761x25519-sha512@tinyssh.org

systemctl restart sshd

Saturday, July 9, 2022

How to Restrict Request Method in NGINX


HTTP and HTTPS protocol has several request methods. POST, GET, PUT, PATCH, HEAD and DELETE. When we configuraing NGINX web server we need to restrict PUT,PATCH and DELETE request methods. Only POST, GET and HEAD methods enough to enable from web sever.

Configurations

For Static Content

location /request {
        if ( $request_method !~ ^(GET|POST|HEAD)$ )
        {
                return 405;
        }
        root  /usr/share/nginx/html;
}

For Proxy Pass

location /request-Proxy {
        if ( $request_method !~ ^(GET|POST|HEAD)$ )
        {
                return 405;
        }
        proxy_pass      https://127.0.0.1:8380;
}

Output

GET Request 




DELETE Request






How to Install Your Own CA Certificate to Linux Server

 

How to Install Your Own CA Certificate to Linux Server

Requirement

Install your own CA certificate to your PC or server.

Step 01: Copy your CA certificate to "/usr/local/share/ca-certificates/"

# cp ./ViduTech-CA.crt /usr/local/share/ca-certificates/

Step: 02: update-ca-certificates

# update-ca-certificates

Step 03: update-ca-certificates --fresh

# update-ca-certificates --fresh

Your CA Certificate will available under trusted list.

How to configure Go-access Real-time HTML Outputs (NGINX)

 

How to configure Go-access Real-time HTML Outputs

Requirement

Configure Go-Access for NGINX real-time access logs.

GoAccess has the ability the output real-time data in the HTML report. You can even email the HTML file since it is composed of a single file with no external file dependencies, how neat is that!

The process of generating a real-time HTML report is very similar to the process of creating a static report. Only --real-time-html is needed to make it real-time.

Pre-Requisites 

  • NGINX web server which support websocket
  • Install goaccess on the same server

Step 01: Configure NGINX proxy pass for goaccess real-time push

Add below proxy pass to relevant NGINX configuration.

location /ws-goaccess {
        proxy_pass  http://127.0.0.1:9870;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
}

In my case Go-Access websocket port listen locally with port 9870.

Step 02: Identify log format of your NGINX web server

I used this GitHum repository to find out log format for goaccess.

URL: https://github.com/stockrt/nginx2goaccess 

Command Usage

Usage: ./nginx2goaccess.sh '<log_format>'

NGINX log format u have to get from your web server. It should be in nginx.conf file. Configuration parameter "log_format"

Step 03: Start the Go-Access WebSocket Server

goaccess /var/log/nginx/data.vidutech.org-access.log /var/log/nginx/www.vidutech.org-access.log --log-format='%h - %^ [%d:%t %^] "%r" "%b" "%R" "%u" "%^"' --date-format=%d/%b/%Y --time-format=%T -o /usr/share/nginx/html/goaccess.html --real-time-html --addr=127.0.0.1 --port=9870 --ws-url=data.vidutech.org/ws-goaccess

Command Explanation

We can pass several log files as input

  • /var/log/nginx/data.vidutech.org-access.log
  • /var/log/nginx/www.vidutech.org-access.log
--log-format  / --date-format / --time-format
  • You can obtain it from Step 02
-o <output File>
  • Go-Access report should be save under nginx share location.  This file should be accessible via browser with server name.
--real-time-html

  • Start server as real-time 
--addr=127.0.0.1 --port=9870
  • Listen address and port
--ws-url
  • Web Socket URL.


Once you start the Go-Access server use web socket client to check whether web-socket is working. Here I am using Google Chrome extension "Simple Web Socket Client"








If Web-Socket is working it will display Open.






How you can access the Go-Access html report from your browser. In my case URL for report is 

URL: https://data.vidutech.org/goaccess.html





How to Save Entire HTML Page as Image

How to Save Entire HTML Page as Image

This python script helps you to download entire html page as image(png). There are lots of online tools available to do the same. But, I hope this is also helpful to you as well. There are set of prerequisites need to be installed before execute the script. 

Note: This script only work in Linux environment.

Prerequisites

  • Python3 package
  • Selenium webdriver (pip3 install -U selenium, pip3 install webdriver-manager
In your PC you may experience some other package missing. Please install them as well.

Source Code

Download the source code from GitHub repository.

Link: Download

Execute

Execute the program as follow. Enter URL as command line argument.

Friday, June 24, 2022

Benchmark Your NGINX WEB Server

 

Benchmark Your NGINX WEB Server

There are lots of commercial and open source tools to benchmark your web server. In this blog I and going to demonstrate benchmark your web server with CIS benchmark policies. Any one can freely download CIS documents.

CIS Download URL:  https://www.cisecurity.org/benchmark/nginx

"The CIS Benchmarks are distributed free of charge in PDF format to propagate their worldwide use and adoption as user-originated, de facto standards. CIS Benchmarks are the only consensus-based, best-practice security configuration guides both developed and accepted by government, business, industry, and academia."

Download benchmark scrip: https://github.com/viduranga0006/nginx-benchmark

This is a bash shell script. You have to run it with supper user. Once you execute, you have to select relevant category. At the end it will list summary of benchmark results.





Monday, June 13, 2022

How to Installing OpenCV from the Source



What is OpenCV

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. 

Install the required dependencies

apt install build-essential cmake git pkg-config libgtk-3-dev libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev gfortran openexr libatlas-base-dev python3-dev python3-numpy libtbb2 libtbb-dev libdc1394-22-dev 

Clone the OpenCV’s and OpenCV contrib repositories

mkdir ~/opencv_build && cd ~/opencv_build
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git 

Once the download is complete, create a temporary build directory, and switch to it

cd ~/opencv_build/opencv
mkdir build && cd build

Set up the OpenCV build with CMake

cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
    -D BUILD_EXAMPLES=ON ..

When the CMake build system is finalized, you will see something like below



















Start the compilation process

make -j8

Modify the -j flag according to your processor. If you do not know the number of cores in your processor, you can find it by typing nproc.

The compilation may take several minutes or more, depending on your system configuration. Once it is completed you will see something like below:










Install OpenCV

make install











To verify whether OpenCV has been installed successfully, type the following command and you should see the OpenCV version

pkg-config --modversion opencv4








Tuesday, April 19, 2022

How to Install and configure Conky Widgets on Ubuntu

 

Conky Widgets for Ubuntu
Conky is a free software desktop system monitor for the X Window System. It is available for Linux, FreeBSD, and OpenBSD. Conky is highly configurable and is able to monitor many system variables including the status of the CPU, memory, swap space, disk storage, temperatures, processes, network interfaces, battery power, system messages, e-mail inboxes, Arch Linux updates, many popular music players (MPD, XMMS2, BMPx, Audacious, etc.), weather updates, breaking news, and much more. Unlike system monitors that use high-level widget toolkits to render their information, Conky is drawn directly in an X window. This allows it to be configured such that it consumes relatively few system resources. [Wikipedia]

Prerequisites

  • Ubuntu Linux installed desktop PC
  • Install "conky" and "conky-all" on your PC
Step 01: Install "conky" and "conky-all"

apt install conky conky-all

Step 02: Download conky themes
  • Download URL: URL
  • Unzip it under user home directory
Step 03: Make it to start at startup time
  • Open Tweaks -> Startup Applications
  • Add "conky-startup.sh" script to start at startup
You can manually start with bellow command as well.

./.conky/conky-startup.sh > /dev/null 2>&1
































Note: You may need to change the interface name 






Sunday, November 7, 2021

How to Generate Self-Signed Certificate with your own CA

 

How to Generate Self-Signed Certificate with your own CA

In this blog I am going to demonstrate how to generate a self-sign certificate for your local domain for testing purpose.

Prerequisites 

You need to have a LINUX PC or a server to do this, because this script is wrote in bash. Other than that u have to install openssl package to generate certificate.

Download the self-sign certificate from GITHUB from this Link. Download.

Step:1: Extract the content

tar -xvzf selfsign-cert.tar.gz










Step: 2: Generate CA Certificate

./start
  • Select "Genarate New CA Certificate" option
  • Enter CA Name without space. 

























Step: 3: Generate Host Certificate

./start
  • Select "Genarate New Host Certificate" Option
  • Enter Host Certificate name.
  • Enter Domain list. If you are going to use it for multiple site, you have to mention each hostnames.



























Step: 4: Sign Host Certificate

./start
  • Select "Sign Host certificate" Option
  • Enter Host Certificate you want to sign.
  • Enter CA to sign with.



























Sign Certificate and Private Key are locate in below path.

Signed Certificate Path.......: cert/server/sign/test.vidutech.org.pem
Private Key Path.................: cert/server/key/test.vidutech.org.key

You can use these sign certificate and private key to put in Apache or NGINX.

By installing CA certificate in browser, you can avoid CA certificate warning in browser.