labs / tiddlers / content / labs / 05 / _Labs_05_Code

Once again, xkcd has a pertinent cartoon for our lab topic: [Source:]

By way of explanation, a carefully crafted piece of text, when treated as data by an unsuspecting computer system, can cause malicious code to be run. The payload code is injected into the system within a container that the system expects to be ordinary, harmless data. Often, the injection will make use of special characters such as text delimiters, comment markers, and statement terminators (these will be discussed in more detail). In this case, an SQL DROP TABLE statement is embedded within the data intended to contain just the name of a student in the database; if this code is run, the Student table (and all its contents) will be deleted!

A general rule should be: never trust user data. There are a number of mitigations to code injection, but all stem from that general principle.


A number of strategies can be used against injection attacks. Many of the following are generally applicable, though some are most relevant for the common case of SQL injection attacks against a back-end database:

  • Validate client-side input to make sure it looks reasonable before attempting to run it.
  • Use specialised user accounts with minimal privileges for different application functionality, e.g. a user for viewing product details should not be able to update anything.
  • Use prepared statements rather than concatenation.
  • Use database constraints (integrity rules) as an extra guard against invalid data, e.g. prohibit anything resembling HTML or JavaScript inside normal table data. Some database designs even prohibit single quotes in user data.
  • Enable software "safety switches" in the database and/or application layer, e.g. to disallow unreasonably large input or multiple statements separated by semicolons.
  • Ensure that user passwords are strong, properly salted, peppered and hashed in their stored form, so that even if they are compromised, they will be of little use to the attacker.