Convert a jks to crt format

keytool -importkeystore -srckeystore <my-certificate-name>.jks -destkeystore <my-certificate-name>.p12 -deststoretype PKCS12

openssl pkcs12 -in <my-certificate-name>.p12 -nokeys -out <my-certificate-name>.crt

openssl pkcs12 -in <my-certificate-name>.p12 -nocerts -nodes -out <my-certificate-name>.key

Advertisements

SSL – Create Root, Intermediate and Certificate in Chain

Create a Chain Certificate (Root, Intermediate & Normal Chain) – Step-by-step
——————————————————————————————
ROOT CERTIFICATE
——————————————————————————————
mkdir /root/ca
cd /root/ca
mkdir certs crl newcerts private
chmod 700 private
touch index.txt
echo 1000 > serial
vim openssl.cnf

[ ca ]
# `man ca`
default_ca = CA_default

[ CA_default ]
# Directory and file locations.
dir               = /root/ca
certs             = $dir/certs
crl_dir           = $dir/crl
new_certs_dir     = $dir/newcerts
database          = $dir/index.txt
serial            = $dir/serial
RANDFILE          = $dir/private/.rand

# The root key and root certificate.
private_key       = $dir/private/root_haritibco.key.pem
certificate       = $dir/certs/root_haritibco.cert.pem

# For certificate revocation lists.
crlnumber         = $dir/crlnumber
crl               = $dir/crl/ca.crl.pem
crl_extensions    = crl_ext
default_crl_days  = 30

# SHA-1 is deprecated, so use SHA-2 instead.
default_md        = sha256

name_opt          = ca_default
cert_opt          = ca_default
default_days      = 375
preserve          = no
policy            = policy_strict

