Linux Permissions

Linux Permissions & Security: Hands-On Guide (Ubuntu)

Prerequisites

  • Ubuntu system (desktop or server)
  • Terminal access
  • Sudo privileges

1. Basic File Permissions

In Linux, each file has three types of permission groups:

  • User (u) – Owner of the file
  • Group (g) – Users belonging to the same group
  • Others (o) – Everyone else

And three types of permissions:

  • Read (r) – View the contents of a file
  • Write (w) – Modify the contents of a file
  • Execute (x) – Run the file as a program or script

Step 1: Create a test file

mkdir ~/perms-test && cd ~/perms-test
touch file.txt
ls -l file.txt

This will show default permissions. You’ll see something like -rw-r--r--.

Step 2: Change permissions using chmod

chmod 644 file.txt  # rw-r--r-- (user can read/write, group/others can read)
chmod u+x file.txt  # Add execute permission to user
chmod o-r file.txt  # Remove read from others

Step 3: Change ownership using chown

sudo chown $USER:$USER file.txt

chown changes the owner and group of a file.


2. Umask (Default Permission Mask)

umask controls the default permission set for new files.

  • Default umask is usually 0022
  • Affects permissions like this: Final = Base - Umask
    • Base is 666 for files, 777 for directories

Step 1: Check current umask

umask

Step 2: Create new file to test

touch test.txt
ls -l test.txt

Step 3: Set a different umask temporarily

umask 027
umask

Now new files will have permissions 640 (rw-r—–)

Step 4: Make it permanent (optional)

Add to ~/.bashrc or ~/.profile:

umask 027

3. Special Permission Bits

3.1 SUID (Set User ID)

  • Makes an executable run with the privileges of the file’s owner. (only works for binary files)
sudo cp /bin/ping ./ping_test
sudo chmod u+s ping_test
ls -l ping_test  # Look for 's' in user exec

3.2 SGID (Set Group ID)

  • For directories: new files inherit the directory’s group.
mkdir sgid_dir
chmod g+s sgid_dir
ls -ld sgid_dir  # Look for 's' in group exec

3.3 Sticky Bit

  • Commonly used in shared directories like /tmp.
  • Only the file owner can delete their files.
mkdir sticky_dir
chmod 1777 sticky_dir
OR
chmod +t sticky_dir
ls -ld sticky_dir  # Look for 't' at the end

4. File Attributes (using chattr and lsattr)

Attributes provide extra protection beyond chmod.

Step 1: Set immutable attribute

touch immutable.txt
sudo chattr +i immutable.txt
lsattr immutable.txt

Immutable files can’t be modified, renamed, or deleted even by root.

Step 2: Try editing or deleting it

echo "test" > immutable.txt  # Should fail
rm immutable.txt             # Should fail

Step 3: Remove the attribute

sudo chattr -i immutable.txt

5. SELinux vs AppArmor (Ubuntu uses AppArmor)

  • SELinux is more common on RedHat-based systems.
  • Ubuntu uses AppArmor by default for Mandatory Access Control (MAC).

Step 1: Check if SELinux is installed

sestatus  # May return command not found

Step 2: Check AppArmor status

sudo aa-status

Shows enforced and complain profiles in use.


6. Mount Options: nosuid, nodev, noexec

These options restrict capabilities at the filesystem mount level.

Step 1: Create a virtual disk and mount it

mkdir ~/mnt-test
dd if=/dev/zero of=loopback.img bs=1M count=50
mkfs.ext4 loopback.img
sudo mount -o loop loopback.img ~/mnt-test

Step 2: Test with nosuid

sudo mount -o remount,nosuid ~/mnt-test

nosuid disables SUID/SGID execution on this filesystem.

Step 3: Test with noexec

echo -e '#!/bin/bash\necho Hello' > ~/mnt-test/test.sh
chmod +x ~/mnt-test/test.sh
~/mnt-test/test.sh  # Should fail with noexec

noexec prevents execution of binaries/scripts on the mounted directory.

Step 4: Unmount

sudo umount ~/mnt-test

7. Additional Topics for Advanced Security

7.1 Access Control Lists (ACLs)

ACLs provide fine-grained file permissions for multiple users and groups.

Commands:

setfacl -m u:username:r file.txt  # Give read access to specific user
getfacl file.txt                  # View ACLs
setfacl -x u:username file.txt    # Remove ACL for user

Useful when more than one user needs different levels of access to a file.

7.2 Sudo Configuration (/etc/sudoers)

Allows restricting and auditing root access per user or group.

Safely edit sudoers file:

sudo visudo

Example entry:

jane ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart apache2

Allows jane to restart Apache without password.

7.3 Systemd Service Permissions

Used to harden services using isolation techniques.

Example: Restrict access

In a systemd service file:

