The book "Kali Linux from developers"

    imageHi, Habrozhiteli! The authors will introduce you step by step to the basics and capabilities of Kali Linux. The book offers a short course on working with the Linux command line and its concepts, and describes typical Kali Linux installation scenarios. After reading this book, you will learn how to configure, debug, and protect Kali Linux, as well as work with the powerful package manager of the Debian distribution. Learn how to install Kali Linux correctly in any environments, including large corporate networks. Finally, you will have to get acquainted with complex topics: compiling the kernel, creating your own ISO images, industrial encryption and professional protection of confidential information.

    Chapter 7. Kali Linux Security and Control

    Once you start using Kali Linux for more sensitive and high profile tasks, you will most likely have to take the security of your installation more seriously. In this chapter, we will first discuss the security policy, highlighting the most important points in determining it, and focus on some of the threats to your system and to you as a security professional. We will also discuss security measures for laptops and desktops, and consider firewalls and packet filtering separately. In conclusion, we will touch on the tools and strategies of monitoring and show the most effective ways to use them to detect potential threats to your system.

    7.1. Security Policy Definition

    It makes no sense to discuss security in general terms, since this concept represents a wide range of concepts, tools and procedures that are not universal. Choosing among them requires an accurate representation of your goals. Protection of the system begins with the answers to several questions. Hasty and reckless implementation of an arbitrary set of utilities leads to the risk of erroneous security aspects.

    It is best to initially identify a specific goal. The correct approach to solving this problem will be the answers to the following questions.

    1. What are you trying to protect? The security policy will differ depending on whether you want to protect computers or data. In the latter case, you also need to know exactly what information needs protection.

    2. What are you trying to protect against? From confidential data leakage? From accidental loss of information? From the loss caused by the failure to provide services?

    3. From whom are you trying to protect yourself? Security measures will be completely different to protect against typos of a simple user of the system and protection against a certain group of intruders.

    The term “risk” is usually used to give a general definition of these factors: what needs to be protected, what should be prevented and for whose fault this can occur. Risk modeling requires answers to all three questions. Based on the model obtained, you can develop a security policy and implement it through specific actions.

    Bruce Schneier, a global security expert (not just a computer), is trying to confront one of the basic myths of security, acting under the motto: "Security is a process, not a product." Assets that need protection change over time, as do the threats and tools available to potential intruders. Even if the security policy was initially ideally designed and implemented, you should never stop there. The components of risk are evolving, and methods of preventing it must evolve accordingly.

    In addition, additional constraints that may limit the range of policies available should be considered. What are you ready to do to protect the system? This question is of great importance for policy choice. Very often, the answer is determined only in terms of monetary costs, but other elements should be taken into account, such as possible inconveniences that users of the system will undergo or deterioration of its performance.

    Once the risk has been modeled, you can think about developing a suitable security policy.

    There are extremes that are worth considering when deciding on the level of security needed. On the one hand, it is extremely simple to ensure basic system security.

    For example, if the system defined for protection only includes a used computer, which is used only to add a pair of numbers at the end of the day, then it would be a reasonable decision not to do anything special to protect it. The true value of such a system is low, and the value of the data is completely zero, since they are not stored on the computer. A potential intruder entering this system will only receive a calculator. The cost of protecting such a system is likely to be greater than the damage from hacking.

    The opposite situation will be the case of protecting the confidentiality of confidential data in the most complete way, overcoming any restrictions. In this case, a suitable solution would be the complete destruction of information (safe erasing files, grinding hard drives into small pieces, then dissolving these pieces in acid, etc.). If there is an additional requirement that data should be stored for future use (not necessarily in constant availability) and cost is still not a limiting factor, then the best idea would be to store data on iridium and platinum alloy plates in bomb shelters under the mountains around the world, each of which (of course) is classified and guarded by a whole army.

    Although these methods may seem exaggerated, they can nevertheless be suitable solutions for certain risks, since they allow one to achieve the intended goals under given restrictions. Based on an informed decision, no security policy is more or less sufficient than any other.

    Returning to a more typical case, the information system can be segmented into compatible and predominantly independent subsystems. All of them have their own requirements and limitations, so risk assessment and development of security policies should be carried out separately for each of these subsystems. It must always be remembered that a small attack surface is easier to defend than a large one. Network organizations should be designed as follows: vulnerable services should be concentrated on a small number of computers, and the latter should be accessible through the minimum number of routes or control points. The logic is simple: it is easier to protect checkpoints than all vulnerable computers from the whole outside world. It is at this point that the benefits of network filtering (including firewalls) become apparent.

    7.2. Possible security measures

    As mentioned above, there is no single answer to the question of how to protect Kali Linux. It all depends on how you use it and what exactly you are trying to protect.

    On the server

    If you are using Kali Linux on a public server, then you should protect network services by changing all the default passwords that can be configured, and probably by restricting access to them using a firewall (sections 7.3 “Protecting network services” and 7.4 "Firewall or packet filtering", respectively, see below).

    If you are transferring user account data directly on the server or on one of the network services, be sure to set strong passwords (they must withstand brute-force attacks). At the same time, you can configure the fail2ban program, which significantly complicates password-breaking through the network (by filtering IP addresses exceeding the limit of failed login attempts). You can install fail2ban using the apt update command and then apt install fail2ban.

    If you use web services, configure them to work through the HTTPS protocol so that network intermediaries do not track your traffic (which may include cookie authentication files).

    On a laptop

    A penetration testing notebook does not suffer the same risks as an open server: for example, you are less susceptible to occasional attacks by an amateur hacker, and if this happens, you probably will not have active network services at this moment.

    The real risk often arises when you drive from one customer to another. For example, your laptop may be stolen during a trip or taken away by customs officers. That's why you should use full disk encryption (see the section “Installing on a fully encrypted file system” section 4.2) and, perhaps, also configure the nuke function (see the sidebar “Setting a self-destruct password for additional security” in Chapter 9): You collected during your work are confidential and require maximum protection.

    You may also need firewall rules (see Section 7.4 below), but not for the same purpose as on the server. You will probably want to block all outgoing traffic, except for the traffic generated by your VPN access. These settings are similar to network security settings, so when the VPN stops working, you will immediately notice this (instead of returning to local network access). Thus, you do not give out the IP addresses of your clients when you browse the web or other online activities. In addition, if you are performing local internal interaction, it is best to continually monitor your activities to reduce the noise generated in the network, which can attract the attention of customers and their protection systems.

    7.3. Network Services Protection

    It is recommended to disable services that you do not use. Kali simplifies this task because most network services are already disabled by default.
    As long as the services remain disabled, they do not pose a security risk. However, you must be careful when turning them on due to the following factors.

    1. By default, they do not have a firewall, so if they listen on all network interfaces, they are largely accessible to the public.

    2. Some services do not have credentials and allow them to be set when first used; others have standard (and, therefore, widely known) credentials. Make sure you (re) set a password that only you know.

    3. Many services are released as root (with full administrator rights), so the consequences of unauthorized access or security breaches are usually serious.

    We will not list here all the tools that come with default credentials. Instead, you should check the README.Debian file for the relevant packages, as well as the and pages to see if the service needs special maintenance to ensure the necessary security.

    If you are running in real time, then the root account password is toor. Thus, you do not need to enable SSH before changing the password of the root account or before configuring the account to prevent login based on a password.

    Notice also the well-known fact that the BeEF project (from the already installed beef-xss package) has the default credentials: the username beef and the password beef, which are “forced” in the configuration file.

    7.4. Firewall or packet filtering

    A firewall is a piece of computer hardware with hardware, software, or both, that analyzes incoming or outgoing network packets (incoming or outgoing from a local area network) and passes only those that meet certain predefined conditions.

    A filtering network gateway is a type of firewall that protects the entire network. It is usually installed on a dedicated computer that is configured as a gateway for the network, so that it can analyze all incoming and outgoing packets from the network. Alternatively, there is a local firewall, which is a software service that runs on one specific computer in order to filter or restrict access to a number of services on that computer, or perhaps prevent outgoing connections from spyware that a user may have made by chance or intentionally.

    The netfilter firewall is built into the Linux kernel. There is no single solution for configuring any firewall, as the network and user requirements differ. However, you can control netfilter from user space with the commands of iptables and ip6tables. The difference between the latter is that the former works for IPv4 networks, while the latter operates on IPv6. Since both network protocol stacks are likely to work for many years, both tools should be used in parallel. You can also use the excellent GUI-based fwbuilder utility, which provides a graphical representation of filtering rules.

    However, if you decide to configure netfilter (the implementation of the Linux firewall), then consider in more detail how it works.

    Netfilter Network Filter Behavior The Netfilter

    filter uses four different tables that store the rules governing three types of package operations:

    1. filter refers to filtering rules (accepting, refusing or ignoring a package);

    2. nat (Network Address Translation) refers to the translation of source or target addresses and ports of packets;

    3. mangle refers to other changes in IP packets (including the ToS (Type of Service) field and options);

    4. raw allows other manual package changes before they (the packets) reach the connection tracking system.

    Each table contains lists of rules called chains. The firewall uses standard chains to process packets based on predefined conditions. The administrator can create other chains that will be used only when transferring one of the standard chains (directly or indirectly).

    The filter table contains three standard circuits:

    1. INPUT — for packets whose purpose is the firewall itself;

    2. OUTPUT - refers to packets originating from the firewall;

    3. FORWARD - refers to packets passing through a firewall (which is neither their source nor destination).

    The nat table also has three standard chains:

    1. PREROUTING — to change packages immediately after they arrive;

    2. POSTROUTING - to change packages when they are ready to be sent;

    3. OUTPUT - for modifying packets generated by the firewall itself.

    These chains are depicted in Fig. 7.1.


    Each chain is a list of rules; each rule is a set of conditions and an action performed when the conditions are met. When processing a packet, the firewall scans the corresponding chain, one rule after another, and when the conditions for one rule are fulfilled, jump (jump) (hence the -j parameter in commands) to the specified action to continue processing. The most common types of behavior are standardized, and for them there are special actions. Doing one of these standard actions interrupts the processing of the chain, since the further fate of the packets is already predetermined (disregarding the exception mentioned below). The following are the Netfilter actions.

    1. ACCEPT (ACCEPT) - allow the package to move further along its route.

    2. REJECT - reject the packet using the Internet Control Message Protocol (ICMP) error packet (the --reject-with parameter for iptables determines the type of error to reject).

    3. DROP - remove (ignore) the packet.

    4. LOG (REGISTER) - register (via the syslogd daemon) a message describing the package. Note that this action does not interrupt processing, and the execution of the chain proceeds from the next rule, therefore registration of rejected packets requires both LOG rules and REJECT / DROP. Common registration options include:

    • --log-level, with the default warning, indicates the severity level of syslog;
    • --log-prefix allows you to specify a text prefix to distinguish registered messages;
    • --log-tcp-sequence, --log-tcp-options and --log-ip-options indicate additional data that should be placed in the message: TCP sequence number, TCP parameters and IP parameters, respectively.

    5. ULOG - register a message through ulogd, which can be better adapted and more efficient than syslogd for processing a large number of messages; note that this action, like LOG, also returns processing to the next rule in the calling chain.

    6. name of the chain - go to the specified chain and evaluate its rules.

    7. RETURN (RETURN) - interrupt the processing of the current chain and return to the calling chain; if the current chain is standard, then there is no calling chain, so instead of it, a default action (defined using the -P option for iptables) is performed.

    8. SNAT (only in the nat table) - apply the Source Network Address Translation (SNAT) source. Additional parameters describe the exact changes to be applied, including the --to-source address: port parameter, which defines the new source IP address and / or port.

    9. DNAT (only in the nat table) - apply the Network Address Translation (DNAT) assignment. Additional parameters describe the exact changes to be used, including the --to-destination address: port parameter, which defines the new source IP address and / or port.

    10. MASQUERADE (MASK) (only in the nat table) - apply masking (a special case of Source NAT).

    11. REDIRECT (REDIRECTION) (only in the nat table) - openly redirect the packet to this port of the firewall itself. You can use it to set up a public web proxy server that works without configuration on the client side, and when the client thinks it is connecting to the recipient, the actual messages go through the proxy server. The --to-ports parameter (s) indicates the port or port range to which packets should be redirected.

    Other actions, especially those related to the mangle table, were not included in this subsection. Their full list can be found on the iptables (8) and ip6tables (8) manual pages.

    Iptables and ip6tables command syntax

    The iptables and ip6tables commands are used to manage tables, chains and rules. Their -t table parameter indicates which table to work with (by default, the filter table).


    The following are the basic parameters for interacting with chains.

    1. -L chain displays the list of rules contained in the chain. Used with the -n option to disable name resolution (for example, iptables -n -L INPUT prints the rules related to incoming packets).

    2. -N chain creates a new chain. You can create new chains for a variety of purposes, including testing a new network service or repelling a network attack.

    3. -X chain removes empty and unused chain (for example, iptables -X ddos-attack).

    4. -A chain rule adds a rule at the end of a given chain. Remember, rules are processed from top to bottom; do not forget to take this moment into account when adding rules.

    5. -I chain rule_number inserts the rule before the rule with the specified number. As in the -A parameter, consider the order of processing when introducing new rules into the chain.

    6. -D chain rule_ number (or -D chain rule) removes the rule in the chain; the first syntax indicates that the rule with a certain number should be deleted (the iptables -L --line-numbers command displays the numbers of the rules), and the second identifies the rule to be deleted in its essence.

    7. -F chain resets the chain (removes all of its rules). For example, to remove all rules related to outgoing packets, you must enter the command iptables -F OUTPUT. If no chains are specified, then all rules in the table are deleted.

    8. -P chain action defines the default action or "policy" for this chain. Please note: this policy applies only to standard circuits. To remove all incoming traffic by default, you must issue the command iptables -P INPUT DROP.


    Each rule is defined according to the following syntax: conditions -j action action_action parameters. If several conditions are described in one rule, then the criterion is the union (logical AND) of conditions, which has a restriction that is at least the same as each individual condition.

    The condition -p protocol corresponds to the IP packet protocol field. The most common values ​​are tcp, udp, icmp and icmpv6. This condition can be supplemented with conditions regarding TCP ports using the parameters --source-port port and --destination-port port.

    Negative Conditions

    Adding an exclamation mark in front of a condition means denying it. For example, the negation of a condition by the parameter -p means "any packet with a protocol other than the one specified." This mechanism of negation can be applied to any other conditions.

    The condition -s address or -s network / mask matches the source address of the packet. Accordingly, -d address or -d network / mask corresponds to the destination address.
    Condition The -i interface selects packets originating from the specified network interface; -o interface - packages that go to a specific interface.

    The condition —state status corresponds to the status of the packet in the connection (this requires the ipt_ conntrack kernel module to track the connection) The NEW status describes the packet starting the new connection, the ESTABLISHED status corresponds to the packets belonging to the existing connection, and the RELATED status corresponds to the packets initiating the new connection associated with the existing ones (which is useful for ftp data connections in the active FTP protocol mode).

    There are many options available for iptables and ip6tables, and it will take a long time to master them. However, one of them, which you will use most often, is a parameter that blocks malicious network traffic from a host or range of hosts.
    For example, to quietly block incoming traffic from the IP address and class C subnet, you need to run a number of commands:

    # iptables -A INPUT -s -j DROP
    # iptables -A INPUT -s -j DROP
    # iptables -n -L INPUT
    Chain INPUT (policy ACCEPT)
    target        prot opt source                  destination

    Another iptables command is often used to allow network traffic for a particular service or port. In order for users to connect to SSH, HTTP and IMAP, you must run the following commands:

    # iptables -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT
    # iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
    # iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
    # iptables -n -L INPUT
    Chain INPUT (policy ACCEPT)
    target        prot opt source                 destination
    ACCEPT      tcp --       state NEW tcp dpt:22
    ACCEPT      tcp --       state NEW tcp dpt:80
    ACCEPT      tcp --       state NEW tcp dpt:143

    The rule of good computer hygiene is cleaning up old and unnecessary rules. The easiest way to remove an iptables rule is to refer to the rules by line number, which you can get using the --line-numbers parameter. Be careful: when you reset the rules, all subsequent rules in the chain will be renumbered.

    # iptables -n -L INPUT --line-numbers
    Chain INPUT (policy ACCEPT)
    num    target    prot    opt    source               destination
    1        DROP     all       --       all       --  tcp      --       state NEW tcp dpt:224ACCEPT  tcp      --       state NEW tcp dpt:805ACCEPT  tcp      --       state NEW tcp dpt:143# iptables -D INPUT 2# iptables -D INPUT 1# iptables -n -L INPUT  --line-numbersChainINPUT (policyACCEPT)
    num target prot opt source destination
    1ACCEPT  tcp      --        state NEW tcp dpt:222ACCEPT  tcp      --        state NEW tcp dpt:803ACCEPT  tcp      --        state NEW tcp dpt:143

    There are more specific conditions depending on the general conditions described above. For more information, refer to the iptables (8) and ip6tables (8) manuals.

    Creating rules

    Each new rule requires one iptables or ip6tables call. Entering these commands manually can be tedious, so calls are usually stored in a script, and as a result, the system automatically adjusts itself the same way every time the computer boots. You can write this script manually, but you may also be interested in preparing it with a high-level tool such as fwbuilder.

    # apt install fwbuilder

    The principle is simple. At the first stage, describe all the elements that will be involved in the new rules:

    1. the firewall itself with its network interfaces;

    2. networks with appropriate ranges of IP addresses;

    3. servers;

    4. ports belonging to services hosted on servers.

    Then create rules using simple drag and drop objects, as shown in Figure. 7.2. Several context menus can change a condition (for example, deny it). Then you need to select and configure the action.


    As for IPv6, you can either create two different sets of rules for IPv4 and IPv6, or create only one and let fwbuilder translate the rules according to the addresses assigned to the objects.

    The fwbuilder tool will create a script that configures the firewall according to the rules you defined. Its modular architecture allows you to generate scripts designed for different systems, including iptables for Linux, ipf for FreeBSD, and pf for OpenBSD.

    Setting rules on every boot

    To implement firewall rules every time the machine boots, you need to register the configuration script in the up directive of the / etc / network / interfaces file. In the following example, the script is stored in /usr/local/etc/arrakis.fw.

    auto eth0
    iface eth0 inet static
         up /usr/local/etc/arrakis.fw

    This example assumes that you are using the ifupdown package to configure network interfaces. If you are using something else (say, NetworkManager or systemd-networkd), then refer to the appropriate documentation to learn how to run the script after starting the interface.

    7.5. Monitoring and logging

    Confidentiality and data protection are important aspects of security, but it is equally important to ensure the availability of services. As an administrator and security specialist, you must ensure that everything works properly, and your responsibility is to identify abnormal behavior and deterioration in the operation of services in a timely manner. Monitoring and logging software plays a key role in this aspect of security, providing insight into what is happening in the system and in the network.

    In this section, we will look at a number of tools that can be used to monitor several aspects of the Kali system.

    Log monitoring with logcheck

    The logcheck program monitors the log files every hour by default and sends non-standard log messages to e-mail messages to the administrator for further analysis.

    The list of monitored files is stored at /etc/logcheck/logcheck.logfiles. The defaults will work properly if /etc/rsyslog.conf has not been completely rebuilt.

    The logcheck program can report using different levels of detail: paranoid (paranoid), server (server) and workstation (for workstations). The paranoid mode is very verbose and probably should be limited to specific servers, such as firewalls. Server mode is the default and recommended for most servers. The workstation mode is obviously designed for workstations and is extremely compressed, filtering more messages than other "brothers".

    In all three cases, logcheck should probably be configured to exclude additional messages (depending on the installed services), if you do not want to receive hourly batches of long unregistered emails. Since the message selection mechanism is rather complicated, the file /usr/share/doc/logcheck-database/README.logcheck-database.gz is required to be read when difficulties arise.

    The applicable rules can be divided into several types:

    1. those that qualify the message as a hacking attempt (stored in a file in the /etc/logcheck/cracking.d/ directory);

    2. ignored hacking attempts (/etc/logcheck/cracking.ignore.d/);

    3. those that classify the message as a security alert (/etc/logcheck/violations.d/);

    4. Ignored security warnings (/etc/logcheck/violations.ignore.d/);

    5. Finally, those that apply to other messages (considered as system events).

    Ignore.d files are used (obviously) to ignore messages. For example, a message marked as a hacking attempt or a security warning (according to the rule stored in the /etc/logcheck/violations.d/myfile file) can be ignored only by the rule in the /etc/logcheck/violations.ignore.d/myfile file or in the /etc/logcheck/changes.ignore.d/myfile file.

    A system event is always reported, unless the rule in one of the /etc/logcheck/ignore.d directories is, Palparanoid, server, workstation} / does not indicate that this event should be ignored. Of course, only those catalogs are taken into account, whose levels of detail equal to or exceed the selected mode of operation.

    Real-time activity monitoring

    The top interactive tool displays the list of processes currently running. The default sorting is based on the current CPU utilization and can be obtained using the P key. Other indication sorts include sorting by occupied memory (M key), total processor time (T key), and process identifier (N key). The k key terminates the process with the entered identifier. The key r changes the priority of the process.

    When the system seems overloaded, top is a great tool to see which processes compete for CPU time or consume too much memory. So, it is often interesting to check whether the processes that consume resources match the actual services that should be placed on the computer. An unknown process running as www-data should really stand out from the list, and should be explored, since it is most likely an example of software installed and running on the system using a vulnerability in a web application.

    The top tool is very flexible, and its manual contains detailed information on how to customize its interface and adapt it to your personal needs and habits.

    The gnome-system-monitor graphical tool is similar to top and provides roughly the same functions.

    »More information about the book can be found on the publisher's website
    » Table of contents
    » Fragment

    For Habrozhiteley 20% discount on the coupon - Linux

    Also popular now: