Skip to content
Permalink
Browse files

Major restructure, minor rewrite:

 * added new pkgs: lattice, kernSmooth, nortest, descr, outliers
 * removing lame startup pkg msg and
 * added INSTALL file for details about required assignInNamspace calls after pkg load
 * new "injected" fn to lattice namespace: latticeParseFormula
 * minor fixes in get, assign
  • Loading branch information...
daroczig committed May 10, 2012
1 parent 5919b60 commit c49699f15d026f4d3d66abe1152fd04d6e7cab89
Showing with 234 additions and 211 deletions.
  1. +4 −1 .gitignore
  2. +1 −1 DESCRIPTION
  3. +10 −0 INSTALL
  4. +47 −0 R/blacklist.R
  5. +0 −6 R/init.R
  6. +34 −33 R/masked.functions.R
  7. +56 −96 R/sandbox.R
  8. +1 −0 R/sandboxR.R
  9. +81 −74 inst/tests/sandbox.R
@@ -1,4 +1,7 @@
*~
\#*
.\#*
_Rsource
_Rsource
tools
TODO
\.*
@@ -18,4 +18,4 @@ Collate:
'masked.functions.R'
'sandbox.R'
'sandboxR.R'
'init.R'
'blacklist.R'
10 INSTALL
@@ -0,0 +1,10 @@

Securing system
===============

To use all power of sandboxR and to really secure your environment, please run the following commands

* assignInNamespace('formula.character', sandboxR:::formula.character.masked, ns = 'stats')
* assignInNamespace('latticeParseFormula', sandboxR:::latticeParseFormula, ns = 'lattice')

