Unit5 - Subjective Questions
CSC202 • Practice Questions with Detailed Answers
Explain the concept of Firewalld in Linux and describe the significance of 'Zones'.
Firewalld is a dynamic firewall manager for Linux systems that provides a dynamically managed firewall with support for network/firewall zones to define the trust level of network connections or interfaces.
Significance of Zones:
- Definition: Zones represent the trust level of the interface used for a connection. Each zone has its own set of rules.
- Common Zones:
- Drop: Any incoming network packets are dropped, there is no reply. Only outgoing network connections are possible.
- Block: Incoming network connections are rejected with an
icmp-host-prohibitedmessage. - Public: For use in public areas. You do not trust the other computers on the network, but selected incoming connections are accepted.
- Work/Home: For use in work or home areas where you mostly trust the other computers.
- Trusted: All network connections are accepted.
- Management: Administrators can assign network interfaces to specific zones using
firewall-cmd.
List and explain five key steps to harden a Linux system to enhance security.
Hardening a Linux system involves reducing the surface of vulnerability. Key steps include:
- User Management: Enforce strong password policies, disable the root login via SSH, and use
sudofor administrative tasks to ensure accountability. - Minimize Software Footprint: Install only necessary packages. The fewer services running, the fewer attack vectors available. Remove or disable unused services.
- SSH Hardening: Configure
/etc/ssh/sshd_configto change the default port (22), disable password authentication (enforce key-based auth), and restrict specific users (AllowUsers). - Firewall Configuration: Configure a firewall (like
iptables,ufw, orfirewalld) to deny all incoming traffic by default and only allow specific ports/services required for operation. - Keep System Updated: Regularly apply security patches and updates using the package manager (
yum updateorapt upgrade) to fix known vulnerabilities.
Define SELinux and explain its three modes of operation.
SELinux (Security-Enhanced Linux) is a mandatory access control (MAC) security architecture for Linux. It provides a mechanism for supporting access control security policies, restricting users and programs to the minimum privileges required.
Modes of Operation:
- Enforcing: This is the default mode. SELinux security policy is enforced, and access is denied based on policy rules. Violations are logged.
- Permissive: SELinux is active but does not enforce the security policy. Instead of denying access, it logs warnings for actions that would have been denied in Enforcing mode. This is useful for troubleshooting.
- Disabled: SELinux is turned off entirely. No policies are loaded, and no labeling occurs.
Compare Symmetric and Asymmetric encryption techniques used in managing network security.
| Feature | Symmetric Encryption | Asymmetric Encryption |
|---|---|---|
| Keys Used | Uses a single shared key for both encryption and decryption. | Uses a pair of keys: a Public Key for encryption and a Private Key for decryption. |
| Speed | Faster and less computationally expensive. | Slower and requires more processing power. |
| Security | Key distribution is a challenge; if the key is intercepted, security is compromised. | More secure for key exchange; the private key is never shared. |
| Usage | Bulk data encryption (e.g., AES). | Key exchange, digital signatures, and authentication (e.g., RSA, ECC). |
| Mathematical Concept | and | and |
Describe the basic components of a Bash Script and explain the significance of the Shebang.
A Bash script is a plain text file containing a series of commands.
Basic Components:
- Interpreter Directive (Shebang): The first line of the script.
- Comments: Lines starting with
#used for documentation (ignored by the shell). - Commands: System commands (e.g.,
ls,cp), control structures (loops, if-else), and variables. - Execution Permission: The file must have the executable bit set (
chmod +x script.sh).
Significance of the Shebang (#!):
- It is an absolute path to the interpreter that should be used to execute the script.
- Example:
#!/bin/bashtells the system to use the Bash shell. - If omitted, the script runs in the user's current shell, which might lead to syntax errors if the current shell differs from the script's intended syntax.
Explain the usage of tcpdump for monitoring network traffic with at least two examples.
tcpdump is a command-line packet analyzer tool used to capture or filter TCP/IP packets received or transferred over a network interface.
Usage:
It captures packet headers and data, useful for debugging network issues or security analysis.
Examples:
- Capture specific interface:
tcpdump -i eth0
This captures all packets flowing through theeth0interface. - Capture specific port:
tcpdump port 80
This captures traffic only related to HTTP (port 80). - Capture specific source IP:
tcpdump src 192.168.1.5
This captures packets originating from the specified IP address.
Differentiate between AppArmor and SELinux.
AppArmor (Application Armor) and SELinux are both Linux kernel security modules that provide Mandatory Access Control (MAC).
- Policy Identification:
- AppArmor: Uses Path-based identification. It restricts programs based on the file path of the executable. Policies are easier to read and configure.
- SELinux: Uses Inode/Label-based identification. Files are assigned security context labels (User:Role:Type:Level). Even if a file is moved, the label persists.
- Complexity:
- AppArmor: Generally considered easier to learn and configure for specific applications.
- SELinux: More complex and granular, offering finer control over system processes and files.
- Default Distributions:
- AppArmor: Default on Ubuntu and SUSE.
- SELinux: Default on RHEL, CentOS, and Fedora.
What is PAM (Pluggable Authentication Modules)? Explain its architecture and configuration file location.
PAM is a mechanism to integrate multiple low-level authentication schemes into a high-level API. It allows system administrators to choose how applications authenticate users without recompiling the applications.
Architecture:
PAM separates the tasks of authentication into four independent management groups:
- Auth: Verifies the user's identity (e.g., password prompt).
- Account: Checks if the user is allowed access (e.g., time of day, account expiration).
- Password: Handles password updates and complexity checks.
- Session: Manages actions before and after user login (e.g., mounting directories, logging).
Configuration:
- Configuration files are located in
/etc/pam.d/. - Each application (e.g.,
sshd,sudo,login) has its own file in this directory defining which modules are used.
Write a Bash script snippet using an if-else statement to check if a file named data.txt exists and is writable. Use appropriate test operators.
bash
!/bin/bash
FILENAME="data.txt"
Check if file exists (-e) AND is writable (-w)
if [ -w "$FILENAME" ]; then
echo "The file '$FILENAME' exists and is writable."
echo "Appending date to file..."
date >> "$FILENAME"
else
if [ -e "$FILENAME" ]; then
echo "The file exists but is NOT writable."
else
echo "The file '$FILENAME' does not exist."
fi
fi
Explanation of Operators:
-e: Returns true if the file exists.-w: Returns true if the file exists and write permission is granted.
Explain the different types of Loops available in Bash scripting with syntax examples.
Bash supports three main types of loops:
-
For Loop: Iterates over a list of items or a range of numbers.
- Syntax:
bash
for i in {1..5}
do
echo "Number $i"
done
- Syntax:
-
While Loop: Executes commands as long as the condition remains true.
- Syntax:
bash
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
- Syntax:
-
Until Loop: Executes commands as long as the condition is false (until it becomes true).
- Syntax:
bash
until [ $count -gt 5 ]
do
echo "Processing..."
((count++))
done
- Syntax:
Describe the process of generating a Self-Signed SSL Certificate in Linux.
Generating a self-signed certificate involves using OpenSSL. The process typically follows these steps:
- Generate Private Key: Create a secure private key.
openssl genrsa -out server.key 2048 - Generate CSR (Certificate Signing Request): Create a request containing organization details linked to the key.
openssl req -new -key server.key -out server.csr - Generate Self-Signed Certificate: Sign the CSR with your own private key (acting as the CA) to create the certificate (
.crt).
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Alternatively, this can be done in a single command using: openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt.
Explain Input and Output Redirection in Linux shell scripts using file descriptors.
Linux uses file descriptors (FD) for data streams: stdin (0), stdout (1), and stderr (2).
-
Output Redirection (
>and>>):>: Redirects stdout to a file, overwriting the file. Example:ls > list.txt.>>: Redirects stdout to a file, appending to it. Example:date >> log.txt.
-
Input Redirection (
<):- Feeds the content of a file into a command. Example:
wc -l < list.txt.
- Feeds the content of a file into a command. Example:
-
Error Redirection (
2>):- Redirects standard error. Example:
command 2> error.log.
- Redirects standard error. Example:
-
Redirecting both stdout and stderr:
command > output.txt 2>&1orcommand &> output.txtsends both success messages and errors to the same file.
How is the sudo command configured? Explain the syntax of the /etc/sudoers file.
sudo (SuperUser DO) allows a permitted user to execute a command as the superuser or another user. It is configured via the /etc/sudoers file, which should always be edited using the visudo command to check for syntax errors.
Syntax of /etc/sudoers entry:
user_name host_name=(target_user:target_group) commands
- user_name: The user getting the privileges (e.g.,
aliceor%wheelfor a group). - host_name: The host where the rule applies (usually
ALL). - target_user: The user the command will run as (usually
ALL). - commands: The specific commands allowed (e.g.,
/bin/ls, orALL).
Example:
alice ALL=(ALL) ALL
This allows user 'alice' to run any command on any host as any user.
Explain the usage of the case statement in Bash scripting with a syntax example.
The case statement is a logical control structure used to execute different blocks of code based on matching a variable against specific patterns. It is often cleaner than multiple if-elif-else statements.
Syntax Structure:
bash
case $VARIABLE in
pattern1)
commands
;;
pattern2)
commands
;;
*)
default_commands
;;
esac
Key Elements:
- Starts with
caseand ends withesac. - Patterns end with
). - Blocks end with double semicolons
;;. - The wildcard
*)acts as a default/catch-all case.
What are Positional Parameters in shell scripting? How are they accessed?
Positional Parameters are special variables used to access arguments passed to a script or function when it is executed.
$0: The name of the script itself.9: The first through ninth arguments provided.${10}: Arguments beyond 9 must be enclosed in braces.$#: The total count of arguments passed.- *``**: Represents all arguments passed.
Example:
If a script myscript.sh is run as ./myscript.sh apple banana:
$0= ./myscript.sh$1= apple$2= banana$#= 2
Discuss how to permanently add a service (e.g., HTTP) to the public zone using firewall-cmd.
To configure firewalld permanently, the --permanent flag is used. Without this flag, changes are lost after a reboot.
Steps:
-
Add the Rule:
firewall-cmd --zone=public --add-service=http --permanent--zone=public: Specifies the zone.--add-service=http: Opens the port associated with the HTTP service (port 80).--permanent: Writes the rule to the configuration file.
-
Reload Firewall:
firewall-cmd --reload
This is necessary to apply the permanent configuration changes immediately without rebooting. -
Verification:
firewall-cmd --zone=public --list-all
Explain Command Substitution in Bash. Provide two different syntax methods.
Command Substitution allows the output of a command to replace the command name itself. This is used to assign the output of a command to a variable or use it as an argument for another command.
Method 1: Using $(...) (Recommended)
- This is the modern, POSIX-compliant method.
- Example:
CURRENT_DATE=$(date)
Method 2: Using Backticks `...` (Legacy)
- This is the older method but is less readable and harder to nest.
- Example:
CURRENT_DATE=date``
Usage:
echo "The current directory is $(pwd)" results in the shell executing pwd and inserting the path into the string.
Define SSH (Secure Shell) and describe how Key-Based Authentication works.
SSH is a cryptographic network protocol for operating network services securely over an unsecured network, most notably for remote login.
Key-Based Authentication Mechanism:
- Key Generation: The user generates a key pair (Public and Private) using
ssh-keygen. - Public Key Placement: The user's Public Key is copied to the server's
~/.ssh/authorized_keysfile. - Connection Attempt: When the user tries to connect, the server generates a random challenge and encrypts it using the stored Public Key.
- Decryption: The client receives the challenge. Only the client holding the corresponding Private Key can decrypt it.
- Access: The client sends the decrypted challenge back. If it matches, the server grants access without requiring a password.
What is the Exit Status of a command? How is it used in logical controls within a script?
Exit Status is an integer value returned by a command to the parent process (shell) upon termination to indicate success or failure.
- 0: Indicates Success.
- Non-zero (1-255): Indicates Failure (specific numbers often denote specific error types).
Accessing Exit Status:
The variable $? holds the exit status of the most recently executed command.
Usage in Logic:
Scripts use this to decide flow:
bash
grep "user" /etc/passwd
if [ $? -eq 0 ]; then
echo "User found."
else
echo "User not found."
fi
Note: if statements implicitly check the exit status of the command provided.
Explain the concept of Arithmetic Expansion in Bash and provide examples.
Arithmetic Expansion allows the shell to perform integer arithmetic evaluations. It follows the syntax $(( expression )).
Features:
- Supports basic operators:
+,-,*,/,%(modulus), and**(exponentiation). - Variables inside the double parentheses do not strictly require the
$prefix.
Examples:
-
Basic Math:
result=$(( 5 + 5 ))(result is 10) -
Using Variables:
bash
num1=10
num2=20
sum=$(( num1 + num2 )) -
Incrementing:
(( num1++ ))(Increments the value of num1)