1

I am working on an interactive Canvas tutorial. I want the students to be able to enter JavaScript into a contenteditable element, but I am afraid that it could introduce vulnerabilities.

I have thought about re-assigning dangerous objects or methods before evaluating their code, and then assigning it back afterwards.

How do I determine the dangerous objects?

Is this the right approach, or should I rather scan their input and only allow certain statements?

4thex
  • 1,094
  • 1
  • 9
  • 21
  • 2
    A good read: https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – Jonathan.Brink Sep 27 '17 at 13:22
  • While the question is interesting it has been asked a lot of times as well as when googling for the exact title several articles and SO posts are displayed and 3rd party APIs able to use eval safely. – Nope Sep 27 '17 at 13:26
  • 1
    do you run those javascript codes from one student on other ones pcs? or every student work with his own copy? – S.Serpooshan Sep 27 '17 at 13:31
  • What exactly do you think is vulnerable? What's your threat model, what things do you need to protect? – Bergi Sep 27 '17 at 13:44
  • About *everything* is dangerous in JS. You can't get away with a blacklist. – Bergi Sep 27 '17 at 13:45

3 Answers3

1

It is hard to give general advice without knowing details but you might want to investigate putting your editable content in a sandboxed iframe.

<iframe sandbox="allow-scripts"></iframe>

You would need to test for support which the https://modernizr.com library supports. Also setting appropriate Content Security Policy headers may be needed depending on how you implement this.

ChrisD
  • 3,378
  • 3
  • 35
  • 40
  • That sounds like a good idea. I didn't know about this feature. I will test it out. If I understand correctly, the thing that makes this safe is that it gets a unique origin, so basically it is treated as if it was a script from another source. – 4thex Sep 27 '17 at 19:59
  • @PalleCogburn that's right. It's as though the contents of the iframe is on a domain all of its own. – ChrisD Sep 27 '17 at 21:20
0

How about providing a bunch of JSBin playpens that the students can then fork and edit?

This takes the security question out of your hands.

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
-1

What about running their JS code inside a JS 'VM' like https://www.npmjs.com/package/vm2 ? It's basically a JS runtime like eval in which you can declare what's available. You can for example prevent access to the fs lib.

SpoBo
  • 2,100
  • 2
  • 20
  • 28