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

Tuesday, July 12, 2022

Unsharp Filter OpenCV C++

 
Unsharp Filter OpenCV C++

Unsharp masking is an image sharpening technique, first implemented in darkroom photography, but now commonly used in digital image processing software. Its name derives from the fact that the technique uses a blurred, or "unsharp", negative image to create a mask of the original image. Wikipedia

Requirement

Implement C++ code to apply  unsharp filter for input image. 

Approach 

  • Blur the original Image
  • Subtract the blurred image from original image (Call this as mask)
  • Add the mask to the original

Source Code

/*
 * UnsharpFilter.cpp
 *
 *  Created on: Jul 12, 2022
 *      Author: viduranga
 */

#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>

using std::cin;
using std::cout;
using std::endl;

using namespace cv;

int kernel[5][5] = {1,4,7,4,1,
4,16,26,16,4,
7,26,41,26,7,
4,16,26,16,4,
1,4,7,4,1};

int accessPixel(unsigned char * arr, int col, int row, int k, int width, int height)
{
    int sum = 0;
    int sumKernel = 0;

    for (int j = -1; j <= 1; j++)
    {
        for (int i = -1; i <= 1; i++)
        {
            if ((row + j) >= 0 && (row + j) < height && (col + i) >= 0 && (col + i) < width)
            {
                int color = arr[(row + j) * 3 * width + (col + i) * 3 + k];
                sum += color * kernel[i + 1][j + 1];
                sumKernel += kernel[i + 1][j + 1];
            }
        }
    }

    return sum / sumKernel;
}

void guassian_blur2D(unsigned char * arr, unsigned char * result, int width, int height)
{
    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            for (int k = 0; k < 5; k++)
            {
                result[3 * row * width + 3 * col + k] = accessPixel(arr, col, row, k, width, height);
            }
        }
    }
}

int main(int argc, char** argv)
{
char* ImageFile = argv[1];
double threshold = 10, amount = 5;

Mat input_imge = imread(ImageFile);

if( argc != 2 || !input_imge.data )
{
   cout <<" No image data" <<endl;
   return -1;
}

Mat blurred_image = input_imge.clone();
guassian_blur2D(input_imge.data, blurred_image.data, input_imge.cols, input_imge.rows);
Mat lowConstrastMask = abs(input_imge - blurred_image) < threshold;
Mat sharpened = input_imge*(1+amount) + blurred_image*(-amount);
sharpened.copyTo(input_imge, lowConstrastMask);

imshow("Original Image", input_imge);
imshow("Mask Image",lowConstrastMask);
imshow("Blurred Image",blurred_image);
imshow("Unsharp Filter", sharpened);

waitKey(0);
return 0;
}

Output

Input Image
























Blurred Image
























Mask Image
























Unsharp Image



Saturday, July 9, 2022

How to Draw Graph for Stocks (Python)

How to Draw Graph for Stocks (Python)

There are lot of online tools available for draw graph. Most of them are not free and limited number of date range. In this blog I am going to share my python experience with financial graph implementation. I wrote 3 python codes for several graph types. Which are

  • Candle Graph
  • Line Grap
  • Ohlc Graph
Those graphs are helpful for financial analyzers to do their analysis. Technical traders use a variety of stock charts to analyze market data in order to pinpoint optimum entry and exit points for their trades. By setting up efficient charts and workspace, you'll gain quick access to the data you need to make profitable trading decisions.

Clone the graph source code from GitHub repository. Sample data sheet also available. Data should be in that format along with column names. 


You may need to install several python packages before continuing.

Candle Graph

Execute "get-candle-graph.py" script to generate candle graph

# python3 get-candle-graph.py

Line Graph

Execute "get-line-graph.py" script to generate line graph

# python3 get-line-graph.py












OHLC Graph

Execute "get-ohlc-graph.py" script to generate OHLC graph

# python3 get-ohlc-graph.py





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.

Sunday, June 26, 2022

How to get Intensity Histogram of an Image

 

How to get Intensity Histogram of an Image

This blog shows how to get intensity histogram of an image.

Language: C++
Libraries: OpenCV

I use Eclipse to develop the code. If you are new to OpenCV and Eclipse, Please follow my previous blogs.

How to install OpenCV

https://sltechgeekx.blogspot.com/2022/06/how-to-installing-opencv-from-source.html

How to Create a Project in Eclipse with OpenCV Libraries

https://sltechgeekx.blogspot.com/2022/06/how-to-convert-rgb-image-to-gray.html

Program Source Code

#include <opencv2/opencv.hpp>

using namespace cv;

int main(int argc, char** argv)
{
char* ImageFile = argv[1];
Mat input_image;  /* mat object for storing original_image */
input_image = imread( ImageFile, IMREAD_COLOR ); /* read ImageFile */

if( argc != 2 || !input_image.data )
{
   printf( " No image data \n " );
   return -1;
}

Mat gray_image; /* mat object for storing gray_image */
cvtColor( input_image, gray_image, COLOR_BGR2GRAY ); /* convert image from color to gray */

    int histogram[256]; /* allcoate memory for no of pixels for each intensity value */

    /* initialize all intensity values to 0 */
    for(int i = 0; i < 255; i++)
    {
        histogram[i] = 0;
    }

    /* calculate the no of pixels for each intensity values */
    for(int y = 0; y < gray_image.rows; y++)
    {
    for(int x = 0; x < gray_image.cols; x++)
    {
            histogram[(int)gray_image.at<uchar>(y,x)]++;
    }
    }

    /* draw the histograms */
    int hist_w = 512; int hist_h = 400;
    int bin_w = cvRound((double) hist_w/256);

    Mat histImage(hist_h, hist_w, CV_8UC1, Scalar(255, 255, 255));

    /* find the maximum intensity element from histogram */
    int max = histogram[0];

    for(int i = 1; i < 256; i++)
    {
        if(max < histogram[i])
        {
            max = histogram[i];
        }
    }

    /* normalize the histogram between 0 and histImage.rows */
    for(int i = 0; i < 255; i++)
    {
        histogram[i] = floor(((double)histogram[i]/max)*histImage.rows);
    }

    /* draw the intensity line for histogram */
    for(int i = 0; i < 255; i++)
    {
        line(histImage, Point(bin_w*(i), hist_h),
                              Point(bin_w*(i), hist_h - histogram[i]),
             Scalar(0,0,0), 1, 8, 0);
    }

namedWindow( "Input Image in Gray", WINDOW_AUTOSIZE );   /* set window name Gray Image */
imshow( "Input Image in Gray", gray_image );   /* show window containing gray_image */

namedWindow("Intensity Histogram", WINDOW_AUTOSIZE);  /* set window name Intensity Histogram */
imshow("Intensity Histogram", histImage);   /* show window containing Intensity Histogram */

waitKey(0);      /* to exit */

return 0;
}

Program Output