GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Beego

NoSQL injection in Beego applications occurs when untrusted user input is passed directly into NoSQL filter maps (like bson.M or bson.D) without type enforcement or sanitization. Attackers can inject operators such as $gt, $ne, or $regex via query parameters to bypass logic, dump databases, or escalate privileges. In Go, this often happens when developers assume GetString() returns a literal value that cannot be interpreted as a query command by the driver.

The Vulnerable Pattern

func (c *UserController) Get() {
    // Attacker sends: /user?id[$ne]=null
    // This results in the driver querying for any user where _id is not null.
    userId := c.GetString("id")
    var user bson.M
    err := mgdb.Collection("users").FindOne(ctx, bson.M{"_id": userId}).Decode(&user)
    c.Data["json"] = user
    c.ServeJSON()
}

The Secure Implementation

The exploit leverages the driver's ability to parse complex objects from input. In the vulnerable example, the driver might interpret the 'id' parameter as a filter object rather than a literal string. The fix implements strict type enforcement. By using primitive.ObjectIDFromHex(), we ensure the input is exactly a 12-byte hex string. If an attacker attempts to pass an operator like {'$ne': 1}, the conversion fails, and the injection is neutralized. For non-ID fields, use white-listing or regex validation to ensure the input matches the expected data format before passing it to the database layer.

func (c *UserController) Get() {
    idStr := c.GetString("id")
    // 1. Strict Type Enforcement: Convert string to primitive.ObjectID
    objID, err := primitive.ObjectIDFromHex(idStr)
    if err != nil {
        c.Abort("400")
        return
    }
var user bson.M
// 2. Query using the typed ObjectID, which cannot contain NoSQL operators
err = mgdb.Collection("users").FindOne(ctx, bson.M{"_id": objID}).Decode(&user)
if err != nil {
    c.Abort("404")
    return
}
c.Data["json"] = user
c.ServeJSON()

}

System Alert • ID: 8175
Target: Beego API
Potential Vulnerability

Your Beego API might be exposed to NoSQL Injection

74% of Beego apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.