Меню Рубрики

Real effective user id linux

Unix / Linux: Difference between Real User ID, Effective User ID and Saved User ID

I am already aware of real user id. It is the unique number for a user in the system.

In my system, My uid is

What are the other two ID’s stands for?
And what is the use of effective user id and saved user id and where we use it in the system?

2 Answers 2

The distinction between a real and an effective user id is made because you may have the need to temporarily take another user’s identity (most of the time, that would be root , but it could be any user). If you only had one user id, then there would be no way of changing back to your original user id afterwards (other than taking your word for granted, and in case you are root , using root ‘s privileges to change to any user).

So, the real user id is who you really are (the one who owns the process), and the effective user id is what the operating system looks at to make a decision whether or not you are allowed to do something (most of the time, there are some exceptions).

When you log in, the login shell sets both the real and effective user id to the same value (your real user id) as supplied by the password file.

Now, it also happens that you execute a setuid program, and besides running as another user (e.g. root ) the setuid program is also supposed to do something on your behalf. How does this work?
After executing the setuid program, it will have your real id (since you’re the process owner) and the effective user id of the file owner (for example root ) since it is setuid.

The program does whatever magic it needs to do with superuser privileges and then wants to do something on your behalf. That means, attempting to do something that you shouldn’t be able to do should fail. How does it do that? Well, obviously by changing its effective user id to the real user id!

Now that setuid program has no way of switching back since all the kernel knows is your id and. your id. Bang, you’re dead.

This is what the saved set-user id is for.

I’ll try to explain step by step with some examples.

Short background

Each process has its own ‘Process credentials’ which includes attributes like PID , the PPID , PGID , session ID and also the real and effective user and group IDs: RUID , EUID , RGID , EGID .

We’ll focus on those.

Part 1: Understand UID and GID

Now I’ll log into a shell with my credentials and run:

You can see my logname (rotem), the UID and GID which are both 1000, and other details like the shell I’m logged into.

Part 2: Understand RUID and RGID

Every process has an owner and belongs to a group.
In our shell, every process that we’ll now run will inherit the privileges of my user account and will run with the same UID and GID.

Lets run a simple command to check it:

And check for the process UID and GID:

Those are the Real user ID ( RUID ) and real group ID ( RGID ) of the process.

For now, accept the fact that the EUID and EGID attributes are ‘redundant’ and just equals to RUID and RGID behind the scenes.

Part 3: Understand EUID and EGID

Let’s take the ping command as an example.

Search for the binary location with the which command then run ls -la :

You can see that owner and group of the file are root . This is because the ping command needs to open up a socket and the Linux kernel demands root privilege for that.

But how can I use ping if I don’t have root privilege?
Notice the ‘s’ letter instead of ‘x’ in the owner part of the file permission.
This is a special permission bit for specific binary executable files (like ping and sudo ) which is known as setuid.

This is where EUID and EGID comes into play.
What will happen is when a setuid binary like ping executes, the process changes its Effective User ID ( EUID ) from the default RUID to the owner of this special binary executable file which in this case is — root .
This is all done by the simple fact that this file has the setuid bit.

The kernel makes the decision whether this process has the privilege by looking on the EUID of the process. Because now the EUID points to root , the operation won’t be rejected by the kernel.

Notice: On latest Linux releases the output of the ping command will look different because of the fact that they adopted the Linux Capabilities approach instead of this setuid approach — for those who are not familiar — read here.

Part 4: What about SUID and SGID?

The Saved user ID ( SUID ) is being used when a privileged process is running (as root for example) and it needs to do some unprivileged tasks.

In that case, the effective UID ( EUID ) from before will be saved inside SUID and then changed to an unprivileged task. When the unprivileged task is completed the EUID will be taken from the value of SUID and switch back to privileged account.

Источник

Real, Effective and Saved UserID in Linux

Every user in Unix like operating system is identified by different integer number, this unique number is called as UserID.

There are three types of UID defined for a process, which can be dynamically changed as per the privilege of task.

The three different types of UIDs defined are :
1. Real UserID
2. Effective UserID
3. Saved UserID

1. Real UserID : It is account of owner of this process. It defines which files that this process has access to.

2. Effective UserID : It is normally same as Real UserID, but sometimes it is changed to enable a non-privileged user to access files that can only be accessed by root.

3. Saved UserID : It is used when a process is running with elevated privileges (generally root) needs to do some under-privileged work, this can be achieved by temporarily switching to non-privileged account.

