Fix SQL Injection (Legacy & Modern) in Beego
Beego's ORM is a powerful abstraction, but developers often bypass it for 'Raw' queries when performance or complexity demands. The critical failure point in Beego applications is the use of fmt.Sprintf or string concatenation to build these raw queries. This allows an attacker to break out of the data context and execute arbitrary SQL. To secure Beego, you must enforce the use of the driver's parameterization engine via placeholders.
The Vulnerable Pattern
// LEGACY & MODERN VULNERABILITY
// Using string formatting to build a query allows SQL Injection
func (c *UserController) GetUser() {
id := c.GetString("id")
o := orm.NewOrm()
var user User
sql := fmt.Sprintf("SELECT * FROM user WHERE id = %s", id)
err := o.Raw(sql).QueryRow(&user)
if err == nil {
c.Data["json"] = user
}
c.ServeJSON()
}
The Secure Implementation
The vulnerability occurs because the database engine interprets the concatenated string as a single command. By switching to the placeholder syntax ('?'), you leverage prepared statements. In this workflow, the SQL template is sent to the DB first, and the user input is sent separately as data only. Even if the input contains malicious SQL keywords, the database treats them as literal string content for the column, not executable instructions. Additionally, using Beego's QueryTable().Filter() API provides an extra layer of abstraction that automatically handles parameterization and type safety.
// SECURE IMPLEMENTATION // Use placeholders (?) to let the underlying driver handle parameterization func (c *UserController) GetUser() { id, _ := c.GetInt("id") // 1. Type validation o := orm.NewOrm() var user User// Method A: Raw with Placeholders (Universal) err := o.Raw("SELECT * FROM user WHERE id = ?", id).QueryRow(&user) // Method B: ORM QuerySetter (Modern/Recommended) // err := o.QueryTable("user").Filter("Id", id).One(&user) if err == nil { c.Data["json"] = user } c.ServeJSON()
}
Your Beego API
might be exposed to SQL Injection (Legacy & Modern)
74% of Beego apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.