CertNote/ Commute Study Notes
Roadmap
KOEN
CLF-C02 · FoundationalCloud Practitioner - Foundational
DVA-C02 · AssociateDeveloper - Associate
SAA-C03 · AssociateSolutions Architect - Associate
SOA-C02 · AssociateCloudOps Engineer - Associate
SAP-C02 · ProfessionalSolutions Architect - Professional
DOP-C02 · ProfessionalDevOps Engineer - Professional
Linux Master 2 · 2급KAIT Linux Master - Level 2
SCS-C03 · SpecialtySecurity - Specialty
Linux Master 1 · 1급KAIT Linux Master - Level 1
  • Week 1
    • 1.Operating Systems and Linux: What the Kernel Does
    • 2.Free Software and Distributions: The Ecosystem Built by Licenses
    • 3.Installation and Booting: From the Moment You Power On
    • 4.Filesystem Structure and File Types: Everything Is a File
    • 5.Week 1 Comprehensive Review: Time to See Through the Concepts
  • Week 2
  • Week 3
  • Week 4
  • Week 5
  • Week 6
  • Week 7
  • Week 8
  • Week 9
  • Week 10
  • Week 11
  • Week 12
  • Week 13
    • 1.Network Configuration and Diagnostics Lab: Bring Up an IP by Hand and Open the Route
    • 2.Service Config File Short Answers: One Directive Decides Pass or Fail
    • 3.Shell Script Writing Tasks: Automate Real Work with Conditions, Loops, and Functions
    • 4.Security, Firewall, and Log Tasks: Write the Rules and Fix the Context
    • 5.Network and Service Lab Mock Exam + Wrong-Answer Notes
  • Week 14
MLA-C01 · AssociateMachine Learning Engineer - Associate
AIF-C01 · FoundationalAI Practitioner - Foundational
DEA-C01 · AssociateData Engineer - Associate
MLS-C01 · SpecialtyMachine Learning - Specialty
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

  • About
  • Changelog
  • Contact
  • Terms
  • Privacy
← Linux Master 1/Week 13/Day 4

Based on the Linux Master 1 exam syllabus·Report an error

Linux Master 1· AssociateWeek 13 · Day 4~20 min read

Day 4 - Security, Firewall, and Log Tasks: Write the Rules and Fix the Context

📌 Key Takeaways

  • Security lab tasks make you write rules and settings yourself. Direction, target, zone, type, and facility.priority must be exact to the letter.
  • iptables is table → chain → rule. Rules stop at the first match from top to bottom, so the position of -A (append) versus -I (insert at front) changes the result.
  • Iron rule of remote work: before -P INPUT DROP, add the SSH (22) allow rule first. Otherwise you cut yourself off.
  • Preventing volatility: for iptables use service iptables save; for firewalld use --permanent + --reload.
  • The key in SELinux is the context's type. Tell apart chcon (temporary) / restorecon (restore to policy) / semanage fcontext (permanent registration).
  • rsyslog distributes by facility.priority and records the given level and above. .none excludes, .= means only that level.
  • logrotate's skeleton is interval + rotate N + compress. TCP Wrapper is allow first, and if neither file matches, access is allowed.

iptables: Controlling netfilter by Hand

  • iptables controls the kernel's netfilter with a table → chain → rule structure.
  • Memorize the three chains of the filter table by direction.
ChainDirectionExample
INPUTIncoming (to the server)External → my port 80
OUTPUTOutgoing (from the server)Me → external DNS
FORWARDPassing through (routing)Via the gateway
  • The main options and targets are as follows.
OptionMeaningTargetMeaning
-AAppend to end of chainACCEPTAllow
-IInsert at the frontDROPDiscard without reply
-DDeleteREJECTSend a rejection reply
-PDefault policyLOGLog and pass through
-jSpecify the target
-pProtocol (tcp/udp)--dportDestination port
-sSource IP--sportSource port
# List rules
iptables -L -n -v --line-numbers     # Detailed listing with line numbers
 
# Allow incoming TCP on 80 (HTTP) and 22 (SSH)
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
 
# Allow only a specific IP range
iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 3306 -j ACCEPT
 
# Block all other INPUT (default policy)
iptables -P INPUT DROP
 
# Delete a rule / reset
iptables -D INPUT 3                   # Delete rule number 3
iptables -F                           # Flush all rules
 
# Save (persist after reboot) - required since rules live only in memory
service iptables save                 # or iptables-save > /etc/sysconfig/iptables

⚠️ Fatal trap: If you run iptables -P INPUT DROP first during a remote SSH session, you cut yourself off. Always add the port 22 ACCEPT rule first, then change the policy.

Order is everything: Rules are matched top to bottom and stop at the first match. If "DROP everything" is above, an ACCEPT added later (-A) never gets reached → insert it at the front with -I for it to work.

firewall-cmd: firewalld's Zone-Based Firewall

  • firewalld manages trust levels by grouping them into zones.
  • The key point is that runtime and permanent configuration are separate.
