<strong>продуктовые партиции</strong>

XDA Форумы

Альтернативный браузер

Android 9 и выше включают поддержку создания разделов product с использованием Android-системы сборки. Ранее Android 8.x требовал отделения компонентов, специфичных для SoC, от раздела system к разделу vendor, не выделяя место для компонентов, специфичных для OEM, построенных из системы сборки Android 9 и выше предоставляют дополнительные разрешения и функции белого списка, применяемые к priv-apps на различных разделах.

Разрешенные приложения

Привилегированные приложения – это системные приложения, находящиеся в каталоге priv-app на разделе образа системы. Разделы, используемые для выпусков Android, следующие:

  • Android 9 и выше: /system, /product, /vendor

  • Android 8.1 и ниже: /system

Файл privapp-permissions.xml может только предоставлять или отвергать разрешения для привилегированных приложений на том же разделе. Например, если приложение на разделе /product запрашивает привилегированные разрешения, запрос может быть предоставлен или отклонен только файлом privapp-permissions.xml на /product.

Привилегированные разрешения

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

Что такое повышение привилегий?

Цель

Почему нам нужно проводить повышение привилегий

Какие техники используются для повышения привилегий?

  1. Эксплойты ядра
  2. Использование служб, работающих от имени root
  3. Эксплуатация исполняемых файлов SUID
  4. Использование прав/пользователя SUDO
  5. Эксплуатация плохо настроенных заданий Cron
  6. Использование пользователей с . в их ПУТИ

Что такое атака на повышение привилегий?

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

Как работает повышение привилегий?

  1. Эксплуатация учетных данных
  2. Уязвимости и эксплойты
  3. Неправильная конфигурация
  4. Вредоносное программное обеспечение
  5. Социальная инженерия

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

Как начинаются атаки на повышение привилегий?

Атака на повышение привилегий начинается с того, что злоумышленники получают доступ в среду. Злоумышленник может получить точку опоры, используя отсутствующие обновления безопасности, социальную инженерию или другие методы, начиная с простого проброса пароля (или проброса учетных данных) до современных техник, использующих генеративное искусственное интеллекта. После успешного проникновения злоумышленники обычно проводят наблюдение и ждут подходящего момента, чтобы продолжать свою миссию.

Привилегированные атаки на повышение привилегий в кибербезопасности

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

Методы компрометации привилегий и учетных данных

In many environments, especially for nonhuman accounts, account lockout attempts can hamper business runtime. Therefore, many disable this security setting. Consequently, if logon failures are not being monitored in event logs, a dictionary attack is an effective attack vector for a threat actor. This is especially true if privileged accounts do not have this setting enabled as a mitigation strategy.

Brute Force Password Attacks

Brute force password attacks are the least efficient method for trying to hack a password, so they are generally used as a last resort. Brute force password attacks utilize a programmatic method to try all the possible combinations for a password. This method is efficient for passwords that are short in string (character) length and complexity but can become infeasible—even for the fastest modern systems—with a password of eight characters or more.

If a password only has alphabetical characters, all in capitals or all in lowercase (not mixed), it will take 8,031,810,176 guesses. You have a better chance of winning the lottery! This estimation also assumes the threat attacker knows the length of the password and complexity requirements. Other factors include numbers, case sensitivity, and special characters in the localized language.

While a brute force attack with the proper parameters will eventually find the password, the time and computing power required may render the brute force test futile. And the time it takes to perform the attacks is not only based on the speed required to generate all the possible password permutations, but also the challenge and response time of a failure on the target system. The response lag time is what really matters when trying to brute force a password.

Enforce an allowlist

After you create your allowlists, enable runtime enforcement by setting the build property ro.control_privapp_permissions=enforce.

Allowlisting is required only for permissions declared by apps withpackage="android". The ro.control_privapp_permissions property state must adhere toSection 9.1 Permissions in the Compatibility Definition Document (CDD).

Objective

