Root User in Ubuntu- Important Things You Should Know

  1. What Is A Superuser?
  2. Add The New User To The “Sudo” Group
  3. Add A Public Key To The New user
  4. Varify The New User’s Login
  5. What is root user? Why is it locked in Ubuntu?
  6. How to run commands as root user in Ubuntu?
  7. How to become root user in Ubuntu?
  8. How to enable root user in Ubuntu?
  9. Updated February 15, 2021
  10. Why is root lower case?
  11. The Linux version of Windows admin
  12. Linux as an upside-down tree
  13. What can you do as root?
  14. Linux User
  15. Read permission
  16. Write permission
  17. How to Change Permissions in Linux Using the chmod Command
  18. How to Change Permissions using Symbolic Mode
  19. Example
  20. How to Change Permissions using Absolute Mode
  21. How to Change Ownership using the chown Command
  22. How to change user ownership with chown
  23. How to change user and group ownership simultaneously
  24. Linux Permissions Guided Exercise
  25. Visualization of the problem
  26. Wrapping up
  27. Local Security Principles
  28. User Accounts
  29. Types of Accounts
  30. Understanding the root Account
  31. Operations Requiring root Privileges
  32. Operations Not Requiring root Privileges
  33. Comparing sudo and su
  34. The sudoers File
  35. Command Logging
  36. Process Isolation
  37. Keeping Current
  38. How Passwords Are Stored
  39. Password Algorithm
  40. Good Password Practices
  41. Requiring Boot Loader Passwords
  42. Hardware Vulnerability
  43. Software Vulnerability
  44. Chapter Summary
  45. Получение прав root без переключения
  46. Переключение на суперпользователя в терминале
  47. Вход под суперпользователем
  48. Графически приложения от имени суперпользователя
  49. Выводы

What Is A Superuser?

The system will ask a set of questions. Answer those and you are all set.

Add The New User To The “Sudo” Group

su — rajib
sudo ls -la /root

Add A Public Key To The New user

Create the authorized_key file inside the .ssh folder and add the public key. Once pasted, please save the file.

sudo nano ~/.ssh/authorized_keys

Varify The New User’s Login

Как вы знаете, Linux очень серьезно относится к управлению пользователями и предоставлению им прав на работу с системой. Обычный пользователь может записывать файлы только в свой каталог и каталог /tmp/. Также есть возможность читать некоторые файлы в корневой файловой системе. Но вы не можете устанавливать программы, ведь для этого нужно право на запись, не можете изменять атрибуты файлов, не можете запускать сервисы, не можете читать некоторые файлы логов и еще много чего не можете.

В Linux управлять корневой файловой системой и создавать там файлы имеет право только пользователь root.

В этой статье мы рассмотрим какие программы нужны для того, чтобы получить права root пользователя linux, как они работают, как выполнять программу с правами root от обычного пользователя и как запускать графические программы с правами root. А также выясним что такое sudo в чем разница su или sudo.

Очень долго перечислять чего не может обычный пользователь Linux, проще сказать на что у него есть право, а именно при стандартной настройке полномочий для файлов в Linux, обычный пользователь может:

Если же нужно сделать что-то большее нам понадобятся права root пользователя linux. У root есть право делать все в вашей файловой системе независимо от того какие права установлены на файл.

Either you run commands with root privilege like this:

What is root user? Why is it locked in Ubuntu?

You don’t need to have root privilege for your daily tasks like moving file in your home directory, downloading files from internet, creating documents etc.

Take this analogy for understanding it better. If you have to cut a fruit, you use a kitchen knife. If you have to cut down a tree, you have to use a saw. Now, you may use the saw to cut fruits but that’s not wise, is it?

Does this mean that you cannot be root in Ubuntu or use the system with root privileges? No, you can still have root access with the help of ‘sudo’ (explained in the next section).

How to run commands as root user in Ubuntu?

