Showing posts with label network. Show all posts
Showing posts with label network. Show all posts

Tuesday, July 23, 2019

IPtables , The Legendary Firewall

A Brief History

Iptables based on netfilter framework has become the default for firewall software in Linux for nearly two decades. Netfilter/iptables framework is a kernel module supported since the 2.3 version, developed by Rusty Russel back on 1999. Here you can check his personal blog: https://rusty.ozlabs.org


A Strong Security Solution

Iptables is a very reliable and secure software, and it is remarkable that is not used only as a local machine firewall. Linux OS, together with iptables, installed on a machine can be used as a hardware router/firewall solution also. In addition to that there are even some open source software appliances used as a router/firewall based on Linux and iptables.


Netfilter Architecture

The Netfilter architecture is divided in the three following layers:Tables-Chains-Rules, see picture below

 

At the lower level we have the tables, which represent the type of packet processing that is happening through the firewall. The basic tables that are frequently used are the following:

- Filter: Table for packet filtering.
- NAT: Table for NAT rules.
- Mangle: Table for mangling packets.

At the next layer there are the Chains, which are simply lists of rules associated with each particular table. And finally, at the top there are the actual firewall rules controlling the access to the system.


Iptables in use


So let's try to see if we have any iptables rules loaded in our system:
give

#iptables -L

and you'll get something like this:


Chain INPUT (policy ACCEPT)
target                                              prot opt source               destination        
KUBE-FIREWALL                           all  --  anywhere             anywhere           

Chain FORWARD (policy DROP)
target                                            prot opt source               destination        
DOCKER-ISOLATION                   all  --  anywhere             anywhere           
DOCKER                                       all  --  anywhere             anywhere           
ACCEPT                                        all  --  any where             anywhere     ctstate RELATED,ESTABLISHED
ACCEPT                                        all  --  anywhere             anywhere           
ACCEPT                                        all  --  anywhere             anywhere           

Chain OUTPUT (policy ACCEPT)
target                                          prot opt source               destination        
KUBE-FIREWALL                       all  --  anywhere             anywhere           

Chain DOCKER (1 references)
target                                         prot opt source               destination        

Chain DOCKER-ISOLATION (1 references)
target                                         prot opt source               destination        
RETURN                                    all  --  anywhere             anywhere           

Chain KUBE-FIREWALL (2 references)
target                                         prot opt source               destination        
DROP                                          all  --  anywhere             anywhere         




On this particular host there are some rules generated from Docker and Kubernetes deployment.
First column is the Chain. Second column (prot) describes the protocol involved with the rule, third column (opt) is the ip options. Finally source and destination represents the source/destination IP or subnet involved with the rule.

Now lets say we need to blacklist an IP address so that our host is blocking every incoming and outgoing packet to this particular IP


#iptables -A INPUT -s <ipaddress to block> -j DROP


In that rule the firewall simply drops every incoming packet from the blacklisted ip address.  The rule is categorized under the FILTER table, and under the INPUT chain. The -s switch is used to filter the source ip address.


#iptables -A OUTPUT -d <ipaddress to block> -j DROP


In that rule the firewall drops every outgoing packet with destination IP same to the  IP address that is blacklisted. This rule is categorized under the FILTER table as well, but this time is under the OUTPUT chain. Now instead of source , we have destination ip address, thus the -d switch.


In some other occasion we may need to allow ssh connections to our host

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


or block ping requests

#iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

So you get the idea how this works.


Iptables as a router.

In that case it is possible to use a Linux box as a gateway to route LAN traffic to internet. For this operation you can utilize chains PREROUTING and POSTROUTING .


PREROUTING chain controls the incoming network packets from the LAN to the Linux box. So in practice you use PREROUTING for port forwarding in most cases
for example:


#iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to 192.168.1.10:80
 

this rule is allowing a web server to operate , by simply redirecting HTTP traffic from outside the LAN (internet) to the port 80 of the web servers IP (192.168.1.10).

POSTROUTING chain controls the outgoing network packets from the Linux box to the internet and is the chain which routes all the LAN traffic outside , so here we talking about the NAT process, so the rule goes

#iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
 

Based on that you can create your own firewall appliance just by using a single PC with a couple of network interfaces.








Wednesday, April 11, 2018

Nginx

