Linux privilege escalation exploit

Linux privilege escalation exploit

LES: Linux privilege escalation auditing tool

Details about LES usage and inner workings:

Additional resources for the LES:

LES tool is designed to assist in detecting security deficiencies for given Linux kernel/Linux-based machine. It provides following functionality:

Assessing kernel exposure on publicly known exploits

Tool assesses (using heuristics methods discussed in details here) exposure of the given kernel on every publicly known Linux kernel exploit. Example of tool output:

For each exploit, exposure is calculated. Following ‘Exposure’ states are possible:

Highly probable — assessed kernel is most probably affected and there’s a very good chance that PoC exploit will work out of the box without any major modifications.

Probable — it’s possible that exploit will work but most likely customization of PoC exploit will be needed to suit your target.

Less probable — additional manual analysis is needed to verify if kernel is affected.

Unprobable — highly unlikely that kernel is affected (exploit is not displayed in the tool’s output)

Verifying state of kernel hardening security measures

LES can check for most of security settings available by your Linux kernel. It verifies not only the kernel compile-time configurations (CONFIGs) but also verifies run-time settings (sysctl) giving more complete picture of security posture for running kernel. This functionality is modern continuation of —kernel switch from checksec.sh tool by Tobias Klein. Example of tool output:

Assess exposure of the Linux box on publicly known exploits:

Show state of security features on the Linux box:

Assess exposure of Linux kernel on publicly known exploits based on the provided ‘uname’ string (i.e. output of uname -a command):

For more usage examples, see here.

You hopefully now know what LES is and what it can do for you. Now see what you can do for LES:

  • Add newly published Linux privilege escalation exploits to it.
  • Test existing exploits on various Linux distributions with multiple kernel versions, then document your findings in a form of Tags in LES, e.g. of a tag: ubuntu=12.04 which states: tagged exploit was verifed to work correctly on Ubuntu 12.04 with kernels: 3.2.0-23-generic, 3.2.0-29-generic, 3.5.0-23-generic and 3.5.0-29-generic;. With this tag added LES will automatically highlight and bump dynamic Rank of the exploit when run on Ubuntu 12.04 with one of listed kernel versions. This will help you (and others) during pentests to rapidly identify critically vulnerable Linux machines.
  • Published exploits are often written only for PoC purposes only for one (or couple of) specific Linux distributions and/or kernel version(s). Pick sources of the exploit of choice and customize it to run on different kernel version(s). Then add your customized version of exploit as ext-url entry to LES and modify Tags to reflect newly added targets. See this article for an excellent example of adapting specific PoC exploit to different kernel versions.
  • Conduct source code analysis of chosen kernel hardening security measure then add it to the FEATURES array (if not already there) and publish your analysis at: https://github.com/mzet-/les-res/blob/master/features/ .md .

bcoles for his excellent and frequent contributions to LES.

Источник

Linux privilege escalation exploit

Linux — Privilege Escalation

There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escelation vectors. Here are a few:

  • Kernel and distribution release details
  • System Information:
    • Hostname
    • Networking details:
    • Current IP
    • Default route details
    • DNS server information
  • User Information:
    • Current user details
    • Last logged on users
    • Shows users logged onto the host
    • List all users including uid/gid information
    • List root accounts
    • Extracts password policies and hash storage method information
    • Checks umask value
    • Checks if password hashes are stored in /etc/passwd
    • Extract full details for ‘default’ uid’s such as 0, 1000, 1001 etc
    • Attempt to read restricted files i.e. /etc/shadow
    • List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
    • Basic SSH checks
  • Privileged access:
    • Which users have recently used sudo
    • Determine if /etc/sudoers is accessible
    • Determine if the current user has Sudo access without a password
    • Are known ‘good’ breakout binaries available via Sudo (i.e. nmap, vim etc.)
    • Is root’s home directory accessible
    • List permissions for /home/
  • Environmental:
    • Display current $PATH
    • Displays env information
  • Jobs/Tasks:
    • List all cron jobs
    • Locate all world-writable cron jobs
    • Locate cron jobs owned by other users of the system
    • List the active and inactive systemd timers
  • Services:
    • List network connections (TCP & UDP)
    • List running processes
    • Lookup and list process binaries and associated permissions
    • List inetd.conf/xined.conf contents and associated binary file permissions
    • List init.d binary permissions
  • Version Information (of the following):
    • Sudo
    • MYSQL
    • Postgres
    • Apache
      • Checks user config
      • Shows enabled modules
      • Checks for htpasswd files
      • View www directories
  • Default/Weak Credentials:
    • Checks for default/weak Postgres accounts
    • Checks for default/weak MYSQL accounts
  • Searches:
    • Locate all SUID/GUID files
    • Locate all world-writable SUID/GUID files
    • Locate all SUID/GUID files owned by root
    • Locate ‘interesting’ SUID/GUID files (i.e. nmap, vim etc)
    • Locate files with POSIX capabilities
    • List all world-writable files
    • Find/list all accessible *.plan files and display contents
    • Find/list all accessible *.rhosts files and display contents
    • Show NFS server details
    • Locate *.conf and *.log files containing keyword supplied at script runtime
    • List all *.conf files located in /etc
    • Locate mail
  • Platform/software specific tests:
    • Checks to determine if we’re in a Docker container
    • Checks to see if the host has Docker installed
    • Checks to determine if we’re in an LXC container

