42born2beroot Guide
Starting Virtual Machine Up:
- Install software (Debian, VirtualBox etc)
- Once installed, open VB and create a new VM by clicking 'new'
- Follow the steps.
- Once done, select the VM you just created and click 'Start'.
- Onces started, use your arrow keys and select 'Install' (once hover over it, click 'Enter')
- Go through the installation procedure.
- Log into it via passphrase and login details you created when setting up
- Type
lsblk
in your Virtual Machine to see the partition
Configuring your Virtual Machine:
- Go to the root directory using
su -
and login - Install Sudo
apt install sudo
"Apt" is a command-line package manager used in Debian-based Linux systems. It is short for "Advanced Package Tool" and is used to install, upgrade, and remove software packages on the system
- Add a group called
user42
usinggroupadd
- Add the user to the newly created group (adds user to 2 groups)
usermod -aG user42,sudo cwenz
a = append user to group
g = the group to which the user gets added to
To remove a user from a group: `deluser ${user} ${group}
- To view if the user was added:
getent group user42
- Install
Git
usingapt-get install git -y
The
-y
tag means that you agree to all prompts that you would normally have to manually agree to
You should see a version number if its installed correctly by using:git --version
- Install SSH via
sudo apt install openssh-server
Check to see if it installed correctly:
systemctl status ssh
- Change the port to
4242
(remember to remove#
) and#PermitRootLogin
tono
insshd_config
file via the commandvim /etc/ssh/sshd_config
Once in VIM, press 'i' to go into 'insert mode'
To exit 'Insest mode' press 'ESC' and to save and quit:wq
Typesudo grep Port /etc/ssh/sshd_config
to check if the port settings are correct, it should bePort 4242
- Restart the ssh server via
systemctl restart ssh
Check the status via
systemctl ssh status
- Now you can connect your own PC's terminal to the VM. Run
ssh username@127.0.0.1 -p 4242
If you get any errors, try:
rm ~/.ssh/known_hosts
and try again
- Run
exit
to close your connection - Edit the file via
vim /etc/security/pwquality.conf
according to the subject - Include the following at the file
vim /etc/pam.d/common-password
:
# Words are spaces with tabs
password requisite pam_pwquality.so
The above takes the changes atpwquality.conf
and applies it to the password policy
- Edit the file
vim /etc/login.defs
with the following as per instructions:
PASS_MAX_DAYS 30
PASS_MIN_DAYS 2
PASS_WARN_AGE 7
- Reboot for the changes to take effect:
sudo reboot
- this change only takes effect for newly created users. You will have to manually change it for the existing user via:
# -m for PASS_MIN_DAYS -M for PASS_MAX_DAYS and -W for PASS_WARN_AGE chage -m 2 -M 30 -W 7 user42
chage -m 2 -M 30 -W 7 root
# Check if rules have been applied.
chage -l user42
chage -l root
Groups
to view all users:
cut -d: -f1 /etc/passwd
To add a new user:sudo adduser new_username
To view which groups your user is part of:groups
Configure Sudo Policy
- Run
visudo
- Add the following:
# Clears out any variables that the user may have set in the terminal environment to start fresh
Defaults env_reset
# Sends a mail of bad sudo password attempts
Defaults mail_badpass
# Secure paths for the sudo user
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/bin:/sbin:/bin:/snap/bin"
# Message when entering a wrong password
Defaults badpass_message="Incorrect password"
# Max number of password attempts
Defaults passwd_tries=3
# Defining a to store sudo commands
Defaults logfile="/var/log/sudo/sudo.log"
# Define that input and output should be locked
Defaults log_input, log_output
# Requires the user to be logged into a terminal to run the sudo command
Defaults requiretty
# User privilege specifications (add your user)
username ALL=(ALL:ALL) ALL
Crontab and Monitoring script Configuation
Crontab is used to automate repetitive tasks, such as system backups, log rotation, and software updates, without requiring manual intervention
- Install net-tools
apt-get install -y net-tools
- Then navigate to
/usr/local/bin/
- Create your script file
touch monitoring.sh
You can check with
ls
if it created the file
- Give the file the correct executables:
chmod 777 monitoring.sh
The command gives full permissions to the owner, group, and other users, allowing them to read, write, and execute the "monitoring.sh" file
- Open the script file via
vim
ornano
- Add the following:
#!/bin/bash
# Get the system arhitecture an kernal version
ak=$(uname -a)
# Get number of physical processors
pcpu=$(grep "physical id" /proc/cpuinfo | uniq | wc -l)
# Get the numbr of virtual processors
vcpu=$(nproc --all)
# Get the curent RAM on server and its utilization rate as a percentage
tram=$(free -m | awk '$1 == "Mem:" {print $2}')
uram=$(free -m | awk '$1 == "Mem:" {print $3}')
pram=$(free | awk '$1 == "Mem:" {printf("%.2f"), $3/$2*100}')
# Get current avaliable memory on server an its utilization as a percentage
tdisk=$(df -BM | grep '^/dev/' | grep -v '/boot$' | awk '{total += $2} END {print total}')
udisk=$(df -BM | grep '^/dev/' | grep -v '/boot$' | awk '{used += $3} END {print used}')
pdisk=$(df -BM | grep '^/dev/' | grep -v '/boot$' | awk '{total += $2} {used += $3} END {printf("%d"),used/total*100}')
# Get current utilization rate of processors as percentage
cpu_per=$(vmstat 1 2 | awk 'NR == 4 {print 100 - $15}')
# Get the date/time of last reboot
lrb=$(who -b | awk '{print $3, $4}')
# Determine whether or not the LVM is active
lvm=$(if [ $(lblk | grep "lvm" | wc -l) eq 0 ]; then echo no; else echo yes; fi)
# Get the number of active connections (TCP)
tcp=$(netstat -an | grep "ESTABLISHED" | wc -l)
# Get the number of users using the server
users=$(users | tr ' ' '\n' | sort | uniq | wc -l)
# Get the IPv4 and MAC address
ipv4=$(hostname -I)
mac=$(ip link show | grep "ether" | awk '{print $2}')
# Get the number of commands executed with the sudo program
scmd=$(journalctl _COMM=sudo | grep "COMMAND" | wc -l)
wall " #Architecture: ${ak}
#CPU physical: ${pcpu}
#vCPU: ${vcpu}
#Memory Usage: ${uram}/${tram}MB (${pram}%)
#Disk Usage: ${udisk}/${tdisk}MB (${pdisk}%)
#CPU load: ${cpu_per}
#Last boot: ${lrb}
#LVM use: ${lvm}
#Connections TCP: ${tcp}
#User log: ${users}
#Network: IP ${ipv4} ${mac}
#Sudo: ${scmd}
"
Explanations:
General commands:
grep
is used to search for a specified pattern or regular expression in a file or set of filesawk
reads each line of the input file(s) and applies the specified pattern and action(s) to each line that matches the pattern.
Basic sytax is:awk 'pattern' { action }' file
1. Get the system architecture and kernal version
ak=$(uname -a)
uname
Used to print system information about the current operating system-a
Is used to display all information
2. Get number of physical processors
pcpu=$(grep "physical id" /proc/cpuinfo | sort | uniq | wc -l)
- Contains information about the system's CPUs. The
uniq
filters out any possible duplicates.
3. Get the numbr of virtual processors
vcpu=$(nproc --all)
Outputs the number of available processing units to the standard output
4. Get the curent RAM on server andd its utilization rate as a percentage
tram=$(free -m | awk '$1 == "Mem:" {print $2}')
uram=$(free -m | awk '$1 == "Mem:" {print $3}')
pram=$(free | awk '$1 == "Mem:" {printf("%.2f"), $3/$2*100}')
1.
free -m
: the free command is used to display information about the memory usage on the system, including the total amount of memory available, used, and free. The -m option is used to display the memory usage in megabytes.
2.awk '$1 == "Mem:" {print $2}'
: the output offree -m
is piped to theawk
command, which is used to search for the line that starts with the string "Mem:" and print the second field
3.awk '$1 == "Mem:" {printf("%.2f"), $3/$2*100}'
: The output offree
is piped to theawk
command, which is used to search for the line that starts with the string "Mem:" and print the percentage of memory used. This is calculated by dividing the third field (memory used) by the second field (total memory), multiplying the result by 100, and formatting it to two decimal places using the printf function.
5. Get current avaliable memory on server an its utilization as a percentage
tdisk=$(df -BM | grep '^/dev/' | grep -v '/boot$' | awk '{total += $2} END {print total}')
udisk=$(df -BM | grep '^/dev/' | grep -v '/boot$' | awk '{used += $3} END {print used}')
tdisk=$(df -BM | grep '^/dev/' | grep -v '/boot$' | awk '{total += $2} {used += $3} END {printf("%d"),used/total*100}')
6. Get current utilization rate of processors as percentage
cpu_per=$(vmstat 1 2 | awk 'NR == 4 {print 100 - $15}')
vmstat 1 2
: Display system statistics. The 1 argument specifies the interval in seconds between each output, and the 2 argument specifies the number of times to display the outputNR == 4
: This is a condition that tells awk to only process the fourth line of the vmstat output, which contains information about CPU utilization.
7. Get the date/time of last reboot
lrb=$(who -b | awk '{print $3, $4}')
who -b
: the who command is used to display information about the currently logged in users on the system. The-b
option is used to display information about the system boot timeawk '{print $3, $4}'
: the output of who-b
is piped to theawk
command, which is used to print the third and fourth fields of the output. These fields represent the date and time of the system boot
8.Determine whether or not the LVM is active
lvm=$(if [ $(lblk | grep "lvm" | wc -l) eq 0 ]; then echo no; else echo yes; fi)
lsblk
: the lsblk command is used to display information about the block devices on the system, including disks and partitionsgrep "lvm"
: the output of lsblk is piped to the grep command, which is used to search for lines containing the string "lvm". If LVM is active on the system, there will be one or more lines containing this stringwc -l
: the output of grep is piped to the wc command with the-l
option, which counts the number of lines in the output. If LVM is active on the system, there will be one or more lines containing the string "lvm", resulting in a non-zero line countif [ $(lblk | grep "lvm" | wc -l) eq 0 ]; then echo no; else echo yes; fi
: this is an if statement that checks whether the line count from the previous command is equal to zero. If the line count is zero, then LVM is not active on the system, and the script echoes "no" using the echo command. If the line count is non-zero, then LVM is active on the system, and the script echoes "yes" using the echo command.
9. Get the number of active connections (TCP)
tcp=$(netstat -an | grep "ESTABLISHED" | wc -l)
netstat -an
: This part of the command uses the netstat utility to display network statistics. The -a option specifies that all connections should be displayed, and the -n option specifies that numeric addresses should be used instead of hostname resolution
10. Get the number of users using the server
users=$(users | tr ' ' '\n' | sort | uniq | wc -l)
users
: Display a list of users currently logged in to the system
11. Get the IPv4 and MAC address
ipv4=$(hostname -I)
mac=$(ip link show | grep "ether" | awk '{print $2}')
ipv4=$(hostname -I)
: thehostname
command is used to retrieve the hostname of the system, and the -I option is used to retrieve the IP address(es) assigned to the system's network interfacesmac=$(ip link show | grep "ether" | awk '{print $2}')
: theip
command is used to display information about the network interfaces on the system, including their MAC addresses. Thelink show
subcommand is used to show the link-layer information for all interfaces, and the output is piped to thegrep
command to filter out all lines except those containing the string "ether". The resulting output is then piped to theawk
command, which is used to print the second field of each line
12. Get the number of commands executed by the sudo program
scmd=$(journalctl _COMM=sudo | grep "COMMAND" | wc -l)
journalctl _COMM=sudo
: thejournalctl
command is used to query the system journal for logs. The_COMM
option is used to filter the logs by the specified process name, which in this case is "sudo"grep "COMMAND"
: the output of journalctl is piped to thegrep
command, which is used to filter the output to only display logs containing the string "COMMAND"wc -l
: the output of grep is piped to the wc command with the-l
option, which counts the number of lines in the output
Crontab setup
- Exit out your iTerm and go back to your virutal machine (if not already)
- Type
sudo visudo
to open your sudoers file - Add in this line
your_username ALL=(ALL) NOPASSWD: /usr/local/bin/monitoring.sh
under where its written%sudo ALL=(ALL:ALL) ALL
- Save and exit
- Reboot sudo with
sudo reboot
- Run
sudo /usr/local/bin/monitoring.sh
to execute your script - Type
sudo crontab -u root -e
to open the crontab and add the rule*/10 * * * * /usr/local/bin/monitoring.sh
at the bottom of the file
The above rule means that the script will run every 10 minutes
crontab takes 5 inputs:minutes, hour, day (month), month, and day (week)
Signiture file setup
- Open iTerm and navigate to where you saved your VM
- Once your in the correct directory type
shasum {name}.vdi
Replace
name
with whatever you named your VM
- Copy the output number and create a signature.txt file and paste that number in the file.
- Push that file to the repo.
Evaluation
Why did I choose Debian?
Easier to install and setup. PDF reccommended it
Difference Debian and CentOS
- Package Management: Rocky Linux uses the
dnf
package manager, which is a newer package management tool that is compatible with the RHEL and Fedora distributions. Debian, on the other hand, uses theapt
package manager, which is a well-established tool that has been used by Debian and its derivatives for many years. - Default Configuration: Rocky Linux is configured with a minimal set of packages, which makes it more suitable for server installations. Debian, on the other hand, includes a more complete set of packages by default, which makes it more suitable for desktop installations.
What is a Virtual Machine?
Computer in a computer essentially. Its a resource that uses software instead of a physically computer to run programs. Works by the VM borrowing resources from the main PC. You can use a VM to test applications/software in a safe environment as it wont affect your main PC.
What is the difference between aptitude and APT (Advanced Packaging Tool)?
- Aptitude is a high-level package manager while APT is lower level which can be used by other higher level package managers Aptitude is smarter and will automatically remove unused packages or suggest installation of dependent packages
- Apt will only do explicitly what it is told to do in the command line
What is AppArmor?
Linux security system that provides Mandatory Access Control (MAC) security. Allows the system admin to restrict the actions that processes can perform. It is included by default with Debian. Run aa-status to check if it is running.
Password Rules
For the password rules, we use the password quality checking library and there are two files the common-password
file which sets the rules like upper and lower case characters, duplicate characters, digits etc.. and the login.defs
file which stores the password expiration rules (30 days etc). Sudo nano /etc/login.defs
Sudo nano /etc/pam.d/common-password
What is LVM
- Logical Volume Manager – allows us to easily manipulate the partitions or logical volume on a storage device.
- Partition is a logical section of a hard disk drive or other storage device that is created to store data.
- A logical volume, on the other hand, is a virtualized partition that is created from one or more physical partitions or disks.
UFW (Uncomplicated Firewall)
UFW is a interface to modify the firewall of the device without compromising security. You use it to configure which ports to allow/close connections. This is useful in conjunction with SSH, can set a specific port for it to work with.
What is SSH?
SSH (Secure Shell) is a secure method of communication between a client and a host that encrypts all communication to ensure data is transmitted securely.
What is Cron?
Cron or cron job is a command line utility to schedule commands or scripts to happen at specific intervals or a specific time each day. Useful if you want to set your server to restart at a specific time each day.
cd /usr/local/bin
– to showmonitoring.sh
sudo crontab -u root -e
– to edit the cron job
change script to*/1 * * * * sleep 30s && script path
– to run it every 30 seconds, delete the line to stop the job from running.
Evaluation Commands for UFW, Group, Host, lsblk and SSH
sudo ufw status
- Get firewall statussudo systemctl status ssh
- Used to check if ssh is running, any errors/warnings and info about servicegetent group sudo
- Gets the groupsudo
getent group user42
sudo adduser new username
sudo groupadd groupname
sudo usermod -aG groupname username
- Adds a user to a groupsudo chage -l username
- check password expire ruleshostnamectl
- view hostnamehostnamectl set-hostname new_hostname
- to change the current hostname- Restart your Virtual Machine.
sudo nano /etc/hosts
- change current hostname to new hostnamelsblk
to display the partitionsdpkg -l | grep sudo
– to show that sudo is installedsudo ufw status numbered
sudo ufw allow port-id
sudo ufw delete rule number
ssh user@127.0.0.1 -p 4242
- do this in terminal to show that SSH to port 4242 is working- Password configurtion:
/etc/pam.d/common-password
and/etc/login.defs
. - SSH configuration:
/etc/ssh/sshd_config
/var/log/sudo/
To find the sudo.log file