[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
# See the POLICY FORMAT section of `man ca`.
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
# See the POLICY FORMAT section of the `ca` man page.
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
# Options for the `req` tool (`man req`).
default_bits        = 2048
distinguished_name  = req_distinguished_name
string_mask         = utf8only

# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = v3_ca

[ req_distinguished_name ]
# See <https://en.wikipedia.org/wiki/Certificate_signing_request&gt;.
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name
localityName                    = Locality Name
0.organizationName              = Organization Name
organizationalUnitName          = Organizational Unit Name
commonName                      = Common Name
emailAddress                    = Email Address

# Optionally, specify some defaults.
countryName_default             = IN
stateOrProvinceName_default     = Maharashtra
localityName_default            = Mumbai
0.organizationName_default      = Hari TIBCO Blog Ltd
organizationalUnitName_default  = HLL
emailAddress_default            = hsivabc@gmail.com

[ v3_ca ]
# Extensions for a typical CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ usr_cert ]
# Extensions for client certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = “OpenSSL Generated Client Certificate”
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

[ server_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = “OpenSSL Generated Server Certificate”
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

[ crl_ext ]
# Extension for CRLs (`man x509v3_config`).
authorityKeyIdentifier=keyid:always

[ ocsp ]
# Extension for OCSP signing certificates (`man ocsp`).
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning

(Create root key)
cd /root/ca
openssl genrsa -aes256 -out private/root_haritibco.key.pem 4096
****test12345***
chmod 400 private/root_haritibco.key.pem
(Create root certificate)
cd /root/ca
openssl req -config openssl.cnf \
-key private/root_haritibco.key.pem \
-new -x509 -days 7300 -sha256 -extensions v3_ca \
-out certs/root_haritibco.cert.pem
chmod 444 certs/root_haritibco.cert.pem
(Verify Root Certificate)
openssl x509 -noout -text -in certs/root_haritibco.cert.pem

——————————————————————————————
INTERMEDIATE CERTIFICATE
——————————————————————————————
mkdir /root/ca/intermediate
cd /root/ca/intermediate
mkdir certs crl csr newcerts private
chmod 700 private
touch index.txt
echo 1000 > serial
echo 1000 > /root/ca/intermediate/crlnumber
cd /root/ca

vim openssl.cnf


# OpenSSL intermediate CA configuration file.
# Copy to `/root/ca/intermediate/openssl.cnf`.

[ ca ]
# `man ca`
default_ca = CA_default

[ CA_default ]
# Directory and file locations.
dir               = /root/ca/intermediate
certs             = $dir/certs
crl_dir           = $dir/crl
new_certs_dir     = $dir/newcerts
database          = $dir/index.txt
serial            = $dir/serial
RANDFILE          = $dir/private/.rand

# The root key and root certificate.
private_key       = $dir/private/inter_haritibco.key.pem
certificate       = $dir/certs/inter_haritibco.cert.pem

# For certificate revocation lists.
crlnumber         = $dir/crlnumber
crl               = $dir/crl/inter_haritibco.crl.pem
crl_extensions    = crl_ext
default_crl_days  = 30

# SHA-1 is deprecated, so use SHA-2 instead.
default_md        = sha256

name_opt          = ca_default
cert_opt          = ca_default
default_days      = 375
preserve          = no
policy            = policy_loose

[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
# See the POLICY FORMAT section of `man ca`.
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
# See the POLICY FORMAT section of the `ca` man page.
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
# Options for the `req` tool (`man req`).
default_bits        = 2048
distinguished_name  = req_distinguished_name
string_mask         = utf8only

# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = v3_ca

[ req_distinguished_name ]
# See <https://en.wikipedia.org/wiki/Certificate_signing_request&gt;.
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name
localityName                    = Locality Name
0.organizationName              = Organization Name
organizationalUnitName          = Organizational Unit Name
commonName                      = Common Name
emailAddress                    = Email Address

# Optionally, specify some defaults.
countryName_default             = IN
stateOrProvinceName_default     = Maharashtra
localityName_default            = Mumbai
0.organizationName_default      = Hari TIBCO Blog Ltd
organizationalUnitName_default  = HLL
emailAddress_default            = hsivabc@gmail.com

[ v3_ca ]
# Extensions for a typical CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ usr_cert ]
# Extensions for client certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = “OpenSSL Generated Client Certificate”
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

[ server_cert ]
# Extensions for server certificates (`man x509v3_config`).
basicConstraints = CA:FALSE
nsCertType = server
nsComment = “OpenSSL Generated Server Certificate”
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

[ crl_ext ]
# Extension for CRLs (`man x509v3_config`).
authorityKeyIdentifier=keyid:always

[ ocsp ]
# Extension for OCSP signing certificates (`man ocsp`).
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning

openssl genrsa -aes256 \
-out intermediate/private/inter_haritibco.key.pem 4096
*****test12345****
chmod 400 intermediate/private/inter_haritibco.key.pem

cd /root/ca
openssl req -config intermediate/openssl.cnf -new -sha256 \
-key intermediate/private/inter_haritibco.key.pem \
-out intermediate/csr/inter_haritibco.csr.pem
cd /root/ca
openssl ca -config openssl.cnf -extensions v3_intermediate_ca \
-days 3650 -notext -md sha256 \
-in intermediate/csr/inter_haritibco.csr.pem \
-out intermediate/certs/inter_haritibco.cert.pem
chmod 444 intermediate/certs/inter_haritibco.cert.pem

openssl x509 -noout -text \
-in intermediate/certs/inter_haritibco.cert.pem

openssl verify -CAfile certs/root_haritibco.cert.pem \
intermediate/certs/inter_haritibco.cert.pem

cat intermediate/certs/inter_haritibco.cert.pem \
certs/ca.cert.pem > intermediate/certs/chain_haritibco.cert.pem
chmod 444 intermediate/certs/chain_haritibco.cert.pem


—————————————————————————
CERTIFICATE
—————————————————————————
cd /root/ca
openssl genrsa -aes256 \
-out intermediate/private/haritibcoblog.key.pem 2048
chmod 400 intermediate/private/haritibcoblog.key.pem

cd /root/ca
openssl req -config intermediate/openssl.cnf \
-key intermediate/private/haritibcoblog.key.pem \
-new -sha256 -out intermediate/csr/haritibcoblog.csr.pem

cd /root/ca
openssl ca -config intermediate/openssl.cnf \
-extensions server_cert -days 375 -notext -md sha256 \
-in intermediate/csr/haritibcoblog.csr.pem \
-out intermediate/certs/haritibcoblog.cert.pem
chmod 444 intermediate/certs/haritibcoblog.cert.pem

openssl x509 -noout -text \
-in intermediate/certs/haritibcoblog.cert.pem

openssl verify -CAfile intermediate/certs/chain_haritibco.cert.pem \
intermediate/certs/haritibcoblog.cert.pem

 

 

 

Linux – Concepts – IPTABLES v/s FIREWALLD

Today we will walk through iptables and firewalld and we will learn about the history of these two along with installation & how we can configure these for our Linux distributions.

Let’s begin wihtout wasting further more time.

What is iptables?

First, we need to know what is iptables. Most of senior IT professionals knows about it and used to work with it as well. Iptables is an application / program that allows a user to configure the security or firewall security tables provided by the Linux kernel firewall and the chains so that a user can add / remove firewall rules to it accordingly to meet his / her security requirements. Iptables uses different kernel modules and different protocols so that user can take the best out of it. As for example, iptables is used for IPv4 ( IP version 4/32 bit ) and ip6tables for IPv6 ( IP version 6/64 bit ) for both tcp and udp. Normally, iptables rules are configured by System Administrator or System Analyst or IT Manager.  You must have root privileges to execute each iptables rules. Linux Kernel uses the Netfilter framework so that it can provide various networking-related operations which can be performed by using iptables. Previously, ipchains was used in most of the Linux distributions for the same purpose. Every iptables rules are directly handled by the Linux Kernel itself and it is known as kernel duty. Whatever GUI tools or other security tools you are using to configure your server’s firewall security, at the end of the day, it is converted into iptables rules and supplied to the kernel to perform the operation.

History of iptables

The rise of the iptables begin with netfilter. Paul Rusty Russell was the initial author and the head think tank behind netfilter / iptables. Later he was joined by many other tech people then form and build the Netfilter core team and develop & maintain the netfilter/iptables project as a joint effort like many other open source projects. Harald Welte was the former leader until 2007 and then Patrick McHardy was the head until 2013. Currently, netfilter core team head is Pablo Neira Ayuso.

To know more about netfilter, please visit this link. To know more about the historicity of netfilter, please visit this link.

To know more about iptables history, please visit this link.

How to install iptables

Now a days, every Linux Kernel comes with iptables and can be found pre build or pre installed on every famous modern Linux distributions. On most Linux systems, iptables is installed in this /usr/sbin/iptables directory. It can be also  found in /sbin/iptables, but since iptables is more like a service rather than an “essential binary”, the preferred location remains in /usr/sbin directory.

For Ubuntu or Debian

sudo apt-get install iptables

For CentOS

sudo yum install iptables-services

For RHEL

sudo yum install iptables

Iptables version

To know your iptables version, type the following command in your terminal.

sudo iptables --version

Start & Stopping your iptables firewall

For OpenSUSE 42.1, type the following to stop.

sudo /sbin/rcSuSEfirewall2 stop

To start it again

sudo /sbin/rcSuSEfirewall2 start

For Ubuntu, type the following to stop.

sudo service ufw stop

To start it again

sudo service ufw start

For Debian & RHEL , type the following to stop.

sudo /etc/init.d/iptables stop

To start it again

sudo /etc/init.d/iptables start

For CentOS, type the following to stop.

sudo service iptables stop

To start it again

sudo service iptables start

Getting all iptables rules lists

To know all the rules that is currently present & active in your iprables, simply open a terminal and type the following.

sudo iptables -L

If there are no rules exits on the iptables means if there are no rules added so far in your iptables firewall, you will see something like the below image.

Iptables_Lists_OpenSUSE42.1

In this above picture, you can see that , there are three (3) chains and they are INPUT, FORWARD, OUTPUT and there are no rules exists. Actually I haven’t add one yet.

Type the following to know the status of the chains of your iptables firewall.

sudo iptables -S

With the above command, you can learn whether your chains are accepting or not.

Clear all iptables rules

To clear all the rules from your iptables firewall, please type the following. This is normally known as flushing your iptables rules.

sudo iptables -F

If you want to flush the INPUT chain only, or any individual chains, issue the below commands as per your requirements.

sudo iptables -F INPUT
sudo iptables -F OUTPUT
sudo iptables -F FORWARD

ACCEPT or DROP Chains

To accept or drop a particular chain, issue any of the following command on your terminal to meet your requirements.

iptables --policy INPUT DROP

The above rule will not accept anything that is incoming to that server. To revert it again back to ACCEPT, do the following

iptables --policy INPUT ACCEPT

Same goes for other chains as well like

iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP

Note: By default, all chains of iptables ( INPUT, OUTPUT, FORWARD ) are in ACCEPT mode. This is known as Policy Chain Default Behavior.

Allowing any port

If you are running any web server on your host, then you must allow your iptables firewall so that your server listen or respond to port 80. By default web server runs on port 80. Let’s do that then.

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

On the above line, A stands for append means we are adding a new rule to the iptables list. INPUT stands for the INPUT chain. P stands for protocol and dport stands for destination port. By default any web server runs on port 80. Similarly, you can allow SSH port as well.

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

By default, SSH runs on port 22. But it’s good practise not to run SSH on port 22. Always run SSH on a different port. To run SSH on a different port, open /etc/ssh/sshd_config file on your favorite editor and change the port 22 to a other port.

Blocking any port

Say we want to block port 135. We can do it by

sudo iptables -A INPUT -p tcp --dport 135 -j DROP

if you want to block your server to initiate any SSH connection from the server to another host/server, issue the following command

sudo iptables -A OUTPUT -p tcp --dport 22 -j DROP

By doing so, no one can use your sever to initiate a SSH connection from the server. The OUPUT chain will filter and DROP any outgoing tcp connection towards another hosts.

Allowing specific IP with Port

sudo iptables -A INPUT -p tcp -s 0/0 --dport 22  -j ACCEPT

Here -s 0/0 stand for any incoming source with any IP addresses. So, there is no way your server is going to respond for a tcp packet which destination port is 22. If you want to allow only any particular IP then use the following one.

sudo iptables -A INPUT -p tcp -s 12.12.12.12/32 --dport 22  -j ACCEPT

On the above example, you are only allowing 12.12.12.12 IP address to connect to port SSH. Rest IP addresses will not be able to connect to port 22. Similarly you can allow by using CIDR values. Such as

sudo iptables -A INPUT -p tcp -s 12.12.12.0/24 --dport 22  -j ACCEPT

The above example show how you can allow a whole IP block for accepting connection on port 22. It will accept IP starting from 12.12.12.1 to 12.12.12.255.

If you want to block such IP addresses range, do the reverse by replacing ACCEPT by DROP like the following

sudo iptables -A INPUT -p tcp -s 12.12.12.0/24 --dport 22  -j DROP

So, it will not allow to get a connection on port 22 from from 12.12.12.1 to 12.12.12.255 IP addresses.

Blocking ICMP

If you want to block ICMP (ping) request to and from on your server, you can try the following. The first one will block not to send ICMP ping echo request to another host.

sudo iptables -A OUTPUT -p icmp --icmp-type 8 -j DROP

Now, try to ping google.com. Your OpenSUSE server will not be able to ping google.com.

If you want block the incoming ICMP (ping) echo request for your server, just type the following on your terminal.

sudo iptables -I INPUT -p icmp --icmp-type 8 -j DROP

Now, It will not reply to any ICMP ping echo request. Say, your server IP address is 13.13.13.13. And if you ping ping that IP of your server then you will see that your server is not responding for that ping request.

Blocking MySql / MariaDB Port

As Mysql is holding your database so you must protect your database from outside attach. Allow your trusted application server IP addresses only to connect with your MySQL server. To block other

sudo iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT

So, it will not take any MySql connection except 192.168.1.0/24 IP block. By default MySql runs on 3306 port.

Blocking SMTP

If you not running any mail server on your host server or if your server is not configured to act like a mail server, you must block SMTP so that your server is not sending any spam or any mail towards any domain. You must do this to block any outgoing mail from your server. To do so,

sudo iptables -A OUTPUT -p tcp --dport 25 -j DROP

Block DDoS

We all are familiar with the term DDoS. To get rid of it, issue the following command in your terminal.

iptables -A INPUT -p tcp --dport 80 -m limit --limit 20/minute --limit-burst 100 -j ACCEPT

You need to configure the numerical value to meet your requirements. This is just a standard to maintain.

You can protect more by

echo 1 > /proc/sys/net/ipv4/ip_forward
echo 1 > /proc/sys/net/ipv4/tcp_syncookies
echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects
echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
echo 1 > /proc/sys/net/ipv4/conf/lo/rp_filter
echo 1 > /proc/sys/net/ipv4/conf/lo/arp_ignore
echo 2 > /proc/sys/net/ipv4/conf/lo/arp_announce
echo 1 > /proc/sys/net/ipv4/conf/all/arp_ignore
echo 2 > /proc/sys/net/ipv4/conf/all/arp_announce
echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout
echo 1800 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 1 > /proc/sys/net/ipv4/tcp_window_scaling 
echo 0 > /proc/sys/net/ipv4/tcp_sack
echo 1280 > /proc/sys/net/ipv4/tcp_max_syn_backlog

Blocking Port Scanning

There are hundred of people out there to scan your open ports of your server and try to break down your server security. To block it

sudo iptables -N block-scan
sudo iptables -A block-scan -p tcp —tcp-flags SYN,ACK,FIN,RST RST -m limit —limit 1/s -j RETURN
sudo iptables -A block-scan -j DROP

Here, block-scan is a name of a new chain.

Blocking Bad Ports

You may need to block some bad ports for your server as well. Here is how you can do this.

badport="135,136,137,138,139,445"
sudo iptables -A INPUT -p tcp -m multiport --dport $badport -j DROP
sudo iptables -A INPUT -p udp -m multiport --dport $badport -j DROP

You can add more ports according to your needs.

What is firewalld?

Firewalld provides a dynamically managed firewall with support for network/firewall zones that defines the trust level of network connections or interfaces. It has support for IPv4, IPv6 firewall settings, ethernet bridges and IP sets. There is a separation of runtime and permanent configuration options. It also provides an interface for services or applications to add firewall rules directly.

The former firewall model with system-config-firewall/lokkit was static and every change required a complete firewall restart. This included also to unload the firewall netfilter kernel modules and to load the modules that are needed for the new configuration. The unload of the modules was breaking stateful firewalling and established connections. The firewall daemon on the other hand manages the firewall dynamically and applies changes without restarting the whole firewall. Therefore there is no need to reload all firewall kernel modules. But using a firewall daemon requires that all firewall modifications are done with that daemon to make sure that the state in the daemon and the firewall in kernel are in sync. The firewall daemon can not parse firewall rules added by the iptables and ebtables command line tools. The daemon provides information about the current active firewall settings via D-BUS and also accepts changes via D-BUS using PolicyKit authentication methods.

So, firewalld uses zones and services instead of chain and rules for performing the operations and it can manages rule(s) dynamically allowing updates & modification without breaking existing sessions and connections.

It has following features.

  • D-Bus API.
  • Timed firewall rules.
  • Rich Language for specific firewall rules.
  • IPv4 and IPv6 NAT support.
  • Firewall zones.
  • IP set support.
  • Simple log of denied packets.
  • Direct interface.
  • Lockdown: Whitelisting of applications that may modify the firewall.
  • Support for iptables, ip6tables, ebtables and ipset firewall backends.
  • Automatic loading of Linux kernel modules.
  • Integration with Puppet.

To know more about firewalld, please visit this link.

How to install firewalld

Before installing firewalld, please make sure you stop iptables and also make sure that iptables are not using or working anymore. To do so,

sudo systemctl stop iptables

This will stop iptables form your system.

And then make sure iptables are not used by your system any more by issuing the below command in the terminal.

sudo systemctl mask iptables

Now, check the status of iptables.

sudo systemctl status iptables

iptables_status_unixmen

Now, we are ready to install firewalld on to our system.

For Ubuntu

To install it on Ubuntu, you must remove UFW first and then you can install Firewalld. To remove UFW, issue the below command on the terminal.

sudo apt-get remove ufw

After removing UFW, issue the below command in the terminal

sudo apt-get install firewall-applet

Or

You can open Ubuntu Software Center and look or seacrh  for “firewall-applet” then install it on to your Ubuntu system.

For RHEL, CentOS & Fedora

Type the below command to install firewalld on your CentOS system.

sudo yum install firewalld firewall-config -y

How to configure firewalld

Before configuring firewalld, we must know the status of firewalld after the installation. To know that, type the following.

sudo systemctl status firewalld

firewalld_status_unixmen

As firewalld works on zones basis, we need to check all the zones and services though we haven’t done any configuring yet.

For Zones

sudo firewall-cmd --get-active-zones

firewalld_activezones_unixmen

or

sudo firewall-cmd --get-zones

firewalld_getzones_unixmen

To know the default zone, issue the below command

sudo firewall-cmd --get-default-zone

firewalld_defaultszones_unixmen

And, For Services

sudo firewall-cmd --get-services

firewalld_services_unixmen

Here, you can see those services covered under firewalld.

Setting Default Zone

An important note is, after each modification, you need to reload firewalld so that your changes can take place.

To set the default zone

sudo firewall-cmd --set-default-zone=internal

or

sudo firewall-cmd --set-default-zone=public

After changing the zone, check whether it changes or not.

sudo firewall-cmd --get-default-zone

Adding Port in Public Zone

sudo firewall-cmd --permanent --zone=public --add-port=80/tcp

firewalld_addport_unixmen

This will add tcp port 80 in the public zone of firewalld. You can add your desired port as well by replacing 80 by your’s.

Now reload the firewalld.

sudo firewall-cmd --reload

Now, check the status to see whether tcp 80 port has been added or not.

sudo firewall-cmd --zone=public --list-ports

firewalld_statusafterport_unixmen

Here, you can see that tcp port 80 has been added.

Or even you can try something like this.

sudo firewall-cmd --zone=public --list-all

firewalld_statusall_unixmen

Removing Port from Public Zone

To remove Tcp 80 port from the public zone, type the following.

sudo firewall-cmd --zone=public --remove-port=80/tcp

You will see a “success” text echoing in your terminal.

You can put your desired port as well by replacing 80 by your’s own port.

Adding Services in Firewalld

To add ftp service in firewalld, issue the below command

sudo firewall-cmd --zone=public --add-service=ftp

You will see a “success” text echoing in your terminal.

Similarly for adding smtp service, issue the below command

sudo firewall-cmd --zone=public --add-service=smtp

Replace ftp and smtp by your’s own service that you want to add in the firewalld.

Removing Services from Firewalld

For removing ftp & smtp services from firewalld, issue the below command in the terminal.

sudo firewall-cmd --zone=public --remove-service=ftp
sudo firewall-cmd --zone=public --remove-service=smtp

Block Any Incoming and Any Outgoing Packet(s)

If you wish, you can block any incoming or outgoing packets / connections by using firewalld. This is known as “panic-on” of firewalld. To do so, issue the below command.

sudo firewall-cmd --panic-on

You will see a “success” text echoing in your terminal.

After doing this, you will not be able to ping a host or even browse any websites.

To turn this off, issue the below command in your terminal.

sudo firewall-cmd --panic-off

Adding IP Address in Firewalld

sudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.4" accept'

By doing so, firewalld will accept IP v4 packets from the source IP 192.168.1.4.

Blocking IP Address From Firewalld

Similarly, to block any IP address

sudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.4" reject'

By doing so, firewalld will drop / discards every IP v4 packets from the source IP 192.168.1.4.

I stuck with the very basic of Firewalld over here so that you can easily understand the working methodology of it and the differences of it with iptables.

That’s all for today. Hope you enjoy reading this article.

Take care.

GnuPG – Public / Private Key Method – Encryption / Decryption (No Digital Signature)

 

<When You Encounter This Error Don’t Panic>

GPG key generation: Not enough random bytes available.

Not enough random bytes available

Generating keys with GnuPG

 

Anyone who wants to create a new key set via GnuPG (GPG) may run into this error:

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
Not enough random bytes available.  Please do some other work to give
the OS a chance to collect more entropy! (Need 142 more bytes)

The problem is caused by the lack of entropy (or random system noise). While trying to get more, you might keep running into this message. In our case running a find on the disk, while making sha1sums and putting that into files, was actually not enough.

To check the available entropy, check the kernel parameters:

cat /proc/sys/kernel/random/entropy_avail
36

To solve it, run the rngd command: rngd -f -r /dev/urandom

Debian / Ubuntu: apt-get install rng-tools

Red Hat / CentOS: yum install -y rng-utils

Checking the available entropy again revealed in our case a stunning 3100, almost 100 times more than before. GnuPG is now happy again and can finish creating the keys.

Certificates – PKCS12

pkcs12

NAME

pkcs12 – PKCS#12 file utility

SYNOPSIS

openssl pkcs12 [-help] [-export] [-chain] [-inkey filename] [-certfile filename] [-name name] [-caname name] [-in filename] [-out filename] [-noout] [-nomacver] [-nocerts] [-clcerts] [-cacerts] [-nokeys] [-info] [-des | -des3 | -idea | -aes128 | -aes192 | -aes256 | -camellia128 | -camellia192 | -camellia256 | -nodes] [-noiter] [-maciter | -nomaciter | -nomac] [-twopass] [-descert] [-certpbe cipher] [-keypbe cipher] [-macalg digest] [-keyex] [-keysig] [-password arg] [-passin arg] [-passout arg] [-rand file(s)] [-CAfile file] [-CApath dir] [-no-CAfile] [-no-CApath] [-CSP name]

DESCRIPTION

The pkcs12 command allows PKCS#12 files (sometimes referred to as PFX files) to be created and parsed. PKCS#12 files are used by several programs including Netscape, MSIE and MS Outlook.

COMMAND OPTIONS

There are a lot of options the meaning of some depends of whether a PKCS#12 file is being created or parsed. By default a PKCS#12 file is parsed. A PKCS#12 file can be created by using the-export option (see below).

PARSING OPTIONS

-help
Print out a usage message.

-in filename
This specifies filename of the PKCS#12 file to be parsed. Standard input is used by default.

-out filename
The filename to write certificates and private keys to, standard output by default. They are all written in PEM format.

-passin arg
the PKCS#12 file (i.e. input file) password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

-passout arg
pass phrase source to encrypt any outputted private keys with. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

-password arg
With -export, -password is equivalent to -passout. Otherwise, -password is equivalent to -passin.

-noout
this option inhibits output of the keys and certificates to the output file version of the PKCS#12 file.

-clcerts
only output client certificates (not CA certificates).

-cacerts
only output CA certificates (not client certificates).

-nocerts
no certificates at all will be output.

-nokeys
no private keys will be output.

-info
output additional information about the PKCS#12 file structure, algorithms used and iteration counts.

-des
use DES to encrypt private keys before outputting.

-des3
use triple DES to encrypt private keys before outputting, this is the default.

-idea
use IDEA to encrypt private keys before outputting.

-aes128, -aes192, -aes256
use AES to encrypt private keys before outputting.

-camellia128, -camellia192, -camellia256
use Camellia to encrypt private keys before outputting.

-nodes
don’t encrypt the private keys at all.

-nomacver
don’t attempt to verify the integrity MAC before reading the file.

-twopass
prompt for separate integrity and encryption passwords: most software always assumes these are the same so this option will render such PKCS#12 files unreadable.

FILE CREATION OPTIONS

-export
This option specifies that a PKCS#12 file will be created rather than parsed.

-out filename
This specifies filename to write the PKCS#12 file to. Standard output is used by default.

-in filename
The filename to read certificates and private keys from, standard input by default. They must all be in PEM format. The order doesn’t matter but one private key and its corresponding certificate should be present. If additional certificates are present they will also be included in the PKCS#12 file.

-inkey filename
file to read private key from. If not present then a private key must be present in the input file.

-name friendlyname
This specifies the “friendly name” for the certificate and private key. This name is typically displayed in list boxes by software importing the file.

-certfile filename
A filename to read additional certificates from.

-caname friendlyname
This specifies the “friendly name” for other certificates. This option may be used multiple times to specify names for all certificates in the order they appear. Netscape ignores friendly names on other certificates whereas MSIE displays them.

-pass arg, -passout arg
the PKCS#12 file (i.e. output file) password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

-passin password
pass phrase source to decrypt any input private keys with. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.

-chain
if this option is present then an attempt is made to include the entire certificate chain of the user certificate. The standard CA store is used for this search. If the search fails it is considered a fatal error.

-descert
encrypt the certificate using triple DES, this may render the PKCS#12 file unreadable by some “export grade” software. By default the private key is encrypted using triple DES and the certificate using 40 bit RC2.

-keypbe alg, -certpbe alg
these options allow the algorithm used to encrypt the private key and certificates to be selected. Any PKCS#5 v1.5 or PKCS#12 PBE algorithm name can be used (see NOTESsection for more information). If a cipher name (as output by the list-cipher-algorithmscommand is specified then it is used with PKCS#5 v2.0. For interoperability reasons it is advisable to only use PKCS#12 algorithms.

-keyex|-keysig
specifies that the private key is to be used for key exchange or just signing. This option is only interpreted by MSIE and similar MS software. Normally “export grade” software will only allow 512 bit RSA keys to be used for encryption purposes but arbitrary length keys for signing. The -keysig option marks the key for signing only. Signing only keys can be used for S/MIME signing, authenticode (ActiveX control signing) and SSL client authentication, however due to a bug only MSIE 5.0 and later support the use of signing only keys for SSL client authentication.

-macalg digest
specify the MAC digest algorithm. If not included them SHA1 will be used.

-nomaciter, -noiter
these options affect the iteration counts on the MAC and key algorithms. Unless you wish to produce files compatible with MSIE 4.0 you should leave these options alone.

To discourage attacks by using large dictionaries of common passwords the algorithm that derives keys from passwords can have an iteration count applied to it: this causes a certain part of the algorithm to be repeated and slows it down. The MAC is used to check the file integrity but since it will normally have the same password as the keys and certificates it could also be attacked. By default both MAC and encryption iteration counts are set to 2048, using these options the MAC and encryption iteration counts can be set to 1, since this reduces the file security you should not use these options unless you really have to. Most software supports both MAC and key iteration counts. MSIE 4.0 doesn’t support MAC iteration counts so it needs the -nomaciter option.

-maciter
This option is included for compatibility with previous versions, it used to be needed to use MAC iterations counts but they are now used by default.

-nomac
don’t attempt to provide the MAC integrity.

-rand file(s)
a file or files containing random data used to seed the random number generator, or an EGD socket (see RAND_egd). Multiple files can be specified separated by an OS-dependent character. The separator is ; for MS-Windows, , for OpenVMS, and : for all others.

-CAfile file
CA storage as a file.

-CApath dir
CA storage as a directory. This directory must be a standard certificate directory: that is a hash of each subject name (using x509 -hash) should be linked to each certificate.

-no-CAfile
Do not load the trusted CA certificates from the default file location

-no-CApath
Do not load the trusted CA certificates from the default directory location

-CSP name
write name as a Microsoft CSP name.

NOTES

Although there are a large number of options most of them are very rarely used. For PKCS#12 file parsing only -in and -out need to be used for PKCS#12 file creation -export and -name are also used.

If none of the -clcerts, -cacerts or -nocerts options are present then all certificates will be output in the order they appear in the input PKCS#12 files. There is no guarantee that the first certificate present is the one corresponding to the private key. Certain software which requires a private key and certificate and assumes the first certificate in the file is the one corresponding to the private key: this may not always be the case. Using the -clcerts option will solve this problem by only outputting the certificate corresponding to the private key. If the CA certificates are required then they can be output to a separate file using the -nokeys -cacerts options to just output CA certificates.

The -keypbe and -certpbe algorithms allow the precise encryption algorithms for private keys and certificates to be specified. Normally the defaults are fine but occasionally software can’t handle triple DES encrypted private keys, then the option -keypbe PBE-SHA1-RC2-40 can be used to reduce the private key encryption to 40 bit RC2. A complete description of all algorithms is contained in the pkcs8 manual page.

Prior 1.1 release passwords containing non-ASCII characters were encoded in non-compliant manner, which limited interoperability, in first hand with Windows. But switching to standard-compliant password encoding poses problem accessing old data protected with broken encoding. For this reason even legacy encodings is attempted when reading the data. If you use PKCS#12 files in production application you are advised to convert the data, because implemented heuristic approach is not MT-safe, its sole goal is to facilitate the data upgrade with this utility.

EXAMPLES

Parse a PKCS#12 file and output it to a file:

 openssl pkcs12 -in file.p12 -out file.pem

Output only client certificates to a file:

 openssl pkcs12 -in file.p12 -clcerts -out file.pem

Don’t encrypt the private key:

 openssl pkcs12 -in file.p12 -out file.pem -nodes

Print some info about a PKCS#12 file:

 openssl pkcs12 -in file.p12 -info -noout

Create a PKCS#12 file:

 openssl pkcs12 -export -in file.pem -out file.p12 -name "My Certificate"

Include some extra certificates:

 openssl pkcs12 -export -in file.pem -out file.p12 -name "My Certificate" \
  -certfile othercerts.pem

 

Certificates – Digital Certificates (Summary)

Introduction to Digital Certificates

Digital Certificates provide a means of proving your identity in electronic transactions, much like a driver license or a passport does in face-to-face interactions.

With a Digital Certificate, you can assure friends, business associates, and online services that the electronic information they receive from you are authentic.

This document introduces Digital Certificates and answers questions you might have about how Digital Certificates are used for information about the cryptography technologies used in Digital Certificates.

Digital certificates are the equivalent of a driver’s license, a marriage license, or any other form of identity.

The only difference is that a digital certificate is used in conjunction with a public key encryption system. Digital certificates are electronic files that simply work as an online passport.

Digital certificates are issued by a third party known as a Certification Authority such as VeriSign or Thawte.

These third party certificate authorities have the responsibility to confirm the identity of the certificate holder as well as provide assurance to the website visitors that the website is one that is trustworthy and capable of serving them in a trustworthy manner.

Digital certificates have two basic functions.

The first is to certify that the people, the website and the network resources such as servers and routers are reliable sources, in other words, who or what they claim to be.

The second function is to provide protection for the data exchanged from the visitor and the website from tampering or even theft, such as credit card information.

Who Uses Digital Certificates

Digital Certificates can be used for a variety of electronic transactions including e-mail, electronic commerce, groupware and electronic funds transfers.

Netscape’s popular Enterprise Server requires a Digital Certificate for each secure server.

For example, a customer shopping at an electronic mall run by Netscape’s server software requests the Digital Certificate of the server to authenticate the identity of the mall operator and the content provided by the merchant.

Without authenticating the server, the shopper should not trust the operator or merchant with sensitive information like a credit card number.

The Digital Certificate is instrumental in establishing a secure channel for communicating any sensitive information back to the mall operator Virtual malls, electronic banking, and other electronic services are becoming more commonplace, offering the convenience and flexibility of round-the-clock service direct from your home.

However, our concerns about privacy and security might be preventing you from taking advantage of this new medium for your personal business.

Encryption alone is not enough, as it provides no proof of the identity of the sender of the encrypted information. Without special safeguards, you risk being impersonated online.

Digital Certificates address this problem, providing an electronic means of verifying someone’s identity.

Used in conjunction with encryption, Digital Certificates provide a more complete security solution, assuring the identity of all parties involved in a transaction.

Similarly, a secure server must have its own Digital Certificate to assure users that the server is run by the organization it claims to be affiliated with and that the content provided is legitimate.

Types of Digital Certificate:-

  1. Identity Certificates

An Identity Certificate is one that contains a signature verification key combined with sufficient information to identify (hopefully uniquely) the key holder.

This type of certificate is much subtler than might first be imagined and will be considered in more detail later.

  1. Accreditation Certificates

This is a certificate that identifies the key holder as a member of a specified group or organization without necessarily identifying them.

For example, such a certificate could indicate that the key holder is a medical doctor or a lawyer.

In many circumstances, a particular signature is needed to authorize a transaction but the identity of the key holder is not relevant.

For example, pharmacists might need to ensure that medical prescriptions are signed by doctors but they do not need to know the specific identities of the doctors involved.

Here the certificate states in effect that the key holder, whoever they are, has permission to write medical prescriptions’.

Accreditation certificates can also be viewed as authorization (or permission) certificates.

It might be thought that a doctor’s key without identity would undermine the ability to audit the issue of medical prescriptions.

However, while such certificate might not contain key holder identity data, the certificate issuer will know this so such requirements can be met if necessary.

  1. Authorizations and Permission Certificates

In these forms of certificate, the certificate signing authority delegates some form of authority to the key being signed.

For example, a Bank will issue an authorization certificate to its customers saying ‘the key in this certificate can be used to authorize the withdrawal of money from account number 271828’.

In general, the owner of any resource that involves  electronic  access  can  use  an  authorization  certificate  to  control  access  to  it.

Other examples include control of access to secure computing facilities and to World Wide Web pages.

In banking an identity certificate might be used to set up an account but the authorization certificate for the account will not itself contain identity data.

To identify the owner of a certificate a bank will typically look up the link between account numbers and owners in its internal databases.

Placing such information in an authorization certificate is actually undesirable since it could expose the bank or its customers to additional risks.

The Parties to a Digital Certificate

In principle there are three different interests associated with a digital certificate:

  1. The Requesting Party

The  party  who  needs  the  certificate  and  will  offer it  for  use  by  others  –  they  will  generally provide some or all of the information it contains.

  1. The Issuing Party

The  party  that  digitally  signs  the  certificate  after  creating  the  information  in  the  certificate  or checking its correctness.

  1. The Verifying Party (or Parties)

They are Parties that validate the signature on the certificate and then rely on its contents for some purpose.

For example, a person – the requesting party –they might present paper documents  giving proof of identity to a government agency – the issuing party – who will then provide an identity certificate that could then be used by a bank – the verifying party – when the requesting party opens a bank account.

The term ‘relying party’ is sometimes uses instead of ‘verifying party’ but this can be misleading since  the  real  purpose  is  to  identify  a  party  who  checks  the  certificate  before  relying  on  it.

In  a credit card transaction many parties might handle a certificate and hence rely on it in some way but  only  a  few  of  these  might  actually  check  the  validity  of  the  certificate.

Hence  a  ‘verifying party’  is  a  party  that  checks  and  then  relies  on  the  contents  of  a  certificate,  not  just  one  that depends on it without checking its validity.

The actual parties involved in using a certificate will vary depending on the type of certificate.

 

Certificates – CSR (Certificate Signing Request).

What is a CSR (Certificate Signing Request)?

What is a CSR?

A CSR or Certificate Signing request is a block of encrypted text that is generated on the server that the certificate will be used on.

It contains information that will be included in your certificate such as your organization name, common name (domain name), locality, and country.

It also contains the public key that will be included in your certificate.

A private key is usually created at the same time that you create the CSR.

A certificate authority will use a CSR to create your SSL certificate, but it does not need your private key.

You need to keep your private key secret.

What is a CSR and private key good for if someone else can potentially read your communications?

The certificate created with a particular CSR will only work with the private key that was generated with it.

So if you lose the private key, the certificate will no longer work.

What is contained in a CSR?

NAME EXPLANATION EXAMPLES
Common Name The fully qualified domain name (FQDN) of your server. This must match exactly what you type in your web browser or you will receive a name mismatch error. *.google.com
mail.google.com
Organization The legal name of your organization. This should not be abbreviated and should include suffixes such as Inc, Corp, or LLC. Google Inc.
Organizational Unit The division of your organization handling the certificate. Information Technology
IT Department
City/Locality The city where your organization is located. Mountain View
State/County/Region The state/region where your organization is located. This shouldn’t be abbreviated. California
Country The two-letter ISO code for the country where your organization is location. US
GB
Email address An email address used to contact your organization. webmaster@google.com
Public Key The public key that will go into the certificate. The public key is created automatically

What is a CSR’s format?

Most CSRs are created in the Base-64 encoded PEM format.

This format includes the “—–BEGIN CERTIFICATE REQUEST—–” and “—–END CERTIFICATE REQUEST—–” lines at the begining and end of the CSR.

A PEM format CSR can be opened in a text editor and looks like the following example:

-----BEGIN CERTIFICATE REQUEST-----
MIIByjCCATMCAQAwgYkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
MRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKEwpHb29nbGUgSW5jMR8w
HQYDVQQLExZJbmZvcm1hdGlvbiBUZWNobm9sb2d5MRcwFQYDVQQDEw53d3cuZ29v
Z2xlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApZtYJCHJ4VpVXHfV
IlstQTlO4qC03hjX+ZkPyvdYd1Q4+qbAeTwXmCUKYHThVRd5aXSqlPzyIBwieMZr
WFlRQddZ1IzXAlVRDWwAo60KecqeAXnnUK+5fXoTI/UgWshre8tJ+x/TMHaQKR/J
cIWPhqaQhsJuzZbvAdGA80BLxdMCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBAIhl
4PvFq+e7ipARgI5ZM+GZx6mpCz44DTo0JkwfRDf+BtrsaC0q68eTf2XhYOsq4fkH
Q0uA0aVog3f5iJxCa3Hp5gxbJQ6zV6kJ0TEsuaaOhEko9sdpCoPOnRBm2i/XRD2D
6iNh8f8z0ShGsFqjDgFHyF3o+lUyj+UC6H1QW7bn
-----END CERTIFICATE REQUEST-----

How to generate a CSR Certificate using Openssl in Linux ?

openssl req -out <name>.csr -new -newkey rsa:2048 -nodes -keyout privateKey_<name>.key

How do I decode a CSR?

In order to decode a CSR on your own machine using OpenSSL, use the following command:

openssl req -in <name>.csr -noout -text

What is a CSR/Private Key’s bit length?

The bit-length of a CSR and private key pair determine how easily the key can be cracked using brute force methods.

A key size of 512 bits is considered weak and could potentially be broken in a few months or less with enough computing power.

If a private key is broken, all the connections initiated with it would be exposed to whomever had the key.

A bit-length of 1024 is exponentially stronger, however, it is more and more likely to be broken as computing power increases.

The Extended Validation guidelines that SSL certificate providers are required to follow (http://cabforum.org/documents.html), require that all EV certificates use a 2048-bit key size to ensure their security well into the future.

Because of this, most providers encourage 2048-bit keys on all certificates whether they are EV or not.