From a23d85ea6c8cf39c3dc7d445a7cb626c790b6751 Mon Sep 17 00:00:00 2001 From: minjaesong Date: Sun, 1 Nov 2020 21:58:13 +0900 Subject: [PATCH] diskdrive: filtering super root access --- .../torvald/tsvm/peripheral/TestDiskDrive.kt | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/net/torvald/tsvm/peripheral/TestDiskDrive.kt b/src/net/torvald/tsvm/peripheral/TestDiskDrive.kt index 519a7a5..6a00de5 100644 --- a/src/net/torvald/tsvm/peripheral/TestDiskDrive.kt +++ b/src/net/torvald/tsvm/peripheral/TestDiskDrive.kt @@ -167,7 +167,7 @@ class TestDiskDrive(private val driveNum: Int, theRootPath: File? = null) : Bloc val pathStr = inputString.substring(6, if (commaIndex == 6) inputString.lastIndex else commaIndex - 1) val driveNum = if (commaIndex == 6) null else inputString.substring(commaIndex + 1, inputString.length).toInt() - val filePath = sanitisePath(pathStr) + val filePath = filterSuperRoot(sanitisePath(pathStr)) // TODO driveNum is for disk drives that may have two or more slots built; for testing purposes we'll ignore it @@ -308,4 +308,29 @@ class TestDiskDrive(private val driveNum: Int, theRootPath: File? = null) : Bloc private fun sanitisePath(s: String) = s.replace('\\','/').replace(Regex("""\?<>:\*\|"""),"-") + // applies a "cap" if the path attemps to access parent directory of the root + private fun filterSuperRoot(path: String): String { + var parentCount = 0 + val paths = path.split('/') + val newPaths = ArrayList() + paths.forEach { + if (it.isBlank() || it.isEmpty()) throw IllegalArgumentException("Path cannot contain whitespaces") + + if (it == "..") { + parentCount -= -1 + } + else if (it != ".") { + parentCount += 1 + } + + if (parentCount < -1) parentCount = -1 + + if (parentCount >= 0) { + newPaths.add(it) + } + } + + return newPaths.joinToString("/") + } + } \ No newline at end of file