If you're involved in Linux and Web stuff you may heard sometime about Nginx. Well Nginx is a "state of the art" platform. It differs from your common web server because it can be used also as a reverse proxy, load balancer, email proxy or even for video streaming.

In this article we will examine the set-up and configuration of Nginx starting using it as a simple web server and then scaling up to web proxy and load balancer.

So lets start the installation, but first ,if you use a CentOS box like me, you have to make sure you have the "epel" repository installed. It's a very useful extra repository created for the enterprise Linux, which contains plenty of extra software including Nginx as well. 

To obtain and install that repo just give

#yum install epel-release-latest-7.noarch.rpm

Now we're ready for Nginx. On my CentOS server to install I just give the command:

#yum install nginx

 Now if you just navigate to /etc/nginx you can see the nginx.conf which is the main configuration file.


Nginx as a web server

We can start with the case which Nginx is used as a simple webserver. The basic configuration inside the nginx.conf is the following:


http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
                       access_log  /var/log/nginx/access.log  main;
         server{
 #server stanza configuration section
         }
        }


The http stanza contains some default information about logging and the server block information which goes as follows:

  server {
        listen       80 default_server;
       
        root         /usr/share/nginx/html;

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

Here the "listen" directive defines the listening port of the web server,  root the root html directory of the web server, location and at last there are some default error pages defined to be displayed in case of an HTTP error request.


Nginx as a reverse proxy

Now we want to use the Nginx so that it can handle all incoming http requests and distribute them among the servers in the insight network. So on the main nginx.conf inside the server stanza we add the  following:

server_name mywebserver.com

location /uri/path/ {
                  proxy pass http://mywebserver.local;
                              }

The "server_name" directive is essential if you have multiple servers, with different server-names apparently. If this is defined ,Nginx processes  the host header according to the configuration stated below server_name.
"location" directive checks the request URI, and forwards all the requests to the address specified by "proxy_pass" directive". In that case where mywebserver.local you can also put IP address and port e.g: 192.168.1.200:8080.


Nginx as a load balancer

As it was mentioned above Nginx can be a very effective load balancer using several different load balancing algorithms (round robin by default). So to set up a simple load balancer, on the nginx.conf, we must go under the http stanza configuration and give the following:


    upstream mywebsite {
        server mywebserver1.com;
        server mywebserver2.com;
        server mywebserver3.com;
        server mywebserver4.com;
    }



All the magic here is been done by the upstream directive which defines the upstream servers where the traffic is distributed. Those servers are listed below defined by the classic server directive. By default uses the round robin algorithm but you can simply change that , by adding under the upstream directive.

least conn; 

for the least connected load balancing or

ip hash;  

for ip hash load balancing.


Nginx SSL 

It is essential to use https in your server http is insecure, obsolete and is going to be abandoned soon. You can count on Nginx to handle all the SSL procedure whether is a webserver or a proxy. To do this under the server stanza on the main configuration you need to add the following lines.

listen   443;

ssl    on;
ssl_certificate    /etc/nginx/conf/mywebsite.com-bundle.crt
ssl_certificate_key    /etc/nginx/conf/mywebsite.key;

Now the "listen" directive is on 443 (SSL), it follows the "SSL on", and then we simply declare the directory that we hold the SSL bundle certificate and the SSL key.


Nginx management and control.

After every configuration change you have to restart the nginx service in order for that to be applied, to do this simply give:

# systemctl restart nginx

But..beware, you have to be very sure that your configuration is correct otherwise the server will fail to start resulting your website or websites to be down. To avoid this you have the option to test your configuration before the restart by giving.

# nginx -t

You can also apply your configuration changes without restarting by giving.

# nginx -s reload

And don't forget to make sure that you have Nginx to run on system startup.

# systemctl enable nginx

So this is enough info for a good start, for additional plenty of information you can always visit https://www.nginx.com/.

enjoy


















Friday, January 5, 2018

Network Tools





Computing co-exists with networking. Thus to operate a Linux system you’ll find yourself very often involved with network operations. Those operations may be between your system and the outside world (whether is a LAN or the Internet) but they may also be inside your own kernel network stack.

One of my favorite packages ever is the net-tools package. It is a set of very useful tools for configuring and gathering information about your network resources.
So let’s start by installing the package, I’ll use my centos 7 server for the demonstration

          #yum –y install net-tools

Now let’s find and inspect the package to see what we got:

          #rpm -qa | grep net-tools

Which gives the exact version of the package (net-tools-2.0-0.22.20131004git.el7.x86_64 )

To inspect that we give:

          #rpm -ql net-tools-2.0-0.22.20131004git.el7.x86_64

Here we get a long file list with man pages, language files, services etc, but we will focus on some binaries of the output list of the previous command:
/bin/netstat
/sbin/arp
/sbin/ifconfig
/sbin/iptunnel
/sbin/route

My favorite here is Netstat. This command operates like a radar for your system, monitoring every single incoming and outgoing network connection. So let’s play with that by giving:

          #netstat –an

By examining the output, we spot two sections. The first section displays the “Active Internet connections (servers and established)” which is obviously the connections in and out of the machine.
Proto     Recv-Q  Send-Q                 Local Address         Foreign Address          State
tcp          0              0                           0.0.0.0:22                      0.0.0.0:*                  LISTEN

Proto is the protocol type it can be tcp or udp, Recv-Q  Send-Q is the  count of bytes in queue ready to be received or sent accordingly, for this particular socket. Local address is the address of our machine and foreign address is the address of the remote connected machine. In this example is zero because the socket is in listening mode, this you can check by the last column “State” which displays the TCP protocol state the time you hit the command. Local address can be 127.0.0.1 or the machine’s unique local ip or machine’s one of multiple ip addresses.

The second section of the output has the pattern:
ProtoRefCnt              Flags              Type                State               I-Node   Path
unix  2                    [ ACC ]            STREAM      LISTENING     17930    /var/run/lsm/ipc/sim

Here the Protocol column is always UNIX which represents a UNIX socket. This kind of socket is used only for process interconnection and not for external networking. The “Flags” column lists the opening TCP Flag of the connection, the “Type” states if the connection is  a stream or a datagram, “State” is the current TCP state, next column is the I-node number where the process file is located, and “Path” is the path of the process file.

Arp is a tool to get information about the apr table on the machine, just for the redord ARP stands for Addresss Resolution Protocoll and is basically maps an ip address to a physical MAC address. So by giving:

          #arp 

We get the following structure
Address                  HWtype             HWaddress                       Flags Mask            Iface
gateway                  ether                d1:68:0a:4a:f2:da               C                         enp1s0

Here we can see this mapping the MAC address (HWaddress) of the gateway connected to our Ethernet (HWtype ) interface enp1s0 (Iface).

Ifconfgig is an interface manipulation tool. With this you can change the IP settings (address ,netmask ,broadcast etc),enable or disable the interface, enter promiscuous mode or add an alias. 
So lets give:

          #ifconfig virbr0-nic

virbr0-nic: flags=4098<BROADCAST,MULTICAST>  mtu 1500
        ether 52:54:00:0f:48:4d  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

“virbr0-nic” is the virtual bridge interface of my KVM Hypervisor. Here we can see the type of the interface the MAC address and some statistics about packet transmission.

Iptunnel is a tool to create tunnels for ipv4 packet encapsulation. The use of it is a bit complicated and I hope I can cover it in a future article

Route is a tool to examine and manipulate your machines routing table. Giving

          # route

We have the following output:
Destination          Gateway         Genmask             Flags        Metric Ref     Use  Iface
default                    gateway         0.0.0.0                    UG          100    0          0    enp1s0
10.0.81.0                0.0.0.0         255.255.255.0             U           100    0          0    enp1s0

This is basically the kernel routing table which shows the network path that a packet follows to reach its destination. The first line is the default route which is the route the packet follows when no other path is specified. Now by analyzing the columns of the routing table we can get information about each route:
Destination is the host or network address the packet is finally destined to, Gateway is the node that each packet uses in order to reach an outside network, Genmask is the netmask of the network, the Flags column indicates information about the state or type of route, Metric is the distance of the target, Ref the number of references to this route, Use is the count of lookups for the route and iface the network interface.

At last, of course I can’t exclude from the article traceroute and dig, although they’re not in network-tools packet.
So if we traceroute a host we get a numbered list of hostnames which are simply the hops the packet passes through in order to reach the final host destination.
Dig is a very powerful tool which gives detailed dns information about an internet address,
Bonus command: 

           #dig +short myip.opendns.com @resolver1.opendns.com

which gives us our external IP address

Of course there are many other network commands and tools, but using the commands mentioned above is a very good toolset that will help you to identify your network surroundings and troubleshoot possible anomalies.