Skip to content

Latest commit

 

History

History
2373 lines (1771 loc) · 67.6 KB

LPIC3-303.wiki

File metadata and controls

2373 lines (1771 loc) · 67.6 KB

back

Table of Contents

LPIC-3 303: Security

325.1 X.509 Certificates and Public Key Infrastructures

Cryptography Concepts Part 1

Cryptography Concepts PKI and Trust Chains Creating and working with certificates Operating a Certificate Authority

What is Cryptography? Practice and study of techniques for secure communication in the presence of third parties called adversaries

Computational context Symmetric or assymetric encryption

Protecting data from untrusted third parties Ensure data between parties is authentic

Encryption is how we can pass info across channels without compromising the content or integrity of the data

Uses of Cryptography Data Encryption Cipher to render data unreadable

Data Integrity Make sure what we send is what they receive Make sure it's not tampered or at least alert if it was

Authentication Confirm we are who we say we are

Two primary elements to cryptography Key Used to encrypt data Like a password Must be secret Can be multiple keys in some situations Needs to be kept private

Algorithm Method of encryption Takes plain text data and makes it unreadable to third party Also unencrypts data May be public Need to know how to use key Examples: 3DES, blowfish, AES

A cipher (algorithm) is used to scramble information

Ciphertext may be deciphered (unencrypted) with a key

Two types of encryption Symmetric and Asymmetric encryption

Cryptography Concepts Part 2

Symmetric Encryption: Only one key Both parties must know key Generally faster than asymmetric encryption

Example algorithms: Blowfish, AES

Asymmetric Two keys Encryption is public Decryption key is private

^^ SSH key

Example algorithms: RSA, DSA

Good for digital signatures, key distribution and digital certificates

Data Integrity through hashes Hash converts a string of any length to an output string of fixed length

Each string provides a unique hash

Hashing is generally used one way

A salt may be used to improve security

Add random text to ciphertext to improve security Don't have just hash to crack, need to handle random data as well