# Status and basic info
firewall-cmd --state                       # Whether it is running
firewall-cmd --get-default-zone            # Default zone
firewall-cmd --list-all                    # All rules of the current zone
 
# Allow a service/port (permanent + immediate)
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload                      # Apply permanent to the current runtime
 
# Allow only a specific IP (rich rule)
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'
 
# Remove
firewall-cmd --permanent --remove-service=http
firewall-cmd --reload
OptionMeaning
--add-service / --add-portAllow a service name / port
--permanentSave permanently (not applied immediately)
--reloadApply permanent to the current session
--list-allCheck all current rules
--get-default-zoneShow the default zone

⚠️ Key trap: Using only --permanent does not apply right now. You must --reload to apply it to the current session. Conversely, running only --add-service without --reload disappears at reboot. "Permanent + immediate" = --permanent then --reload.

Saving in iptables vs firewalld: iptables uses service iptables save, firewalld uses --permanent. Both solve the same problem, "rules in memory are volatile," in different ways.

SELinux: Mandatory Access Control on Top of DAC

  • SELinux layers type-based mandatory access control (MAC) on top of traditional permissions (DAC).
  • The three modes and the context are the key.
getenforce                    # Current mode (Enforcing/Permissive/Disabled)
setenforce 0                  # Temporarily switch to Permissive
setenforce 1                  # Temporarily switch to Enforcing
# For a permanent change (including disabled), edit SELINUX= in /etc/selinux/config and reboot
ModeBehavior
EnforcingPolicy violations blocked + logged
PermissiveViolations allowed but only logged
DisabledSELinux fully off
  • The context has the form user:role:type:level, and the type is the key.
ls -Z /var/www/html           # Check file context (-Z)
ps -eZ                         # Process contexts
 
# Change a context
chcon -t httpd_sys_content_t /web/index.html      # Change immediately (temporary)
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"   # Register permanently in policy
restorecon -Rv /web           # Restore the default context per policy
 
# Booleans (feature on/off)
getsebool -a | grep httpd
setsebool -P httpd_can_network_connect on    # -P = permanent
CommandRole
ls -ZShow context
chcon -t typeTemporarily change context
restoreconRestore default context
semanage fcontextRegister context in permanent policy
setsebool -PPermanently change a boolean

Diagnostic signal: "Permissions (rwx) are right but access fails" → suspect SELinux. If setenforce 0 fixes it, it is an SELinux problem (in production, do not turn it off; fix the context with restorecon/chcon).

chcon vs restorecon: chcon sets it directly (may vanish on relabeling), restorecon restores per policy, and semanage fcontext + restorecon is the permanent standard. You cannot reach Disabled with setenforce (permanent is the config file).

