Skip to content

Run evaluation of inlined quotes in secured sandbox #4111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/src/dotty/tools/dotc/config/ScalaSettings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ class ScalaSettings extends Settings.SettingGroup {
val silentWarnings = BooleanSetting("-nowarn", "Silence all warnings.")
val fromTasty = BooleanSetting("-from-tasty", "Compile classes from tasty in classpath. The arguments are used as class names.")

/** Macro settings */
val macroTimeout = IntSetting("-macro-timeout", "Timeout for the evaluation of a macro in ms", 1000, 1 to Int.MaxValue)

/** Decompiler settings */
val printTasty = BooleanSetting("-print-tasty", "Prints the raw tasty when decompiling.")
val printLines = BooleanSetting("-print-lines", "Show source code line numbers.")
Expand Down
9 changes: 6 additions & 3 deletions compiler/src/dotty/tools/dotc/transform/Splicer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package transform

import java.io.{PrintWriter, StringWriter}
import java.lang.reflect.Method
import java.net.URLClassLoader

import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Contexts._
Expand All @@ -14,6 +13,7 @@ import dotty.tools.dotc.core.Names.Name
import dotty.tools.dotc.core.quoted._
import dotty.tools.dotc.core.Types._
import dotty.tools.dotc.core.Symbols._
import dotty.tools.dotc.util.Sandbox

import scala.util.control.NonFatal
import dotty.tools.dotc.util.Positions.Position
Expand Down Expand Up @@ -73,8 +73,11 @@ object Splicer {
}