This blog is all about security issues that could lead to a successful privilege escalation attack on any Linux based systems. We will also discuss about how an attacker can use the possible known techniques to successfully elevate his privileges on a remote host and how we can protect our systems from any such attack. At the end, there will be some examples to demonstrate how we achieved privilege escalation on different Linux systems under different conditions.

It is not a cheat sheet for enumeration using Linux commands, instead the blog is particularly aimed at helping beginners understand the fundamentals of Linux privilege escalation with examples.

Privilege escalation is all about proper enumeration. There are multiple ways to perform the same tasks that I have shown in the examples.

Permission model in Linux

Linux privilege escalation permission model

Linux is inherited from UNIX, the concept of ownership and file permissions. File permissions are one way the system protects itself from malicious tampering. On a UNIX web server, every single file and folder stored on the hard drive has a set of permissions associated with it, which says who is allowed to do what with the file.

Linux privilege escalation permission model

Implementing product partitions

  • BOARD_USES_PRODUCTIMAGE

  • BOARD_PRODUCTIMAGE_PARTITION_SIZE

  • BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE

  • PRODUCT_PRODUCT_PROPERTIES for /product/build.prop. These must be within a $(call inherit-product path/to/device.mk), as in PRODUCT_PRODUCT_PROPERTIES += product.abc=ok.

Installing a module to the product partition

  • product_specific: true in Android.bp

  • LOCAL_PRODUCT_MODULE := true in Android.mk

Enabling verified boot

Why we Need to Perform Privilege Escalation?

We need to perform Privilege esclation to:

  • Read/Write any sensitive file

  • Persist easily between reboots

  • Insert a permanent backdoor

Exploiting Users With ‘.’ in their PATH

With ‘.’ in path – program

Without ‘.’ in path – ./program

This happens because Linux first searches for the program in the current directory when ‘.’ is added in the PATH at the beginning and then searches anywhere else.

> Inside a file saved as ‘ls’, a code has been added which will print “Hello world”

<strong>продуктовые партиции</strong>

<strong>продуктовые партиции</strong>

$ ls – executed ./ls file instead of running list command.

<strong>продуктовые партиции</strong>

Here we conclude a successful privilege escalation attack on any Linux based systems. Now you know how attackers can leverage certain techniques to elevate their privileges, which can be further utilized by you to protect your systems and applications from intrusion and attacks.
















What is Privilege Escalation?

While organizations are statistically likely to have more Windows clients, Linux privilege escalation attacks are significant threats to account for when considering an organization’s information security posture. Consider that an organization’s most critical infrastructure, such as web servers, databases, firewalls, etc. are very likely running a Linux operating system.

Compromises to these critical devices have the potential to severely disrupt an organization’s operations, if not destroy them entirely. Furthermore, Internet of Things (IoT) and embedded systems are becoming ubiquitous in the workplace, thereby increasing the number of potential targets for malicious hackers. Given the prevalence of Linux devices in the workplace, it is of paramount importance that organizations harden and secure these devices.

Add an allowlist

Permission allowlists for apps can be listed in a single XML file or in multiple XML files located in the frameworks/base/etc/permissions directory:

  • /etc/permissions/privapp-permissions-OEM_NAME.xml

  • /etc/permissions/privapp-permissions-DEVICE_NAME.xml

  • Permissions for apps already included in theAndroid Open Source Project (AOSP) tree are listed in /etc/permissions/privapp-permissions-platform.xml.

  • For other apps, use files of the form,/etc/permissions/privapp-permissions-DEVICE_NAME.xml.

Customize an allowlist

AOSP includes an allowlist implementation that can be customized as needed.

If a permission must be denied, edit the XML to use a deny-permission tag instead of a permissiontag. For example:

<!– This XML file declares which signature|privileged permissions to grant to

privileged apps that come with the platform –>