WARNING: These calls are updating some _base_ (internal) functions and might have some unwanted side-effects!
@@ -0,0 +1,47 @@
#' Blacklisted functions
#' @param pkg package name(s) where to look for blacklisted functions. All packages' functions will be returned in a list if not set.
#' @return vector or list of function names
#' @note Only base is added ATM.
#' @examples \dontrun{
#' commands.blacklist()
#' commands.blacklist('base')
#' }
#' @export
commands.blacklist <- function(pkg) {

## blacklisted packages which would never be added:
## * from base packages: compiler, parralel, splines, stats4, rcltk, tools
## * foreign, knitr, base64, brew etc.: file operations
## * xtable: no need for HTML/TeX output in templates
## * rook, rredis etc. as no network connection should be allowed
## * devtools, roxygen(2): no dev package needed
## * RJSONIO, opencpu.encode etc.
## * microbenchmark, logging, profiling etc.

## TODO:
## * look over if really all functions are to be blacklisted
## * free up: mget
## * do.call and similar

blacklist <- list( base = c('.amatch_bounds', '.amatch_costs', 'as.call', 'asNamespace', 'asS3', 'asS4', 'attach', 'attachNamespace', 'autoload', 'autoloader', 'baseenv', 'bindingIsActive', 'bindingIsLocked', 'bindtextdomain', 'body', 'browser', 'browserCondition', 'browserSetDebug', 'browserText', 'builtins', 'bzfile', '.C', '.cache_class', 'call', '.Call', '.Call.graphics', 'cat', 'charToRaw', 'chartr', 'close', 'closeAllConnections', 'close.connection', 'close.srcfile', 'close.srcfilealias', 'close.txtProgressBar', '.colMeans', '.colSums', 'Cstack_info', 'debug', 'debugonce', '.decode_numeric_version', '.Defunct', 'deparse', '.deparseOpts', '.Deprecated', 'detach', 'dget', '.difftime', 'dir', 'dir.create', 'do.call', '.doTrace', 'dput', 'dump', 'dump.frames', '.dynLibs', 'dyn.load', 'dyn.unload', 'enc2native', 'enc2utf8', '.encode_numeric_version', 'encodeString', 'Encoding', 'environment', 'environmentIsLocked', 'environmentName', 'env.profile', 'eval.parent', 'evalq', 'exists', '.expand_R_libs_env_var', '.Export', '.External', '.External.graphics', 'fifo', 'file', 'file.access', 'file.append', 'file.choose', 'file.copy', 'file.create', 'file.edit', 'file.exists', 'file.info', 'file.link', 'file.path', 'file.remove', 'file.rename', 'file.show', 'file.symlink', '.find.package', 'find.package', 'findPackageEnv', '.First.sys', 'flush', 'flush.connection', 'force', 'formals', '.Fortran', 'gc', 'gcinfo', 'gc.time', 'gctorture', 'gctorture2', 'getAllConnections', 'getCallingDLL', 'getCallingDLLe', 'getCConverterDescriptions', 'getCConverterStatus', 'getConnection', 'getDLLRegisteredRoutines', 'getDLLRegisteredRoutines.character', 'getDLLRegisteredRoutines.DLLInfo', 'getElement', 'geterrmessage', 'getExportedValue', 'getHook', 'getLoadedDLLs', 'getNamespace', 'getNamespaceExports', 'getNamespaceImports', 'getNamespaceInfo', 'getNamespaceName', 'getNamespaceUsers', 'getNamespaceVersion', 'getNativeSymbolInfo', 'getNumCConverters', '.getRequiredPackages', '.getRequiredPackages2', 'getRversion', 'getSrcLines', 'getTaskCallbackNames', 'gettext', 'gettextf', 'getwd', 'globalenv', '.gt', '.gtn', 'gzcon', 'gzfile', '.handleSimpleError', '.__H__.cbind', '.__H__.rbind', 'iconv', 'iconvlist', '.Import', '.ImportFrom', 'importIntoEnv', 'interactive', '.Internal', 'intToBits', 'intToUtf8', 'invokeRestart', 'invokeRestartInteractively', 'isBaseNamespace', 'is.call', 'isdebugged', 'isIncomplete', 'is.loaded', '.isMethodsDispatchOn', 'isNamespace', '.isOpen', 'isSeekable', '.kronecker', 'l10n_info', 'lazyLoad', 'lazyLoadDBexec', 'lazyLoadDBfetch', '.libPaths', 'library.dynam', 'library.dynam.unload', 'licence', 'license', 'list2env', 'list.dirs', 'list.files', 'load', 'loadedNamespaces', 'loadingNamespaceInfo', 'loadNamespace', 'local', 'lockBinding', 'lockEnvironment', 'makeActiveBinding', '.makeMessage', '.make_numeric_version', 'manglePackageName', 'memCompress', 'memDecompress', 'mem.limits', 'memory.profile', '.mergeExportMethods', '.mergeImportMethods', 'mget', 'namespaceExport', 'namespaceImport', 'namespaceImportClasses', 'namespaceImportFrom', 'namespaceImportMethods', 'new.env', 'NextMethod', 'ngettext', '.NotYetImplemented', '.NotYetUsed', 'on.exit', 'open', 'open.connection', 'open.srcfile', 'open.srcfilealias', 'open.srcfilecopy', '.OptRequireMethods', 'packageEvent', 'packageHasNamespace', '.packages', 'packageStartupMessage', '.packageStartupMessage', 'package_version', 'packBits', 'parent.env', 'parent.frame', 'parse', 'parseNamespaceFile', 'path.expand', '.path.package', 'path.package', 'pipe', '.POSIXct', '.POSIXlt', 'pos.to.env', '.Primitive', '.primTrace', '.primUntrace', 'pushBack', 'pushBackLength', 'q', 'quit', 'rawConnection', 'rawConnectionValue', 'rawShift', 'rawToBits', 'rawToChar', 'readBin', 'readChar', 'read.dcf', 'readline', 'readLines', 'readRDS', '.readRDS', 'readRenviron', 'Recall', 'registerS3method', 'registerS3methods', 'remove', 'removeCConverter', 'remove.packages', 'removeTaskCallback', 'requireNamespace', 'restartDescription', 'restartFormals', 'retracemem', 'R.home', 'rm', 'RNGkind', 'RNGversion', '.rowMeans', '.row_names_info', '.rowSums', 'R_system_version', 'R.Version', '.S3method', 'save', 'save.image', 'saveRDS', '.saveRDS', 'scan', '.Script', 'search', 'searchpaths', 'seek', 'seek.connection', 'serialize', 'setHook', 'setNamespaceInfo', '.set_row_names', 'setSessionTimeLimit', 'setTimeLimit', 'setwd', 'showConnections', '.signalSimpleWarning', 'sink', 'sink.number', 'socketConnection', 'socketSelect', 'source', 'srcfile', 'srcfilealias', 'srcfilecopy', 'srcref', '.standard_regexps', '.subset', '.subset2', 'sys.call', 'sys.calls', 'Sys.chmod', 'Sys.Date', 'sys.frame', 'sys.frames', 'sys.function', 'Sys.getenv', 'Sys.getlocale', 'Sys.getpid', 'Sys.glob', 'Sys.info', 'sys.load.image', 'Sys.localeconv', 'sys.nframe', 'sys.on.exit', 'sys.parent', 'sys.parents', 'Sys.readlink', 'sys.save.image', 'Sys.setenv', 'Sys.setFileTime', 'Sys.setlocale', 'Sys.sleep', 'sys.source', 'sys.status', 'system', 'system2', 'system.file', 'system.time', 'Sys.time', 'Sys.timezone', 'Sys.umask', 'Sys.unsetenv', 'Sys.which', '.TAOCP1997init', 'taskCallbackManager', 'tempdir', 'tempfile', 'testPlatformEquivalence', 'textConnection', 'textConnectionValue', 'topenv', 'trace', 'traceback', 'tracemem', 'truncate', 'truncate.connection', 'undebug', 'unlink', 'unloadNamespace', 'unlockBinding', 'unserialize', 'untrace', 'untracemem', 'unz', 'url', 'url.show', 'UseMethod', 'utf8ToInt', 'warnings', 'withCallingHandlers', 'write', 'writeBin', 'writeChar', 'write.csv', 'write.csv2', 'write.dcf', 'write.ftable', 'writeLines', 'write.socket', 'write.table', 'xzfile'), utils = c('alarm', 'apropos', 'argsAnywhere', 'aspell', 'aspell_package_Rd_files', 'aspell_package_vignettes', 'aspell_write_personal_dictionary_file', 'assignInMyNamespace', 'assignInNamespace', 'available.packages', 'browseEnv', 'browseURL', 'browseVignettes', 'bug.report', 'capture.output', 'checkCRAN', 'chooseBioCmirror', 'chooseCRANmirror', 'close.socket', 'compareVersion', 'contrib.url', 'count.fields', 'CRAN.packages', 'create.post', 'dataentry', 'data.entry', 'de', 'debugger', 'demo', 'de.ncols', 'de.restore', 'de.setup', '.DollarNames', 'download.file', 'download.packages', 'dump.frames', 'edit', 'edit.data.frame', 'edit.default', 'edit.matrix', 'edit.vignette', 'emacs', 'example', 'file.edit', 'file_test', 'find', 'findLineNum', 'find.package', 'fix', 'fixInNamespace', 'flush.console', 'getAnywhere', 'getCRANmirrors', 'getFromNamespace', 'getS3method', 'getSrcDirectory', 'getSrcFilename', 'getSrcLocation', 'getSrcref', 'getTxtProgressBar', 'help', 'help.request', 'help.search', 'help.start', 'history', 'installed.packages', 'install.packages', 'loadhistory', 'localeToCharset', 'lsf.str', 'ls.str', 'maintainer', 'make.packages.html', 'makeRweaveLatexCodeRunner', 'make.socket', 'memory.limit', 'memory.size', 'menu', 'methods', 'mirror2html', 'new.packages', 'news', 'nsl', 'object.size', 'old.packages', 'package.contents', 'packageDescription', 'package.skeleton', 'packageStatus', 'packageVersion', 'page', 'pico', 'prompt', 'promptData', 'prompt.data.frame', 'prompt.default', 'promptPackage', 'rc.getOption', 'rc.options', 'rc.settings', 'rc.status', 'readCitationFile', 'read.csv', 'read.csv2', 'read.delim', 'read.delim2', 'read.DIF', 'read.fortran', 'read.fwf', 'read.socket', 'read.table', 'recover', 'remove.packages', 'removeSource', 'Rprof', 'Rprofmem', 'RShowDoc', 'RSiteSearch', 'rtags', 'Rtangle', 'RtangleSetup', 'RtangleWritedoc', 'RweaveChunkPrefix', 'RweaveEvalWithOpt', 'RweaveLatex', 'RweaveLatexFinish', 'RweaveLatexOptions', 'RweaveLatexSetup', 'RweaveLatexWritedoc', 'RweaveTryStop', 'savehistory', 'sessionInfo', 'setBreakpoint', 'setRepositories', 'setTxtProgressBar', 'Stangle', 'summaryRprof', 'Sweave', 'SweaveHooks', 'SweaveSyntConv', 'tar', 'timestamp', 'toBibtex', 'toBibtex.bibentry', 'toBibtex.person', 'toLatex', 'toLatex.sessionInfo', 'txtProgressBar', 'untar', 'unzip', 'update.packages', 'update.packageStatus', 'upgrade', 'upgrade.packageStatus', 'url.show', 'vi', 'View', 'vignette', 'write.csv', 'write.csv2', 'write.socket', 'write.table', 'wsbrowser', 'xedit', 'xemacs', 'zip', 'zip.file.extract' ),
stats = c('read.ftable', 'write.ftable'),
graphics = NULL,
grDevices = c('bitmap', 'bmp', 'cairo_pdf', 'cairo_ps', 'CIDFont', 'dev2bitmap', 'devAskNewPage', 'dev.capabilities', 'dev.capture', 'dev.control', 'dev.copy', 'dev.copy2eps', 'dev.copy2pdf', 'dev.cur', 'dev.flush', 'dev.hold', 'deviceIsInteractive', 'dev.interactive', 'dev.list', 'dev.new', 'dev.next', 'dev.off', 'dev.prev', 'dev.print', 'dev.set', 'dev.size', 'embedFonts', 'getGraphicsEvent', 'getGraphicsEventEnv', 'graphics.off', 'jpeg', 'pdf', 'pdfFonts', 'pdf.options', 'pictex', 'png', 'postscript', 'postscriptFont', 'postscriptFonts', 'ps.options', 'quartz', 'quartzFont', 'quartzFonts', 'quartz.options', 'recordGraphics', 'recordPlot', 'replayPlot', 'savePlot', 'setEPS', 'setGraphicsEventEnv', 'setGraphicsEventHandlers', 'setPS', 'svg', 'tiff', 'Type1Font', 'x11', 'X11', 'X11Font', 'X11Fonts', 'X11.options', 'xfig'),
methods = c('addNextMethod', 'allGenerics', 'allNames', 'asMethodDefinition', 'assignClassDef', 'assignMethodsMetaData', 'balanceMethodsList', 'cacheGenericsMetaData', 'cacheMetaData', 'cacheMethod', 'callGeneric', 'callNextMethod', 'canCoerce', 'checkSlotAssignment', '.classEnv', 'classesToAM', 'classLabel', 'classMetaName', 'className', 'completeClassDefinition', 'completeExtends', 'completeSubclasses', 'conformMethod', 'defaultDumpName', 'defaultPrototype', 'doPrimitiveMethod', '.doTracePrint', 'dumpMethod', 'dumpMethods', 'el', 'elNamed', 'empty.dump', 'emptyMethodsList', 'evalOnLoad', 'evalqOnLoad', 'evalSource', 'existsFunction', 'existsMethod', 'finalDefaultMethod', 'findClass', 'findFunction', 'findMethod', 'findMethods', 'findMethodSignatures', 'findUnique', 'fixPre1.8', 'formalArgs', 'functionBody', 'generic.skeleton', 'getAccess', 'getAllMethods', 'getAllSuperClasses', 'getClass', 'getClassDef', 'getClasses', 'getClassName', 'getClassPackage', 'getDataPart', 'getExtends', 'getFunction', 'getGeneric', 'getGenerics', 'getGroup', 'getGroupMembers', 'getLoadActions', 'getMethod', 'getMethods', 'getMethodsForDispatch', 'getMethodsMetaData', 'getPackageName', 'getProperties', 'getPrototype', 'getRefClass', 'getSlots', 'getSubclasses', 'getValidity', 'getVirtual', 'hasArg', 'hasLoadAction', 'hasMethod', 'hasMethods', '.hasSlot', 'implicitGeneric', 'inheritedSlotNames', 'initFieldArgs', 'initialize', 'initRefFields', 'insertMethod', 'insertSource', 'isClass', 'isClassDef', 'isClassUnion', 'isGeneric', 'isGrammarSymbol', 'isGroup', 'isSealedClass', 'isSealedMethod', 'isVirtualClass', 'isXS3Class', 'languageEl', '.Last.lib', 'linearizeMlist', 'listFromMethods', 'listFromMlist', 'loadMethod', 'Logic', 'makeClassRepresentation', 'makeExtends', 'makeGeneric', 'makeMethodsList', 'makePrototypeFromClassDef', 'makeStandardGeneric', 'matchSignature', 'mergeMethods', 'metaNameUndo', 'MethodAddCoerce', 'methodSignatureMatrix', 'method.skeleton', 'MethodsList', 'MethodsListSelect', 'methodsPackageMetaName', 'missingArg', 'mlistMetaName', 'multipleClasses', 'new', 'newBasic', 'newClassRepresentation', 'newEmptyObject', 'new.env', 'new.packages', 'Ops', 'Ops.data.frame', 'Ops.Date', 'Ops.difftime', 'Ops.factor', 'Ops.numeric_version', 'Ops.ordered', 'Ops.POSIXt', 'Ops.raster', 'Ops.ts', 'packageSlot', 'possibleExtends', 'prohibitGeneric', 'promptClass', 'promptMethods', 'prototype', 'Quote', 'reconcilePropertiesAndPrototype', 'registerImplicitGenerics', 'rematchDefinition', 'removeClass', 'removeGeneric', 'removeMethod', 'removeMethods', 'removeMethodsObject', 'representation', 'requireMethods', 'resetClass', 'resetGeneric', 'S3Class', 'S3Part', 'sealClass', 'seemsS4Object', 'selectMethod', 'selectSuperClasses', '.selectSuperClasses', 'sessionData', 'setAs', 'setClass', 'setClassUnion', 'setDataPart', 'setGeneric', 'setGenericImplicit', 'setGroupGeneric', 'setIs', 'setLoadAction', 'setLoadActions', 'setMethod', 'setOldClass', 'setPackageName', 'setPrimitiveMethods', 'setRefClass', 'setReplaceMethod', 'setValidity', 'showClass', 'showDefault', 'showExtends', 'showMethods', 'showMlist', 'signature', 'SignatureMethod', 'sigToEnv', 'slot', 'slotNames', '.slotNames', 'slotsFromS3', 'substituteDirect', 'substituteFunctionArgs', 'superClassDepth', 'testInheritedMethods', 'testVirtual', 'traceOff', 'traceOn', '.TraceWithMethods', 'tryNew', 'trySilent', 'unRematchDefinition', '.untracedFunction', 'validObject', 'validSlotNames', '.valueClassTest'),
datasets = NULL,
grid = c('draw.details', 'drawDetails', 'drawDetails.recordedGrob', 'grid.record', 'postDrawDetails', 'preDrawDetails', 'recordGrob'),
lattice = c('trellis.device', 'checkArgsAndCall'),
KernSmooth = NULL,
nortest = NULL,
descr = c('file.head', 'fwf2csv'),
outliers = NULL)

if (missing(pkg))
pkg <- names(blacklist)

if (!all(pkg %in% names(blacklist)))
stop('Unknown package specified!')

return(blacklist[pkg])

}

