Notes: SELinux, Encryption and GPG
Check your understanding of SELinux modes, contexts, labeling, booleans and denial analysis, and of hashing, GPG, OpenSSL, LUKS and key-file handling.
Q. A file has mode -rw-r--r--, yet nginx running in the httpd_t domain gets "Permission denied" reading it on an enforcing SELinux system. Which statement explains this?
- SELinux overrides the file mode, so the Unix permissions are ignored once SELinux is enforcing
- The file mode only applies to root, while SELinux rules apply to service accounts
- Access needs both the normal permissions (DAC) and the SELinux policy (MAC) to allow it
- SELinux denies every read until the file owner grants access with
chmod
Explanation: SELinux adds Mandatory Access Control on top of Discretionary Access Control; it does not replace it. A request succeeds only if DAC allows it and the policy allows the process domain to access the object's type.
system_u:object_r:httpd_sys_content_t:s0
-
system_u -
object_r -
s0 -
httpd_sys_content_t
Explanation: A context is
user:role:type:level, so the third field is the type.system_uis the SELinux user,object_rthe role used for files ands0the MLS/MCS level. Everyday troubleshooting focuses on the type.
Q. Under the targeted policy, what does type enforcement mainly compare when httpd tries to read a file?
- The domain of the process with the type of the file, against the loaded policy rules
- The Linux user ID of the process with the file's owner and group
- The full path of the file with a list of paths allowed for
httpd - The SELinux user field of the process with the SELinux user field of the file
Explanation: Policy rules have the form "domain X may do Y to type Z", such as
httpd_treadinghttpd_sys_content_t. Paths matter only because they decide which label a file gets; UIDs are the separate DAC check.
- The long listing of the file plus a column naming the process allowed to open it
- The file's security context followed by its name, without mode, owner or size
- Only the type field of the context, such as
httpd_sys_content_t - The extended ACL entries of the file, in the same format as
getfacl
Explanation: With GNU
ls,-Zprints the context (for examplesystem_u:object_r:httpd_sys_content_t:s0) before the name. Combine it with-l(ls -lZ) to see mode, owner and size as well; add-dfor a directory itself.
-
ls -Z /usr/sbin/sshd -
getsebool -a | grep sshd -
ps -eZ | grep sshd -
semanage port -l | grep ssh
Explanation:
ps -Zadds aLABELcolumn with each process's context, such assystem_u:system_r:sshd_t:s0-s0:c0.c1023.ls -Zshows the label of the executable file, which is not the same as the domain of the running process.
- It is blocked, but no AVC message is written to the audit log
- It is blocked and logged, exactly as in enforcing mode
- It is allowed and nothing is logged, as if SELinux were disabled
- It is allowed, and an AVC denial is logged as if it had been blocked
Explanation: Permissive mode keeps SELinux and its policy loaded but only audits violations. That makes it useful for diagnosis. In disabled mode no policy is loaded and no denials are logged.
avc: denied { read } for pid=1234 comm="nginx" path="/srv/mywebsite/index.html" scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:default_t:s0 tclass=file permissive=1
- The read was logged as a denial but was actually allowed to proceed
- The read was blocked, and SELinux will allow it next time it is attempted
- The file is labeled with a permissive type that any domain may read
- The AVC message was generated by
audit2allowrather than by the kernel
Explanation:
permissive=1means the check failed but was not enforced, because the system or that domain was permissive. In enforcing mode the same record showspermissive=0and the read fails.
- SELinux is loaded immediately and starts enforcing until the next reboot
- It fails; SELinux has to be enabled in the boot configuration and the system rebooted
- SELinux switches to permissive mode first and then to enforcing after a relabel
- The setting is written to
/etc/selinux/configand takes effect at the next login
Explanation:
setenforceonly switches an enabled SELinux between enforcing and permissive. To enable a disabled SELinux you change the boot configuration (/etc/selinux/config, kernel parameters) and reboot, usually with a relabel.
Q. sestatus shows the lines below. What mode will SELinux be in after the next reboot, assuming nothing else changes?
SELinux status: enabled
Current mode: permissive
Mode from config file: enforcing
Policy name: targeted
- Permissive, because the current mode is saved at shutdown
- Disabled, because the running mode and the config file disagree
- Permissive, until someone runs
restorecon -R / - Enforcing, because the mode in
/etc/selinux/configapplies at boot
Explanation: Someone ran
setenforce 0, which lasts only until reboot. At boot theSELINUX=value in/etc/selinux/configis used, hereenforcing. To make permissive permanent you would edit that file.
Q. SELinux was disabled for months and is now being re-enabled. Why do administrators usually run touch /.autorelabel before rebooting?
- It tells the kernel to load the targeted policy instead of the MLS policy
- It resets all SELinux booleans to their default values during boot
- Files created while SELinux was off have no labels, so the boot relabels them from policy
- It switches SELinux to permissive mode for one boot so services can start
Explanation: With SELinux disabled, new and changed files do not get labels. The
/.autorelabelflag makes the boot process relabel the file systems according to policy, which can take a while on large disks.
Q. Under the Fedora targeted policy, files under /srv/mywebsite have type var_t, which httpd_t cannot read. You run the commands below. What type does index.html have afterwards?
sudo chcon -R -t httpd_sys_content_t /srv/mywebsite
sudo restorecon -Rv /srv/mywebsite-
var_t, becauserestoreconapplies the policy's default label for that path -
httpd_sys_content_t, becausechconstores the new label as a permanent rule -
httpd_sys_content_t, becauserestorecononly changes files that have no label -
default_t, becauserestoreconremoves custom labels and leaves the generic type
Explanation:
chconwrites a label to the file but adds no file-context rule.restoreconrelabels from the rules, and the rule for/srv/.*saysvar_t, so the change is undone. That is whychconis for testing only.
Q. Which pair of commands permanently labels a custom web root /srv/mywebsite so that the label survives restorecon and full relabels?
-
semanage fcontext -a -t httpd_sys_content_t "/srv/mywebsite(/.*)?"thenrestorecon -Rv /srv/mywebsite -
chcon -R -t httpd_sys_content_t /srv/mywebsitethentouch /.autorelabel -
setsebool -P httpd_sys_content_t onthenrestorecon -Rv /srv/mywebsite -
restorecon -Rv /srv/mywebsitethensemanage fcontext -l | grep mywebsite
Explanation:
semanage fcontext -aadds a local file-context rule andrestoreconapplies it to existing files. A later relabel uses the same rule.httpd_sys_content_tis a type, not a boolean.
Q. You add a rule with semanage fcontext -a -t httpd_sys_content_t "/srv/mywebsite(/.*)?", but ls -Z /srv/mywebsite/index.html still shows var_t. Why?
- The rule only applies to files created after the next reboot
-
semanage fcontextchanges the labeling rules, not existing files; runrestoreconto apply them - The rule needs
setenforce 1before the kernel will read it -
ls -Zcaches labels, so the new type appears only afterls --clear-cache
Explanation: The rule is stored in the policy's local file contexts. Files keep their existing labels until something relabels them, usually
restorecon -Rv /srv/mywebsite. New files may still inherit the parent directory's label.
- Only files directly inside
/srv/mywebsite, not the directory itself - Only the directory
/srv/mywebsite, not anything inside it - Any path containing the word
mywebsiteanywhere on the system - The directory
/srv/mywebsiteitself and everything below it
Explanation: File-context specs are regular expressions anchored to the whole path.
(/.*)?optionally matches a slash followed by anything, so the rule covers the directory and all of its contents. Quote it so the shell does not expand it.
Q. A file has context unconfined_u:object_r:var_t:s0, and the matching file-context rule says system_u:object_r:httpd_sys_content_t:s0. What context does the file have after restorecon -v (without -F)?
-
system_u:object_r:httpd_sys_content_t:s0 -
unconfined_u:object_r:httpd_sys_content_t:s0 -
unconfined_u:object_r:var_t:s0 -
system_u:object_r:var_t:s0
Explanation: According to
restorecon(8), a file that already has a context only has its type changed.-Fforces the user, role and range to be reset as well. The SELinux user rarely matters in the targeted policy.
httpd_can_network_connect (on , off) Allow httpd to can network connect
- It goes back to off, because it was turned on with
setseboolwithout-P - It stays on, because
semanageonly lists booleans that were set with-P - It stays on until the next policy update, and then it is reset to off
- It goes back to off only if SELinux is switched to permissive mode
Explanation: The columns are the current state and the persistent default.
setsebool name onchanges only the running value;setsebool -P name onalso writes it to the policy on disk so it survives reboots.
Q. A PHP application behind Apache must open TCP connections to an API server on another host. The firewall allows it, but ausearch shows denied { name_connect } for httpd_t. What is the usual fix?
-
semanage port -a -t http_port_t -p tcp 8000 -
chcon -t httpd_sys_content_t /var/www/html/app.php -
setsebool -P httpd_can_network_connect on -
setenforce 0in the Apache unit'sExecStartPre=line
Explanation:
name_connectis an outgoing connection, and the targeted policy gates it forhttpd_twith thehttpd_can_network_connectboolean. Labeling a porthttp_port_tcontrols which portshttpdmay listen on (name_bind), not where it may connect.
Q. You move nginx to listen on TCP 8085. It fails to start and the audit log shows denied { name_bind } ... src=8085. Assuming 8085 has no SELinux port type yet, which command fixes it?
-
semanage port -a -t http_port_t -p tcp 8085 -
setsebool -P httpd_can_network_connect on -
semanage fcontext -a -t http_port_t "/etc/nginx(/.*)?" -
chcon -t http_port_t /usr/sbin/nginx
Explanation:
name_bindis the right to listen on a port, andhttpd_tmay bind to ports of typehttp_port_t.semanage port -alabels the port; if it already has another type, use-minstead. Check withsemanage port -l | grep http_port_t.
type=AVC msg=audit(1609459200.123:456): avc: denied { read } for pid=1234 comm="nginx" name="index.html" scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file
- A process in the
user_home_tdomain tried to read a file labeledhttpd_t - The user
nginxtried to read a file owned byunconfined_u - A process in
httpd_ttried to read a directory calledindex.html - A process in
httpd_ttried to read a file labeleduser_home_t
Explanation:
scontextis the source (the process),tcontextthe target object andtclassits class. Here the web server domain was deniedreadon a regular file with a home-directory type, which suggests content copied or moved from a home directory.
- Events since the last boot
- Events since midnight today
- Events from the last 10 minutes
- Only the most recent single AVC event
Explanation: In
ausearch(8),recentmeans 10 minutes ago,todaymeans since midnight andbootmeans since the last boot.-m avclimits the search to AVC records; add-c nginxto filter by command name.
- A reason for each denial, such as a missing allow rule or a boolean that is off
- A compiled policy module that allows the denied accesses from then on
- A list of the files with wrong labels, which it then relabels automatically
- The list of booleans that
setsebool -Pchanged since the last boot
Explanation:
audit2why(the same asaudit2allow -w) translates denials into reasons, for example a missing type enforcement rule or a boolean that would allow the access. It changes nothing; you still choose the fix.
Q. httpd_t is denied reading files under /srv/mywebsite labeled var_t. audit2allow suggests the rule below. Why is installing it a bad fix?
allow httpd_t var_t:file read;
- Generated rules apply only in permissive mode, so the denial would come back
- It lets the web server read every
var_tfile on the system, when the real fault is a wrong label -
semodulerefuses modules created byaudit2allowunless they are signed - The rule only lasts until the next reboot, like
setseboolwithout-P
Explanation:
audit2allowgenerates rules that would have permitted the logged accesses, often far more broadly than needed. Here the right fix is to label the contenthttpd_sys_content_t. Check labels, booleans and port types before writing custom policy.
Q. After reviewing the output, you run ausearch -m avc -c myapp | audit2allow -M myapp_local. What do you have to do next for the rules to take effect?
- Nothing;
audit2allow -Mloads the module into the kernel immediately - Run
restorecon -Rv /so the new rules are applied to every file - Reboot, because policy modules are only read at boot
- Install the generated package with
semodule -i myapp_local.pp
Explanation:
-Mwrites a type enforcement source file (myapp_local.te) and a compiled package (myapp_local.pp) but does not load it. Read the.tefile first, then load the package withsemodule -i.
- Every process, including users' login shells, under strict per-user rules
- Only processes started by root; processes of regular users run unrestricted
- Selected services such as
httpd,sshdandnamed, while most user processes run unconfined - Only processes inside containers; host processes are never confined
Explanation: The targeted policy, the default on Fedora and RHEL, confines chosen services and leaves ordinary user sessions in unconfined domains. The MLS policy confines far more and is harder to administer.
Q. A colleague's fix for every SELinux problem is SELINUX=disabled. What is the better first step when a service gets "Permission denied"?
- Run
chcon -R -t unconfined_t /so that all files are readable by every domain - Check the AVC denial, then fix the label, boolean or port type it points to
- Reinstall the
selinux-policy-targetedpackage to reset the policy - Set the service's domain to permissive permanently in
/etc/selinux/config
Explanation: Most denials come from wrong file labels, a boolean that is off or an unlabeled port, and each has a narrow fix. Disabling SELinux removes the protection for every service. Permissive mode is for short-term diagnosis only.
-
/etc/selinux/targeted/audit.log -
/var/log/selinux/avc.log -
/var/log/audit/audit.log -
/proc/self/attr/current
Explanation: With
auditdrunning, AVC records go to/var/log/audit/audit.log, whichausearch,audit2whyandsealertread. Withoutauditd, they go to the kernel log, so look indmesgor the journal.
- Symmetric uses one shared secret key; asymmetric uses a public and a private key
- Symmetric is used for files only; asymmetric is used for network traffic only
- Symmetric needs no key at all; asymmetric needs a password to be shared first
- Symmetric is always more secure than asymmetric, but it is much slower
Explanation: With symmetric ciphers such as AES, both sides must already share the secret. Asymmetric schemes let anyone encrypt to a published public key that only the private key can decrypt. Symmetric ciphers are usually much faster.
Q. A colleague wants to "decrypt" a SHA-256 value back into the original file. What is wrong with that idea?
- SHA-256 can only be decrypted with the private key that created it
- SHA-256 output can be reversed only by the root user
- A hash is a one-way fixed-length digest, not encryption, so there is no key to reverse it
- SHA-256 is symmetric encryption, so the same password is needed to reverse it
Explanation: Hash functions map any input to a fixed-size digest and are designed so the input cannot be recovered from it. They are used to check integrity and to store passwords; encryption is reversible with the right key.
echo hello | sha256sum
echo -n hello | sha256sum-
sha256summixes in a random salt each time it runs -
echoadds a trailing newline, so the first input is six bytes -
-nmakessha256sumswitch to printing SHA-512 output - Reading from a pipe makes
sha256suminclude a timestamp
Explanation: SHA-256 is deterministic, but any change in the input, even a trailing newline, gives a completely different digest. The second command hashes exactly
helloand prints2cf24dba...9824.
Q. SUMS was created with sha256sum p.txt > SUMS. Then a line is appended to p.txt. What does sha256sum -c SUMS do?
- Prints
p.txt: OK, because the file name and size are unchanged - Updates
SUMSwith the new digest and printsp.txt: UPDATED - Prints the new digest and leaves the comparison to the user
- Prints
p.txt: FAILED, warns that a checksum did not match and exits with status 1
Explanation:
-crecomputes each listed file's digest and compares it with the stored one. A changed file printsFAILEDand the exit status is non-zero, which makes it easy to use in scripts.
- Your own private key
- Jane's public key
- Jane's private key
- Your own public key
Explanation: Anything encrypted to Jane's public key can be decrypted only with Jane's private key, which never leaves her hands. Signing is the operation that uses your own private key.
- You sign with the recipient's public key, and they verify with their private key
- A signature encrypts the file so only people with your public key can read it
- Signing and verifying both need the same shared passphrase
- You sign with your private key, and anyone with your public key can verify it
Explanation: A signature proves the data was signed by the holder of the private key and has not changed since. It does not hide the content; use encryption for confidentiality, or both together.
- A binary file
file.txt.gpgthat only Jane's private key can decrypt - An ASCII file
file.txt.ascthat anyone with Jane's public key can decrypt - The ciphertext printed to standard output, leaving no file behind
- A detached signature
file.txt.sigmade with Jane's key
Explanation: Without
--armor, GPG writes binary OpenPGP data tofile.txt.gpg. With-a/--armorthe output is text infile.txt.asc, which is easier to paste into an email.-ochooses another output name.
Q. A project ships release.tar.gz and release.tar.gz.sig. You have imported its public key. Which command verifies the download?
-
gpg --decrypt release.tar.gz.sig -
gpg --detach-sign release.tar.gz -
gpg --verify release.tar.gz.sig release.tar.gz -
gpg --import release.tar.gz.sig
Explanation: A detached signature is verified by giving
--verifythe signature first and then the data file. If even one byte of the tarball changed, GPG printsBAD signatureand exits non-zero.
Q. gpg --verify prints the output below for a key you imported from a key server. What does it mean?
gpg: Good signature from "Jane Smith <jane@example.com>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
- The signature matches the key, but nothing confirms the key really belongs to Jane
- The file was modified after it was signed, so the signature no longer matches
- The key has expired, so the signature can no longer be checked
- GPG could not find the public key, so it checked only the file's checksum
Explanation: The maths checks out for that key, but anyone can create a key with Jane's name. Compare the fingerprint (
gpg --fingerprint jane@example.com) with Jane through a trusted channel before relying on it.
- Encrypts
file.txtwith a key derived from a passphrase, writingfile.txt.gpg - Encrypts
file.txtto your own public key and signs it with your private key - Creates a new key pair whose public and private halves are identical
- Prints a hash of
file.txtthat can be compared on another machine
Explanation: Symmetric mode needs no key pair: anyone who knows the passphrase can decrypt with
gpg -d. Current GnuPG uses AES-256 by default. The hard part is getting the passphrase to the other person safely.
- It contains a copy of your private key for disaster recovery
- It lets you declare the key invalid even after losing the private key
- It must be supplied every time you sign or decrypt a file
- It extends the key's expiry date automatically each year
Explanation: Publishing the certificate tells others to stop trusting the key. GnuPG 2.1 and later create one automatically under
~/.gnupg/openpgp-revocs.d/when you generate a key. Anyone holding it can revoke your key, so protect it.
-
gpg --gen-key -
gpg --gen-revoke -
gpg --edit-key -
gpg --full-generate-key
Explanation: In GnuPG 2.1 and later,
--gen-keyasks only for name, email and passphrase and uses the default algorithm.--full-generate-key(--full-gen-key) shows all the prompts.--edit-keychanges an existing key, for example withaddkey.
- GPG refuses to run until the directory is owned by root
- GPG deletes the private keys to protect them
- GPG still works but prints
WARNING: unsafe permissions on homedir - Nothing; GPG does not check the permissions of its home directory
Explanation: GPG checks that its home directory is not accessible to other users and warns when it is. The private keys inside should not be readable by anyone else;
chmod 700 ~/.gnupgfixes it.
WARNING: UNPROTECTED PRIVATE KEY FILE!
Permissions 0644 for 'mykey' are too open.
-
chmod 600 mykey -
chmod 644 mykey.pub -
chmod +x mykey -
chown root mykey
Explanation: OpenSSH refuses a private key file that group or others have any access to, because someone else could have copied it. Mode
600(owner read/write) fixes it. The.pubfile may stay world-readable.
Q. openssl enc -aes-256-cbc -in p.txt -out p.enc prints the warning below (OpenSSL 3.0). What should you add?
*** WARNING : deprecated key derivation used.
Using -iter or -pbkdf2 would be better.
-
-nosalt, so the output does not include a random salt -
-base64, so the ciphertext is stored as text -
-pbkdf2, so the key is derived from the password with PBKDF2 -
-md5, so a faster digest is used for the key
Explanation: Without
-pbkdf2or-iter,encturns the password into a key with a single fast hash, which makes guessing easy. The same option must be given when decrypting with-d.-aonly changes the output encoding.
-
openssl req -new -key key.pem -subj "/CN=rsa2048" -out key.csr -
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out key.pem -
openssl x509 -req -in key.csr -signkey key.pem -days 2048 -
openssl enc -aes-256-cbc -pbkdf2 -in /dev/urandom -out key.pem
Explanation:
genpkeygenerates private keys for any algorithm; here the file starts with-----BEGIN PRIVATE KEY-----.openssl pkey -in key.pem -puboutextracts the public key.reqandx509work with requests and certificates.
- A self-signed certificate valid for
www.example.com - A new RSA private key, protected by a passphrase you choose
- A copy of the server certificate fetched from
www.example.com - A certificate signing request to send to a certificate authority
Explanation: A CSR holds the public key and the requested subject, signed with the private key to prove you hold it. The CA returns a certificate; the private key never leaves your server. Adding
-x509would produce a self-signed certificate instead.
Q. In openssl req -x509 -newkey rsa:2048 -noenc -keyout k.pem -out c.crt -days 365, what does -noenc do?
- It produces a certificate whose public key is not encrypted
- It writes the new private key without passphrase protection
- It disables encryption on TLS connections that use the certificate
- It skips signing, so the certificate has no signature
Explanation:
-noenc(called-nodesbefore OpenSSL 3.0) stores the key unencrypted, as unattended services usually need. Without it, OpenSSL asks for a passphrase and writes an encrypted private key. Either way, keep the key file at mode600.
-
openssl req -in c.crt -noout -subject -
openssl s_client -connect c.crt:443 -
openssl genpkey -in c.crt -text -
openssl x509 -in c.crt -noout -enddate
Explanation:
openssl x509reads certificates;-enddateprintsnotAfter=...,-datesshows both validity dates and-nooutsuppresses the PEM output.-checkend 86400exits non-zero if it expires within a day.
Q. echo | openssl s_client -connect 127.0.0.1:44330 prints the output below, and the TLS session is still established. Why?
subject=CN = test
issuer=CN = test
Verify return code: 18 (self-signed certificate)
-
s_clientreports failed verification but continues unless given-verify_return_error - Self-signed certificates are always trusted when connecting to
127.0.0.1 - Return code 18 means that the certificate chain was verified successfully
-
s_clientnever checks certificates unless the-showcertsoption is given
Explanation:
s_clientis a debugging tool, so it shows the result of verification and keeps the connection open even when it fails. Here the subject equals the issuer and no trusted CA signed it. Real clients such ascurlwould refuse.
- It sends the name via SNI, so a multi-site server returns the matching certificate
- It makes
s_clientresolve the name through DNS instead of using the IP - It checks that the server's reverse DNS record matches the given name
- It sets the HTTP
Host:header for the request typed after connecting
Explanation: With Server Name Indication the client names the site in the handshake. Without it, a server with many virtual hosts may present a default certificate that does not match. Recent OpenSSL sends SNI from a host name given in
-connect, but not from an IP address.
Q. What does cryptsetup luksFormat /dev/sdb1 do to a partition that already holds an ext4 file system with data?
- Encrypts the existing ext4 file system in place, keeping the data
- Creates an encrypted copy of the data on
/dev/mapper/sdb1 - Writes a new LUKS header and keyslots, so the old data should be treated as lost
- Asks for a passphrase, then mounts the partition at
/mnt/sdb1
Explanation:
luksFormatinitializes a new LUKS container and asks you to typeYES. Afterwards youcryptsetup openit to get a/dev/mapper/NAMEdevice, runmkfson that mapping once, and mount it.
Q. A LUKS volume is unlocked with a passphrase. You add a second passphrase with cryptsetup luksAddKey. Why is this fast even on a large disk?
- It only encrypts new data; existing blocks keep using the old passphrase
- It copies the disk in the background after the command returns
- It stores the new passphrase in plain text inside the LUKS header
- Each keyslot encrypts the same volume key, so the data itself is not re-encrypted
Explanation: The data is encrypted with a volume key, and every passphrase or key file unlocks a keyslot holding a copy of it. Adding, changing or removing a passphrase only rewrites keyslots. Losing the header loses the data, so back it up with
luksHeaderBackup.
Q. You have finished with an opened LUKS volume mounted at /mnt/secure. What is the correct order to lock it again?
-
cryptsetup close securefirst, thenumount /mnt/secure -
umount /mnt/securefirst, thencryptsetup close secure -
cryptsetup luksFormat /dev/sdb1, thenumount /mnt/secure -
shred -u /dev/mapper/secure, thenumount /mnt/secure
Explanation: The file system on
/dev/mapper/securemust be unmounted before the mapping can be removed.cryptsetup closethen removes the mapping and wipes the key from kernel memory.