<permissions>

  <privapp-permissions package="com.android.backupconfirm">

    <permission name="android.permission.BACKUP"/>

    <permission name="android.permission.CRYPT_KEEPER"/>

  </privapp-permissions>



  <privapp-permissions package="com.android.cellbroadcastreceiver">



    <!-- Don't allow the application to interact across users -->



    <deny-permission name="android.permission.INTERACT_ACROSS_USERS"/>

    <permission name="android.permission.MANAGE_USERS"/>

    <permission name="android.permission.MODIFY_PHONE_STATE"/>

    <permission name="android.permission.READ_PRIVILEGED_PHONE_STATE"/>

    <permission name="android.permission.RECEIVE_EMERGENCY_BROADCAST"/>

  </privapp-permissions>

...

Find missing permissions

To find missing permissions when starting a new device, enable transitional log mode:

ro.control_privapp_permissions=log

PackageManager: Privileged permission {PERMISSION_NAME} for package {PACKAGE_NAME} – not in privapp-permissions allowlist

Больше проверок:  Запущен цифровой сервис аутентификации по протоколу Unified Testing Portal

All violations must be addressed by adding the missing permissions to the appropriate allowlists. Note that in:

  • Android 9 and higher, violations of privileged permissions prevent the device from starting. Instead, you must explicitly allow or deny all privileged permissions.

  • Android 8.0 and lower, missing permissions are not granted to the affected apps despite being in the priv-app path.

Pass-the-Hash (PtH)

Modern systems can defend against Pass-the-Hash attacks in a variety of ways. However, changing the password frequently (after every interactive session) is a good defense to keep the hash different between the sessions. Password management solutions that frequently rotate passwords or customize the security token are good defenses against this technique.

Security Questions

However, many organizations also use common security questions and thus present potentially far-reaching risks. For instance, the more places and people that know the answers to your security questions, the more likely they can be answered by someone else. Additionally, if the information is public, then it is not a legitimate security question at all.

Credential Stuffing

Password Spraying

Password spraying is a credential-based attack that tries to access a multitude of accounts by using a few common passwords. This is conceptually the opposite of a brute force password attack.

Password Changes and Resets

How often do you change your passwords? Every 30 or 90 days when prompted to at work? How about at home? How often do you rotate passwords for your banking, e-commerce, streaming, or social media accounts? Probably not often, if ever, and surprisingly, that might be okay!

Without a password manager, keeping all of one’s passwords unique and complex is a daunting task—even for the most seasoned security professional.

  • Easily guessable, pattern-based passwords (as described earlier) when reset

  • Passwords reset via email or text message and kept by the end user

  • Passwords reset by the help desk that are reused every time a password reset is requested

  • Automated password resets blindly given due to account lockouts

  • Passwords that are verbally communicated and can be heard aloud

  • Complex password resets that are written down by the end user

  • The password should be random and meet the complexity requirements per business policy.

  • The password should be changed by the end user after the first logon and require, if implemented, two-factor or MFA to validate.

  • Password reset requests should always come from a secure location.

  • Public websites for businesses (not personal) should never have “Forgot Password” links.

  • Password resets via email assume the end user maintains access to email in order to receive the new password. If the email password itself requires resetting, another method needs to be established.

  • Do not use SMS text messages—they are not sufficiently secure for sending password reset information.

  • If possible, password resets should be ephemeral. That is, the password reset should only be active for a predefined duration. If the end user has not accessed the account again within the predefined amount of time, an account lockout will occur.

While changing passwords frequently remains a security best practice for privileged accounts, resetting passwords and transmitting them through unsecure mediums is not. For the individual, a simple password reset can be the difference between a threat actor trying to own your account and a legitimate reason.

Access Token manipulation

UAC (User Account Control) bypass techniques

  • Deny the operation to continue and terminate the process immediately

  • Allow the user to perform the action if they are in the local administrators group

  • Prompt the user to supply credentials that have privileges to continue the operation.

Identity Enumeration

  • In an application login page, based on a failed authentication response

  • ‘Forgot Password’ functionality that may trigger a workflow or reply “no account found”