This file was deleted.

Oops, something went wrong.
@@ -1,74 +1,72 @@
eval <- function(expr, envir, enclos) {

if (!missing(envir) | !missing(enclos))
stop('Tried to leave sandboxed environment.')

e <- parent.frame()
sandbox(deparse(substitute(expr)), e)

}


get <- function(x, pos, envir, ...) {

mc <- match.call()

if (!is.null(mc$envir)| !is.null(mc$pos))
stop('Tried to leave sandboxed environment.')

e <- parent.frame()
sandbox(x, e)


sandbox.pretest(x)

mc[[1]] <- quote(base::get)
mc$pos <- parent.frame()
base::eval(mc)

}


assign <- function(x, value, ...) {

mc <- match.call()

if (!is.null(mc$envir) | !is.null(mc$pos))
stop('Tried to leave sandboxed environment.')

e <- parent.frame()
sandbox(deparse(substitute(value)), e)


sandbox.pretest(deparse(substitute(value)))

mc[[1]] <- quote(base::assign)
mc$pos <- parent.frame()
base::eval(mc)

}


objects <- ls <- function(...) {

mc <- match.call(base::ls)

if (!is.null(mc$envir) | !is.null(mc$pos) | !is.null(mc$name))
stop('Tried to leave sandboxed environment.')

mc[[1]] <- quote(base::ls)
mc$pos <- parent.frame()
res <- base::eval(mc)

setdiff(res, c(as.character(unlist(commands.blacklist())), sub('\\.masked$', '', base::ls(pattern = ".*\\.masked", envir = getNamespace("sandboxR")))))

}