rsyslog: Classifying Logs by facility.priority

  • /etc/rsyslog.conf (or /etc/rsyslog.d/*.conf) distributes logs.
  • The format is facility.priority destination.
# facility.priority         destination file
*.info;mail.none;authpriv.none;cron.none   /var/log/messages
authpriv.*                                  /var/log/secure
mail.*                                      /var/log/maillog
cron.*                                      /var/log/cron
*.emerg                                     :omusrmsg:*
kern.*                                      /var/log/kern.log
local7.*                                    /var/log/boot.log
facilityMeaningpriority (low→high)
auth/authprivAuthentication, securitydebug
cronCroninfo
kernKernelnotice
mailMailwarning/warn
daemonDaemonserr/error
local0~7User-definedcrit, alert, emerg
  • A priority records the given level and above. The special notations are as follows.
NotationMeaning
mail.infoEverything from mail at info and above
mail.=infoExactly the info level only
mail.noneExclude mail
*.infoinfo and above of all facilities
# Apply after editing
systemctl restart rsyslog

The setting that gathers security authentication logs into /var/log/secure is authpriv.* /var/log/secure. .none excludes, and .= means exactly that level only.

logrotate: Rotating, Compressing, and Retaining Logs

  • /etc/logrotate.conf and /etc/logrotate.d/* keep logs from growing without limit.
# /etc/logrotate.d/myapp
/var/log/myapp/*.log {
    weekly                  # Rotation interval: daily/weekly/monthly
    rotate 4                # Number to keep (4 = about 4 weeks), older ones deleted
    compress                # gzip-compress rotated logs
    delaycompress           # Delay compression by one generation (latest log stays readable)
    missingok               # No error if the file is missing
    notifempty              # Do not rotate if empty
    create 0640 root root   # Permissions and owner of the new log file
    size 100M               # (Optional) rotate by size
    postrotate              # Command to run after rotation
        systemctl reload rsyslog > /dev/null 2>&1 || true
    endscript
}
DirectiveMeaning
daily/weekly/monthlyRotation interval
rotate NNumber of generations to keep
compressgzip compression
sizeRotate by size
createPermissions and owner of the new file
postrotate...endscriptCommand after rotation
logrotate -d /etc/logrotate.d/myapp   # Debug (does not actually run, predicts behavior)
logrotate -f /etc/logrotate.d/myapp   # Force an immediate rotation

Exam interpretation: weekly + rotate 4 + compress = rotate every week, keep the latest 4 (about 4 weeks) compressed, delete the excess. Size-based is size, interval-based is daily/weekly.

TCP Wrapper: Per-Service Access Control

  • Above the firewall layer, services that use libwrap (sshd, vsftpd, etc.) control access with two files.
# /etc/hosts.allow  (checked first, allowed on match)
sshd: 192.168.1.0/24
vsftpd: 192.168.1.10
 
# /etc/hosts.deny   (checked next, denied on match)
ALL: ALL
  • The check order is hosts.allow (allow) → hosts.deny (deny) → if neither matches, allow by default.
  • The syntax is service : host, and the keywords ALL/LOCAL/EXCEPT are used.
KeywordMeaning
ALLAll services/hosts
LOCALLocal hosts with no dot (.)
EXCEPTSpecify an exception

Order changes the result: allow takes priority over deny. The security standard is to put ALL: ALL in hosts.deny and whitelist only the targets to allow in hosts.allow. If both are empty, everything is allowed.

Firewall and Security Tasks at a Glance

TaskiptablesfirewalldCaution
Allow a port-A INPUT -p tcp --dport N -j ACCEPT--permanent --add-port=N/tcpDirection, protocol
Block-j DROP/REJECT--remove-serviceDROP = no response
Saveservice iptables save--permanent --reloadPrevent volatility
Policy-P INPUT DROPZone defaultAllow SSH first

Try It Yourself

# Firewall status at a glance
iptables -L -n -v --line-numbers
firewall-cmd --list-all
 
# SELinux status and context
getenforce
ls -Z /var/www/html 2>/dev/null
 
# Preview log settings (no actual rotation)
logrotate -d /etc/logrotate.conf 2>&1 | head -20

Lab tasks ultimately ask for exact options and directives. One direction, one type, one --reload decides pass or fail.

📖 Glossary

  • netfilter : The packet filtering engine built into the kernel. Both iptables and firewalld manipulate it.
  • Chains (INPUT/OUTPUT/FORWARD) : Sets of rules applied respectively to packets coming into the server, leaving the server, and passing through the server.
  • -A / -I : Append a rule to the end of the chain / insert it at the very front. Since matching stops at the first hit, position changes the result.
  • DROP / REJECT : Silently discard without a reply / send a rejection reply to notify immediately.
  • zone : A rule set that firewalld groups by trust level. Interfaces or sources are assigned to it.
  • --permanent / --reload : The option that saves a setting permanently to a file / the command that applies that permanent configuration to the current session.
  • rich rule : An extended rule in firewalld for fine-grained specification combining source, service, and action.
  • SELinux context : The user:role:type:level label attached to files and processes. The verdict depends on the type.
  • chcon / restorecon / semanage fcontext : Temporarily change a context / restore per policy / register permanently in policy.
  • SELinux boolean : An on/off switch that enables or disables a specific feature. Change it permanently with setsebool -P.
  • facility / priority : The classification of the log's source / the severity of the message. rsyslog splits logs using this pair.
  • .none / .= : rsyslog notation meaning exclude that facility from recording / record exactly that level only.
  • rotate N : The number of previous log generations logrotate keeps. The excess is deleted.
  • hosts.allow / hosts.deny : TCP Wrapper's allow and deny lists. allow is checked first, and if neither matches, access is allowed.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

Which iptables command allows incoming TCP connections to port 22 (SSH) from outside?

Question 2

While managing a server over remote SSH, you want to change the firewall default policy to DROP. What is the correct order of operations?

Question 3

How do you allow the http service in firewalld so that it persists after reboot and takes effect immediately?

Question 4

Which SELinux mode only logs policy violations without blocking them?

Question 5

Which command restores a file's SELinux context to the default per policy?

Question 6

In rsyslog.conf, which is the correct meaning of mail.none?

Question 7

What is the correct behavior of the logrotate settings weekly, rotate 4, compress?

PreviousShell Script Writing Tasks: Automate Real Work with Conditions, Loops, and FunctionsWeek 13 · Day 3Next Network and Service Lab Mock Exam + Wrong-Answer NotesWeek 13 · Day 5

Official references

  • Linux Master 1 official exam syllabus(opens in a new tab)

On this page

  • Key Takeaways
  • iptables: Controlling netfilter by Hand
  • firewall-cmd: firewalld's Zone-Based Firewall
  • SELinux: Mandatory Access Control on Top of DAC
  • rsyslog: Classifying Logs by facility.priority
  • logrotate: Rotating, Compressing, and Retaining Logs
  • TCP Wrapper: Per-Service Access Control
  • Firewall and Security Tasks at a Glance
  • Try It Yourself
  • Glossary
  • Practice Questions