Essentially, the threat actor is looking for the server’s response based on the validity of submitted credentials to determine if the account they tried is valid. This is a common response mechanism for many applications.

Finally, if the threat actor can determine the naming pattern for a company (i.e., first initial last name), then building a list for enumeration and future attacks becomes much easier.

Is there a way to make an app into a system app?

  • Aserar

  • Aug 4, 2023

I’m using a AOSP gapps build custom rom and the Google app isn’t installed and apparently installing it as a regular app not a system app causes an issue with Google assistant. Is there a way to make it into a system app? I found different ways but all outdated and none of them worn on Android 13. Tried to flash gapps but since the rom is not vanilla it gave me an error

PS: Changing the rom is not an option

Any ideas?

xXx yYy

If Android OS is rooted then move the app in question to /system/app or /system/priv-app.

You may use Link2SD app to perform this

convert-user-app-to-system-app.png

If Android OS is rooted then move the app in question to /system/app or /system/priv-app.

You may use Link2SD app to perform this

convert-user-app-to-system-app.png

This is one of the outdated methods. Won’t work on any newer versions of android.

fastxcrust

I’m using a AOSP gapps build custom rom and the Google app isn’t installed and apparently installing it as a regular app not a system app causes an issue with Google assistant. Is there a way to make it into a system app? I found different ways but all outdated and none of them worn on Android 13. Tried to flash gapps but since the rom is not vanilla it gave me an error

PS: Changing the rom is not an option

Any ideas?

try this

Also one of the outdated methods I have tried.

Droidriven

I’m using a AOSP gapps build custom rom and the Google app isn’t installed and apparently installing it as a regular app not a system app causes an issue with Google assistant. Is there a way to make it into a system app? I found different ways but all outdated and none of them worn on Android 13. Tried to flash gapps but since the rom is not vanilla it gave me an error

PS: Changing the rom is not an option

Any ideas?

Extract your ROM zip, find the system/app or system/priv-app folder and place the apk in whichever of these two folders that you want. Then recompile/zip your ROM back into a flashable zip and flash it.

Extract your ROM zip, find the system/app or system/priv-app folder and place the apk in whichever of these two folders that you want. Then recompile/zip your ROM back into a flashable zip and flash it.

I’ll give this a try. Thank you

Droidriven

I’ll give this a try. Thank you

If you are flashing a ROM zip and a Gapps zip, you could put the apps in the Gapps zip instead of the ROM, either way, it would get flashed to system, whichever you find easiest to edit.

If you are flashing a ROM zip and a Gapps zip, you could put the apps in the Gapps zip instead of the ROM, either way, it would get flashed to system, whichever you find easiest to edit.

I tried this actually but the rom is gapps variant and flashing a gapps zip (even though it only has a missing app) caused errors rendering the OS unusable. As for including the apk into the rom zip, I’m not up to date on cooking roms but when I tried to unpack the bin file with android Image Kitchen 3.8 it says unrecognized file! Should I use a different software?

IMPORTANT:

  • You must have root access to your device in order to use thiese ADB commands:

adb devices

adb root

adb shell "pm set-install-location system"

adb install <PATH-TO-APK-FILE-ON-COMPUTER>

adb shell "chmod 7777 /system/app/<NAME-OF-APK-FILE>"

adb shell "pm set-install-location internal"

adb reboot

  • A rooted device
  • A root-enabled app like Magisk
  • The APK file of the app you want to install as a system-app

Once you have all of the necessary requirements, follow these steps to install the user-app as a system-app:

  1. Install the root-enabled app on your device.
  1. Open the root-enabled app and grant it root permissions.
  1. Locate the APK file of the user-app you want to install as a system-app.
  1. In the root-enabled app, select the APK file and tap on the "Install as System App" button.
  1. The root-enabled app will change the SELinux context of the user-app and install it as a system-app.
  1. Reboot your device.