While performing under-privileged work, the effective UID is changed to some lower privilege value, and the euid is saved to saved userID(suid), so that it can be used for switching back to privileged account when task is completed.

You can print UID by simply typing id on terminal :

id command can be used to print real and effective user and group IDs

Different options of id :

Note : While you use id command with -r option, you will get error like

To deal with this, use -r option in conjunction with other option, for example, id -rg
Now, for setting up real user ID, the effective user ID, and the saved set-user-ID of the calling process, we use setresuid() and setresgid()

Syntax :

Return Value :
On success, 0 is returned.
On error, -1 is returned.

For more details : Use linux mannual page (man user id).

Источник

Реальный, эффективный и сохраненный идентификатор пользователя в Linux

Каждый пользователь в Unix-подобной операционной системе идентифицируется различным целым числом, этот уникальный номер называется UserID.

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

Определены три различных типа UID:
1. Реальный ID пользователя
2. Эффективный идентификатор пользователя
3. Сохраненный идентификатор пользователя

1. Real UserID: это учетная запись владельца этого процесса. Он определяет, к каким файлам этот процесс имеет доступ.

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

3. Сохраненный идентификатор пользователя: он используется, когда процесс, выполняющийся с повышенными привилегиями (обычно root), должен выполнить некоторую работу с недостаточными привилегиями, это может быть достигнуто путем временного переключения на непривилегированную учетную запись.

При выполнении работы с недостаточными привилегиями эффективный UID изменяется на более низкое значение привилегии, а euid сохраняется в сохраненном идентификаторе пользователя (suid), чтобы его можно было использовать для возврата к привилегированной учетной записи после завершения задачи.

Вы можете распечатать UID, просто набрав id на терминале:

Команда id может быть использована для печати реальных и эффективных идентификаторов пользователей и групп

Различные варианты идентификатора:

Примечание. Пока вы используете команду id с параметром -r, вы получите сообщение об ошибке, подобное

Чтобы справиться с этим, используйте опцию -r в сочетании с другой опцией, например, id -rg
Теперь для настройки реального идентификатора пользователя, эффективного идентификатора пользователя и сохраненного set-user-ID вызывающего процесса мы используем setresuid () и setresgid ()

Синтаксис:

Возвращаемое значение:
В случае успеха возвращается 0.
При ошибке возвращается -1.

Для получения более подробной информации: Используйте страницу mannual linux (идентификатор пользователя man).

Источник

How do real and effective user IDs work?

When a normal user wants to make change to the passwd file, the user will by setuid be given the effective user access. User becomes root temporarily and can edit passwd.

However you can only edit your password right, and not everybody else? However your effective user access is root. So how come you’re not allowed to change other passwords beside yours?

When you run a program with setuid, what does it mean actually when effective user is root, but real user id is still your name?

4 Answers 4

You can’t change other passwords because the program won’t allow you to. The program has system permissions to change any password it wants, because it is running as root , but the program has been specifically designed not to give the user any way to get it to use those permissions.

It is not quite that the user becomes root temporarily, it is that the trusted program runs with root permissions. Obviously, only programs that are specifically designed to limit users to doing only what they should be permitted to do can safely be made setuid.

You are only allowed to change only your password inspite of having effective user id of root because at the time of password change the real user id is checked not the effective user id . You can only change the effective user id and not the real user id.
Only root user can change the real user id to run the program as non-privileged user. The real user id can not be changed as it is set at the time of session start.
That’s why only your password can be changed as the real user id is not changed(as it is still yours not root’s).

An early hack in Unix was to make a symbolic link to a setuid shell script and call the link -i . This results in the script being called as sh -i which instead of executing the script called -i as intended launches an interactive shell, which then gives full powers. Effective user ID can be used to modify the passwd file for any user or root itself. The best way to guard against this is to use SELinux to prevent trust scripts or programs from modifying outside the area SELinux allows them to run.

Another technique is to have an immutable bit on important files which one set cannot be modified even by the root user (apart from in single-user mode)

As root you can invite users to log on to your system without a password and appear as any user but normal privileged processes try very hard to prevent this from happening.

If you use network filing systems of some sort the root user will be treated as nobody in that file space instead of root which allows untrusted computers to join a trusted network such as a university campus.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Остановить процесс в mac os
  • Особенности работы с mac os
  • Основы работы mac os
  • Основные программы для mac os
  • Основные возможности os mac