ProtectSystem=full
ReadOnlyPaths=/etc
PrivateTmp=true

Prevents service from modifying system files and isolates /tmp.

7.4 Auditd and Logging

To track who accessed/modified files or ran sensitive commands.

Install and start Auditd:

sudo apt install auditd
sudo systemctl enable --now auditd

Add a watch rule:

audctl -w /etc/passwd -p wa -k passwd_watch

View logs:

aureport -f  # File access reports
aureport -au # Authentication reports

8. Summary & Cleanup

Summary Table

FeatureDescriptionCommand Example
chmodChange file permissionschmod 755 file.sh
chownChange file ownershipsudo chown user:group file
umaskDefault permission for new filesumask 027
SUIDRun program with file owner’s privilegeschmod u+s /bin/file
SGIDNew files inherit directory’s groupchmod g+s dir
Sticky BitOnly owner can delete their file in dirchmod +t /tmp
ImmutablePrevent modification/deletionsudo chattr +i file
AppArmorMAC system used on Ubuntusudo aa-status
Mount OptionsRestrict capabilities like exec/suid/devicemount -o nosuid,nodev,noexec …
ACLsExtra user-specific permissionssetfacl -m u:user:rw file
SudoersControl admin rightssudo visudo
Systemd SecService-level isolation and hardeningProtectSystem=full etc.
AuditdFile access and auth loggingauditctl, aureport

Cleanup

cd ~
rm -rf ~/perms-test
sudo umount ~/mnt-test 2>/dev/null
rm -f loopback.img

1,043 Replies to “Linux Permissions”

  1. Тяговые аккумуляторные https://ab-resurs.ru батареи для складской техники: погрузчики, ричтраки, электротележки, штабелеры. Новые АКБ с гарантией, помощь в подборе, совместимость с популярными моделями, доставка и сервисное сопровождение.

  2. Крупнейший проект купить аккаунты для арбитража предоставляет возможность заказать учетки для рекламы. Если вам нужно купить Facebook-аккаунты, чаще всего важен не «одном логине», а в контроле и порядке: предсказуемая операционка, разделение задач внутри команды и аккуратные изменения. Мы оформили понятную навигацию, чтобы вы сразу понимали куда кликать перед покупкой.Навигация по теме: FAQ. Важно: покупка — стартовая точка. Дальше решает порядок: как выдаются права, как вы меняете настройки без хаоса, как фиксируете изменения и как разделяете тестовые и стабильные процессы. Особенность данной площадки — заключается в наличии масштабной базы знаний, где собраны рабочие чек-листы по операционке. Мы поможем, каким образом без лишних рисков организовать доступы, чтобы вы тесты не превращались в хаос а также всё было в рамках правил платформ . Заказывая здесь, вы получаете не только комплект, но и всестороннюю поддержку, прозрачные правила, гарантию на вход плюс самые приятные прайсы в нише. Дисклеймер: действуйте в рамках закона и с учетом правил сервисов.

  3. Мультимедийный интегратор айтек интеграция мультимедийных систем под ключ для офисов и объектов. Проектирование, поставка, монтаж и настройка аудио-видео, видеостен, LED, переговорных и конференц-залов. Гарантия и сервис.

  4. I will immediately seize your rss feed as I can’t find your e-mail subscription link or newsletter service. Do you have any? Please permit me recognise so that I may subscribe. Thanks.

  5. I’ll immediately clutch your rss feed as I can not in finding your e-mail subscription hyperlink or e-newsletter service. Do you have any? Kindly permit me recognize so that I may subscribe. Thanks.

  6. I really like what you guys are usually up too. This kind of clever work and coverage! Keep up the awesome works guys I’ve you guys to our blogroll.

  7. Hi, I do believe this is an excellent blog. I stumbledupon it 😉 I may come back yet again since i have bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.

  8. Incredible! This blog looks just like my old one! It’s on a completely different subject but it has pretty much the same layout and design. Outstanding choice of colors!

  9. For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
    MaxiSpin.us.com serves as a modern solution for content creators and marketers alike.

    **Features of MaxiSpin.us.com**
    Additionally, the platform offers a robust spin-text generator, allowing users to create unique versions of their content with ease.

    **Benefits of Using MaxiSpin.us.com**
    MaxiSpin.us.com provides businesses with a major advantage by simplifying the content creation process.

  10. For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
    By prioritizing efficiency, MaxiSpin.us.com assists users in rapidly creating top-tier articles, blogs, and marketing copy.

    **Features of MaxiSpin.us.com**
    Additionally, the platform offers a built-in editor for making real-time edits to achieve optimal results.

    **Benefits of Using MaxiSpin.us.com**
    This saves time and resources, allowing companies to focus on other critical aspects of their operations.

Leave a Reply to pinup_huEr Cancel reply

Your email address will not be published.