So method 1: Though adb had root access, when I issue (adb shell "pm set-install-location system") I get an error that says install location has to be a number. Not sure how to get it to flash to system.

Больше проверок:  Проверки на 2023 год план и график проверок краснодарский край по инн

Method 2: I’m not sure which app could be used as root-enabled app. Does magisk have a file browser feature like that?

Renate

Recognized Contributor / Inactive Recognized Dev

There is always the "nuclear option".

You can re-sign everything on your system with your own signing.

This will probably will not do good things with Google services as they check the signing.

Droidriven

I tried this actually but the rom is gapps variant and flashing a gapps zip (even though it only has a missing app) caused errors rendering the OS unusable. As for including the apk into the rom zip, I’m not up to date on cooking roms but when I tried to unpack the bin file with android Image Kitchen 3.8 it says unrecognized file! Should I use a different software?

Extract with 7zip on PC or ZArchiver app on Android.

There is always the "nuclear option".

You can re-sign everything on your system with your own signing.

This will probably will not do good things with Google services as they check the signing.

Doesn’t sound ideal and above my pay grade lol

Extract with 7zip on PC or ZArchiver app on Android.

No mate inside the main zip files contained in a single .BIN file incompatible with windows archivers

IMPORTANT:

  • You must have root access to your device in order to use thiese ADB commands:

adb devices

adb root

adb shell "pm set-install-location system"

adb install <PATH-TO-APK-FILE-ON-COMPUTER>

adb shell "chmod 7777 /system/app/<NAME-OF-APK-FILE>"

adb shell "pm set-install-location internal"

adb reboot

  • A rooted device
  • A root-enabled app like Magisk
  • The APK file of the app you want to install as a system-app

Once you have all of the necessary requirements, follow these steps to install the user-app as a system-app:

  1. Install the root-enabled app on your device.
  1. Open the root-enabled app and grant it root permissions.
  1. Locate the APK file of the user-app you want to install as a system-app.
  1. In the root-enabled app, select the APK file and tap on the "Install as System App" button.
  1. The root-enabled app will change the SELinux context of the user-app and install it as a system-app.
  1. Reboot your device.

I have tried method 1 ..got some Error: install location has to be a number..Please help me out how to convert apk as system app in android 13 with permissions .

Masleyko

i actually found the way ..https://www.getdroidtips.com/install-third-party-apps-system-apps-android/

using this guide..

on android 14 and on crdroid 10

Yeah ..Thank you ..I will try this ..

But Permissions are not granted for the system app in that ..how can we get permissions for that system app even after factory reset.

Masleyko

Yeah ..Thank you ..I will try this ..

But Permissions are not granted for the system app in that ..how can we get permissions for that system app even after factory reset.

you mean permisions for rwx for folder or permissions for app

3ncrypt3d_Droid

I am also having this same trouble with Google assistant on Android 13 CR droid …When I had issues with previous versions of Android like this I used link2 SD and it worked flawlessly but now not so much and would greatly appreciate another way to convert user apps to system apk’s.

Similar threads

Malware

  • Bugs are a type of error, flaw, vulnerability, or failure that produces an undesirable or unexpected result due to poor software coding or unexpected operational conditions.

  • Worms rely on bugs, vulnerabilities, and exploits to deliver a payload and propagate themselves to other resources.

  • A virus is any piece of malicious software loaded onto your website or computer without your knowledge.

  • Bots are malicious software programs created to perform a specific set of tasks with a known intent.

  • A Trojan disguises itself as a normal file or application and tricks the user into downloading, opening, or executing it.

  • Ransomware denies access to your files, typically through encryption, and demands a ransom (usually in the form of digital and cryptocurrencies like Bitcoin) to release the threat actor’s grip on your data.

  • Adware is a type of malware used to automatically display unwanted, and potentially illegal, advertisements to an end user.

  • Spyware is a type of malware used to conduct surveillance on a user’s activity. These functions can include monitoring the user’s screen, capturing keystrokes, and even enabling the asset’s camera and microphone for surveillance.