Looting for passwords

Files containing passwords

Old passwords in /etc/security/opasswd

The /etc/security/opasswd file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them.

⚠️ Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes

Last edited files

Files that were edited in the last 10 minutes

Источник

Расширение локальных привилегий в Linux при помощи эксплоита для ядра

Получение прав суперпользователя сродни Граалю для специалистов, занимающихся эксплуатацией уязвимостей в Linux.

Получение прав суперпользователя сродни Граалю для специалистов, занимающихся эксплуатацией уязвимостей в Linux. Так же как и системная учетная запись в Windows, в Linux аккаунт root дает полный административный доступ к операционной системе. Однако иногда даже при помощи эксплоита, который сработал успешно, мы получаем низкоуровневый шелл, и нужно нечто, позволяющее расширить полномочия, для получения доступа к более привилегированным аккаунтам и полного контроля над целевой системой.

Шаг 1: Сбор информации и поиск эксплоита

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

В этой статье будет рассмотрено решение этой задачи при помощи эксплоита для ядра. Поскольку у нас уже есть шелл, воспользуемся командой uname –a для получения первоначальной информации о системе. Кроме того, команда lsb_release –a также может оказаться полезной для выяснения дистрибутива и сведений о релизе.

Мы выяснили, что система работает на базе Ubuntu 8.04 с ядром 2.6.24, и теперь приступаем к поиску эксплоита. В Kali есть локальная версия сайта Exploit-DB, представляющая собой базу данных, которая содержит эксплоиты, код и публикации. Поиск по базе осуществляется прямо из терминала при помощи команды searchsploit:

Поскольку мы ищем эксплоит для расширения привилегий, то используем ключевое слово privilege, а затем уточняем результаты поиска при помощи утилиты grep (флаг –i говорит о том, что не нужно учитывать регистр). Например, мы можем воспользоваться эксплоитом 8572.c, который эксплуатирует брешь в менеджере устройств UDEV и позволяет выполнять код через непроверенные сообщения в сокетах Netlink. Просто копируем путь к эксплоиту и при помощи команды locate выясняем полный путь:

Как вы могли догадаться, эксплоит написан на С, однако мы не будем углубляться в дебри, а просто скомпилируем исходник. Хотя если вы знакомы с языком С, будет совсем не лишним ознакомиться с логикой работы эксплоита. Чтобы получить базовое представление о том, чем мы будем пользоваться, при помощи команды cat заглянем вовнутрь файла и посмотрим комментарии:

Шаг 2: Доставка эксплоита в целевую систему

Для начала эксплоит нужно скопировать на целевую машину. Самый простой способ решить эту задачу – настроить локальный веб-сервер (например, Apache), подключиться к этому серверу с целевой системы и загрузить файл. Однако вначале нужно выполнить подготовительную работу.

Во-первых, убедитесь, что сервер поднят и работает в Kali. В терминале запустите команду service apache2 restart. Затем нужно создать символическую ссылку между директорией, где хранится и эксплоит и папкой с файлами сервера, при помощи следующей команды:

Теперь наш эксплоит доступен для загрузки.

В целевой системе эксплоит будет запускаться из директории /tmp, и нам нужно вначале создать исполняемый файл. В Kali введите команду nano /var/www/html/run и добавьте следующие строки:

После запуска этого файла для подключения и организации шелла к системе, в которой работает Kali, через IP-адрес и порт 4321, будет использоваться Netcat. Нажмите Ctrl-X, затем Y и далее клавишу Enter для сохранения файла.

Теперь мы готовы к загрузке файлов на целевую машину. Используя полученный ранее низкоуровневый шелл, переходим в директорию /tmp, при помощи утилиты wget подключаемся к веб-серверу, на котором установлен Kali, и загружаем файлы все необходимые файлы.

Шаг 3: Компиляция и запуск эксплоита

Когда все файлы, необходимые для запуска эксплоита, оказались в целевой системе, остался последний шаг – компиляция исходника. Мы не будем погружаться в дебри программирования, но, если коротко – исполняемый файл должен быть собран из исходного текста. В нашем случае компиляция будет осуществляться при помощи GCC (GNU Compiler Collection; Набор компиляторов проекта GNU).

Для компиляции файла 8572.c используйте следующую команду (флаг –o задает имя конечного исполняемого файла):

gcc — o exploit 8572. c

Если в процессе компиляции не будет найден динамический линковщик, воспользуйтесь флагом –B для указания директории, где находится ld:

После компиляции при помощи команды ls проверяем, что исполняемый файл появился.

