Skip to content

Commit

Permalink
safe-read is working, but the exceptions it throws need some work
Browse files Browse the repository at this point in the history
  • Loading branch information
amalloy committed Jan 11, 2011
1 parent 6f5b16c commit 2b1a36e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
2 changes: 1 addition & 1 deletion project.clj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
(defproject clojail "0.3.2"
(defproject clojail "0.3.3"
:description "An experimental sandboxing library."
:dependencies [[clojure "1.2.0"]
[clojure-contrib "1.2.0"]]
Expand Down
37 changes: 34 additions & 3 deletions src/clojail/core.clj
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
(ns clojail.core
(:use [clojure.walk :only [macroexpand-all postwalk]]
(:use clojure.stacktrace
[clojure.walk :only [macroexpand-all postwalk]]
clojail.jvm)
(:import (java.util.concurrent TimeoutException TimeUnit FutureTask)))
(:import (java.util.concurrent TimeoutException TimeUnit FutureTask)
(clojure.lang LispReader$ReaderException)))

(defn enable-security-manager
"Enable the JVM security manager. The sandbox can do this for you."
Expand Down Expand Up @@ -153,4 +155,33 @@
(. ~object# ~method# ~@args#))))
~(with-bindings bindings (dotify code)))]
(jvm-sandbox #(with-bindings bindings (eval code)) context))))
timeout :ms transform)))))
timeout :ms transform)))))

(defn safe-read
"Read a string from an untrusted source. Mainly just disables read-eval,
but also repackages thrown exceptions to make it easier to discriminate among
them. read-eval errors will be thrown as IllegalStateException; end-of-input
will be thrown as EOFException; other exceptions will be unchanged."
([]
(binding [*read-eval* false]
(let [repackage (fn [e]
(let [cause (root-cause e)
msg (str (.getName (class e))
": "
(.getMessage cause))]
(if (.contains msg "EvalReader")
(IllegalStateException. msg)
(java.io.EOFException. msg))))]
(try
(read)
(catch LispReader$ReaderException e
(throw (repackage e)))
(catch Throwable e
(let [cause (.getCause e)]
(cond
(not cause) (throw e)
(not (instance? LispReader$ReaderException cause)) (throw e)
:else (throw (repackage cause)))))))))
([str]
(with-in-str str
(safe-read))))

0 comments on commit 2b1a36e

Please sign in to comment.