overview edit doc new doc remove

Jan 26, 2018

updated at: Apr 12, 2018

Linux security

Basic Security

First of all you need to understand that the more layers of security, the more secure.

Checklist

Chage

# chage -M 60 -m 7 -w 7 <user>

Faillog

To see failed attempts:

# faillog

To unlock an account:

# faillog -r -u username

Secure SSH

Disable if you don't need:

# chkconfig sshd off
# erase openssh-server
# remove openssh-server

Only allow a couple of users, edit /etc/ssh/sshd_config and add:

AllowUsers root sebastiaan

Disable root login:

PermitRootLogin no

Set up a banner via /etc/issue and edit /etch/motd.

Disable password authentication to require all users connecting via a key, edit /etc/ssh/sshd_config:

PasswordAuthentication no

Restart ssh service:

# systemctl restart sshd

Fail2ban (Nginx protection)

Add the following to /etc/fail2ban/filter.d/nginx-req-limit.conf.

# Fail2Ban configuration file
#
# supports: ngx_http_limit_req_module module

[Definition]

failregex = limiting requests, excess:.* by zone.*client: <HOST>

# option: ignoreregex
# notes.: regex to ignore. If this regex matches, the line is ignored.
# values: TEXT
#
ignoreregex =

Run "cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local" And add the following towards the end:

[nginx-req-limit]