Common hashing algorithms, crc-32 (don't use, insecure), md5, sha-1 (most common)

If file is modified md5 sum changes

PKI and Trust Chains

PKI = Public Key Infrastructure

Use ID, Gov't and airline as an example ID to verify who you are to airline Gov't provisioned ID, valid institution

PKI is made up of a hierarcy of Certificate Authorities (CA) and a Certificate Signing Request (CSR) process

Root Trusted Top level CA Client

CA Trusted third party that validates the authenticity of a public key Root trusted CA that signs and vets CA certificates By trusting a CA cert you ctrust all certs signed by that CA

CSR are essentially public keys that are generated and submitted to a CA to be signed When a CA signs a CSR it produces a certificate that is trusted by the signing CA CA can also invalidate a cert if needed by using either OCSP (Online Certificate Status Protocol) or by using a CRL (Certificate Revocation List) CRL almost completely deprecited in favor of OCSP

Request, Sign, and Manage Certificates

Creating and working with certificates

Creating a private key openssl genrsa -ALGORITHM -out KEY KEYSIZE openssl genrsa -aes128 -out mykey.pem 2048

Generating a self-signed cert (public key) openssl req -utf8 -new -key KEY -x509 -days LIFESPAN -out CERT

Display certificate openssl x509 -in CERT -text -noout

Creating a CSR openssl req -new -key PRIVKEY -out CSR

The openssl command creates PEM formatted files by default. Other formats, DER - A binary form of ASCII PEM P7B/PKCS#7 - Base64 encoded ASCII popular in Windows PFX/PKCS#12 - A binary format capable of storing keys, certs and intermediary certs together.

Openssl command can convert between formats. Check x509, rsa, pkcs7 or pkcs12 man pages. Doesn't work with all formats.

Operating a Certificate Authority

Understangind CAs What makes a CA is really a unique key pair

A CA public key is typically signed by another CA that is trusted

Three primary reponsibilities Sign valid CSRs Maintain security of their private key Revoke compromised or misused certificates

Operating a CA Creating a private key openssl genrsa -ALGORITHM -out KEY KEYSIZE openssl genrsa -aes128 -out mykey.key 2048

Generating a self-signed certificate (public key) openssl -utf8 -new -key KEY -x509 -days LIFESPAN -out CERT

Add -set_serial SERIAL for a CA certificate

Signing a CSR as a CA (requires CA keys) openssl ca -in CSR -out CRT

325.2 X.509 Certificates for Encryption, Signing and Authentication

SSL, TLS, and Apache HTTPD Server

SSL, TLS, and common Transport Security Layer Threats Working with Apache's mod_ssl Troubleshooting using openssl

SSL stands for Secure Sockets Layer SSL was the original protocol for securing web traffic Latest version is SSLV3 which is deprecated It should not be used

TLS for Transport Layer Security TLS successor to SSL begginning with TLS 1.0 TLS 1.2 is the current standard TLS 1.3 proposed as new standard

Transport Layer Security TLS and SSL aim to address the issue of secure communication over a public network protocols meet the following needs Securely encrypt exchanged data Authenticate at least one part Ensure data integrity Prevent replay attacks

TLS achieves this through the use of PKI as well as general encryption practice

"Man in the middle" style attacks can be a threat to TLS. Attack third party intercepts and/or alters data between parties Use TLS 1.2 or newer as soon as feasible Encrypt all traffic Each TLS update, vulns like POODLE and BEAST are patched and weak ciphers are deprecated Some security measures do lie with the client (not using bank website on public wifi)

The ssl.conf File: Important Directives and Security Focused Configurations

Working with mod_ssl Secure http traffic with PKI: SSLCertificateFile CERT SSLCertificateKeyFile KEY

Authenticate with a client certificate: SSLVerifyClient require SSLVerifyDepth 1 SSLCACertificateFile CACERT

Configure Cipher usage: SSLCipherSuite HIGH:!aNULL:!MD5

OCSP Stapling: SSLUseSXtapling On SSLStaplingCache "shmcb:logs/ssl_stapling(32768)"

Understanding SNI and HSTS

Apache and mod_ssl Server name Indication (SNI) Only able to bind a cert to a single socket One cert for every IP/port combo

Starting with Apache 2.2.12 and OpenSSL 0.9.8j It's possible to have many certs on the same socket Allows the use of name-based virtual hosts with unique certificates SSLStrictSNIVHostCheck Directive for SNI On or off Non-SNI clients able to use SNI virtualhosts Can cause issues

HTTPS Strict Transport Security (HSTS) HSTS is a way to encourage encryption for an entire domain rather than select parts Special header is sent by teh web server which instructs the browser to direct all traffic over SSL

header always set Strict-Transport-Security "max-age=300; includeSubDomains;preload".

max age important, what tells browser how long to operate When cutting over a legacy website you might need to roll back TTL Want to start with a low number If it goes sideways browser will check on a non-secure port Preload List of known hsts website Tells browser to treat site as a known HSTS website

Using the openssl Command to Work with Certificates and Web Servers

More on openssl Establish a secure connection: openssl s_client -connect HOST

Validate a trust chain: openssl verify -verbose CERT

View Certificate details: openssl x509 -text CERT

Hands-On Lab: Working with OpenSSL and Httpd

Open your terminal application, and run the following command (remember to replace with the public IP you were provided on the lab instructions page): ssh cloud_user@<PUBLIC_IP>

Type yes at the prompt. Enter your cloud_user password at the prompt.

Install mod_ssl on the Host webserver Log in to the webserver host. ssh webserver Escalate privileges to root. sudo su -

Install mod_ssl. yum install -y mod_ssl

Generate and Sign a Private Key Change to the /tls/ directory. cd /etc/pki/tls/

Create a new encrypted private key. openssl genrsa -aes128 -out private/httpdkey.pem

Enter httpd at the next two passphrase prompts. Generate a self-signed certificate using the encrypted private key. openssl req -new -x509 -key private/httpdkey.pem -out certs/httpdcert.pem -days 365

Enter httpd at the passphrase prompt. At the next prompt, enter the following information: Country Name: US State or Province Name: Texas Locality Name: Dallas Organization Name: Example Corp Common Name: shop.example.com Email Address: [email protected]

Configure the Default Apache Virtual Host Edit /etc/httpd/conf.d/ssl.conf. vim /etc/httpd/conf.d/ssl.conf

Type /Virtual to search for the SSH Virtual Host Context section. At the end of the section, add the following on a new line: ServerName shop.example.com:443

Type /SSLCert to search for the Server Certificate section. Locate the line SSLCertificateFile /etc/pki/tls/certs/localhost.crt, and change it to the following: SSLCertificateFile /etc/pki/tls/certs/httpdcert.pem

Locate the line SSLCertificateKeyFile /etc/pki/tls/private/localhost.key, and change it to the following: SSLCertificateKeyFile /etc/pki/tls/private/httpdkey.pem

Press Esc, then type :wq to exit the vim text editor. Restart the Apache httpd server. systemctl restart httpd

Enter httpd at the passphrase prompt. Open port 443 on the OS firewall. firewall-cmd --add-service=https --permanent

Reload the firewall. firewall-cmd --reload

Verify the Configuration

Press Ctrl + D twice to log out of webserver and return to workstation. Verify that the configuration is working properly. openssl s_client -connect shop.example.com:443

Press Ctrl + C to return to the command prompt. Write the s_client output to a file. openssl s_client -connect shop.example.com:443 > /home/cloud_user/httpd_output

List the contents of the file to verify that the certificate information is there. cat /home/cloud_user/httpd_output

325.3 Encrypted Files Systems

Creating Encrypted Volumes

Disk Encryption Concepts File System Encryption with eCryptfs Working with LUKS

Use cases of disk encryption Protect data at rest Protect removable media Add additional data security such as an onboard drive

Methods of disk encryption Block device - LUKS File system level - eCryptfs

Disk encryption tools em-encrypt and luks cryptmount eCryptfs EncFS

Disk Encryption with eCryptfs and EncFS eCryptfs provides file system level encryption Uses ecryptfs package Mount a new directory using the ecryptfs type PAM module provided for automatic mounting options ecryptfs-utils provides helper utilities EncFS is similar but targets non-superusers Allows for creation of encrypted repos by standard users

Demo: Working with LUKS

Working with LUKS Create encrypted volumes cryptsetup luksFormat DEVICE cryptsetup luksOpen DEVICE mapping

mapping can be anything you'd like, it's a name

Luks Keys Example LUKS key dd if=/dev/urandom of=/root/lukskey bs=4096 count=1 cryptsetup luksAddKey DEVICE keyfile

Mount on boot with Crypttab /etc/crypttab mapping DEVICE keyfile filesystemtype (luks)

/etc/fstab

mount -a will not work Must reboot

Hands-On Lab: Disk Encryption with eCryptfs

Install eCryptfs

Run the following command: sudo apt-get install ecryptfs-utils

Type y at the prompt.

Configure /opt/protected as an Encrypted Mount Ensure that the /opt/protected directory exists. ll /opt/

Encrypt the file system. sudo mount -t ecryptfs /opt/protected /opt/protected

Type supersecret! at the passphrase prompt. Press Enter to accept the default options at the next two prompts. Type y to accept the defaults at the next two prompts. Type yes at the next two prompts.

Copy the Contents of /etc/profile.d to /opt/protected Run the following command: sudo cp /etc/profile.d/* /opt/protected/

Verify that the file is readable. cat /opt/protected/apps-bin-path.sh

Re-encrypt /opt/protected and Verify that the Contents of the Directory Are Unreadable Unmount the file system.

sudo umount /opt/protected

Attempt to view the contents of one of the files in /opt/protected. cat /opt/protected/apps-bin-path.sh

325.4 DNS and Cryptography

Working with DNS

Working with DNS Securing DNS with DNSSEC DNS is short for Domain Name System DNS is a hierarchical system used to resolve hostnames Starts with a root server that branches Resolves attempt to lookup hostnames against local forwarders if configured Resolvers will go directly to the root name server which delegates Zones and resource records DNS configurations are made up of zones and resource records (RRs) Consist of a type and a series of labels that make up domains, subdomains, hosts etc.

EDNS proposed Extension for DNS Documented in RFC 2671 Address backwards compatibility for older versions of DNS

BIND is a popular implementation of a DNS server Primary config is /etc/named.conf Objectives on LPIC exam 303 cover securing DNS with BIND in particular

Securing BIND Means of securing DNS TSIGs - a method of digitally signing data provided to a resolver or data sent in a zone transfer. DNS poisoning can occur without TSIGs Running a named server in a chroot jail Restrict access Configuration directives Allow query Recursion Prevent DNS from reaching out to other servers Allow Transfer What DNS servers are allowed to transfer zones

RNDC stands for Remote Name server Daemon Control Allows for remote name server management Remote control for bind Secure with a key Must be secured using a secret key that is shared with the BIND server.

BIND Configuration Directives: allow query recursion allow transfer

DNS utilities dig New version called delv

Securing DNS with DNSSEC

What is DNSSEC? Domain Name System Security Extension DNSSEC guarantees the authenticity of Zone Transfers and RR lookups. Resource Record Security by digitally signing zone files to sensure they have not been altered or spoofed.

Enabling DNSSEC Dnssec-enable and dnssec-validation in named.conf On by default

Must create Zone Singing Keys (ZSKs), Key signing Keys (KSKs) and have your registration publish a Delegations Signer (DS) record for your domain

Zone Signing Keys (ZSK) Signs a particular zone file. Generated using dnssec-keygen. Should be rotated on a monthly interval for optimal security Can be cronned

Key signing keys (KSK) What authenticate your servers' ZSKs Created using dnssec-keygen but with -f KSK parameter

Dnssec-signzone Generated key records are placed in a zone file dnssec-signzone creates a signed zone file for use with BIND.

Chain of Trust KSKs are provided and published by the parent of a child zone This continues all the way to the root dns servers which have their KSK signed in a key signing ceremony

Other commands to understand dnssec-settime - Manages the validity period of a given key dnssec-dsfromkey - Used to generate the DS RR for a given KSK Review the man pages

DO and AD bits Contained in DNS queries and responses. DO stands for DNSSEC OK and indicates taht a client will understand a DNSSEC response. AD stands for Authenticated Data and is set when data returned by a server that is authenticated with DNSSEC

Understanding DANE

DNS-Based Authentication of Named Entities Domain Name System Security Extension DNSSEC guarantees the authenticity of Zone Transfers and RR lookups. Digitally signing zone files to ensure they hve not been altered or spoofed. TLSA record A TLS A record \_port\_.protocol Note the port and protocol designation in the label Fully qualified domain name TLSA Record are not limited to HTTPS, replace with other ports to use with other services

326.1 Host Hardening

Kernel Security Part 1

Kernel Security Securing Grub Disabling unnecessary software Smaller attack surface All running software is a security threat Disabling unused services is a good security practice Use systemctl and chkconfig to disable services

systemctl used to interact with services chkconfig for enabling/disabling services mask maps service to null so it won't start Commonly disabled services atd, avahi-daemon, cups

Limiting resource usage Limit system resources such as threads, open files and memory pam_limits.so module allows operaters to control how much of any one resource a user may access hard/soft links hard links can't be surpassed Use ulimit Most systems have it preloaded ulimit can be used to adjust limits at runtime Persistant limits at /etc/security/limits.conf

Tuning kernel parameters sysctl command mapped to procfs filesystem Kernel parameters set persistently in /etc/sysctl.conf See kernel-docs for additional information

Managing ASLR Address Space Layout Randomization Ensures every time a program loads it loads into a different place in memory

NX Bit CPU feature Prevents execution from protected memory areas Exec-Shield software solution for CPUs that lack feature Still exists very few processors that use it

ICMP security Settings Network security may be enhaqnced through kernel parameter tuning Disabling ICMP is a common security measure net.ipv4.icmp_echo_ignore_all to 1

Kernel Security Part 2

Systectl Review sysctl -a sysctl -ar SEARCH_PATTERN procfs

Setting parameters sysctl -w PARAM=VALUE sysctl -w net.ipv4.icmp_echo_ignore_all=0 echo "sysctl -w net.ipv4.icmp_echo_ignore_all=0" > /etc/sysctl.conf

Persistent changes: /etc/sysctl.conf

/proc/sys

Chroot environments Fake root that is set for a specific user and process Root file system in regular file system Only the essential files necessary for a process to function SFTP and DNS are two common use cases

An unprivileged user/process is unable to access outside a chroot environment Be mindful of hard links

Virtualization Similar but more advanced Containerization is similar in nature Segments resources and processes from each other

Securing Grub

Boot parameters present a security threat: Specific options may allow unauthorized access to a system

Grub is capable of password protection for menu entries Grub 1 was only able to support passwords and not unique user accounts Grub 2 has more robust security

Configuring users in /etc/grub.d/01_users: set superusers="USER" Password USER PASSWORD Password notsuper OTHERPASS

Needs to be in cat section

Configuring menu entries grep menuentry /boot/grub2/grub.cfg in /etc/grub.d/40_custom: menuentry "menu item" --usersnotsuper

unrestricted line Change to --users Only superuser can boot

--users USERNAME,USERNAME Other users can boot

Now only those usernames can edit

Building grub configuration: grub2-mkconfig -o /boot/grub2/grub.cfg

Write to tmp first just in case it doesn't work grub2-mkconfig -o /temp/grub.cfg

Hands-On Lab: Linux Kernel Security

Create a Text File for the Kernel Parameters Create a new text file called investigate.txt. touch /home/cloud_user/investigate.txt

Install the Kernel Documentation Run the following command: sudo yum install kernel-doc

Type y at the prompt.

Find and Document the Value of the randomize_va_space Parameter Open the kernel.txt file of the sysctl documentation. vim /usr/share/doc/kernel-doc-3.10.0/Documentation/sysctl/kernel.txt

Type /random to search the document for entries pertaining to address space randomization. Press Esc, and type :q to exit the vim text editor. Search for the term "randomize_va" using sysctl. sysctl -ar randomize_va

Add the value of the parameter to the investigate.txt file. sysctl -ar randomize_va >> investigate.txt

Find and Document the Values of All ICMP Kernel Parameters Search for the term "ICMP" using sysctl. sysctl -ar icmp

Add the values of the ICMP parameters to the investigate.txt file. sysctl –ar icmp >> investigate.txt

Temporarily Disable ICMP Using a Kernel Parameter Run the following command: sudo sysctl –w net.ipv4.icmp_echo_ignore_all=1

Find and Document the Current Kernel Security Limits View the contents of /etc/security/limits.conf. vim /etc/security/limits.conf

Press Esc, and type :q to exit the vim text editor. Write the contents of /etc/security/limits.conf to investigate.txt. cat /etc/security/limits.conf >> investigate.txt

Locate the current security limits for cloud_user. ulimit -a

Write the output of the ulimit -a command to investigate.txt. ulimit -a >> investigate.txt

Review the contents of the investigate.txt file. vim investigate.txt

326.2 Host Intrustion Detection

Threat Detection

Threat Detection Tools System Auditing with Auditd

Important thing Post-incident tools. Tools only find something after an incident occurs

Tools in question AIDE OpenSCAP Linux Malware Detect Rkhunter Chkrootkit

Important for the test Know commands and options Understand broad concepts Know configuration directives

AIDE Advanced Intrusion Detection Environment aide --init aide --check

Config /etc/aide.conf

Once Aide run and database stored, store database in offline location in case it's tampered with

Note rules and what options are for (p: permissions etc.) Not everything you want watched in the same way

Once rules are defined they can be applied to a filepath

Filepaths can also be set to ignore

Defaults should be okay

Initial command once configuration complete aide --init

Slow, will generate database. Run as root.

Check against database with aide --check

OpenSCAP SCAP Security Content Automation Protocol Community project started by Red Hat

OpenSCAP An implementation of SCAP Vulnerability Assessment Security Compliance Be aware of what it is

Working with Maldet

Linux Malware Detect LMD Maldet

Commands: maldet -a maldet -e systemctl cat maldet

Configuration /usr/local/maldet/conf.maldet /usr/local/maldet/monitor_paths

Uses external signatures to look for threats inotify-tools package Realtime monitoring

Clamav tool Not tested on Can be used with maldet

Note monitor_paths and ignore_paths

scan_clamscan Used to integrate clamscan

quarantine options Option to quarantine file By default only alerts Set to 1 to alert file

Directives to note How to scan, maldet -a /path/to/file

Can use ? as a wildcard

maldet -e to view reports

Monitor mode maldet --monitor Real time monitoring via inotify-tools Performance hit

Help Lists flags

Help is closest to man page

Understanding Rootkits

Rootkit detection Chkrootkit chkrootkit -q

Rkhunter rkhunter -c --cronjob -rwo /var/log/rkhunter/rkhunter.log

/etc/rkhunter.conf

rkhunter --update Cron that

AIDE may also detect rootkits Kernel modules are popular places to hide rootkits

Only run commands as root if you need to

System Auditing in Linux

Auditing vs. Logging Logs vary by system and software Audit runs at the OS level

Auditd Built into RHEL distros Installable on DEB distros

Customizable

Working with Auditd Commands ausearch aureport auditctl

Configuration /etc/audit/auditd.conf /etc/audit/rules.d /etc/audit/audit.rules

Files /var/log/audit.log /etc/pam.d/system-auth

Hands-On Lab: Working with the Audit Log

Create the Audit Rules

Create an audit rule to watch /etc/passwd for reads. sudo auditctl -w /etc/passwd -p w -k userwatch

Create an audit rule to watch /etc/sudoers/ for reads and writes. sudo auditctl -w /etc/sudoers -p rw -k sudowatch

Create an audit rule to watch /sbin/visudo for executions. sudo auditctl -w /sbin/visudo -p x -k sudowatch

Verify that the audit rules were successfully created. sudo auditctl -l

Generate an Audit Rule List in a Text File

Output the contents of the audit rule list to a file called rules.txt. sudo auditctl -l > /home/cloud_user/rules.txt

Generate Logs

Create a new user. sudo useradd bob

Run the visudo command. sudo visudo

Press Esc, and type :q to exit the vim text editor.

Generate the Text File Reports

Generate the userwatch.txt report in /home/cloud_user. sudo ausearch -k userwatch > /home/cloud_user/userwatch.txt

Verify that this was successful. less /home/cloud_user/userwatch.txt

Type q to exit the less screen. Generate the sudowatch.txt report in /home/cloud_user. sudo ausearch -k sudowatch > /home/cloud_user/sudowatch.txt

Verify that this was successful. less /home/cloud_user/sudowatch.txt

326.3 User Management and Authentication

Linux Login Essentials

Linux Login Basics PAM Concepts and Configuration Kerberos Understanding SSSD

/etc/login.defs: Used to be main login configuration Replaced by PAM (Pluggable Authentication Modules)

Still used, MAIL_DIR UID and GID settings UMASK

Typically >500 system users

chage Requires root for most functionality User must be in /etc/shadow Local user

-E yyyy-mm-dd login Set expiration

-I days login Set number of days of inactivity to expire user

-W days login How many days for password expiration

-1 may be used to disable options

NSS Name Service Switch Calls for info from a system database to a back-end service Know contents of /etc/nsswitch.conf

/etc/nsswitch.conf Databases passwd shadow group hosts

Services files sss dns

passwd: files sss /etc/passwd sss User makes an action Checks file If it doesn't find it it'll query sss service Follows order of services listed

hosts: files dns myhostname Check /etc/hosts first then dns

If using something like LDAP most goes through SSSD

PAM Concepts

Pluggable Authentication Module Modules handling unique function for authentication and authorization

Four groups Auth: Used for authentications Account: Deals with account work Password: Work with passwords Session: Interact with user session properties

PAM Configuration: /etc/pam.d/*

Modules: pam_tally2.so pam_cracklib.so

Kerberos Concepts

Kerberos Terms: Key Distribution Center (KDC) Realm Principal Ticket TGT (Ticket Granting Ticket) TGS (Ticket Granting Server)

Important Files: /etc/krb5.conf

Commands: kinit Create Kerberos session kinit [email protected]

klist See service tickets currently active

kdestroy Eliminate current service tickets Useful if ID not required anymore

Everything is a principal

Process 1. Send principal ID and credentials (TGT Request from user to KDC) 2. Lookup and verify Principal (KDC -> Principal DB) 3. Return TGT protected by principal's user key (Principal DB -> User) 4. Store decrypted TGT in cache (User -> Credential Cache) 5. Check TGT from Cache (App -> Cache)

Understanding SSSD

System Security Services Daemon Set of daemons to manage access to remote directories and authentication mechanisms

Key integrations Active Directory FreeIPA LDAP Kerberos Local Domain through SSS NSS pam_sss.so

Configurations /etc/sssd.conf

Utilities sss_useradd sss_userdel sss_usermod sss_groupadd sss_cache sss_obfuscate

They have a man page Work similar to actual commands, just use SSSD backend

man sssd.conf

Set mode on sssd.conf file cp /usr/share/doc/sssd-common-#/sssd-example.con /etc/sssd/sssd.conf

chmod 600 /etc/sssd/sssd.conf

Required for sssd to use file

man pam_sss

Hands-On Lab: Configuring PAM

Install pam_cracklib

Escalate permissions to root. sudo su -

Install the necessary libraries for pam_cracklib. apt-get install libpam-cracklib

Type y at the prompt.

Configure pam_cracklib Install the vim text editor. apt-get install vim

Edit /etc/pam.d/common-password. vim /etc/pam.d/common-password

Locate the password settings within the file. Change the existing pam_cracklib password configuration to the following: password requisite pam_cracklib retry=3 minlen=10

Press Esc, then type :wq to save our changes and exit the vim text editor. Enable and Configure pam_tally2

Edit /etc/pam.d/common-auth. vim /etc/pam.d/common-auth

Create a new line above the default block. Add the following text to create a pam_tally2 configuration: auth required pam_tally2.so deny=2 unlock_time=600

Press Esc, then type :wq to save our changes and exit the vim text editor.

Hands-On Lab: Configuring SSSD

Install SSSD

Escalate privileges to root. sudo su -

Install the necessary SSSD packages. yum install -y sssd sssd-tools

Configure SSSD

Copy the base configuration file from /usr/share/doc/. (Remember to replace with the actual current version number.) sudo cp /usr/share/doc/sssd-common-<CURRENT_VERSION>/sssd-example.conf /etc/sssd/sssd.conf && sudo chmod 0600 /etc/sssd/sssd.conf

Edit the /etc/sssd/sssd.conf file.

vim /etc/sssd/sssd.conf

Under the line "; domains = LDAP", add the following text: domains = LOCAL

[domain/LOCAL] id_provider = local auth_provider = local min_id = 2000

Press Esc, then type :wq to exit the vim text editor. Start the SSSD service. systemctl start sssd

Create and Configure a New User and Group Add the user jsmith. sss_useradd jsmith

Create the sis group. sss_groupadd sis

Add sis as a supplemental group to jsmith. sss_usermod -a sis jsmith

Verify That the New User Does Not Exist in /etc/passwd Search /etc/passwd for jsmith.

grep jsmith /etc/passwd

Verify that the user exists in the sis group. id jsmith

326.4 FreeIPA Installation and Samba Integration

Overview of FreeIPA

FreeIPA is a suite of tools that provide ID and authentication services Samba is a Windows to Linux cross platform tool Not a drop in replacement for Active Directory

Provide user directory via LDAP Provide Kerberos Authentication Maintain a central sudo rule set Keep autofs configurations Hold SELinux user mapping data

The FreeIPA Suite: 389 Directory Server LDAP core piece MIT Kerberos DNS (BIND) NTP Network Time Protocol Dogtag Cert management service

Certmonger daemon monitors certs for impending expiration Refersh soon to be expired certs

ipa-getcert list ipa-getcert request -f /path/to/server.crt -k /path/to/private.key -r

By default certmonger works with the CA configured for the IPA noted in /etc/ipa/default.conf

Prereqs Local DNS configuration IPA server must have a static hostname in /etc/hosts that matches the system hostname and is in the planned DNS domain

Installtion utilty verifies that

Firewall considerations Number of ports that need open:

  • HTTP/S TCP (80,443)
  • Kerberos TCP (88,464) UDP (88,464)
  • DNS UDP 53
  • NTP UDP 123
  • LDAP TCP (389,636)
There is a web interface

Installing and Configuring FreeIPA

Packages ipa-server ipa-server-trust-ad

Commands ipa-server-install Guided

ipa-replica-install

ipa-replica-prepare Create a replica file from an existing server Also guided

ipa-replica-manage ip-adtrust-install Setting up trust connections to an Active Directory Takes Options, also guided

Working with FreeIPA

Packages ipa-client

Commands ipa-client-install ip user-add USER --first FIRSTNAME --last LAST ipa group-add staff --desc "DESCRIPTION" ipa help

Hands-On Lab: Working with FreeIPA

Configure the Host File and Name

Escalate privileges to root. sudo su -

Edit the /etc/hosts file. vim /etc/hosts

Scroll down to a blank line, and add the following: 10.0.1.100 ipa.example.com

Press Esc, then type :wq to exit the vim text editor. Set the host name. hostnamectl set-hostname ipa.example.com

Configure the Base IPA Domain

Create the base IPA domain. ipa-server-install

Press Enter at the next four prompts. Enter your cloud_user password at the next four prompts. Type yes at the prompt. Wait a few minutes for the installation to finish.

Create and Verify a New Session

Create a new session for the admin user. kinit admin

Enter your cloud_user password at the prompt. Verify that this was successful. klist

Create a New User in Directory Services Create the user jsmith with the first name john and last name smith in directory services. ipa user-add jsmith --first john --last smith

327.1 Discretionary Access Control

Basic System Permissions

Basic System Permission - DAC

Discretionary Access Control (DAC) Commands chown chmod

Permissions read/write/execute SUID Allows files to be executed with permission of owner Leading numerical bit 4644 u+x will remove SUID Typically circumvented Not very secure

SGID Also represented by an S, uses a 2 Executed under group chmod g+s

Inherit perms

Sticky Bit Prevents users from deleting files unless they own the file

Extended Attributes

The Concept: xattr if the libattr feature is enabled in the kernel configuration

Regular file may have a list of extended attributes denoted by name

SELinux and ACL use

Xattr namespaces User Trusted Security, set aside for SELinux specifically System, used by kernel

Must be in one of the four Not a lot of use in day to day

Xattr Getting xattrs getfattr -n NAME -m PATTERN

Setting xattrs setfattr -n NAME -v VALUE -x NAME

Using ACLs

Access Control Lists Commands: setfacl -m u:USER:r FILE setfacl -m m::rx FILE getfacl filename

Add rules to ACL list to allow other users to interact with the file Mask sets overarching mask on ACL list Revokes write access from all users/groups

Hands-On Lab: Managing File Attributes and Permissions

Grant Access to the Directory

Change to the opt directory. cd /opt

Next, open all of the directory's files and permissions with the following command: ls -la

Let's try to access the myapp directory. Run the following command: cd myapp/

We get a "Permission denied" message because permissions are currently restricted to the tkirk user. Let's change that now. Enter the following command: sudo chmod 777 myapp

Then, enter your password when prompted.

Reopen the directory files and permissions using the ls -la command. Now let's try to open the directory again. cd myapp

We can now open the directory. Change the Directory Permissions

The next step is to give all users read and write permissions for this directory. However, we also need to make sure no one can execute anything. Let's start by removing execute permissions. Enter the following command: sudo chmod -f -x -R *

Now let's give everyone read and write permissions. Note that this would also remove the execute permissions we did in the previous step, but we wanted to show how to do that explicitly. sudo chmod 666 -f -R *

List the directory files and permissions again. ls -la

We can see that everyone now has read and write permissions.

Note: For users to be able to navigate into directories, the directories must be set as executable. You can do this with: sudo find /opt/myapp -type d -exec chmod o+x {} \;

327.2 Mandatory Access Control

Understanding MAC

MAC Mandatory Access Control SELinux MAC Alternatives

MAC access is based on context and not ownership

Class of objects or users

MAC users roles and type enforcement to allow access to users who are authorized to use resources of a specific type.

Standard Linux perms are checked first Standard perms can override SELinux

MAC is generally implemented by means of a kernel module and through use of extended attributes

MAC Systems SELinux AppArmor Smack

SELinux

SELinux Commands semanage setsebool, getsebool restorecon newrole sealert

Files /etc/selinux/config

Will need to relabel files if SELinux disabled and re-enabled

getenforce Is selinux enforcing?

setenforce 0/1 Enable or disable selinux enforcement

getsebool List booleans

setsebool Set booleans

restorecon Restores default SELinux security contexts

fixfiles Fix file SELinux security contexts

newrole Run a shell with a new SELinux role

Rarely done outside specialized environments

Test without setting

semanage Basic interface to SELinux Run subcommands Most common commands are fcontext and boolean

semanage-fcontext Man page for extra commands like so

Logged in Audit log by default sealert for reading logs sealert -a Analyze a log file

A lot of issues can be fixed with restorecon

audit2allow Generate SELinux makes policy allow/dontaudit rules from logs of denied operations

audit2why, alias for audit2allow -w

AppArmor and Smack: MAC alternatives

AppArmor Less cumbersome that SELinux Assigning types to filepaths rather than inodes Links Two modes: Enforcement and complain Enforce/permissive

aa-genprof and aa-logprof used to craft policies

Not managed with extended attributes

Smack Must be compiled into the kernel Uses extended file attributes for label assignment -Z flag like SELinux Displays attribute information chsmack command may be used to query and set label information

Shell script that works with extended attributes Tizen is the only distribution that implements smack.

Hands-On Lab: Troubleshooting SELinux

Troubleshooting SELinux

Introduction

Mandatory access control (MAC) is an essential element to modern system security. SELinux is a common implementation of MAC that must be well understood by engineers in order to incorporate the most ideal security practices into production systems. This exercise delves into a common occurrence relating to MAC; troubleshooting a system that is experiencing errors as a consequence of SELinux.

The website is down! The primary company web page is not presenting correctly, and the sales team is looking to you to fix it. A new junior security engineer was asking about SELinux and the web server earlier in the day. Checking out the www server's SELinux configuration may be a good place to start looking. Verify the error by attempting to access localhost:80/index.html on the www server and correct any issues.

Summary tasks list:

Verify there is an error by trying to access localhost:80/index.html using curl on the www host and check the audit log using sealert. Direct the output from sealert to /home/cloud_user/seinfo.txt. Examine /home/cloud_user/seinfo.txt to figure out what is wrong and fix the error regarding /var/www/html/index.html. Restart httpd to check for other possible issues and correct any issues you might find. Confirm localhost:80/index.html loads correctly with curl on the www host.

Solution

Start by logging in to the lab server using the credentials provided on the hands-on lab page:

ssh cloud_user@PUBLIC_IP_ADDRESS

Verify there is an error Verify there is an error by trying to access localhost:80/index.html using curl on the www host: curl localhost:80/index.html

Check the audit log using sealert and direct the output from sealert to /home/cloud_user/seinfo.txt: sudo sealert -a /var/log/audit/audit.log > /home/cloud_user/seinfo.txt

Figure out what is wrong and fix the error Reviewing the seinfo.txt file should indicate the context for /var/www/html/index.html is incorrect. sudo less /home/cloud_user/seinfo.txt

At the bottom of the file, we should see the SELinux alert, as well as a suggested way to fix the issue. Fix the issue: sudo /sbin/restorecon -v /var/www/html/index.html

Verify that the issue is resolved: curl localhost:80/index.html

Check for other possible issues and correct any issues you might find Restart httpd to check for other possible issues and correct any issues you might find.

Restart Apache: sudo systemctl restart httpd

Note: httpd should fail to restart.

Based on journalctl --xe (or by re-examining the audit log with sealert), you will see the file context is incorrect on /etc/httpd/conf/httpd.conf.

journalctl -xe

We are looking for the httpd: Could not open configuration file... line. Verify the SELinux context on /etc/httpd/conf/httpd.conf: ls -lZ /etc/httpd/conf/httpd.conf

The user_home_dir_t context is set on this file, which is not correct. Run restorecon to fix the context on httpd.conf: sudo /sbin/restorecon /etc/httpd/conf/httpd.conf

Verify the SELinux context was updated: ls -lZ /etc/httpd/conf/httpd.conf

The context has been correctly set to httpd_config_t.

Restart Apache again and the service should be restored. sudo systemctl start httpd

Confirm the error is resolved Confirm localhost:80/index.html loads correctly with curl on the www host. curl localhost:80/index.html

Conclusion Congratulations, you've completed this hands-on lab!

327.3 Network File Systems

NFSv4 Improvements

Access Security Kerberos Authentication built in Requires use of additional services to run and tap into GSS (Generic Security Services) API GSS API uses LIPKEY and SPKM Public key authentication methods

Pseudo File System Mount exports via parent directory

Port Mapper not required Uses TCP and eliminates the need for port mapper

NFS in Practice

Packages nfs nfs-utils

exports man page sec= Allow for kerberos authentication

root_squash, no_root_squash Map any requests from UID/gid 0 to nobody uid/gid

no_root_squash allows root behaviour

Examples at bottom of man page

nfs-server runs services

Files: /etc/exports /etc/idmapd.conf

man idmapd.conf Conf file for libnfsidmap Bottom of man page has example

Commands: showmount -e

NFS4 ACLs

nfs4_setfacl nfs4_getfacl

nfs4-acl-tools

man nfs4_acl man nfs4_setfacl

CIFS Configuration

Samba Popular software suite designed for inter-operation with Windows smbd and nmbd CIFS maps Windows logins to Linux logins and is part of the Samba suite

Winbind Service that allows CIFS to integrate with an AD domain. Run winbind daemon Integrate with NSS via the windbing service pam_winbind

CIFS Commands getcifsacl setcifsacl mount.cifs

Files /etc/samba/smb.conf

getcifsacl /path/to/mount Prefixes for entries Owner, group etc. Also returns ACL info

man setcifsacl man mount.cifs

Hands-On Lab: Exporting an NFSv4 Volume with ACLs

Configure a New NSF Export

Escalate privileges to root. sudo su -

Edit the /etc/exports file. vim /etc/exports

Add the following line to the file: /nfs/ *(rw,acl,no_root_squash)

Press Esc, then typw :wq to exit the vim text editor. Restart the NFS server. systemctl restart nfs-server

Test the New Export Mount localhost:/nfs to /mnt on the local system. mount -t nfs localhost:/nfs /mnt

Verify that this was successful. mount

Give the User alice Read-Write Access List the contents of the /mnt directory. ll /mnt

Create an ACL on mnt/nsftestfile that gives alice the appropriate permissions. nfs4_setfacl -a A::alice@localdomain:RW /mnt/file

Give the User bob Read and Execute Permissions Create an ACL on mnt/nsftestfile that gives bob the appropriate permissions. nfs4_setfacl -a A::bob@localdomain:RX /mnt/file

Give Everyone Read Access Create an ACL on /mnt/nfstestfile that gives everyone the appropriate permissions. nfs4_setfacl -a A::EVERYONE@:R /mnt/nfstestfile

Verify that all permissions have been configured properly. nfs4_getfacl /mnt/nfstestfile Run id for each user to verify the user IDs in each access control entry.

328.1 Network Hardening

Configuring FreeRADIUS

Freeradius Network utilities Network threats

Packages Freeradius Remote Authentication Dial In User Service Authentication for network nodes

Files /etc/raddb/radiusd.conf /etc/raddb/*

/etc/raddb/clients.conf Network clients Two pieces Name and address client private-network-1 { ipaddr =IP secret =SECRET }

Commands (all have man pages) radmin Key configuration tool Sub command w/ flags

radtest Test connection to server Wrapper around radclient Used to interact with radius server

radwho radlast Analgous to who/last commands but for radius

Analyzing Network Traffic

Wireshark GUI tool that can perform packet captures Provides filtering capability tshark CLI utility Be familiar with filters

tcpdump CLI utility for capturing network traffic Capable of filter Both use pcap library

Commands (Both have man pages) tshark tcpdump

tshark -Y http -Tfields

man pcap-filter dst destination src source dst portrange

Filters: host IP port PORT prtrange PORT-PORT tcp portrange PORT-PORT

Network Utilities and Threats

ndpmon Neighbor Discovery Protocol Monitor Used for monitoring ICMPv6 packets Writes output to syslog

nmap Network Mapper tool Capable of doing various scans against target networks Be careful running nmap against networks you do not own

nmap.scanme.nmap.org

Commands: nmap

options -sS s scan S type of scan TCP Syn/connect() scan

-T# 1-5 Faster scans, less thorough Higher = faster

-sN/-sF/-sX TCP Null, FIN and Xmas scan

Rogue Router Advertisements IPv6 networks where malicious router advertisements may be used to hijack traffic on unsecured networks Can be mitigated by adjusting kernel to not accept router advertisements: /proc/sys/net/ipv6/conf/<interface>/forwarding /proc/sys/net/ipv6/conf/&lt;interface&gt;&lt;/interface&gt&lt;/accept_ra turn&gt;</interface>off on all interfaces

Rouge DHCP Messages Best handled at switch level DHCP traffice should be restricted to solely the switch port running the DHCP server that is trusted. This is done using DHCP snooping

Hands-On Lab: Packet Capture and Analysis

Use a tshark capture filter to collect TCP traffic on port 80.

Use a tshark capture filter to collect TCP traffic on port 80. Store the capture command output in /root/http_out. tshark -f "tcp port 80" -V -R http > http_out

In another SSH session, run curl www.exapmle.com/index.html during the capture. curl www.example.com/index.html Note: curl may produce output but it does not need to be recorded.

Use a tshark display filter to collect HTTP traffic and print only HTTP response codes Use a tshark display filter to collect HTTP traffic and print only HTTP response codes. Store the capture command output in /root/http_response. tshark -Y http -Tfields -e http.response.code > http_resopnse

In a separate SSH session, run curl www.example.com/index.html and then curl www.example.com/error.html during the capture: curl www.example.com/index.html curl www.example.com/error.html Note: curl may produce output but it does not need to be recorded.

Use a tshark capture filter that prints the IP address of hosts sending traffic to the test workstation on TCP port 22. Use a tshark capture filter that prints the IP address of hosts sending traffic to the test workstation on TCP port 22. Observe any IP addresses printed after several seconds. tshark -f "tcp src port 22" -Tfields -e ip.dst

Add the IP address(es) to /root/ssh_ip in a newline-delimited format.

Conclusion Congratulations — you've completed this hands-on lab!

328.2 Network Intrustion Detection

Network Monitoring

Network Monitoring Working with Snort OpenVas and NASL Scanner and test language

Ntop Network traffic probe that provides network usage information

ntop -P /etc/ntop -w4242 -d -P /path/to/config -w What port to run on -d Run in daemon mode

CLI commands and administrating it Reset ntop admin password ntop --set-admin-password=NEWPASSWORD

Cacti Another network monitoring tool Known for graphic functionality More general purpose than ntop

Configure and Use Snort

Packages: snort Packet sniffer Log packets Intrustion prevention

daq

Files: /etc/snort/* snort.conf base configuration Defined variables Home, external, dns

Variables can be referenced using a dollar sign like a BASH variable Ports [80,81,443,]

!inverse Exclude a port or IP

rules/ Where custom rules are defined community-rules Also have a paid rules available

File format NAME.rules Rule header alert tcp $EXTERNAL_NET $FILE_DATA_PORTS -> $HOME_NET any

Note BASH vars from snort.conf

Commands: snort snort-stat

man snort Without parameters snort functions like tcpdump -D daemon mode Actively monitor traffic

snort-stat Removed from newer versions Read syslog Port scan statistics

OpenVAS Overview

OpenVAS and NASL Commands: openvas-mkcert man openvas-mkcert -q make a cert without asking questions -f force overwrite existing cert

openvas-nvt-sync Have to keep vulnerability definitions up to date

Files: /etc/openvas/openvasd.conf Uses certificates Two-way SSL Clients also have to have the cert

Be aware of daemon Keep NVTs up to date

328.3 Packet filtering

Firewall Concepts

Firewall Review Advanced Firewall Concepts Nftables

Firewall Review Files /etc/sysconfig/iptables Where daemon looks by default for rules

Commands: iptables Create, delete and rearrange rules

ip6tables Same but for ipv6

iptables-save Write rules to file Can overwrite /etc/sysconfig/iptables iptables reads for rules

iptables-restore Load in rules

Works with netfilter tables and each table can have a number of chains Chains made up of rules

filter Default table Input, forward and output chains

nat mangle raw security

iptables -t table Defaults to filter

Advanced Firewall Concepts

IP Sets Depending on the type of the set an IP set may store: IP 4 or 6 addresses TCP/UDP port numbers IP and Mac address pairs IP address and port number pairs the ipset command is used to create and work with IP sets netfilter is able to use the IP Sets

IP Sets Files /etc/sysconfig/ipset

Commands ipset create ipset create RULE hash:OPTIONS

ipset add ipset add RULE IP

ipset save ipset list

Won't survive a reboot

Firewall DMZ Provides additional security for a network It is a subnet that is separate from a general LAN May be accessed by an external network Where services and hosts that require a public face are located on a network Typically the internal LAN is firewalled off from external network access

Between your network and the internet at large

Connection Tracking Used so that the firewall may track a connection state conntrackd daemon does the tracking

network address translation Used to load balance service or to translate external to internal addresses Handled by firewalls and/or routers Uses nat tables in iptables and the OUTPUT, PREROUTING and POSTROUTING chains

Network address translation Table nat

Chains OUTPUT PREROUTING POSTROUTING

man iptables-extensions

Ebtables and Nftables

Ebtables Used to insert and filter Ethernet frames Mostly analogous to the iptables command except it works with ethernet frames Default chains: filter broute nat

Specific options to ebtables -Ln List line numbers when printing a rule set -Lc List pack and byte counters with each rule

Nftables Alternative to iptables Simpler interface to netfilter nft command May use iptables rules with nftables Only brief familiarity required for the exam

Hands-On Lab: Working with IP Sets and iptables

Create a New IP Set Called clienthosts

Become root user: sudo su -

Create a new IP set: ipset create clienthosts hash:ip,port

Add IP port combinations: ipset add clienthosts 10.0.1.100,80 ipset add clienthosts 10.0.1.200,80

Save the configuration so it will persist a reboot: ipset save clienthosts > /etc/sysconfig/ipset

Add a new rule to the INPUT chain that accepts traffic from all IP/port combinations as source IP/destination port in the clienthostsIP set. Create a new rule: iptables -I INPUT -m set --match-set clienthosts src,dst -j ACCEPT

Verify the rule: iptables -nvL

We should see the rule at the top.

Save the rule configuration: iptables-save > /etc/sysconfig/iptables

Restart iptables: systemctl restart iptables

Check to make sure the rule persisted the reboot: iptables -nvL

We should still see the rule at the top.

Log in to one of the bootstrap servers on the lab page: ssh cloud_user@

Run the following: curl config-server:80

We should see we're able to curl from config-server.

Conclusion Congratulations on successfully completing this hands-on lab!

328.4 Virtual Private Networks

OpenVPN

OpenVPN Working with IPSec Server and Clients

Files: /etc/openvpn/server.conf

cp /usr/share/doc/openvpn-VERSION/sample/sample-config-files/server.conf /etc/openvpn/

Server and client same package Just use files port 1194

Certs ca, cert and key

Configure the server and bridge

Commands: openvpn --mlock Disable paging by calling POSIX mlockall function Doesn't write key material or tunnel data to disk

openvpn --push OPTION Push a config file back to client for remote execution.

tls-timeout SECONDS packet retransmit timeout

Two services openvpn@server openvpn@client

man openvpn

IPSec Concepts

The Concept IPSec is used to create a peer to peer secure connection Configurations reside /etc/ipsec-tools.conf

Kernel maintains two databases for IPSec: Security Association Database: Security Association (SA) describes how entities will use security services to communicate SAD entries contain the key of each IPSec-SA Security Policy Database: Used to determine if IPSec applies to a given packet Also determines how an IPSec Security Association applies to a packet setkey utility may add, update, dump or flush SAD or SPD entries in the kernel

Notable setkey directives Following are used to manipulate the SAD: add get delete flush Dump

Any directive may be prefaced with spd (spdadd) and will work for the SPD

Racoon and L2TP Racoon is an IKEv1 keyring daemon /etc/racoon/racoon.conf

L2TP is a VPN technology By itself it is insecure Requires ipsec be configured to be secure Must be used over an IPSec link

StrongSwan and OpenVPN are more dominant

Hands-On Lab: Working with OpenVPN (and iptables)

Install and Configure the OpenVPN Server on vpn-server

Become root user: sudo su -

Install OpenVPN: yum install -y openvpn

Copy the server config: cp /usr/share/doc/openvpn-2.4.7/sample/sample-config-files/server.conf /etc/openvpn/

Open the server config file: vim /etc/openvpn/server.conf

Edit the file to contain the following topology configuration (you can do so by un-commenting the line): topology subnet

Save and quit the file.

Install the Provided Server Certificates Run: cp /home/cloud_user/certs/ca.crt /home/cloud_user/certs/server.crt /home/cloud_user/certs/server.key /etc/openvpn

Generate the Required Server Keys Generate the dhparam key (this may take a few minutes): openssl dhparam -out /etc/openvpn/dh2048.pem 2048

Generate the key for tls-auth: openvpn --genkey --secret /etc/openvpn/ta.key

Copy it to client: ``` scp /etc/openvpn/ta.key cloud_user@vpn-client:/home/cloud_user/ta.key ```

Make the Necessary Firewall and Routing Configurations for OpenVPN on vpn-server Open the UDP 1194 port: iptables -I INPUT -p udp --dport 1194 -j ACCEPT

Create a network address translation rule: iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

Enable IPv4 IP forwarding: sysctl -w net.ipv4.ip_forward=1

Save the iptables rules: iptables-save > /etc/sysconfig/iptables

Enable and Start the OpenVPN Server Enable the server: systemctl enable openvpn@server

Start the server: systemctl start openvpn@server

Log out of root: logout

Change to the certs directory: cd certs Copy the certificates over from the home/cloud_user directory that the client will need for VPN configuration: scp ca.crt vpn-client:/home/cloud_user/ scp client.crt vpn-client:/home/cloud_user/ scp client.key vpn-client:/home/cloud_user/

Install and Configure the OpenVPN Client on vpn-client Log in as vpn-client: ssh vpn-client

Escalate to root: sudo su -

Install OpenVPN: yum install y openvpn

Copy the client.conf file from /usr/share/doc: cp /usr/share/doc/openvpn-2.4.7/sample/sample-config-files/client.conf /etc/openvpn/

Open the file: vim /etc/openvpn/client.conf

Update the remote command hostname directive as follows: remote vpn-server 1194

Save and quit the file.

Install the Provided Client and ca-certificates on vpn-client Copy the provided certificates off of vpn-server and to the noted directories on vpn-client: cp /home/cloud_user/ca.crt /etc/openvpn/ cp /home/cloud_user/client.key /etc/openvpn/ cp /home/cloud_user/client.crt /etc/openvpn/ Install the tls Key from vpn-server on vpn-client

Run the following: cp /home/cloud_user/ta.key /etc/openvpn/

Enable and Start the OpenVPN Client

Enable the client: systemctl enable openvpn@client

Start the client: systemctl start openvpn@client

Conclusion Congratulations on successfully completing this hands-on lab!

335: Threats and Vulnerability Assessment

The following is from Omidznlp's review of the LPIC 3: https://github.com/Omidznlp/LPIC-3-Exam-Topics-303-300-Security/tree/master

Common Security Vulnerabilities and Threats

Threats against individual nodes: Malware infections: Malware is a type of software designed to cause harm to a computer system. It can infect individual nodes, such as laptops or servers, and spread to other systems within a network.

Physical theft or tampering: Physical threats to individual nodes can include theft or tampering, which can compromise the confidentiality and integrity of sensitive data stored on the device.

Unauthorized access: Unauthorized access to individual nodes can occur through hacking or exploitation of vulnerabilities, leading to unauthorized data access or theft.

Outdated software vulnerabilities: Outdated software can contain known vulnerabilities that are easy targets for attackers.

Threats against networks: DDoS attacks: A Distributed Denial of Service (DDoS) attack is a type of attack that floods a network with traffic, overwhelming its resources and making it unavailable. Man-in-the-middle attacks: A man-in-the-middle (MitM) attack is a type of cyber attack where an attacker intercepts and alters communications between two parties, often without either party being aware. Rogue devices/attacks from inside the network: Rogue devices and attacks from within a network can be a major threat, as insiders may have access to sensitive data and systems. Unsecured network protocols: Unsecured network protocols can be vulnerable to exploitation by attackers, leading to data theft or unauthorized access.

Threats against applications: SQL injections: SQL injection is a type of attack where an attacker inserts malicious code into a web application's SQL statement, allowing them to gain unauthorized access to sensitive data stored in a database. Cross-site scripting (XSS): Cross-site scripting (XSS) is a type of attack that allows an attacker to inject malicious code into a web application, which can then be executed by unsuspecting users. Remote code execution: Remote code execution is a type of vulnerability that allows an attacker to execute code on a target system, often with the same privileges as the user running the vulnerable application. Improper authentication and authorization: Improper authentication and authorization can lead to unauthorized access to sensitive data and systems, as well as data theft.

Threats against credentials and confidentiality: Phishing attacks: Phishing is a type of social engineering attack where an attacker pretends to be a trusted entity in order to trick a user into revealing sensitive information, such as login credentials. Social engineering: Social engineering is the use of psychological manipulation to trick individuals into divulging sensitive information or performing actions that compromise their security. Password cracking: Password cracking is the process of attempting to guess or uncover a password, often using automated tools or exploiting vulnerabilities in password storage systems. Unsecured data storage: Unsecured data storage refers to the failure to properly secure sensitive data, such as through encryption or proper access controls, leaving it vulnerable to theft or unauthorized access. Honeypots: Decoy systems to distract attackers: A honeypot is a decoy system designed to distract and divert attackers away from more valuable systems and data.

Collect information on attacker behavior and tools: Honeypots can be used to collect information on attacker behavior and tools, providing valuable intelligence for security teams. Help identify and mitigate emerging threats: By monitoring attacker behavior, honeypots can help identify and mitigate emerging threats, improving overall security posture. Monitor and detect unauthorized access attempts: Honeypots can also be used to detect unauthorized access attempts, providing early warning of security incidents and helping to prevent more serious breaches.

The following is a partial list of the used files, terms and utilities: Trojans: A Trojan is a type of malicious software that is disguised as a legitimate program. Trojans can be used to perform a variety of malicious activities, such as stealing sensitive information, installing other malicious software, or giving an attacker remote access to the infected system. Viruses: A virus is a type of malicious software that replicates itself by infecting other files on a computer. Viruses can cause damage to files and systems, or use the infected computer as a platform for further attacks. Rootkits: A rootkit is a type of malicious software that is designed to hide its presence and actions on an infected system. Rootkits can be used to gain persistent access to a system, bypass security measures, or steal sensitive information. Keylogger: A keylogger is a type of malicious software or hardware device that records every keystroke made on a computer or device. Keyloggers are often used to steal passwords, credit card numbers, and other sensitive information. DoS and DDoS: A Denial of Service (DoS) attack is an attempt to make a network resource unavailable to its intended users. A Distributed Denial of Service (DDoS) attack is a type of DoS attack that involves multiple devices attacking a single target. DoS and DDoS attacks can be used to disrupt online services, websites, and other networked systems. Man-in-the-Middle: A man-in-the-middle (MitM) attack is a type of security attack where the attacker intercepts and alters the communication between two parties. MitM attacks can be used to steal sensitive information, alter data, or perform other malicious activities. ARP and NDP Forgery: Address Resolution Protocol (ARP) and Neighbor Discovery Protocol (NDP) forgery are types of security attacks that involve falsifying ARP or NDP packets in a network. These attacks can be used to redirect network traffic, steal sensitive information, or perform other malicious activities. Rogue Access Points, Routers, and DHCP Servers: Rogue access points, routers, and DHCP servers are unauthorized network devices that are placed on a network without the knowledge or consent of network administrators. These devices can be used to perform various malicious activities, such as intercepting network traffic, redirecting network traffic, or stealing sensitive information.

Penetration Testing

Penetration testing, also known as ethical hacking, is a simulated attack on a computer system or network to identify vulnerabilities and assess the security posture of the target. It is performed by ethical hackers who use the same tools and techniques as malicious hackers, but with the permission of the target organization. The legal implications of penetration testing vary by jurisdiction and must be considered before conducting a test. In some countries, unauthorized access to computer systems is illegal, and penetration testers must have written permission from the target organization to perform the test. Penetration testing is a method of evaluating the security of a computer system or network by simulating an attack. It involves several phases that help to identify vulnerabilities and evaluate the effectiveness of security measures.

Here's an overview of the phases of a penetration test: Active and passive information gathering: This phase involves collecting information about the target system or network, both passively (without interacting with the target) and actively (by interacting with the target). Passive information-gathering techniques include researching public information about the target, while active techniques include using tools like Nmap to scan the target network.

Enumeration: This phase involves actively interacting with the target to gather information about its systems, services, and users. This information can be used to identify potential vulnerabilities and attack vectors.

Gaining access: This phase involves attempting to exploit vulnerabilities and gain access to the target system or network. This can involve techniques like brute force attacks, exploiting software vulnerabilities, or social engineering attacks.

Privilege escalation: This phase involves increasing the level of access or control on the target system once access has been gained. This can be done by exploiting vulnerabilities in the operating system or applications, or by compromising additional systems or user accounts.

Access maintenance: This phase involves maintaining access to the target system, including covering tracks to conceal the presence of the attacker and creating backdoors to allow future access.

Covering tracks: This phase involves removing the evidence of the attack, such as log files or configuration changes, and cleaning up any malware or other malicious software that may have been installed during the attack.

These phases are not always performed in a strict order, and the focus and scope of a penetration test can vary depending on the specific requirements and objectives of the test. However, they provide a general framework for conducting a penetration test and evaluating the security of a computer system or network.

Metasploit is a popular framework for security testing that includes a collection of modules for various purposes. These modules can be divided into three main categories: exploits, payloads, and auxiliary modules.

Exploits: Exploits are modules that take advantage of vulnerabilities in software or systems to gain unauthorized access or control. Exploits are typically used to deliver payloads to target systems.

Payloads: Payloads are modules that are executed on the target system once an exploit has been successful. Payloads can perform a variety of actions, such as capturing keystrokes, stealing data, or establishing a reverse shell connection back to the attacker.

Auxiliary modules: Auxiliary modules are modules that perform a variety of other functions, such as reconnaissance, network scanning, and vulnerability analysis. Auxiliary modules can be used to gather information about a target system or network, identify potential vulnerabilities, and assist in the execution of exploits and payloads. Each of these types of modules has a specific purpose and can be used together to achieve different objectives during a penetration test. The Metasploit framework provides a flexible and modular platform for security testing that can be customized to meet specific needs.

Nmap is a tool used for network exploration and security auditing. It allows users to scan networks and hosts to identify open ports, operating systems, and running services. Nmap supports different scan methods, including version scans and operating system recognition, and also has a scripting engine that allows users to automate and customize their scans. Here are some of the most important Nmap scans and the corresponding commands: Ping scan (-sP): This scan is used to determine if a host is up and responding. It sends a simple ping request to the target host and reports if it received a response. Command: nmap -sP <target_host></target_host>

Port scan (-p): This scan is used to identify open ports on a target host. It sends packets to the specified ports and analyzes the response to determine if the port is open, closed, or filtered. Command: nmap -p <port_range></port_range> <target_host></target_host>

Version scan (-sV): This scan is used to determine the version of services running on a target host's open ports. It sends requests to the open ports and analyzes the responses to determine the software and version being used. Command: nmap -sV <target_host></target_host>

OS scan (-O): This scan is used to determine the operating system running on a target host. It analyzes the responses from the target host to determine the operating system type and version. Command: nmap -O <target_host></target_host>

Stealth scan (-sS): This scan is a type of port scan that is designed to be less detectable. It uses a technique called half-open scanning, where only a single packet is sent to the target host to determine if the port is open. Command: nmap -sS <target_host></target_host>

TCP scan: A TCP scan is used to determine if a target host's TCP ports are open, closed, or filtered. It sends packets to the target host's TCP ports and analyzes the responses to determine the status of the port. Command: nmap -sT <target_host></target_host>

UDP scan: A UDP scan is used to determine if a target host's UDP ports are open, closed, or filtered. It sends packets to the target host's UDP ports and analyzes the responses to determine the status of the port. Command: nmap -sU <target_host></target_host>

It is important to note that UDP scans are typically slower than TCP scans because the UDP protocol does not provide the same level of reliability as TCP. As a result, UDP scans may not receive a response from all target hosts, and false negatives can occur. However, UDP scans are useful for identifying open UDP ports, which can sometimes be overlooked during a TCP scan.

Kali Linux is a widely used distribution of Linux designed specifically for security testing and ethical hacking. It comes pre-installed with a variety of tools, including Nmap, Metasploit, and Armitage, a graphical interface for Metasploit. The Social Engineer Toolkit (SET) is another tool that can be used for penetration testing and is focused on exploiting human vulnerabilities through social engineering techniques.