diff --git a/changelog.md b/changelog.md index 18472a5e615d4..762aa7953ccf2 100644 --- a/changelog.md +++ b/changelog.md @@ -290,6 +290,14 @@ parameter and result types, not just their source-level shape. Use - Hot code reloading works on Linux on arm64 with glibc; before, it was limited to musl there and the HCR runtime did not compile. +- The new switch `--compileTime:restricted` limits what compiling a project + can do: compile-time code runs only the command lines given with + `--staticExecWhitelist:""`, reads only below the project, `--path`, + nimble package and Nim `lib` directories, and cannot write files or change + the environment; configuration files of the project and its parent + directories are not read. The default, `--compileTime:normal`, is unchanged. + `{.passC.}`, `{.passL.}`, `{.compile.}`, `{.link.}` and `getEnv` are not + covered. See "Compiling code you have not read" in the compiler user guide. - An import annotated with `{.cyclic.}` (`import b {.cyclic.}`) makes the modules of an import cycle a group whose types and leading routines are diff --git a/compiler/commands.nim b/compiler/commands.nim index 1d62b6a5be582..2f09ebf99c256 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -678,6 +678,14 @@ proc pathRelativeToConfig(arg: string, pass: TCmdLinePass, conf: ConfigRef): str else: result = arg +proc checkVmopsDangerConflict(conf: ConfigRef; info: TLineInfo) = + # vmopsDanger enables `execCmdEx` at compile time, which bypasses the + # `--staticExecWhitelist` + if vmopsDanger in conf.features and conf.compileTimeMode == ctmRestricted: + liMessage(conf, info, errGenerated, + "--experimental:vmopsDanger cannot be combined with --compileTime:restricted", + doAbort, instLoc()) + proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; conf: ConfigRef) = var key = "" @@ -1087,6 +1095,16 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; if conf.backend == backendJs: # for now, -r uses nodejs, so define nodejs defineSymbol(conf.symbols, "nodejs") + of "compiletime": + expectArg(conf, switch, arg, pass, info) + case arg.normalize + of "normal": conf.compileTimeMode = ctmNormal + of "restricted": conf.compileTimeMode = ctmRestricted + else: localError(conf, info, "expected 'normal' or 'restricted' but found '$1'" % arg) + checkVmopsDangerConflict(conf, info) + of "staticexecwhitelist": + expectArg(conf, switch, arg, pass, info) + if arg notin conf.staticExecWhitelist: conf.staticExecWhitelist.add arg of "maxloopiterationsvm": expectArg(conf, switch, arg, pass, info) var value: int = 10_000_000 @@ -1262,6 +1280,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo; conf.features.incl parseEnum[Feature](arg) except ValueError: localError(conf, info, "unknown experimental feature") + checkVmopsDangerConflict(conf, info) of "legacy": try: conf.legacyFeatures.incl parseEnum[LegacyFeature](arg) diff --git a/compiler/gorgeimpl.nim b/compiler/gorgeimpl.nim index da911c84cf513..459f6b9e805ee 100644 --- a/compiler/gorgeimpl.nim +++ b/compiler/gorgeimpl.nim @@ -28,7 +28,18 @@ proc readOutput(p: Process): (string, int) = result[0].setLen(result[0].len - "\n".len) result[1] = p.waitForExit +proc checkCommandAllowed*(conf: ConfigRef; cmd: string; info: TLineInfo) = + ## Under `--compileTime:restricted`, compile-time code runs only the command + ## lines given with `--staticExecWhitelist`, compared as whole strings: allowing a + ## program by name would allow its options that run other commands + ## (`sh -c`, `git -c alias.x=!cmd`). + if compileTimeEffects(conf, skippedByCheck = false) == cteRestrict and + cmd notin conf.staticExecWhitelist: + globalError(conf, info, "command refused by --compileTime:restricted, " & + "it is not in --staticExecWhitelist: '" & cmd & "'") + proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (string, int) = + checkCommandAllowed(conf, cmd, info) # before the cache: a cached result is still a run let workingDir = parentDir(toFullPath(conf, info)) result = ("", 0) if cache.len > 0: diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index 822ee844c9315..79e4e5e41525a 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -286,15 +286,19 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen: if cfg == DefaultConfig: runNimScriptIfExists(getUserConfigPath(DefaultConfigNims)) + # `--compileTime:restricted` reads no configuration from the project or the + # directories above it: `nim.cfg` runs commands too (`gcc.exe`, `@putenv`). + # Only the system and user configuration and the command line are trusted. + let restricted = conf.compileTimeMode == ctmRestricted let pd = if not conf.projectPath.isEmpty: conf.projectPath else: AbsoluteDir(getCurrentDir()) - if optSkipParentConfigFiles notin conf.globalOptions: + if optSkipParentConfigFiles notin conf.globalOptions and not restricted: for dir in parentDirs(pd.string, fromRoot=true, inclusive=false): readConfigFile(AbsoluteDir(dir) / cfg) if cfg == DefaultConfig: runNimScriptIfExists(AbsoluteDir(dir) / DefaultConfigNims) - if optSkipProjConfigFile notin conf.globalOptions: + if optSkipProjConfigFile notin conf.globalOptions and not restricted: readConfigFile(pd / cfg) if cfg == DefaultConfig: runNimScriptIfExists(pd / DefaultConfigNims) @@ -319,10 +323,10 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen: if not conf.ideActive and conf.cmd notin {cmdCheck, cmdDump}: if conf.cmd == cmdNimscript: runNimScriptIfExists(conf.projectFull, isMain = true) - else: + elif not restricted or scriptIsProj: runNimScriptIfExists(scriptFile, isMain = true) else: - if not scriptIsProj: + if not scriptIsProj and not restricted: runNimScriptIfExists(scriptFile, isMain = true) else: # 'nimsuggest foo.nims' means to just auto-complete the NimScript file diff --git a/compiler/options.nim b/compiler/options.nim index 0a601032c8de5..0f246d4d2099f 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -260,6 +260,19 @@ type # gcRefc and the GCs that follow it use a write barrier, # as far as usesWriteBarrier() is concerned + CompileTimeMode* = enum ## `--compileTime` + ctmNormal = "normal" + ctmRestricted = "restricted" + + CompileTimeEffects* = enum + ## What compile-time code may do to the world outside the compiler: run a + ## program, or change files or the environment. See `compileTimeEffects`. + cteRun ## the call runs + cteSkip ## `nim check` and nimsuggest: the call does nothing, so that + ## checking code never changes anything + cteRestrict ## `--compileTime:restricted`: a command runs only when it is + ## on the `--staticExecWhitelist`; any other call is an error + IdeCmd* = enum ideNone, ideSug, ideCon, ideDef, ideUse, ideDus, ideChk, ideChkFile, ideMod, ideHighlight, ideOutline, ideKnown, ideMsg, ideProject, ideGlobalSymbols, @@ -611,6 +624,8 @@ type expandPosition*: TLineInfo currentConfigDir*: string # used for passPP only; absolute dir + compileTimeMode*: CompileTimeMode + staticExecWhitelist*: seq[string] # exact command lines (`--staticExecWhitelist`) clientProcessId*: int @@ -879,6 +894,18 @@ proc icReuseSemLowering*(conf: ConfigRef): bool {.inline.} = ## doc/ic_backend_simplify.md ยง6b. isDefined(conf, "icReuseSemLowering") +proc compileTimeEffects*(conf: ConfigRef; skippedByCheck = true): CompileTimeEffects = + ## The one answer to "may compile-time code (macros, `static`, NimScript) run + ## a program or change files or the environment?". + ## `skippedByCheck` is false for the calls that `nim check` has always run + ## (`putEnv`, `delEnv`, NimScript's `mkDir`); `nim check` keeps doing so. + if skippedByCheck and (defined(nimsuggest) or conf.cmd == cmdCheck): + cteSkip + elif conf.compileTimeMode == ctmRestricted: + cteRestrict + else: + cteRun + proc importantComments*(conf: ConfigRef): bool {.inline.} = conf.ideActive or conf.cmd in cmdDocLike proc usesWriteBarrier*(conf: ConfigRef): bool {.inline.} = conf.selectedGC >= gcRefc proc usesSso*(conf: ConfigRef): bool {.inline.} = conf.selectedStrings == stringSso diff --git a/compiler/scriptconfig.nim b/compiler/scriptconfig.nim index 0ae78f6de6a8c..79f8f769208ce 100644 --- a/compiler/scriptconfig.nim +++ b/compiler/scriptconfig.nim @@ -12,7 +12,7 @@ import ast, modules, idents, condsyms, - options, llstream, vm, vmdef, commands, + options, llstream, vm, vmdef, vmdeps, gorgeimpl, commands, wordrecg, modulegraphs, lineinfos, pathutils, pipelines @@ -60,6 +60,13 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; template cbos(name, body) {.dirty.} = cbexc(name, OSError, body) + template effect(name: string; skippedByCheck: bool; body) {.dirty.} = + ## `body` changes files or the environment; see `compileTimeEffects`. + case compileTimeEffects(conf, skippedByCheck) + of cteSkip: discard + of cteRestrict: refuseCompileTimeEffect(conf, a.currentLineInfo, name) + of cteRun: body + # Idea: Treat link to file as a file, but ignore link to directory to prevent # endless recursions out of the box. cbos listFilesImpl: @@ -67,17 +74,14 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; cbos listDirsImpl: listDirs(a, {pcDir}) cbos removeDir: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + effect("removeDir", skippedByCheck = true): os.removeDir(getString(a, 0), getBool(a, 1)) cbos removeFile: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + effect("removeFile", skippedByCheck = true): os.removeFile getString(a, 0) cbos createDir: - os.createDir getString(a, 0) + effect("createDir", skippedByCheck = false): + os.createDir getString(a, 0) result.registerCallback "stdlib.system.getError", proc (a: VmArgs) = setResult(a, errorMsg) @@ -87,24 +91,16 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; cbos getCurrentDir: setResult(a, os.getCurrentDir()) cbos moveFile: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + effect("moveFile", skippedByCheck = true): os.moveFile(getString(a, 0), getString(a, 1)) cbos moveDir: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + effect("moveDir", skippedByCheck = true): os.moveDir(getString(a, 0), getString(a, 1)) cbos copyFile: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + effect("copyFile", skippedByCheck = true): os.copyFile(getString(a, 0), getString(a, 1)) cbos copyDir: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + effect("copyDir", skippedByCheck = true): os.copyDir(getString(a, 0), getString(a, 1)) cbos getLastModificationTime: setResult(a, getLastModificationTime(getString(a, 0)).toUnix) @@ -112,9 +108,8 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; setResult(a, os.findExe(getString(a, 0))) cbos rawExec: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: - discard - else: + if compileTimeEffects(conf) != cteSkip: + checkCommandAllowed(conf, getString(a, 0), a.currentLineInfo) setResult(a, osproc.execCmd getString(a, 0)) cbconf getEnv: @@ -122,9 +117,11 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; cbconf existsEnv: setResult(a, os.existsEnv(a.getString 0)) cbconf putEnv: - os.putEnv(a.getString 0, a.getString 1) + effect("putEnv", skippedByCheck = false): + os.putEnv(a.getString 0, a.getString 1) cbconf delEnv: - os.delEnv(a.getString 0) + effect("delEnv", skippedByCheck = false): + os.delEnv(a.getString 0) cbconf dirExists: setResult(a, os.dirExists(a.getString 0)) cbconf fileExists: @@ -183,12 +180,12 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; cbconf cppDefine: options.cppDefine(conf, a.getString(0)) cbexc stdinReadLine, EOFError: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: + if compileTimeEffects(conf) == cteSkip: setResult(a, "") else: setResult(a, stdin.readLine()) cbexc stdinReadAll, EOFError: - if defined(nimsuggest) or graph.config.cmd == cmdCheck: + if compileTimeEffects(conf) == cteSkip: setResult(a, "") else: setResult(a, stdin.readAll()) diff --git a/compiler/vm.nim b/compiler/vm.nim index 91054111ae143..a973faacf0f18 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -1979,8 +1979,8 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): Address = putStr(ra, opSlurp(str(instr.regB), c.debug[pc], c.module, c.config)) of opcGorge: let rb = instr.regB - if defined(nimsuggest) or c.config.cmd == cmdCheck: - discard "don't run staticExec for 'nim suggest'" + if compileTimeEffects(c.config) == cteSkip: + discard "don't run staticExec for 'nim check' and 'nim suggest'" putStr(ra, "") else: when defined(nimcore): diff --git a/compiler/vmdeps.nim b/compiler/vmdeps.nim index 84cd80cdb2f40..228128edab2b9 100644 --- a/compiler/vmdeps.nim +++ b/compiler/vmdeps.nim @@ -8,18 +8,67 @@ # import ast, types, msgs, options, idents, lineinfos -from pathutils import AbsoluteFile +from pathutils import AbsoluteFile, AbsoluteDir, isEmpty import std/[os, tables] +from std/strutils import split when defined(nimPreviewSlimSystem): import std/syncio +proc refuseCompileTimeEffect*(conf: ConfigRef; info: TLineInfo; op: string) = + ## The error for a call that `compileTimeEffects` answers with `cteRestrict`. + globalError(conf, info, "'" & op & "' refused by --compileTime:restricted") + +proc realPath(path: string): string = + ## `path` made absolute with every symbolic link resolved, the way the OS + ## resolves it. From the first part that does not exist on, the rest is + ## appended as written: the OS cannot open such a path anyway. + ## Note: on Windows `expandFilename` does not resolve links. + let parts = absolutePath(path).split({DirSep, AltSep}) + result = parts[0] & DirSep # "/" or a drive like "C:\" + var exists = true + for i in 1.. 0: result.parentDir else: result) + else: result / part + if exists and (fileExists(next) or dirExists(next)): + result = expandFilename(next) + else: + exists = false + result = next + +proc checkCompileTimeRead*(conf: ConfigRef; path: string; info: TLineInfo) = + ## Under `--compileTime:restricted`, compile-time code reads only below the + ## project directory, the `--path` and nimble package directories and Nim's + ## `lib`; after symbolic links are resolved. Project configuration files are + ## not read in this mode, so every root was given by the command line or the + ## system or user configuration. + if compileTimeEffects(conf, skippedByCheck = false) != cteRestrict: return + var roots = @[conf.libpath] + if not conf.projectPath.isEmpty: roots.add conf.projectPath + roots.add conf.searchPaths + roots.add conf.lazyPaths + roots.add conf.nimblePaths + try: + let real = realPath(path) + for root in roots: + if dirExists(root.string) and real.isRelativeTo(realPath(root.string)): + return + except OSError: + globalError(conf, info, "read refused by --compileTime:restricted: '" & path & + "' cannot be resolved: " & getCurrentExceptionMsg()) + globalError(conf, info, "read refused by --compileTime:restricted: '" & path & + "' is outside the project, --path, nimble package and Nim lib directories") + proc opSlurp*(file: string, info: TLineInfo, module: PSym; conf: ConfigRef): string = try: var filename = parentDir(toFullPath(conf, info)) / file if not fileExists(filename): filename = findFile(conf, file).string + if filename.len > 0: # else readFile fails with "cannot open file" below + checkCompileTimeRead(conf, filename, info) result = readFile(filename) # we produce a fake include statement for every slurped filename, so that # the module dependencies are accurate: diff --git a/compiler/vmops.nim b/compiler/vmops.nim index 7c417d88899b3..bdc884395ad73 100644 --- a/compiler/vmops.nim +++ b/compiler/vmops.nim @@ -100,41 +100,32 @@ template wrap2s(op, modop) {.dirty.} = setResult(a, op(getString(a, 0), getString(a, 1))) modop op -template wrap2si(op, modop) {.dirty.} = - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - setResult(a, op(getString(a, 0), getInt(a, 1))) - modop op - -template wrap1svoid(op, modop) {.dirty.} = - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - op(getString(a, 0)) - modop op - -template wrap2svoid(op, modop) {.dirty.} = - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - op(getString(a, 0), getString(a, 1)) +template wrapEffect(op, modop: untyped; skippedByCheck: bool; call: untyped) {.dirty.} = + ## Registers `op`, which changes files or the environment, under the policy of + ## `compileTimeEffects`. + block: + let policy = compileTimeEffects(c.config, skippedByCheck) + if policy == cteRestrict: + proc `op Wrapper`(a: VmArgs) = + refuseCompileTimeEffect(c.config, a.currentLineInfo, astToStr(op)) + modop op + elif policy == cteSkip and vmopsDanger notin c.config.features: + proc `op Wrapper`(a: VmArgs) {.nimcall.} = + discard + modop op + else: # cteRun, or cteSkip overridden by vmopsDanger + proc `op Wrapper`(a: VmArgs) {.nimcall.} = + call + modop op + +template wrapRead(op, modop, call: untyped) {.dirty.} = + ## Registers `op`, which reads the path in its first argument, with the + ## check of `checkCompileTimeRead`. + proc `op Wrapper`(a: VmArgs) = + checkCompileTimeRead(c.config, getString(a, 0), a.currentLineInfo) + call modop op -template wrapDangerous1svoid(op, modop) {.dirty.} = - if vmopsDanger notin c.config.features and (defined(nimsuggest) or c.config.cmd == cmdCheck): - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - discard - modop op - else: - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - op(getString(a, 0)) - modop op - -template wrapDangerous2svoid(op, modop) {.dirty.} = - if vmopsDanger notin c.config.features and (defined(nimsuggest) or c.config.cmd == cmdCheck): - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - discard - modop op - else: - proc `op Wrapper`(a: VmArgs) {.nimcall.} = - op(getString(a, 0), getString(a, 1)) - modop op - proc getCurrentExceptionMsgWrapper(a: VmArgs) {.nimcall.} = setResult(a, currentExceptionMsg(a.ctx, a.currentException)) @@ -254,30 +245,35 @@ proc registerAdditionalOps*(c: PCtx) = when defined(nimcore): wrap2s(getEnv, envvarsop) wrap1s(existsEnv, envvarsop) - wrap2svoid(putEnv, envvarsop) - wrap1svoid(delEnv, envvarsop) - wrap1s(dirExists, oscommonop) - wrap1s(fileExists, oscommonop) - wrapDangerous2svoid(writeFile, ioop) - wrapDangerous1svoid(createDir, osdirsop) - wrap1s(readFile, ioop) - wrap2si(readLines, ioop) + wrapEffect(putEnv, envvarsop, skippedByCheck = false, + putEnv(getString(a, 0), getString(a, 1))) + wrapEffect(delEnv, envvarsop, skippedByCheck = false, delEnv(getString(a, 0))) + wrapRead(dirExists, oscommonop, setResult(a, dirExists(getString(a, 0)))) + wrapRead(fileExists, oscommonop, setResult(a, fileExists(getString(a, 0)))) + wrapEffect(writeFile, ioop, skippedByCheck = true, + writeFile(getString(a, 0), getString(a, 1))) + wrapEffect(createDir, osdirsop, skippedByCheck = true, createDir(getString(a, 0))) + wrapRead(readFile, ioop, setResult(a, readFile(getString(a, 0)))) + wrapRead(readLines, ioop, setResult(a, readLines(getString(a, 0), getInt(a, 1)))) systemop getCurrentExceptionMsg systemop getCurrentException systemop raiseDefect - registerCallback c, "stdlib.staticos.staticWalkDir", proc (a: VmArgs) {.nimcall.} = + registerCallback c, "stdlib.staticos.staticWalkDir", proc (a: VmArgs) = + checkCompileTimeRead(c.config, getString(a, 0), a.currentLineInfo) setResult(a, staticWalkDirImpl(getString(a, 0), getBool(a, 1))) - registerCallback c, "stdlib.staticos.staticDirExists", proc (a: VmArgs) {.nimcall.} = + registerCallback c, "stdlib.staticos.staticDirExists", proc (a: VmArgs) = + checkCompileTimeRead(c.config, getString(a, 0), a.currentLineInfo) setResult(a, dirExists(getString(a, 0))) - registerCallback c, "stdlib.staticos.staticFileExists", proc (a: VmArgs) {.nimcall.} = + registerCallback c, "stdlib.staticos.staticFileExists", proc (a: VmArgs) = + checkCompileTimeRead(c.config, getString(a, 0), a.currentLineInfo) setResult(a, fileExists(getString(a, 0))) registerCallback c, "stdlib.compilesettings.querySetting", proc (a: VmArgs) = setResult(a, querySettingImpl(c.config, getInt(a, 0))) registerCallback c, "stdlib.compilesettings.querySettingSeq", proc (a: VmArgs) = setResult(a, querySettingSeqImpl(c.config, getInt(a, 0))) - if defined(nimsuggest) or c.config.cmd == cmdCheck: - discard "don't run staticExec for 'nim suggest'" + if compileTimeEffects(c.config) == cteSkip: + discard "don't run staticExec for 'nim check' and 'nim suggest'" else: systemop gorgeEx macrosop getProjectPath diff --git a/doc/advopt.txt b/doc/advopt.txt index 189269e4c0a74..d3357370a60b5 100644 --- a/doc/advopt.txt +++ b/doc/advopt.txt @@ -144,6 +144,16 @@ Advanced options: --skipUserCfg:on|off do not read the user's configuration file --skipParentCfg:on|off do not read the parent dirs' configuration files --skipProjCfg:on|off do not read the project's configuration file + --compileTime:normal|restricted + restricted: compile-time code runs only the commands + given with --staticExecWhitelist, reads only below the + project, --path, nimble package and lib directories, + and cannot change files or the environment; the + project's and parent dirs' configuration files are + not read. Default: normal + --staticExecWhitelist:"CMD" + with --compileTime:restricted, let compile-time code + run exactly the command line CMD; can be repeated --mm:orc|arc|refc|markAndSweep|boehm|go|none|regions select which memory management to use; default is 'orc' --exceptions:setjmp|cpp|goto|quirky diff --git a/doc/nimc.md b/doc/nimc.md index ae3c8d8ef7790..28a9491ae9c73 100644 --- a/doc/nimc.md +++ b/doc/nimc.md @@ -238,6 +238,9 @@ directories (in this order; later files overwrite previous settings): Command-line settings have priority over configuration file settings. +With `--compileTime:restricted`:option: only the files of 1) and 2) are read; +see [Compiling code you have not read]. + The default build of a project is a `debug build`:idx:. To compile a `release build`:idx: define the `release` symbol: @@ -252,6 +255,46 @@ To compile a `dangerous release build`:idx: define the `danger` symbol: ``` +Compiling code you have not read +-------------------------------- + +Compiling a Nim project can run code: macros and `static` blocks run at +compile time and can call `staticExec`, `gorgeEx`, `readFile`, `writeFile`, +`putEnv` and similar procs; configuration files (``nim.cfg`` included, through +settings like ``gcc.exe`` and ``@putenv``) and NimScript files can run +commands too. The `--compileTime:restricted`:option: switch limits this, for +example when a tool compiles code nobody has reviewed: + +- `staticExec`, `gorge` and `gorgeEx` run only the command lines given with + `--staticExecWhitelist`:option:, compared as whole strings + (``--staticExecWhitelist:"git rev-parse HEAD"``). Any other command is a + compile-time error that names it. Allowing a program by name would not be + enough, as most programs have options that run other commands. +- `staticRead`/`slurp`, `readFile`, `readLines`, `fileExists`, `dirExists` + and the procs of `std/staticos` read only below the project directory, the + `--path`:option: and nimble package directories and Nim's ``lib`` + directory, after symbolic links are resolved. Other paths are compile-time + errors. +- `writeFile`, `createDir`, `putEnv` and `delEnv` at compile time, and the + NimScript procs that change files or the environment, are errors. +- Configuration files of the project and its parent directories + (``nim.cfg``, ``config.nims``, ``$project.nims``, ``$project.nim.cfg``) + are not read. The system and user configuration and the command line still + apply, so `--compileTime`:option: and `--staticExecWhitelist`:option: can only + come from them. A NimScript file named on the command line still runs. +- `--experimental:vmopsDanger`:option: cannot be combined with it. + +`nim check`:cmd: and nimsuggest keep skipping `staticExec` and the procs that +write files, with or without the switch. + +The switch does not cover: the `{.passC.}`, `{.passL.}`, `{.compile.}` and +`{.link.}` pragmas, which hand flags and files to the C compiler and linker; +`getEnv`, which can embed environment variables (secrets) into the program; +`include` and `import` of files outside the directories above; on Windows, +symbolic links in the paths read are not resolved; and whatever a package +manager does before it starts the compiler. + + Search path handling -------------------- diff --git a/tests/compiletime_restricted/tcreatedir_refused.nim b/tests/compiletime_restricted/tcreatedir_refused.nim new file mode 100644 index 0000000000000..f381b96c12e33 --- /dev/null +++ b/tests/compiletime_restricted/tcreatedir_refused.nim @@ -0,0 +1,11 @@ +discard """ + cmd: '''nim c --compileTime:restricted --hints:off $file''' + errormsg: "'createDir' refused by --compileTime:restricted" + line: 11 +""" + +# R4 +import std/os + +static: + createDir("trestricted_created") diff --git a/tests/compiletime_restricted/tdelenv_refused.nim b/tests/compiletime_restricted/tdelenv_refused.nim new file mode 100644 index 0000000000000..c71befe160549 --- /dev/null +++ b/tests/compiletime_restricted/tdelenv_refused.nim @@ -0,0 +1,11 @@ +discard """ + cmd: '''nim c --compileTime:restricted --hints:off $file''' + errormsg: "'delEnv' refused by --compileTime:restricted" + line: 11 +""" + +# R4 +import std/envvars + +static: + delEnv("NIM_TRESTRICTED_UNSET") diff --git a/tests/compiletime_restricted/tgorgeex_refused.nim b/tests/compiletime_restricted/tgorgeex_refused.nim new file mode 100644 index 0000000000000..6b7d85930d977 --- /dev/null +++ b/tests/compiletime_restricted/tgorgeex_refused.nim @@ -0,0 +1,8 @@ +discard """ + cmd: '''nim c --compileTime:restricted --hints:off $file''' + errormsg: "command refused by --compileTime:restricted, it is not in --staticExecWhitelist: 'echo hi'" + line: 8 +""" + +# R1: an empty whitelist runs nothing; `gorgeEx` takes the same check. +const res = gorgeEx("echo hi") diff --git a/tests/compiletime_restricted/tputenv_refused.nim b/tests/compiletime_restricted/tputenv_refused.nim new file mode 100644 index 0000000000000..dbc0c331b6cbc --- /dev/null +++ b/tests/compiletime_restricted/tputenv_refused.nim @@ -0,0 +1,11 @@ +discard """ + cmd: '''nim c --compileTime:restricted --hints:off $file''' + errormsg: "'putEnv' refused by --compileTime:restricted" + line: 11 +""" + +# R4: C compiler processes inherit the environment (e.g. `LD_PRELOAD`). +import std/envvars + +static: + putEnv("NIM_TRESTRICTED", "1") diff --git a/tests/compiletime_restricted/trestricted.nim b/tests/compiletime_restricted/trestricted.nim new file mode 100644 index 0000000000000..c7c714ca07d0f --- /dev/null +++ b/tests/compiletime_restricted/trestricted.nim @@ -0,0 +1,228 @@ +discard """ + joinable: false + disabled: "windows" +""" + +## `--compileTime:restricted` (RFC #578): the rules that need a project tree on +## disk (configuration files, symbolic links, the user configuration) are +## checked here by running the compiler on generated projects. +## Disabled on Windows: the fixtures use symbolic links and `sh` scripts. + +import std/[os, osproc, strutils, strtabs, unittest] + +const nim = getCurrentCompilerExe() + +let root = getTempDir() / ("nim_trestricted_" & $getCurrentProcessId()) +removeDir(root) +createDir(root) + +proc write(path, content: string) = + createDir(path.parentDir) + writeFile(path, content) + +proc envWith(key, val: string): StringTableRef = + result = newStringTable(modeCaseSensitive) + for k, v in envPairs(): result[k] = v + result[key] = val + +proc runNim(args: string; dir = root; env: StringTableRef = nil): tuple[output: string, exitCode: int] = + ## Runs the compiler under test with an empty user configuration unless + ## `env` names another one, so that the developer's own config is not read. + let env = if env != nil: env else: envWith("XDG_CONFIG_HOME", root / "xdg_empty") + result = execCmdEx(nim & " " & args, env = env, workingDir = dir) + +proc refusedRead(output: string): bool = + "read refused by --compileTime:restricted" in output + +suite "--compileTime:restricted": + test "R5: project and parent configuration files are not read": + # Given: a project whose configuration files would each leave a trace. + # `nim.cfg` replaces the C compiler with a script, which is how a + # configuration file runs commands without NimScript. + let parent = root / "r5" + let proj = parent / "proj" + let ccScript = parent / "cc.sh" + write(ccScript, "#!/bin/sh\necho ran > \"" & (parent / "cc.marker") & "\"\nexec cc \"$@\"\n") + setFilePermissions(ccScript, {fpUserRead, fpUserWrite, fpUserExec}) + write(parent / "nim.cfg", "@putenv \"NIM_TRESTRICTED_PARENTCFG\" \"1\"\n") + write(parent / "config.nims", "writeFile(\"" & (parent / "parentnims.marker") & "\", \"\")\n") + write(proj / "nim.cfg", + "@putenv \"NIM_TRESTRICTED_NIMCFG\" \"1\"\n" & + "clang.exe = \"" & ccScript & "\"\nclang.linkerexe = \"" & ccScript & "\"\n" & + "gcc.exe = \"" & ccScript & "\"\ngcc.linkerexe = \"" & ccScript & "\"\n") + write(proj / "config.nims", "writeFile(\"" & (parent / "confignims.marker") & "\", \"\")\n") + write(proj / "m.nims", "writeFile(\"" & (parent / "projnims.marker") & "\", \"\")\n") + write(proj / "m.nim.cfg", "@putenv \"NIM_TRESTRICTED_PROJCFG\" \"1\"\n") + write(proj / "m.nim", """ +import std/envvars +const seen = getEnv("NIM_TRESTRICTED_PARENTCFG") & "," & getEnv("NIM_TRESTRICTED_NIMCFG") & "," & + getEnv("NIM_TRESTRICTED_PROJCFG") +echo "seen:", seen +""") + let markers = ["cc.marker", "parentnims.marker", "confignims.marker", "projnims.marker"] + + # When: compiled normally, every file takes effect (the fixture works). + let normal = runNim("c -f -r --hints:off --nimcache:" & (parent / "cache_normal") & " m.nim", proj) + check normal.exitCode == 0 + check "seen:1,1,1" in normal.output + for m in markers: + check fileExists(parent / m) + removeFile(parent / m) + + # When: compiled with --compileTime:restricted, none of them is read. + let restricted = runNim("c -f -r --hints:off --compileTime:restricted --nimcache:" & + (parent / "cache_restricted") & " m.nim", proj) + check restricted.exitCode == 0 + check "seen:,," in restricted.output + for m in markers: + check not fileExists(parent / m) + + test "R5: a NimScript file named on the command line still runs": + write(root / "r5s" / "s.nims", "echo \"script ran\"\n") + let res = runNim("e --hints:off --compileTime:restricted s.nims", root / "r5s") + check res.exitCode == 0 + check "script ran" in res.output + + test "R4: NimScript cannot change files or the environment; exec takes the whitelist": + let dir = root / "r4s" + for (name, code, expected) in [ + ("rm.nims", "rmFile(\"x\")\n", "'removeFile' refused by --compileTime:restricted"), + ("mk.nims", "mkDir(\"d\")\n", "'createDir' refused by --compileTime:restricted"), + ("wr.nims", "writeFile(\"w\", \"\")\n", "'writeFile' refused by --compileTime:restricted"), + ("env.nims", "putEnv(\"NIM_TRESTRICTED\", \"1\")\n", "'putEnv' refused by --compileTime:restricted"), + ("exec.nims", "exec \"echo nope\"\n", "it is not in --staticExecWhitelist: 'echo nope'")]: + write(dir / name, code) + let res = runNim("e --hints:off --compileTime:restricted " & name, dir) + checkpoint name & ":\n" & res.output + check res.exitCode != 0 + check expected in res.output + check not dirExists(dir / "d") + check not fileExists(dir / "w") + write(dir / "ok.nims", "exec \"echo yes\"\n") + let ok = runNim("e --hints:off --compileTime:restricted \"--staticExecWhitelist:echo yes\" ok.nims", dir) + check ok.exitCode == 0 + check "yes" in ok.output + + test "R2: a project configuration cannot widen the whitelist or switch the mode off": + let proj = root / "r2" + write(proj / "nim.cfg", "--compileTime:normal\n--staticExecWhitelist:\"echo pwned\"\n") + write(proj / "m.nim", "const x = staticExec(\"echo pwned\")\n") + let res = runNim("c --compileOnly --hints:off --compileTime:restricted m.nim", proj) + check res.exitCode != 0 + check "command refused by --compileTime:restricted, it is not in --staticExecWhitelist: 'echo pwned'" in res.output + + test "R2: the user configuration can set the mode and the whitelist": + let xdg = root / "r2u" / "xdg" + write(xdg / "nim" / "nim.cfg", "--compileTime:restricted\n--staticExecWhitelist:\"echo fromuser\"\n") + let proj = root / "r2u" / "proj" + write(proj / "nim.cfg", "--staticExecWhitelist:\"echo fromproject\"\n") + write(proj / "ok.nim", "const x = staticExec(\"echo fromuser\")\nstatic: doAssert x == \"fromuser\"\n") + write(proj / "ng.nim", "const x = staticExec(\"echo fromproject\")\n") + let env = envWith("XDG_CONFIG_HOME", xdg) + let ok = runNim("c --compileOnly --hints:off ok.nim", proj, env) + check ok.exitCode == 0 + let ng = runNim("c --compileOnly --hints:off ng.nim", proj, env) + check ng.exitCode != 0 + check "it is not in --staticExecWhitelist: 'echo fromproject'" in ng.output + + test "R6: vmopsDanger from the user configuration is refused in restricted mode": + let xdg = root / "r6" / "xdg" + write(xdg / "nim" / "nim.cfg", "--experimental:vmopsDanger\n") + write(root / "r6" / "m.nim", "echo 1\n") + let res = runNim("c --compileOnly --hints:off --compileTime:restricted m.nim", root / "r6", + envWith("XDG_CONFIG_HOME", xdg)) + check res.exitCode != 0 + check "--experimental:vmopsDanger cannot be combined with --compileTime:restricted" in res.output + + test "R1: a cached staticExec result does not bypass the whitelist": + let proj = root / "r1c" + write(proj / "m.nim", "const x = staticExec(\"echo cached\", cache = \"k\")\necho x\n") + let cache = proj / "cache" + let normal = runNim("c --compileOnly --hints:off --nimcache:" & cache & " m.nim", proj) + check normal.exitCode == 0 + let restricted = runNim("c --compileOnly --hints:off --compileTime:restricted --nimcache:" & + cache & " m.nim", proj) + check restricted.exitCode != 0 + check "it is not in --staticExecWhitelist: 'echo cached'" in restricted.output + + test "R7: nim check still skips staticExec and writeFile, with or without the switch": + let proj = root / "r7" + write(proj / "m.nim", "const x = staticExec(\"echo bye\")\nstatic: writeFile(\"r7.marker\", \"\")\n") + for args in ["check --hints:off m.nim", "check --hints:off --compileTime:restricted m.nim"]: + let res = runNim(args, proj) + check res.exitCode == 0 + check not fileExists(proj / "r7.marker") + + # R3: compile-time reads stay under the project, --path, nimble and lib. + let r3 = root / "r3" + let proj = r3 / "proj" + let outside = r3 / "outside" + let extra = r3 / "extra" + write(outside / "secret.txt", "secret") + write(extra / "extra.txt", "extra") + write(proj / "inside.txt", "inside") + write(proj / "sub" / "data.txt", "data") + createSymlink(outside / "secret.txt", proj / "link_file") + createSymlink(outside, proj / "link_dir") + write(proj / "r3.nim", """ +import std/[os, staticos, compilesettings] +const which {.strdefine.} = "" +const outside {.strdefine.} = "" +const extra {.strdefine.} = "" +when which == "inside": + const a = staticRead("inside.txt") + const b = slurp(currentSourcePath.parentDir / "sub" / "data.txt") + const c = staticRead(extra / "extra.txt") + const d = staticRead(querySetting(libPath) / "system.nim") + static: + doAssert a == "inside" and b == "data" and c == "extra" and d.len > 0 + doAssert readFile("inside.txt") == "inside" + doAssert readLines("inside.txt", 1) == @["inside"] + doAssert fileExists("inside.txt") and not fileExists("missing.txt") + doAssert dirExists("sub") + doAssert staticFileExists("inside.txt") + doAssert staticDirExists("sub") + doAssert staticWalkDir("sub").len == 1 + echo "inside ok" +elif which == "slurpAbs": + static: discard staticRead(outside / "secret.txt") +elif which == "slurpRel": + static: discard staticRead("../outside/secret.txt") +elif which == "slurpLinkFile": + static: discard staticRead("link_file") +elif which == "slurpLinkDir": + static: discard staticRead("link_dir/secret.txt") +elif which == "readFile": + static: discard readFile("link_file") +elif which == "readLines": + static: discard readLines(outside / "secret.txt", 1) +elif which == "fileExists": + static: discard fileExists(outside / "secret.txt") +elif which == "dirExists": + static: discard dirExists("link_dir") +elif which == "staticWalkDir": + static: discard staticWalkDir(outside) +elif which == "staticFileExists": + static: discard staticFileExists(outside / "missing.txt") +elif which == "staticDirExists": + static: discard staticDirExists(outside) +""") + + proc runR3(which: string): tuple[output: string, exitCode: int] = + runNim("c --compileOnly --hints:off --compileTime:restricted --path:" & extra & + " -d:which=" & which & " -d:outside=" & outside & " -d:extra=" & extra & " r3.nim", proj) + + test "R3: reads under the project, --path and lib are allowed": + let res = runR3("inside") + check res.exitCode == 0 + + test "R3: reads outside are refused, also through symbolic links": + for which in ["slurpAbs", "slurpRel", "slurpLinkFile", "slurpLinkDir", "readFile", + "readLines", "fileExists", "dirExists", "staticWalkDir", + "staticFileExists", "staticDirExists"]: + let res = runR3(which) + checkpoint which & ":\n" & res.output + check res.exitCode != 0 + check refusedRead(res.output) + +removeDir(root) diff --git a/tests/compiletime_restricted/tstaticexec_allowed.nim b/tests/compiletime_restricted/tstaticexec_allowed.nim new file mode 100644 index 0000000000000..7d1df299c2282 --- /dev/null +++ b/tests/compiletime_restricted/tstaticexec_allowed.nim @@ -0,0 +1,9 @@ +discard """ + cmd: '''nim c --compileTime:restricted "--staticExecWhitelist:echo hi" -r --hints:off $file''' + output: "hi" + disabled: "windows" +""" + +# R1: a command line that is on the whitelist runs. +const greeting = staticExec("echo hi") +echo greeting diff --git a/tests/compiletime_restricted/tstaticexec_refused.nim b/tests/compiletime_restricted/tstaticexec_refused.nim new file mode 100644 index 0000000000000..d800f0347ab23 --- /dev/null +++ b/tests/compiletime_restricted/tstaticexec_refused.nim @@ -0,0 +1,9 @@ +discard """ + cmd: '''nim c --compileTime:restricted "--staticExecWhitelist:echo hi" --hints:off $file''' + errormsg: "command refused by --compileTime:restricted, it is not in --staticExecWhitelist: 'echo hi there'" + line: 9 +""" + +# R1: the whitelist matches the whole command line, so a longer command line +# that starts with an allowed one is refused. +const greeting = staticExec("echo hi there") diff --git a/tests/compiletime_restricted/tvmopsdanger_conflict.nim b/tests/compiletime_restricted/tvmopsdanger_conflict.nim new file mode 100644 index 0000000000000..a0e99ec32cc0a --- /dev/null +++ b/tests/compiletime_restricted/tvmopsdanger_conflict.nim @@ -0,0 +1,8 @@ +discard """ + cmd: '''nim c --compileTime:restricted --experimental:vmopsDanger --hints:off $file''' + errormsg: "--experimental:vmopsDanger cannot be combined with --compileTime:restricted" + file: "command line" +""" + +# R6: vmopsDanger enables `execCmdEx` at compile time, which bypasses the +# staticExec whitelist. diff --git a/tests/compiletime_restricted/twritefile_refused.nim b/tests/compiletime_restricted/twritefile_refused.nim new file mode 100644 index 0000000000000..5704801a35261 --- /dev/null +++ b/tests/compiletime_restricted/twritefile_refused.nim @@ -0,0 +1,9 @@ +discard """ + cmd: '''nim c --compileTime:restricted --hints:off $file''' + errormsg: "'writeFile' refused by --compileTime:restricted" + line: 9 +""" + +# R4 +static: + writeFile("trestricted_written.txt", "x")