HIGH format stringadonisjs

Format String in Adonisjs

How Format String Manifests in Adonisjs

Format string vulnerabilities in Adonisjs typically emerge through improper handling of user-controlled input in logging, database queries, and template rendering. The framework's flexibility with template engines and logging mechanisms creates several attack vectors that developers must be aware of.

One common manifestation occurs in logging operations. Adonisjs's Logger module allows string interpolation, but when user input is directly passed without proper sanitization, attackers can inject format specifiers. Consider this vulnerable pattern:

const { logger } = require('@adonisjs/core')
const username = request.input('username')
logger.info(`User logged in: ${username}`)

If an attacker submits a username like %n, the logger attempts to write to stdout, causing unexpected behavior. More dangerous is when format specifiers like %x or %p are used, potentially exposing memory contents or causing crashes.

Database operations present another significant risk. Adonisjs's query builder and Lucid ORM support both parameterized queries and string interpolation. When developers mix these approaches or use unsafe string concatenation, format string vulnerabilities emerge:

const id = request.input('id')
const user = await Database.query(`SELECT * FROM users WHERE id = ${id}`)

An attacker could supply 1 OR 1=1 -- %x, where the %x is interpreted by the database engine, potentially leading to information disclosure or query manipulation.

Template rendering in Adonisjs, particularly with Edge templates, can also be exploited. While Edge templates are generally safe, mixing raw JavaScript with user input creates risks:

{{ user.name }}
{{ user.name.toString() }}

If user input contains format specifiers and is processed through toString() or similar methods, unexpected behavior can occur, especially when combined with custom filters or helpers.

Adonisjs-Specific Detection

Detecting format string vulnerabilities in Adonisjs applications requires a multi-layered approach combining static analysis, runtime monitoring, and automated scanning.

Static analysis tools can identify suspicious patterns in your codebase. Look for these red flags in your Adonisjs application:

// Vulnerable patterns to flag
const unsafe = `Hello ${userInput}`
logger.info(`Value: ${unsafeValue}`)
Database.query(`SELECT * FROM table WHERE id = ${id}`)

middleBrick's scanning engine specifically targets these Adonisjs patterns. The scanner analyzes your running API endpoints, testing for format string injection by submitting payloads containing various format specifiers (%n, %x, %p, %s) and monitoring for abnormal responses, crashes, or information disclosure.

For template-based vulnerabilities, middleBrick examines Edge template files for unsafe interpolation patterns. The scanner looks for:

  • Direct user input in template expressions without sanitization
  • Custom helpers that might process format strings
  • JavaScript blocks mixing user data with format operations
  • Database queries embedded in templates

Runtime detection can be implemented using Adonisjs middleware. Create a security middleware that validates request parameters:

class FormatStringMiddleware {
async handle({ request, response }, next) {
const hasFormatSpecifiers = /%[npxs]/i.test(request.raw())
if (hasFormatSpecifiers) {
return response.status(400).send('Invalid input detected')
}
await next()
}
}

This middleware catches basic format string attempts before they reach your application logic. For comprehensive protection, integrate middleBrick's GitHub Action into your CI/CD pipeline to automatically scan your Adonisjs API endpoints before deployment.

Adonisjs-Specific Remediation

Remediating format string vulnerabilities in Adonisjs requires adopting secure coding practices and leveraging the framework's built-in security features. The primary defense is consistent use of parameterized queries and proper input validation.

For database operations, always use Adonisjs's query builder with parameter binding:

// Vulnerable - DO NOT USE
const id = request.input('id')
const user = await Database.query(`SELECT * FROM users WHERE id = ${id}`)

Instead, use parameterized queries:

// Secure - USE THIS
const id = request.input('id')
const user = await Database.query()
.select('*')
.from('users')
.where('id', id)

This approach ensures user input is properly escaped and never interpreted as SQL code or format specifiers.

For logging operations, use structured logging instead of string interpolation:

// Vulnerable - DO NOT USE
logger.info(`User ${username} logged in from ${ip}`)

Instead, use object-based logging:

// Secure - USE THIS
logger.info('User login', {
username,
ip,
timestamp: new Date()
})

This prevents format string injection while providing better structured data for log analysis.

Template rendering requires careful input validation. In Edge templates, use the built-in sanitization filters:

{{ user.name | safe }}
{{ user.name | escape }}

Where safe indicates trusted content and escape sanitizes potentially dangerous characters. For dynamic content, create custom filters that validate against format string patterns:

const { filter } = require('@adonisjs/core/templating')

filter('noFormat', (value) => {
if (typeof value === 'string' && /%[npxs]/i.test(value)) {
throw new Error('Format string detected')
}
return value
})

Then use it in templates: {{ userInput | noFormat }}

For comprehensive protection, implement input validation middleware that checks for format string patterns across all request data:

class InputValidationMiddleware {
async handle({ request }, next) {
const checkFormatStrings = (data) => {
if (typeof data === 'string' && /%[npxs]/i.test(data)) {
throw new Error('Format string injection detected')
}
if (typeof data === 'object') {
Object.values(data).forEach(checkFormatStrings)
}
}

checkFormatStrings(request.all())
await next()
}
}

This multi-layered approach, combined with middleBrick's automated scanning, provides comprehensive protection against format string vulnerabilities in Adonisjs applications.

Frequently Asked Questions

How does middleBrick detect format string vulnerabilities in Adonisjs applications?
middleBrick performs black-box scanning of your Adonisjs API endpoints, injecting payloads containing format specifiers like %n, %x, and %p. The scanner monitors responses for crashes, abnormal behavior, or information disclosure. It also analyzes your OpenAPI/Swagger specifications to identify potential injection points and validates template files for unsafe interpolation patterns.
Can format string vulnerabilities in Adonisjs lead to remote code execution?
Yes, in severe cases format string vulnerabilities can lead to remote code execution, particularly when combined with other weaknesses. For example, if an attacker can control format specifiers in a logging context and the application runs with elevated privileges, they might trigger memory writes or execute arbitrary code. This is why proper input validation and the use of parameterized queries are critical in Adonisjs applications.