How to Prevent and Stop Privilege Escalation Attacks

Because privilege escalation attacks can start and advance in a myriad of different ways, multiple defense strategies and tactics are required for protection. However, implementing an identity-centric approach and privileged access management controls will help your organization protect against the broadest range of attacks and go the furthest to reducing the attack surface. Here are some best practices:

  1. Fully manage the identity lifecycle, including provisioning and de-provisioning of identities and accounts to ensure there are no orphaned accounts to hijack.

  2. Use a password management solution to consistently apply strong credential management practices (discovery, vaulting, central management, check-in, check-out) for both humans and machines. This also entails eliminating default and hardcoded credentials.

  3. Enforce least privilege: Remove admin rights from users and reduce application and machine privileges to the minimum required. Just-in-time access should also be implemented to reduce persistent or standing privileges.

  4. Apply advanced application control and protection to enforce granular control over all application access, communications, and privilege elevation attempts.

  5. Monitor and manage all privileged sessions to detect and quickly address any suspicious activity that might indicate a hijacked account or an illicit attempt at privilege escalation or lateral movement.

  6. Harden systems and applications: This complements the principle of least privilege and can involve configuration changes, removing unnecessary rights and access, closing ports, and more. This improves system and application security and helps prevent and mitigate the potential for bugs that leave vulnerability to injection of malicious code (i.e., SQL injections), buffer overflows, etc. or other backdoors that could allow privilege escalation.

  7. Vulnerability management: Continuously identify and address vulnerabilities, such as with patching, fixing misconfigurations, eliminating default and/or embedded credentials, etc.

  8. Secure remote access should always be monitored and managed for any form of privileged access since attacks can occur horizontally and vertically to exploit privileges.

About product partitions

Using separate partitions has some disadvantages, such as managing disk space (a limited amount of space must remain reserved for future growth) and maintaining a stable application binary interface (ABI) between partitions. Before deciding to use product partitions, take time to consider your unique AOSP implementation and possible mitigation tactics (such as repartitioning a device during an over-the-air (OTA) update, which isn’t done by Google but is done by some OEMs).Dynamic partitioning will be a good solution for this.

Product partitions and permissions

In Android 9 and higher, a change in the permissions and whitelisting process affects how you grant priv-apps permissions on your `product` partitions. The permissions.xml file must reside in the same partition as the priv-apps. Placing apermissions.xml file in the system partition for priv-apps doesn’t extend those permissions to priv-apps in the product partition, even though the former is an extension of the latter. For details on the permissions and whitelisting processes, seePrivileged Permission Allowlisting.

Legacy /oem vs /product

We have two kinds of attributes of the product partition depending on the product interface enforcement. Also, the product partition is different than the legacy oem partition:

| Partition | Attributes |

| —————————– | ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- |

| oem | Not updateable; usually flashed once at the factory. Built per small variations, such as branding and color. Having different oem partition contents doesn’t mean the product software is different. The system partition doesn’t depend on the oem partition. (It uses the oem partition only when a specific file is found there). Only uses public API on the system partition. |

| product | Updateable Coupled with the system image (they update together) Built per product or product families. System partition can depend on product partition. Can use non-public APIs since they are updated simultaneously. |

| product (enforced interfaces) | Updateable Decoupled with the system image. Built per product or product families. The system partition doesn’t depend on the product partition. Cannot use hidden APIs, but only uses public and system APIs on thesystem partition. |

For these reasons, Android 9 supports the product partition while retaining support for the legacy oem partition, for devices that depend on it. To decouple the product partition from the system partition, Android 11 supportsenforcing product interfaces.

Больше проверок:  Порядок проведения налоговых проверок