So, how do you run commands as root? The simple answer is to add sudo before the commands that require to be run as root.

sudo apt update

If you are absolutely new to Linux, you might be surprised that when you start typing your password in the terminal, nothing happens on the screen. This is perfectly normal because as the default security feature, nothing is displayed on the screen. Not even the asterisks (*). You type your password and press enter.

Bottom line:To run commands as root in Ubuntu, add sudo before the command.When asked for password, enter your account’s password.When you type the password on the screen, nothing is visible. Just keep on typing the password and press enter.

How to become root user in Ubuntu?

The sudo command allows you to simulate a root login shell with this command:

You’ll notice that when you switch to root, the shell command prompt changes from $ (dollar key sign) to # (pound key sign). This makes me crack a (lame) joke that pound is stronger than dollar.

If you try to use the su command without sudo, you’ll encounter ‘su authentication failure’ error.

How to enable root user in Ubuntu?

sudo passwd root

Again, this is not recommended and I won’t encourage you to do that on your desktop. If you forgot it, you won’t be able to change the root password in Ubuntu again.

sudo passwd -dl root

I hope you have a slightly better understanding of the root concept now. If you still have some confusion and questions about it, please let me know in the comments. I’ll try to answer your questions and might update the article as well.

Дополнительно:  Root T-Mobile Galaxy Note 4 SM-N910T using CF Auto Root

Updated February 15, 2021

Who cares about root access? Do you need it? If you do, what can you do with it? Learn about the Linux root, what it can do for you, and how a Unix-like operating system is organized as an upside-down tree.

Why is root lower case?

Why does this decision bother people? Well, because there is a certain logic to the non-use of capital letters in that context. The idea is that initial-caps of words – or “proper case” – within case-sensitive code is typically only a convention that is applied to void methods and properties; you should start with the lower case for methods that return a value and local variables, says this perspective.

Oscilatingcretin notes that he has too often felt that the supposed need to use this convention is perhaps more arbitrary than it is rational – although he does note that he has “never needed a casing convention to tell me whether or not something is a local variable or property” because he has “always used a very intuitive naming convention.”

The bottom line is that you should write root without a capital letter; and if you want, you can question whether the lack of a capital letter makes sense.

The Linux version of Windows admin

KnownHost, buy your VPS Now!

Linux as an upside-down tree

To better understand how the concepts in the above section interrelate, this account is called root because it has exclusive write permissions within the root directory – i.e. it can change any files contained therein.

The root directory is called that because the hierarchy of a Unix-like OS is designed to be similar to a tree, with everything sprouting and branching off from one directory that serves as the roots. Flip the tree over, and you see the hierarchy, with root on top.

What can you do as root?

This question could be rephrased as, “What are example root privileges?” That is essentially what we are talking about with privileges is the ability to do other stuff on your dedicated or VPS server (the latter provided you have full root access). Here are 5 broad examples of what you can do within this account:

1. Edit whatever files you choose

2. Change the system however you want

3. Provide and remove permissions to other accounts (which will affect whether they can read, change, or execute certain directories and files)

4. Install software server-wide (MySQL, Apache, etc.)

5. Set up configurations for software throughout the server

You can get root access on a dedicated or virtual private server, provided this feature is available through your hosting provider. With a good service, logging in as root should be a snap. At KnownHost, support is something we pride ourselves on, so you can rest easy knowing we’ve got your back. See our full-root-access fully managed VPS plans.

Linux User

File permissions fall in three categories: read, write, and execute.

Read permission

Similarly for directories, read permissions allow the listing of directory content without any modification in the directory.

Write permission

Symbolic representation of permissions

Note that we can find permissions of files and folders using long listing (ls -l) on a Linux terminal.

Output of long listing

In the output above, d represents a directory and- represents a regular file.

How to Change Permissions in Linux Using the chmod Command

Now that we know the basics of ownerships and permissions, let’s see how we can modify permissions using the chmod command.

Syntax of chmod:

