CVE-2021-23422 (published 2021-08-16T08:15Z)

This affects the package bikeshed before 3.0.0. This can occur when an untrusted source file containing Inline Tag Command metadata is processed. When an arbitrary OS command is executed, the command output would be included in the HTML output.

Severity: MEDIUM
CVSS v2 base score: 6.8 (AV:N/AC:M/Au:N/C:P/I:P/A:P)
CVSS v3 base score: 7.8, HIGH (CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-78
cwe_name: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
extended_description: 
		   This weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process does not follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage.
            There are at least two subtypes of OS command injection:
               
				 The application intends to execute a single, fixed program that is under its own control. It intends to use externally-supplied inputs as arguments to that program. For example, the program might use system("nslookup [HOSTNAME]") to run nslookup and allow the user to supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from executing. However, if the program does not remove command separators from the HOSTNAME argument, attackers could place the separators into the arguments, which allows them to execute their own program after nslookup has finished executing.
				 The application accepts an input that it uses to fully select which program to run, as well as which commands to use. The application simply redirects this entire command to the operating system. For example, the program might use "exec([COMMAND])" to execute the [COMMAND] that was supplied by the user. If the COMMAND is under attacker control, then the attacker can execute arbitrary commands or programs. If the command is being executed using functions like exec() and CreateProcess(), the attacker might not be able to combine multiple commands together in the same line.
               
            From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input.
         
         

Fix information:
repo_url: https://github.com/tabatkins/bikeshed
commit_details: repo_url: https://github.com/tabatkins/bikeshed
author: Tab Atkins-Bittner
author_date: 2021-08-06 17:41:38-07:00
msg: Prevent escaping the source doc's folder, or running arbitrary code, without explicit opt-in at the command-line.
repository: repo_url: https://github.com/tabatkins/bikeshed
repo_name: speced/bikeshed
description: :bike: A preprocessor for anyone writing specifications that converts source files into actual specs.
repo_language: HTML
owner: tabatkins
file_changes: filename: InputSource.py
change_type: ModificationType.MODIFY
diff: @@ -13,6 +13,7 @@ import attr
 import requests
 import tenacity
 
+from . import config
 from .Line import Line
 
 
@@ -38,17 +39,17 @@ class InputSource:
     manager for temporarily switching to the directory of a file InputSource.
     """
 
-    def __new__(cls, sourceName: str):
+    def __new__(cls, sourceName: str, **kwargs):
         """Dispatches to the right subclass."""
         if cls != InputSource:
             # Only take control of calls to InputSource(...) itself.
             return super().__new__(cls)
 
         if sourceName == "-":
-            return StdinInputSource(sourceName)
+            return StdinInputSource(sourceName, **kwargs)
         if sourceName.startswith("https:"):
-            return UrlInputSource(sourceName)
-        return FileInputSource(sourceName)
+            return UrlInputSource(sourceName, **kwargs)
+        return FileInputSource(sourceName, **kwargs)
 
     @abstractmethod
     def __str__(self) -> str:
@@ -157,11 +158,17 @@ class UrlInputSource(InputSource):
 
 
 class FileInputSource(InputSource):
-    def __init__(self, sourceName: str):
+    def __init__(self, sourceName: str, *, chroot: bool, chrootPath: Optional[str] = None):
         self.sourceName = sourceName
+        self.chrootPath = chrootPath
         self.type = "file"
         self.content = None
 
+        if chroot and self.chrootPath is None:
+            self.chrootPath = self.directory()
+        if self.chrootPath is not None:
+            self.sourceName = config.chrootPath(self.chrootPath, self.sourceName)
+
     def __str__(self) -> str:
         return self.sourceName
 
@@ -179,7 +186,7 @@ class FileInputSource(InputSource):
         return os.path.dirname(os.path.abspath(self.sourceName))
 
     def relative(self, relativePath) -> FileInputSource:
-        return FileInputSource(os.path.join(self.directory(), relativePath))
+        return FileInputSource(os.path.join(self.directory(), relativePath), chroot=False, chrootPath=self.chrootPath)
 
     def cheaplyExists(self, relativePath) -> bool:
         return os.access(self.relative(relativePath).sourceName, os.R_OK)

programming_language: Python
filename: Spec.py
change_type: ModificationType.MODIFY
diff: @@ -58,7 +58,7 @@ class Spec:
                 "No input file specified, and no *.bs or *.src.html files found in current directory.\nPlease specify an input file, or use - to pipe from STDIN."
             )
             return
-        self.inputSource = InputSource(inputFilename)
+        self.inputSource = InputSource(inputFilename, chroot=constants.chroot)
         self.transitiveDependencies = set()
         self.debug = debug
         self.token = token

programming_language: Python
filename: cli.py
change_type: ModificationType.MODIFY
diff: @@ -75,6 +75,18 @@ def main():
         choices=["nothing", "fatal", "link-error", "warning", "everything"],
         help="Determines what sorts of errors cause Bikeshed to die (quit immediately with an error status code). Default is 'fatal'; the -f flag is a shorthand for 'nothing'",
     )
+    argparser.add_argument(
+        "--allow-nonlocal-files",
+        dest="allowNonlocalFiles",
+        action="store_true",
+        help="Allows Bikeshed to see/include files from folders higher than the one your source document is in."
+    )
+    argparser.add_argument(
+        "--allow-execute",
+        dest="allowExecute",
+        action="store_true",
+        help="Allow some features to execute arbitrary code from outside the Bikeshed codebase."
+    )
 
     subparsers = argparser.add_subparsers(title="Subcommands", dest="subparserName")
 
@@ -444,6 +456,8 @@ def main():
             constants.printMode = "console"
     else:
         constants.printMode = options.printMode
+    constants.chroot = not options.allowNonlocalFiles
+    constants.executeCode = options.allowExecute
 
     update.fixupDataFiles()
     if options.subparserName == "update":

programming_language: Python
filename: main.py
change_type: ModificationType.MODIFY
diff: @@ -4,6 +4,9 @@ import re
 
 import lxml
 
+from .. import constants
+from .. import messages
+
 
 def englishFromList(items, conjunction="or"):
     # Format a list of strings into an English list.
@@ -168,7 +171,19 @@ def flatten(arr):
 
 def scriptPath(*pathSegs):
     startPath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
-    return os.path.join(startPath, *pathSegs)
+    path = os.path.join(startPath, *pathSegs)
+    return path
+
+
+def chrootPath(chrootPath, path):
+    chrootPath = os.path.abspath(chrootPath)
+    path = os.path.abspath(path)
+    if not path.startswith(chrootPath):
+        messages.die(f"Attempted to access a file ({path}) outside the source document's directory ({chrootPath}). See --allow-nonlocal-files.")
+        raise Exception()
+    else:
+        return path
+
 
 
 def doEvery(s, action, lastTime=None):

programming_language: Python
filename: retrieve.py
change_type: ModificationType.MODIFY
diff: @@ -63,7 +63,7 @@ defaultRequester = DataFileRequester(
 )
 
 
-def retrieveBoilerplateFile(doc, name, group=None, status=None, error=True):
+def retrieveBoilerplateFile(doc, name, group=None, status=None, error=True, allowLocal=True):
     # Looks in three or four locations, in order:
     # the folder the spec source is in, the group's boilerplate folder, the megagroup's boilerplate folder, and the generic boilerplate folder.
     # In each location, it first looks for the file specialized on status, and then for the generic file.
@@ -77,7 +77,7 @@ def retrieveBoilerplateFile(doc, name, group=None, status=None, error=True):
             status = doc.md.rawStatus
     megaGroup, status = splitStatus(status)
 
-    searchLocally = doc.md.localBoilerplate[name]
+    searchLocally = allowLocal and doc.md.localBoilerplate[name]
 
     def boilerplatePath(*segs):
         return scriptPath("boilerplate", *segs)
@@ -101,13 +101,13 @@ def retrieveBoilerplateFile(doc, name, group=None, status=None, error=True):
                 # We should remove this after giving specs time to react to the warning:
                 sources.append(doc.inputSource.relative(f))
     if group:
-        sources.append(InputSource(boilerplatePath(group, statusFile)))
-        sources.append(InputSource(boilerplatePath(group, genericFile)))
+        sources.append(InputSource(boilerplatePath(group, statusFile), chroot=False))
+        sources.append(InputSource(boilerplatePath(group, genericFile), chroot=False))
     if megaGroup:
-        sources.append(InputSource(boilerplatePath(megaGroup, statusFile)))
-        sources.append(InputSource(boilerplatePath(megaGroup, genericFile)))
-    sources.append(InputSource(boilerplatePath(statusFile)))
-    sources.append(InputSource(boilerplatePath(genericFile)))
+        sources.append(InputSource(boilerplatePath(megaGroup, statusFile), chroot=False))
+        sources.append(InputSource(boilerplatePath(megaGroup, genericFile), chroot=False))
+    sources.append(InputSource(boilerplatePath(statusFile), chroot=False))
+    sources.append(InputSource(boilerplatePath(genericFile), chroot=False))
 
     # Watch all the possible sources, not just the one that got used, because if
     # an earlier one appears, we want to rebuild.

programming_language: Python
filename: constants.py
change_type: ModificationType.MODIFY
diff: @@ -9,6 +9,8 @@ refStatus = StringEnum("current", "snapshot")
 biblioDisplay = StringEnum("index", "inline")
 specClass = None
 testAnnotationURL = "https://test.csswg.org/harness/annotate.js"
+chroot = True
+executeCode = False
 
 
 def errorLevelAt(target):

programming_language: Python
filename: extensions.py
change_type: ModificationType.MODIFY
diff: @@ -1,8 +1,9 @@
 from . import config
+from . import constants
 from .h import *  # noqa: F401
 from .messages import *  # noqa: F401
 
 
 def load(doc):
-    code = config.retrieveBoilerplateFile(doc, "bs-extensions")
+    code = config.retrieveBoilerplateFile(doc, "bs-extensions", allowLocal=constants.executeCode)
     exec(code, globals())

programming_language: Python
filename: __init__.py
change_type: ModificationType.MODIFY
diff: @@ -1,11 +1,15 @@
 from subprocess import PIPE, Popen
 
+from .. import constants
 from ..h import *
 from ..messages import *
 
 
 def processTags(doc):
     for el in findAll("[data-span-tag]", doc):
+        if not constants.executeCode:
+            die("Found an inline code tag, but arbitrary code execution isn't allowed. See the --allow-execute flag.")
+            return
         tag = el.get("data-span-tag")
         if tag not in doc.md.inlineTagCommands:
             die("Unknown inline tag '{0}' found:\n  {1}", tag, outerHTML(el), el=el)

programming_language: Python