/product components

  • Product-specific system properties (/product/build.prop)

  • Product-specific RROs (/product/overlay/*.apk)

  • Product-specific apps (/product/app/*.apk)

  • Product-specific priv-apps (/product/priv-app/*.apk)

  • Product-specific libraries (/product/lib/*)

  • Product-specific java libraries (/product/framework/*.jar)

  • Product-specific Android Framework system configs (/product/etc/sysconfig/* and/product/etc/permissions/*)

  • Product-specific media files (/product/media/audio/*)

  • Product-specific bootanimation files

No custom_images

  • Installing modules into a specific target.custom_images support copying artifacts into an image but can’t install a module into a specific partition by specifying its target partition as a part of a build rule.

  • Soong support. custom_images can’t be built using the Soong build system.

  • OTA update support. custom_images are used as factory ROM images that can’t receive OTA updates.

Maintaining ABIs between partitions

The product partition in Android 9 is an extension of thesystem partition. There’s a weak ABI betweenproduct and system partitions, so both must be upgraded at the same time, and the ABI should be system SDK-based. If the system SDK doesn’t cover all API surfaces between product andsystem, OEMs must maintain their own ABIs between the two partitions.

The product and system partitions can have dependency on each other. However, tests with theGeneric System Image (GSI) must work properly without the product partition.

When the product interfaces are enforced, the product partition is decoupled with the system partition. The product partition uses only the allowed interfaces from the system partition.

What are the Techniques Used for Privilege Escalation?

We assume that now we have shell on the remote system. Depending upon how we got there, we probably might not have ‘root’ privilege. The below mentioned techniques can be used to get ‘root’ access on the system.

1. Kernel Exploits

  1. Trick the kernel into running our payload in kernel mode

  2. Manipulate kernel data, e.g. process privileges

  3. Launch a shell with new privileges Get root!

Consider that for a kernel exploit attack to succeed, an adversary requires four conditions:

  1. A vulnerable kernel

  2. A matching exploit

  3. The ability to transfer the exploit onto the target

  4. The ability to execute the exploit on the target

The infamous DirtyCow exploit – Linux Kernel <= 3.19.0-73.8

Exploiting a vulnerable machine via dirtycow

 Linux privilege escalation permission model

You can check out other variants of dirtycow exploits

There are a lot of different local privilege escalation exploits publicly available for different Kernel and OS. Whether you can get root access on a Linux host using a kernel exploit depends upon whether the kernel is vulnerable or not. Kali Linux has a local copy of exploit-db exploits which make it easier to search for local root exploits. Though I would not suggest to completely rely on this database while searching for Linux Kernel exploits.

$ searchsploit Linux Kernel 2.6.24 – It shows us all the available exploits for a particular Linux kernel which are already there in kali Linux.

Linux privilege escalation permission model, exploit

Why you Should Avoid Running Local Privilege Escalation Exploit at First Place?

Though, it feels very tempting to just run an exploit and get root access, but you should always keep this as your last option.

  1. The remote host might crash as many of the root exploits publicly available are not very stable.

  2. You might get root and then crash the box.

  3. The exploit might leave traces/logs that can get you caught.

You should always try the other techniques to get root which have been discussed below before directly jumping to run a local root exploit.

  • Keep the kernel patched and updated.

2. Exploiting Services Which are Running as Root

Exploiting any service which is running as root will give you Root!

The famous EternalBlue and SambaCry exploit, exploited smb service which generally runs as root.

With just one exploit, an attacker can get remote code execution and Local Privilege Escalation as well.

It was heavily used to spread ransomware across of the globe because of it’s deadly combination.

$ netstat -antup – It shows you all the ports which are open and are listening. We can check for services which are running locally if they could be exploited or not.

Exploiting a vulnerable version of MySQL which is running as root to get root access

MySQL UDF Dynamic Library exploit lets you execute arbitrary commands from the mysql shell. If mysql is running with root privileges, the commands will be executed as root.

> We can execute arbitrary commands using MySQL shell which will be executed as root.

<strong>продуктовые партиции</strong>

Linux privilege escalation permission model, MySQL Shell

Binary exploits of a root owned program are far less dangerous than a kernel exploit because even if the service crashes, the host machine will not crash and the services will probably auto restart.

  • Never run any service as root unless really required, especially web, database and file servers.

3. Exploiting SUID Executables

> -rwsr-xr-x The ‘s’ character instead of ‘x’ indicates that the SUID bit is set.

Linux privilege escalation permission model, Exploiting SUID Executables

Exploiting vulnerable SUID executable to get root access

$ find / -perm -u=s -type f 2>/dev/null – It prints the executables which have SUID bit set

Linux privilege escalation permission model, Exploiting SUID Executables for root access

$ ls -la /usr/local/bin/nmap – Let’s confirm if nmap has SUID bit set or not.

<strong>продуктовые партиции</strong>

> However, there is a functionality in nmap older versions where you can run nmap in an interactive mode which allows you to escape to shell. If nmap has SUID bit set, it will run with root privilege and we can get access to ‘root’ shell through it’s interactive mode.

$ nmap –interactive – runs nmap interactive mode

$ !sh – Lets you escape to the system shell from nmap shell

Linux privilege escalation permission model, Exploiting SUID Executables

  • SUID bit should not be set to any program which lets you escape to the shell.

  • You should never set SUID bit on any file editor/compiler/interpreter as an attacker can easily read/overwrite any files present on the system.

4. Exploiting SUDO Rights/User

Exploiting misconfigured SUDO rights to get root access

$ sudo -l – Prints the commands which we are allowed to run as SUDO

Linux privilege escalation permission model, Exploiting misconfigured SUDO rights

We can run find, cat and python as SUDO. These all commands will run as root when run with SUDO. If we can somehow escape to the shell through any of these commands, we can get root access.

$ sudo find /home -exec sh -i \; – find command’s exec parameter can be used for arbitrary code execution.

<strong>продуктовые партиции</strong>

> Never give SUDO rights to any of the programming language compiler, interpreter and editors.

> This technique can also be applied to vi, more, less, perl, ruby, gdb and others.

$ sudo python -c ‘import pty;pty.spawn(“/bin/bash”);’ – spawns a shell

 Linux privilege escalation permission model, Exploiting misconfigured SUDO rights

  • Do not give sudo rights to any program which lets you escape to the shell.

  • Never give SUDO rights to vi, more, less, nmap, perl, ruby, python, gdb and others.

5. Exploiting Badly Configured Cron Jobs

Cron jobs, if not configured properly can be exploited to get root privilege.

  1. Any script or binaries in cron jobs which are writable?

  2. Can we write over the cron file itself.

  3. Is cron.d directory writable?

Cron jobs generally run with root privileges. If we can successfully tamper any script or binary which are defined in the cron jobs then we can execute arbitrary code with root privilege.

Exploiting badly configured cron jobs to get root access

$ ls -la /etc/cron.d – prints cron jobs which are already present in cron.d

Linux privilege escalation permission model, Exploiting badly configured cron jobs

$ find / -perm -2 -type f 2>/dev/null – prints world writable files

$ ls -la /usr/local/sbin/cron-logrotate.sh – Let’s confirm if the cron-logrotate.sh is world writable.

Linux privilege escalation permission model, Exploiting badly configured cron jobs

> cron-lograte.sh is world writable and it is being run by logrotate cronjob. Any command we write/append in cron-lograte.sh would be executed as ‘root’.

> We write a C file in /tmp directory and compile it.

Linux privilege escalation permission model, Exploiting badly configured cron jobs

> The rootme executable will spawn a shell.

Linux privilege escalation permission model, attack and defense

$ ls -la rootme – After 5 minutes, the logrotate cronjob was run and cron-logrotate.sh got execute with root privilege.

$ ./rootme – spawns a root shell.

Linux privilege escalation permission model, need and importance

  • Any script or binaries defined in cron jobs should not be writable

  • cron file should not be writable by anyone except root.

  • cron.d directory should not be writable by anyone except root.