chmod permissions filename

We can change permissions using two modes:

Now, let’s see them in detail.

How to Change Permissions using Symbolic Mode

We can use mathematical operators to add, remove, and assign permissions. The table below shows the summary:


Suppose, I have a script and I want to make it executable for owner of the file zaira.

Let’s split the permissions like this:

To add execution rights (x) to owner (u) using symbolic mode, we can use the command below:

chmod u+x

Now, we can see that the execution permissions have been added for owner zaira.

Additional examples for changing permissions via symbolic method:

How to Change Permissions using Absolute Mode

Absolute mode uses numbers to represent permissions and mathematical operators to modify them.

The below table shows how we can assign relevant permissions:

Permissions can be revoked using subtraction. The below table shows how you can remove relevant permissions.

chmod 451 file-name

This is how we performed the calculation:

Note that this is the same as r—r-x—x.

To remove execution from other and group, subtract 1 from the execute part of last 2 octets.

This would be the same as rwxr-xr—.

How to Change Ownership using the chown Command

Next, we will learn how to change the ownership of a file. You can change the ownership of a file or folder using the chown command. In some cases, changing ownership requires sudo permissions.

Syntax of chown:

How to change user ownership with chown

chown news

Command to change ownership: sudo chown news

How to change user and group ownership simultaneously

In case we only need to change the group owner, we can use chown by preceding the group name by a colon :

Дополнительно:  Ошибка 0xc000007b при запуске Windows и программ

Linux Permissions Guided Exercise

Up until now we have explored permissions, ownerships, and the methods to change them. Now we will reinforce our learning with a guided exercise.

Visualization of the problem

We can visualize the problem like this:

Use the sudo command with flag i.

If you have the root password, you can login using that as well.

If you do not have root access, use the commands with appending sudo.

Step 2: Create a group dev-team

Use the groupadd command.

Syntax: groupadd group-name

Enter groupadd dev-team to create the dev-team group

Where -G specifies the group.

Use command passwd

Step 5: Create a directory in /home and name it dev-team

Use command mkdir

mkdir creates a directory.

Syntax: mkdir directory-name

Step 6: Change the group ownership of the folder dev-team to group dev-team

Use command chown

Syntax: chown :group-name folder

chown :dev-team /home/dev-team/

Step 7: Make sure the permissions of folder dev-team allow group members to create and delete files.

Use command chmod

Syntax: chmod permissions folder

chmod g+w /home/dev-team/

Step 8: Ensure that ‘others’ don’t have any access to the files of dev-team folder.

Remove read, write, execute permissions from ‘others’ if they exist.

chmod o-rx dev-team

Step 9: Exit the root session and switch to John

su — John

Verify with command whoami.

Step 10: Navigate to folder: /home/dev-team

Use command cd to switch folders.

Syntax: cd /path/to/folder

Confirm current path with pwd.

Step 11: Create an empty file in the folder: /home/dev-team

Use command touch to create an empty file.

Syntax: touch filename

Verify: ls -lrt

Step 12: Change the group ownership of the created file to dev-team and verify.

Use command chown to change ownership.

Syntax: chown :group file-name

chown :dev-team john-file.txt

Once group ownership is modified, all members of the group can access this file.

Verify ls -lrt

Use command exit to exit the terminal.

su — Bob

Step 14: Navigate to the path /home/dev-team

Step 15: Find out Bob’s privileges to access john-file.txt

Use command ls -l for long listing.

Does group have rw- permissions?

Step 16: Modify the file john-file.txt while logged in as Bob

This would redirect the quoted text to end of the file.

If all the permissions are correctly set, Bob would be allowed to edit and save this file. Otherwise you would get an error like this: Permission denied.

Verify cat john-file.txt

Step 17: Create another group project-manager and assign a member Fatima to it

Use command groupadd to add a new group.

Step 18: Navigate to folder /home/dev-team and verify if Fatima can access it