private def evaluateLambda(lambda: Seq[Any] => Object, args: Seq[Any], pos: Position)(implicit ctx: Context): Option[scala.quoted.Expr[Nothing]] = {
try Some(lambda(args).asInstanceOf[scala.quoted.Expr[Nothing]])
catch {
try {
val timeout = ctx.settings.macroTimeout.value
val res = Sandbox.runInSecuredThread(timeout)(lambda(args))
Some(res.asInstanceOf[scala.quoted.Expr[Nothing]])
} catch {
case ex: scala.quoted.QuoteError =>
ctx.error(ex.getMessage, pos)
None
Expand Down
93 changes: 93 additions & 0 deletions compiler/src/dotty/tools/dotc/util/Sandbox.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package dotty.tools.dotc.util


import java.lang.reflect.{InvocationTargetException, ReflectPermission}
import java.security.Permission

import scala.quoted.QuoteError

object Sandbox {

def runInSecuredThread[T](timeout: Int)(thunk: => T): T = {
runWithSandboxSecurityManager { securityManager =>
class SandboxThread extends Thread {
var result: scala.util.Try[T] =
scala.util.Failure(new Exception("Sandbox failed with a fatal error"))
override def run(): Unit = {
result = scala.util.Try {
securityManager.enable() // Enable security manager on this thread
thunk
}
}
}
val thread = new SandboxThread
thread.start()
thread.join(timeout)
if (thread.isAlive) {
// TODO kill the thread?
Copy link
Contributor

@Blaisorblade Blaisorblade Mar 20, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any chance to add a test with an infinite loop to test this case?

Because Dotty can be embedded in build tools VMs, this means we must kill the thread I think.

I'd use thread.interrupt() first, and specify/hope that the thread must not catch InterruptedException. If the thread doesn't handle interrupt by exiting, I'm not sure what's a sensible behavior — using stop might leave monitors held hence cause a deadlock release monitors while data is inconsistent causing corruption, not using stop might leave a thread wasting CPU, so I suspect the thread should be stoped and the compiler should not be reused.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared data that might be corrupted by Thread.stop includes

  • shared static mutable data such as the name table (Slow memory leak in Dotty's parser #1584), that is reused across all compiler instances in the same classloader. More such fields might exist.
  • any compiler-specific data that is internally mutable and shared across threads. The second isn't a problem currently because compiler instances are currently not reused by build tools, though that might change in the future.

After some discussion on Gitter and with Allan, I learned that build tools usually fork Scala compilers in the same JVM (though that's configurable) — they typically create fresh compiler instances (which is safer) though @smarter suggests it could be faster to reuse them sometimes (which is only safe for instances which didn't get corrupted).

throw new InvocationTargetException(new QuoteError(s"Failed to evaluate inlined quote. Caused by timeout ($timeout ms)."))
} else thread.result.fold[T](throw _, identity)
}
}

private def runWithSandboxSecurityManager[T](run: SandboxSecurityManager => T): T = {
val ssm: SandboxSecurityManager = synchronized {
System.getSecurityManager match {
case ssm: SandboxSecurityManager =>
assert(ssm.running > 0)
ssm.running += 1
ssm
case sm =>
assert(sm == null)
val ssm = new SandboxSecurityManager
System.setSecurityManager(ssm)
ssm
}
}
try run(ssm)
finally synchronized {
ssm.running -= 1
assert(ssm.running >= 0)
if (ssm.running == 0) {
assert(System.getSecurityManager eq ssm)
System.setSecurityManager(null)
}
}
}

/** A security manager that can be enabled on individual threads.
*
* Inspired by https://github.com/alphaloop/selective-security-manager
*/
private class SandboxSecurityManager extends SecurityManager {

@volatile private[Sandbox] var running: Int = 1

private[this] val enabledFlag: ThreadLocal[Boolean] = new ThreadLocal[Boolean]() {
override protected def initialValue(): Boolean = false
}

def enable(): Unit = {
enabledFlag.set(true)
}

override def checkPermission(permission: Permission): Unit = {
if (enabledFlag.get() && !isClassLoading)
super.checkPermission(permission)
}

override def checkPermission(permission: Permission, context: Object): Unit = {
if (enabledFlag.get())
super.checkPermission(permission, context)
}

private def isClassLoading: Boolean = {
try {
enabledFlag.set(false) // Disable security to do the check
Thread.currentThread().getStackTrace.exists(elem => elem.getClassName == "java.lang.ClassLoader")
} finally {
enabledFlag.set(true)
}
}
}
}
10 changes: 10 additions & 0 deletions tests/neg/quote-security-1/Macro_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import java.io.File

import scala.quoted._
object Macros {
inline def foo(): Int = ~fooImpl()
def fooImpl(): Expr[Int] = {
System.setSecurityManager(null)
'(1)
}
}
6 changes: 6 additions & 0 deletions tests/neg/quote-security-1/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Macros._
object Test {
def main(args: Array[String]): Unit = {
Macros.foo() // error: Failed to evaluate inlined quote. Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "setSecurityManager")
}
}
10 changes: 10 additions & 0 deletions tests/neg/quote-security-2/Macro_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import java.io.File

import scala.quoted._
object Macros {
inline def foo(): Int = ~fooImpl()
def fooImpl(): Expr[Int] = {
(new File("dfsdafsd")).exists()
'(1)
}
}
6 changes: 6 additions & 0 deletions tests/neg/quote-security-2/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Macros._
object Test {
def main(args: Array[String]): Unit = {
Macros.foo() // error: Failed to evaluate inlined quote. Caused by: access denied ("java.util.PropertyPermission" "user.dir" "read")
}
}
10 changes: 10 additions & 0 deletions tests/neg/quote-security-3/Macro_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import java.io.File

import scala.quoted._
object Macros {
inline def foo(): Int = ~fooImpl()
def fooImpl(): Expr[Int] = {
(new File("dfsdafsd")).createNewFile()
'(1)
}
}
6 changes: 6 additions & 0 deletions tests/neg/quote-security-3/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Macros._
object Test {
def main(args: Array[String]): Unit = {
Macros.foo() // error: Failed to evaluate inlined quote. Caused by: access denied ("java.util.PropertyPermission" "user.dir" "read")
}
}
10 changes: 10 additions & 0 deletions tests/neg/quote-timeout/Macro_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import java.io.File

import scala.quoted._
object Macros {
inline def foo(): Int = ~fooImpl()
def fooImpl(): Expr[Int] = {
while (true) ()
'(1)
}
}
6 changes: 6 additions & 0 deletions tests/neg/quote-timeout/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Macros._
object Test {
def main(args: Array[String]): Unit = {
Macros.foo() // error: Failed to evaluate inlined quote. Caused by timeout (3000 ms).
}
}