library <- function(...) {

mc <- match.call(base::library)

if (!is.null(mc$pos) | !is.null(mc$lib.loc))
stop('Tried to leave sandboxed environment.')

if (!is.null(mc$help))
stop('Sorry, read docs on localhost.')

if (!is.null(mc$package)) {
if (!is.character(mc$package))
mc$package <- deparse(mc$package)
@@ -77,19 +75,19 @@ library <- function(...) {
} else {
return(names(commands.blacklist()))
}

mc[[1]] <- quote(base::library)
res <- base::eval(mc)

return(invisible(res))

}


require <- function(...) {

mc <- match.call(base::require)

if (!is.null(mc$lib.loc))
stop('Tried to leave sandboxed environment.')
if (!is.null(mc$package)) {
@@ -100,19 +98,22 @@ require <- function(...) {
} else {
return(names(commands.blacklist()))
}

mc[[1]] <- quote(base::require)
res <- base::eval(mc)

return(invisible(res))

}


formula.character <- function(x, env = parent.frame(), ...)
{
sandbox(x)
sandbox.pretest(x)
ff <- formula(base::eval(base::parse(text = x)[[1L]]))
environment(ff) <- env
ff
}

latticeParseFormula <- lattice:::latticeParseFormula
body(latticeParseFormula) <- as.call(c(as.symbol("{"), c(substitute(if (inherits(groups, "formula")) sandbox.pretest(as.character(groups)[2])), as.list(body(latticeParseFormula))[-1])))
Oops, something went wrong.

0 comments on commit c49699f

Please sign in to comment.
You can’t perform that action at this time.