Use cd to navigate to /home/dev-team.

We get this error:

This is because, others don’t have any access to the folder dev-team.

If we recall, below are the rights of the dev-team folder.

Wrapping up

Thanks to Tom Mondloch for his help with the guided exercise.

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

This is part two. First read part one:

Local Security Principles

By the end of this chapter, you should be able to:

User Accounts

Types of Accounts

By default, Linux distinguishes between several account types in order to isolate processes and workloads. Linux has four types of accounts:

Understanding the root Account

When you are signed in as, or acting as root, the shell prompt displays ‘#’ (if you are using bash and you have not customized the prompt, as we have discussed previously). This convention is intended to serve as a warning to you of the absolute power of this account.

Operations Requiring root Privileges

root privileges are required to perform operations such as:

Operations Requiring root Privileges

Operations Not Requiring root Privileges

The table provides examples of operations which do not require root privileges:

Comparing sudo and su

The sudoers File

who where = (as_whom) what

# visudo /etc/sudoers# visudo -f /etc/sudoers.d/student

The actual specific editor invoked will depend on the setting of your EDITOR environment variable.

The sudoers File

Command Logging

By default, sudo commands and any failures are logged in /var/log/auth.log under the Debian distribution family, and in /var/log/messages and/or /var/log/secure on other systems. This is an important safeguard to allow for tracking and accountability of sudo use. A typical entry of the message contains:

Running a command such as sudo whoami results in a log file entry such as:

Process Isolation

More recent additional security mechanisms that limit risks even further include:

Hardware Device Access

Keeping Current

When security problems in either the Linux kernel or applications and libraries are discovered, Linux distributions have a good record of reacting quickly and pushing out fixes to all systems by updating their software repositories and sending notifications to update immediately. The same thing is true with bug fixes and performance improvements that are not security related.

So the best practice is to take advantage of your Linux distribution’s mechanism for automatic updates and never postpone them. It is extremely rare that such an update will cause new problems.

How Passwords Are Stored

Originally, encrypted passwords were stored in the /etc/passwd file, which was readable by everyone. This made it rather easy for passwords to be cracked.

How Passwords Are Stored

On modern systems, passwords are actually stored in an encrypted format in a secondary file named /etc/shadow. Only those with root access can read or modify this file.

Дополнительно:  Не работает кнопка Windows на клавиатуре Windows 10: 6 способов исправления

Password Algorithm

Protecting passwords has become a crucial element of security. Most Linux distributions rely on a modern password encryption algorithm called SHA-512 (Secure Hashing Algorithm 512 bits), developed by the U.S. National Security Agency (NSA) to encrypt passwords.

The SHA-512 algorithm is widely used for security applications and protocols. These security applications and protocols include TLS, SSL, PHP, SSH, S/MIME and IPSec. SHA-512 is one of the most tested hashing algorithms.

For example, if you wish to experiment with SHA-512 encoding, the word «test» can be encoded using the program sha512sum to produce the SHA-512 form (see graphic):

Password Encryption: sha512sum

Good Password Practices

Requiring Boot Loader Passwords

Furthermore, you never edit grub.cfg directly; instead, you can modify the configuration files in /etc/grub.d and /etc/defaults/grub, and then run update-grub, or grub2-mkconfig and save the new configuration file.

Hardware Vulnerability

When hardware is physically accessible, security can be compromised by:

Your IT security policy should start with requirements on how to properly secure physical access to servers and workstations. Physical access to a system makes it possible for attackers to easily leverage several attack vectors, in a way that makes all operating system level recommendations irrelevant.

The guidelines of security are:

Software Vulnerability

Like all software, hackers occasionally find weaknesses in the Linux ecosystem. The strength of the Linux (and open source community in general) is the speed with which such vulnerabilities are exposed and remediated. Specific coverage of vulnerabilities is beyond the scope of this course, but the Discussion Board can be used to carry out further discussion.

