Технология су-вид: полный путеводитель

Setuid en directorios

El indicador setgid en un directorio tiene un significado completamente distinto del de su aplicación en ficheros. Los directorios con permiso setgid fuerzan a todos los archivos y subdirectorios creados en ellos a pertenecer al grupo del dueño del directorio y no al grupo del usuario que crea el archivo o subdirectorio.

El indicador setuid, en cambio, no tiene efecto si es aplicado a un directorio. La causa es que si propagara el dueño del directorio a los objetos creados dentro de ese directorio, el usuario que cree un fichero allí perdería inmediatamente sus permisos de dueño sobre el fichero, impidiendo tal vez que pueda usarlo o modificarlo nunca más.

Пример

bob@foo$ cat /etc/passwd
alice:x:1007:1007::/home/alice:/bin/bash
bob:x:1008:1008::/home/bob:/bin/bash

bob@foo$ cat printid.c

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
    printf("Real UID\t= %d\n", getuid());
    printf("Effective UID\t= %d\n", geteuid());
    printf("Real GID\t= %d\n", getgid());
    printf("Effective GID\t= %d\n", getegid());

    return EXIT_SUCCESS;
}

bob@foo$ gcc -Wall printid.c -o printid
bob@foo$ chmod ug+s printid
bob@foo$ su alice 
Password: 
alice@foo$ ls -l
-rwsr-sr-x 1 bob bob 6944 2007-11-06 10:22 printid
alice@foo$ ./printid 
Real UID = 1007
Effective UID = 1008
Real GID = 1007
Effective GID = 1008
alice@foo$

Setuid en ejecutables

Normalmente este bit se activa en ejecutables.
Cuando a un ejecutable binario se le asigna el atributo setuid, usuarios normales del sistema pueden ejecutar ese archivo y obtener privilegios del usuario que posee dicho archivo (generalmente, root) en el proceso creado. Cuando el proceso obtiene privilegios de administrador, la aplicación puede realizar tareas en el sistema que usuarios normales generalmente no podrían hacer. El sistema impedirá al usuario que invocó el ejecutable alterar el nuevo proceso de ningún modo, como utilizando ptrace, LD_LIBRARY_PATH o enviarle señales a él (señales desde la propia terminal sí se aceptarán).

Por ejemplo el bit setuid se utiliza en el fichero /usr/bin/passwd para que todo el mundo pueda cambiar su contraseña de forma controlada. Pudiendo ejecutar este programa se consigue que un usuario pueda escribir en el fichero de claves (/etc/shadow, no confundirlo con /etc/passwd) pero sin tener que dar permisos de escritura al fichero, lo cual seria un gran agujero de seguridad

Aunque la característica setuid es muy útil en muchos casos, puede plantear un riesgo de seguridad si el atributo setuid se asigna a programas ejecutables que no fueron diseñados cuidadosamente. Los usuarios pueden explotar vulnerabilidad en programas defectuosos para conseguir privilegios elevados permanentemente, o ejecutar de forma no intencionada un troyano.

El atributo setgid permitirá cambiar los privilegios basados en el grupo en un proceso, del mismo modo que setuid hace para privilegios basados en el usuario.

How to set sticky bit

An example of the sticky bit is the /tmp directory. Use the ls -ld /tmp command to view the permissions:

# ls -ld /tmp
drwxrwxrwt  24 root root  4096 2017-10-30 22:00 tmp

The t at the end symbolizes that the sticky bit is set. A file created in the /tmp directory can only be removed by its owner, or the root user. For example, run the following command to set the sticky bit on the folder1 folder:

# chmod a+t folder1

Alternatively, prepend a 1 to the mode of a directory to set the sticky bit:

# chmod 1777 folder1

The permissions should be read, write, and execute for the owner, group, and everyone else, on directories that have the sticky bit set. This allows anyone to cd into the directory and create files.

How to set SUID bit on a file?

You must be the owner of the file or the root user to set the setuid bit. Run the following command to set the setuid bit:

# chmod u+s file1

View the permissions using the ls -l command:

# ls -l file1
-rwSrw-r-- 1 user1 user1 0 2017-10-29 21:41 file1

Note the capital S. This means there are no execute permissions. Run the following command to add execute permissions to the file1 file, noting the lower case s.

# chmod u+x file1
# ls -l file1
-rwsrw-r-- 1 user1 user1 0 2017-10-29 21:41 file1

Note the lower case s. This means there are execute permissions.

Alternatively, you can set the setuid bit using the numeric method by prepending a 4 to the mode. For example, to set the setuid bit, read, write, and execute permissions for the owner of the file1 file, run the following command:

# chmod 4700 file1

Интеграция, адаптация и прочие непонятные слова

В итоге мы таки получили рута! При последующем посещении web-шелла мы уже
будем рутом (при условии, что наш суид-шелл не увидит рут, и не удалит его).

Однако шелл у нас получился довольно примитивный; чтобы интегрировать наши
прелести в привычные шелла типа r57, c99, WSO2 и т.д., принцип работы тот же.

На диске ты найдешь подправленный
мной код шелла r57. Единственное, что отличает подправленный r57 от того,
который мы сегодня написали, – в r57 я эксплойт и суид-шелл скомпилировал,
перевел полученные бинарники в base64 и вставил полученный код в сам шелл. Далее
мы расшифровываем base64 код и сохраняем в файл. Таким образом, у нас получается
один файл, – это удобнее в плане транспортирования и заливки.

С интеграцией в другие шеллы разобрались, осталось разобрать ситуацию с
применением эксплойтов для других операционных систем и других версий. Причина,
по которой я выбрал для теста FreeBSD – в том, что этот эксплойт под версию 7.1
и 7.2 результатом своей работы возвращает не /bin/sh, которой мы бы пользовались
при простом бекконекте, а возвращает uid и gid 0 для текущего процесса. То есть
является универсальным. Последний способ для нас удачен, так как мы можем
использовать его непосредственно из web’a. Так мы пришли к выводу, что для
использования эксплойта с нашими условиями необходимо переписать эксплойты,
чтобы они устанавливали uid, gid. Как это организовать — история уже для другой
статьи.

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

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

Adblock
detector