В комментариях файла 8572.c говорилось, что нам нужно найти PID (идентификатор процесса) сокета Netlink, который обычно равен идентификатору процесса UDEVD минус 1. Запускаем команду cat /proc/net/netlink и ищем ненулевой идентификатор. Проверяем найденное значение при помощи команды ps aux | grep udev. Идентификатор процесса UDEVB должен быть на единицу больше.

Затем нужно настроить слушатель на машине с Kali, с которым будет устанавливаться соединение после запуска скрипта run на целевой системе. На машине с Kali введите команду nc -lvp 4321, после чего начнут отслеживаться входящие подключения.

После настройки слушателя, можно приступать к запуску эксплоита. Вспоминаем, что нужно передать PID сокета Netlink в качестве аргумента, который в нашем случае равен 2459 (у вас это значение может отличаться). Выполняем следующую команду в непривилегированном шелле:

Через некоторое время должно появиться подключение к нашему слушателю, и мы сможем запускать разные команды, как, например, id и whoami для просмотра информации о пользователе. Далее становится понятно, что у нас появился доступ с правами суперпользователя, и мы можем выполнять любые операции в целевой системе.

Источник

Linux privilege escalation exploit

dirty_sock: Linux Privilege Escalation (via snapd)

In January 2019, current versions of Ubuntu Linux were found to be vulnerable to local privilege escalation due to a bug in the snapd API. This repository contains the original exploit POC, which is being made available for research and education. For a detailed walkthrough of the vulnerability and the exploit, please refer to the blog posting here.

Ubuntu comes with snapd by default, but any distribution should be exploitable if they have this package installed. You can easily check if your system is vulnerable. Run the command below. If your snapd is 2.37.1 or newer, you are safe.

Note that some systems return the distribution package version of snapd when you run this command, as opposed to the upstream version shown in the example above. If your snapd version has a reference to something like an Ubuntu version number appended to it (example: 2.34.2ubuntu0.1 or 2.35.5+18.10.1 then please consult this link to determine if you are running a patched version.

Version One (requires outbound Internet and running SSH service)

This exploit bypasses access control checks to use a restricted API function (POST /v2/create-user) of the local snapd service. This queries the Ubuntu SSO for a username and public SSH key of a provided email address, and then creates a local user based on these value.

Successful exploitation for this version requires an outbound Internet connection and an SSH service accessible via localhost.

To exploit, first create an account at the Ubuntu SSO. After confirming it, edit your profile and upload an SSH public key. Then, run the exploit like this (with the SSH private key corresponding to public key you uploaded):

Version Two (does not require Internet or SSH, but may trigger a snapd upgrade)

This exploit bypasses access control checks to use a restricted API function (POST /v2/snaps) of the local snapd service. This allows the installation of arbitrary snaps. Snaps in «devmode» bypass the sandbox and may include an «install hook» that is run in the context of root at install time.

dirty_sockv2 leverages the vulnerability to install an empty «devmode» snap including a hook that adds a new user to the local system. This user will have permissions to execute sudo commands.

As opposed to version one, this does not require the SSH service to be running. It will also work on newer versions of Ubuntu with no Internet connection at all, making it resilient to changes and effective in restricted environments.

Note for clarity: This version of the exploit does not hide inside a malicious snap. Instead, it uses a malicious snap as a delivery mechanism for the user creation payload. This is possible due to the same uid=0 bug as version 1

This exploit should also be effective on non-Ubuntu systems that have installed snapd but that do not support the «create-user» API due to incompatible Linux shell syntax.

Some older Ubuntu systems (like 16.04) may not have the snapd components installed that are required for sideloading. If this is the case, this version of the exploit may trigger it to install those dependencies. During that installation, snapd may upgrade itself to a non-vulnerable version. Testing shows that the exploit is still successful in this scenario. See the troubleshooting section for more details.

To exploit, simply run the script with no arguments on a vulnerable system.

If using version two, and the exploit completes but you don’t see your new account, this may be due to some background snap updates. You can view these by executing snap changes and then snap change # , referencing the line showing the install of the dirty_sock snap. Eventually, these should complete and your account should be usable.

Version 1 seems to be the easiest and fastest, if your environment supports it (SSH service running and accessible from localhost).

Non-vulnerable systems will output something like the following:

Please open issues for anything weird.

The issue was reported directly to the snapd team via Ubuntu’s bug tracker. You can read the full thread here.

I was very impressed with Canonical’s response to this issue. The team was awesome to work with, and overall the experience makes me feel very good about being an Ubuntu user myself.

Public advisory links:

Note: I am posting information only to this GitHub repo, my blog at initblog.com, and my team’s blog at shenaniganslabs.io. Any site masquerading as an official source is unfortunately beyond my control.

About

Linux privilege escalation exploit via snapd (CVE-2019-7304)

Источник

Читайте также:  Рабочий стол выходит за рамки монитора windows 10 radeon
Оцените статью