enabled = true
filter = nginx-req-limit
action = iptables-multiport[name=ReqLimit, port="http,https", protocol=tcp]
logpath = /var/log/nginx/*error.log
findtime = 600
bantime = 7200
maxretry = 10

Check with:

# fail2ban-client status nginx-req-limit

Disable IPv6

Add this to /etc/sysctl.conf:

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.ipv6.conf.eth0.disable_ipv6 = 1

Arp monitor tools

Monitor Ethernet traffic activity (like Changing IP and MAC Addresses) on your network and maintains a database of ethernet/ip address pairings. These tools are useful for Network administrators to keep a watch on ARP activity to detect ARP spoofing or unexpected IP/MAC addresses modifications.

# install arpwatch
# systemctl start arpwatch
# arpwatch -i <interface>

Pam_cracklib

You can be configured to verify that passwords (read as weak password) cannot be guessed easily using Linux PAM module called pam_cracklib.so. It will check the passwd against dictionary words. User is not allowed to set new password until and unless conditions satisfied (i.e. weak password is not allowed).

# install libpam-cracklib
# password required pam_cracklib.so retry=2 minlen=10 difok=6

Security scanners

$ git clone https://github.com/CISOfy/lynis.git
# ./lynis audit system  -Q

Chroot

Chroot is a tool for isolating processes for installation, debugging and legacy library usage. Therefore Chroot was never inteded to be a security device and is perhaps sometimes being misused.

Capabilities

Capabilities in Linux are flags that tell the kernel what the application is allowed to do, but unlike file access, capabilities for an application are system-wide: there is no "target" to which it applies. Think about an "ability" of an application. See for yourself through man capabilities. If you have no additional security mechanism in place, the Linux root user has all capabilities assigned to it. And you can remove capabilities from the root user if you want to, but generally, capabilities are used to grant applications that tiny bit more privileges, without needing to grant them root rights.

Some people say that you should drop them all and use other security measures instead.

PAM

Pluggable Authentication Modules (PAM) was invented by Sun Microsystems and originally implemented in the Solaris OS, today most Linux distro's use PAM. PAM simplifies the authentication management process, authentication is the process of determining that a subject is who he says he is. Applications can be written to use PAM and are called "PAM-aware". PAM also does a little more than just the application authentication. It can also manage resources, restrict access times, enforce good password selection, and so on. The benefits of using PAM on your Linux system include the following:

How it works

A series of steps is taken by PAM using the modules and configuration files to ensure that proper application authentication occurs:

  1. A subject (users or process) requests access to an application.
  2. The application's PAM config file is open and read.
  3. Each PAM module is invoked in the order it is listed.
  4. Each PAM module returns either a success or a failure status.
  5. The status results of all the PAM modules are combined into a single overall result of authentication success or failure.

Typically if a single PAM modules returns a failure status, access to the application is denied, however this can depend on the config file settings.

Configuration

File locations

Syntax

PAM configuration files are made up of a context, control flag, module-path and arguments

Example
#context   flag       module      arguments
auth       include    password-auth   invoke
account    required   pam_access.so   prepare
account    include    password-auth   revoke
session    required   pam_loginuid.so
session    include    password-auth

Mandatory Access Controls

Mandatory Access Control (MAC) is is a set of security policies constrained according to system classification, configuration and authentication. MAC policy management and settings are established in one secure network and limited to system administrators. MAC defines and ensures a centralized enforcement of confidential security policy parameters.

SELinux

SELinux stand for Secured Enchanted Linux. It is all about policies and is made by the NSA. It implements the RBAC access control model, which is considered the strongest access control model. SELinux allows process sandboxing which means processes cannot access other processes or their files unless special permissions are granted.

Policies can be set to determine access between:

turn SELinux on and off

# sestatus or getenforce
# setenfore 0
# setenfore 1

Labeling

Everything in the filesystem is labeled with an SELinux context.

format: SELinuxUser:rol :type:level

check via

# ls -dlZ file
# id -Z file
# ps axZ

example: ports that are allowed for http in SELinux

# semanage port -l | grep http

type enforcement is quite nice, the main purpose here is to have an extra layer of protection for files to read acces other files, for example httpd with shadow.

Troubleshoot

Labeling and policies

Booleans are just on/off settings for SELinux.

commands:

# getsebool -a
# setsebool [boolean] [0|1]
# setsebool -P [boolean] [0|1]

Custom booleans:

# cat /var/lib/selinux/targeted/active/booleans.local
Logs
# cat /var/log/*
$ dmesg
$ journalctl -r
$ journalctl | grep sealert

better, mostly you will find information about SELinux here:

# cat /var/log/messages
# cat /var/log/audit/audit.log

To fix the errors, copy paste the output for example:

# sealert -l 65465456bb-54564b-465454a-6456b-54545641d541

or

# grep **selinuxerror** /var/log/audit/audit.log | audit2allow
# semodule -i selinuxerror.pp

Restorecon (fixing labels)

for example you moved some files and now it's not working anymore (fe. apache), problems lies with labels.

do:

# ls -aZ
# chcon --reference parentFolder file

or

# restorecon -vR /parentFolder (/var/www/)

If you want to give a folder the same label as an other folder for example /var/www/ and /foo/

# semanage fcontext -a -e /var/www/ /foo/
# restorecon -vR /foo/

Install extra software

You can install setroubleshoot and setroubleshoot-server then restart auditd.

This will help you diagnose and fix SELinux issues. A GUI of SELinux can be installed with the policycoreutils package, to launch the GUI use the command: system-config-selinux.

AppArmor

The operation of AppArmor is based on profiles defined in plain text files where the allowed permissions and access control rules are set. Profiles are then used to place limits on how applications interact with processes and files in the system.

Like SELinux, AppArmor runs profiles in two modes. In enforce mode, applications are given the minimum permissions that are necessary for them to run, whereas in complain mode AppArmor allows an application to take restricted actions and saves the “complaints” resulting from that operation to a log (/var/log/kern.log, /var/log/audit/audit.log, and other logs inside /var/log/apparmor).

# apparmor_status

Profiles are stored in:

To switch between profile modes:

# aa-complain /path/to/file
# aa-enforce /path/to/file

Grsecurity

Is the only serious kernel hardening patchset with minimal kernel modules. you need to patch Grsecurity into your kernel and recompile it.

SMACK

SMACK or Simplified Mandatory Access Control Kernel is an integrated Linux kernel security module. It protects data and proccess interaction using custom mandatory access control rules. Another integrated Linux kernel security module is Seccomp, short for Secure Computing Mode.

Firewall

A firewall is a network security device that monitors incoming and outgoing network traffic and decides whether to allow or block specific traffic based on a defined set of security rules. There are different types of firewalls.

Proxy firewall

An early type of firewall device, a proxy firewall serves as the gateway from one network to another for a specific application. Proxy servers can provide additional functionality such as content caching and security by preventing direct connections from outside the network. However, this also may impact throughput capabilities and the applications they can support.

Stateful inspection firewall

Now thought of as a “traditional” firewall, a stateful inspection firewall allows or blocks traffic based on state, port, and protocol. It monitors all activity from the opening of a connection until it is closed. Filtering decisions are made based on both administrator-defined rules as well as context, which refers to using information from previous connections and packets belonging to the same connection. In Linux there a lot of implementations of stateful inspection firewall, here are some examples.

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.

FirewallD uses zones and services.

# firewall-cmd --get-active-zones

Flush tables:

# firewall-cmd --reload

Allow ports, services or block:

# firewall-cmd --zone=public --remove-port=80/tcp
# firewall-cmd --zone=public --add-port=80/tcp
# firewall-cmd --zone=public --add-service=ftp

Iptables

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 chain and rules.

Get all iptables rules list:

# iptables -L

Flush Tables:

# iptables -F (INPUT, OUTPUT, FORWARD)

Allow ports or block them:

# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# iptables -A OUTPUT -p tcp --dport 22 -j DROP

NFTables

Nftables is the project that aims to replace the existing {ip,ip6,arp,eb}tables framework. Basically, this project provides a new packet filtering framework, a new userspace utility and also a compatibility layer for {ip,ip6}tables. nftables is built upon the building blocks of the Netfilter infrastructure such as the existing hooks, the connection tracking system, the userspace queueing component and the logging subsystem.

UFW

UFW, or Uncomplicated Firewall, is a front-end to iptables. Its main goal is to make managing your firewall drop-dead simple and to provide an easy-to-use interface. It’s well-supported and popular in the Linux community—even installed by default in a lot of distros. As such, it’s a great way to get started securing your sever.

FireHOL

FireHOL is a language (and a program to run it) which builds secure, stateful firewalls from easy to understand, human-readable configurations. The configurations stay readable even for very complex setups.

Unified threat management (UTM) firewall

A UTM device typically combines, in a loosely coupled way, the functions of a stateful inspection firewall with intrusion prevention and antivirus. It may also include additional services and often cloud management. UTMs focus on simplicity and ease of use.

Next-generation firewall (NGFW)

Firewalls have evolved beyond simple packet filtering and stateful inspection. Most companies are deploying next-generation firewalls to block modern threats such as advanced malware and application-layer attacks.

A NGFW has the following aspects:

A threat-focused NGFW is the same as a normal NGFW but also provides advanced threat detection and remediation. With a threat-focused NGFW you can:

Containers

Containers encapsulate discrete components of application logic provisioned only with the minimal resources needed to do their job. Unlike virtual machines (VM), containers have no need for embedded operating systems (OS); calls are made for OS resources via an application programming interface (API). Containerisation is, in effect, OS-level virtualisation (as opposed to VMs, which run on hypervisors, each with a full embedded OS). Containers are easily packaged, lightweight and designed to run anywhere. Multiple containers can be deployed in a single VM.

LXC

What if it wasn't one cpu with multiple kernels, but one kernel with multiple userlands. A Linux container separates Network device, IP, MAC, routing table, firewall, ... It is used as a sandbox. A process in a container will have another PID in the host than in the lxc. for example. "sleep 1000" will have a PID of 324 in the lxc and 26052 in the host. Containers is all about isolation.

getting a LXC container (fedora):

# dnf install lxc lxc-templates lxc-extra debootstrap libvirt
# systemctl start libvirtd

$ lxc-create -n container1 -t fedora
$ lxc-attach -n container1
$ lxc-console -n container1

LXC webpanel (Ubuntu only): https://lxc-webpanel.github.io/install.html.

NOTE: Use ctrl+a ctrl+q to exit.

SELinux sometimes generates problems with use of LXC, best is to set SELinux to permissive mode.

LXC weaknesses

Docker

Docker ideally focuses on one app per container, one process in one container with the libraries and files it needs, nothing else. Docker makes it really easy to run containers. Originally it was based on LXC now it has it own libraries, REST API and it's written in go.

The core idea is isolating systems, for example having a java7 and a java8 application running on the same machine.

Example:

# install docker
# systemctl start docker
$ docker run -t -i fedora /bin/bash

Docker weaknesses

CoreOS

CoreOS is a minimal OS for hosting containers, it separates itself from Docker and LXC. Rocket is their main software for running containers.

CoreOS weaknesses

1