Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
ASP.NET Core 5 Secure Coding Cookbook

You're reading from   ASP.NET Core 5 Secure Coding Cookbook Practical recipes for tackling vulnerabilities in your ASP.NET web applications

Arrow left icon
Product type Paperback
Published in Jul 2021
Publisher Packt
ISBN-13 9781801071567
Length 324 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Roman Canlas Roman Canlas
Author Profile Icon Roman Canlas
Roman Canlas
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Secure Coding Fundamentals 2. Chapter 2: Injection Flaws FREE CHAPTER 3. Chapter 3: Broken Authentication 4. Chapter 4: Sensitive Data Exposure 5. Chapter 5: XML External Entities 6. Chapter 6: Broken Access Control 7. Chapter 7: Security Misconfiguration 8. Chapter 8: Cross-Site Scripting 9. Chapter 9: Insecure Deserialization 10. Chapter 10: Using Components with Known Vulnerabilities 11. Chapter 11: Insufficient Logging and Monitoring 12. Chapter 12: Miscellaneous Vulnerabilities 13. Chapter 13: Best Practices 14. Other Books You May Enjoy

Fixing NoSQL injection

NoSQL databases are a different type of database in which non-relational and semi-structured data is stored. There are many kinds of NoSQL databases to name, such as Cassandra, Redis, DynamoDB, and MongoDB, each with its own query language. Although distinct from one another, these queries are also prone to injection attacks.

In this recipe, we will identify the NoSQL injection vulnerability in code that is using MongoDB as the backend and fix the problem by applying several countermeasures.

Getting ready

Using Visual Studio Code, open the sample Online Banking app folder at Chapter02\nosql-injection\before\OnlineBankingApp.

How to do it…

Let's take a look at the steps for this recipe:

  1. Launch Visual Studio Code and open the starting exercise folder by typing the following command:
    code .
  2. Navigate to Terminal | New Terminal in the menu or simply press Ctrl + Shift + ' in Visual Studio Code.
  3. Type the following command in the terminal to build the sample app to confirm that there are no compilation errors:
    dotnet build
  4. Open the Services/PayeeService.cs file and locate the vulnerable part of the code in the Get(string name) method:
    public List<Payee> Get(string name) {
        var filter = "{$where: \"function()         {return this.Name == '" + name + "'}\"}";
        return payees.Find(filter).ToList();
    }
  5. To remediate the NoSQL injection vulnerability, change the preceding highlighted code:
    public List<Payee> Get(string name) {
        return payees.Find(payee => payee.Name ==         name).ToList();
    }  

The filter passed into the Find method is now replaced with a Lambda expression, a much more secure way of searching for a payee by name.

How it works…

The Get method has a string parameter that can be supplied with a non-sanitized or validated value. This value can alter the MongoDB filter composed with it, making the NoSQL database perform an unintended behavior.

The name parameter can be appended with an expression that would evaluate the query into a logical result different from what the query was expected to perform. A JavaScript clause can also be inserted into a query that can terminate the statement and add a new block of arbitrary code.

By way of some general advice, avoid using the $where operator. Simply apply a C# Lambda expression as a filter to prevent any injectable JSON or JavaScript expression.

There's more…

Suppose the preceding options are not possible and it is necessary to use the $where clause, you must then JavaScript-encode the input. Use the JavaScriptEncoder class from the System.Text.Encodings.Web namespace to encode the value being passed into the parameter:

  1. First, modify the PayeeService.cs file to add a reference to the Encoder namespace:
    using System.Text.Encodings.Web;
  2. Next, define a property for JavaScriptEncoder:
    private readonly JavaScriptEncoder _jsEncoder;
  3. Change the PayeeService constructor and add a new parameter to inject JavaScriptEncoder:
    public PayeeService(IOnlineBankDatabaseSettings settings,JavaScriptEncoder jsEncoder)
  4. Lastly, encode the name parameter using the Encode function of JavaScriptEncoder:
    var filter = "{$where: \"function() {return this.Name == '" + _jsEncoder.Encode(name) + "'}\"}";

If a malicious input was passed into the name parameter and was escaped by the Encode method, the C# MongoDB driver will throw an exception if the escaped value could not be interpreted as a valid JavaScript expression.

To prevent NoSQL injections, developers must avoid building dynamic queries using string concatenation. NoSQL databases offer ways to query and process data, but you must be aware of potential security implications a feature might bring into the ASP.NET Core web application.

You have been reading a chapter from
ASP.NET Core 5 Secure Coding Cookbook
Published in: Jul 2021
Publisher: Packt
ISBN-13: 9781801071567
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image