Chapter Summary

You have completed Chapter 18. Let’s summarize the key concepts covered:

Получение прав root без переключения

Чтобы реализовать максимально безопасный интерфейс для работы с правами суперпользователя в Linux была разработана команда sudo. Давайте рассмотрим что такое sudo. Эта команда пишется перед каждой командой, которую нужно выполнить от имени суперпользователя, и для ее выполнения нужно ввести пароль уже не root, а всего лишь вашего пользователя. Так же, как и в предыдущей, в этой утилиты есть свои опции. Сначала рассмотрим синтаксис:

Вы можете выполнить те же эксперименты, только для этой команды, чтобы понять как использовать команду sudo. Например:

sudo -u test ls

Использование sudo — это рекомендованный способ выполнять команды от имени суперпользователя в Linux. Так вы не забудете с чем имеете дело и меньше всего рискуете повредить систему. Более подробно о команде sudo читайте здесь. Но остался еще один нерешенный вопрос — как быть с графическими утилитами? Ведь команда sudo их не запускает, а запускать графическую оболочку от имени root небезопасно. Это мы и рассмотрим далее.

Переключение на суперпользователя в терминале

Теперь мы подошли к более интересному и практичному. С помощью специальных утилит вы можете переключить текущий эмулятор терминала в окружения суперпользователя и выполнять все следующие команды не от своего имени, а от его, таким образом, дав программе права root linux. Для этого существует утилита su. Вообще говоря, эта утилита позволяет не только переключаться на пользователя root но и на любого другого пользователя, но по умолчанию используется именно root. Рассмотрим ее подробнее. Команда su linux имеет следующий синтаксис:

Вот ее основные опции:

Теперь немного поэкспериментируем, чтобы понять как работает команда su linux.

Сначала выполним su без параметров, но для начала создадим переменную окружения, чтобы проверить как с ними обходится эта команда:

Теперь смотрим что получилось:

Из этих команд мы видим, что теперь мы пользователь root, но домашней директорией считается директория нашего предыдущего пользователя и наша переменная не сохранилась также изменилась переменная PATH, теперь там добавлен путь /sbin.

И повторим ту же комбинацию:

Та же ситуация, только на этот раз изменена ко всему еще и домашняя директория на директорию root. Но мы можем сохранить наши переменные окружения, если это нужно, для этого есть опция -p:

Как видите, наша переменная осталась. Вы также можете переключится на любого другого пользователя. Например:

su — test

Более подробно о команде su вы можете почитать в отдельной статье. Получение прав суперпользователя таким способом используется во многих дистрибутивах, например, Debian, OpenSUSE, ArchLInux, Gentoo и т д. Но в Ubuntu, как дистрибутиве для начинающих вход под пользователем root отключен. Это сделано потому, что это тоже не очень безопасно, вы можете забыть что выполняете команду от root и что-то натворить в системе. Поэтому переходим к следующей программе.

Вход под суперпользователем

Вы получите полноценное окружение root с возможностью выполнять все действия, но такой способ очень непрактичный, так как вы теряете все преимущества использования графического интерфейса.

Графически приложения от имени суперпользователя

Для запуска графических приложений от имени суперпользователя существуют специальные утилиты. Они сохраняют все необходимые переменные окружения и полномочия. В KDE это команда kdesu, а в Gnome команда gksu.

Просто наберите gksu или kdesu, а затем нужную команду:

Эта команда запустит файловый менеджер KDE с правами суперпользователя. В Gnome это будет выглядеть вот так:

Программа запросит пароль, уже в графическом окне, а потом откроется файловый менеджер.


Вот и все. Теперь вы знаете как получить права суперпользователя в Linux, знаете как использовать команду sudo и в чем разница sudo или su. Теперь программы, требующие дополнительных привилегий в системе, не вызовут у вас проблем. Если остались вопросы, пишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Оцените статью
Master Hi-technology
Добавить комментарий