CVE-2021-41242: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (CWE-22)
value: OpenOlat is a web-basedlearning management system. A path traversal vulnerability exists in OpenOlat prior to versions 15.5.12 and 16.0.5. By providing a filename that contains a relative path as a parameter in some REST methods, it is possible to create directory structures and write files anywhere on the target system. The attack could be used to write files anywhere in the web root folder or outside, depending on the configuration of the system and the properly configured permission of the application server user. The attack requires an OpenOlat user account, an enabled REST API and the rights on a business object to call the vulnerable REST calls. The problem is fixed in version 15.5.12 and 16.0.5. There is a workaround available. The vulnerability requires the REST module to be enabled. Disabling the REST module or limiting the REST module via some firewall or web-server access rules to be accessed only be trusted systems will mitigate the risk.
CWE description: The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
CVSS v3 base score: 8.1
Published: 2021-12-10T23:15Z
Repository: https://github.com/OpenOLAT/OpenOLAT
Language: Java
Files changed: src/main/java/org/olat/core/util/vfs/LocalFolderImpl.java, src/main/java/org/olat/core/util/vfs/VFSContainer.java, src/main/java/org/olat/modules/fo/restapi/ForumWebService.java, src/main/java/org/olat/restapi/repository/course/CourseElementWebService.java, src/main/java/org/olat/restapi/support/MultipartReader.java, src/test/java/org/olat/restapi/ForumTest.java
Commit date: 2021-11-01 11:48:12 +0100
Commit message: OO-5819: container can only create file in its own path
Diff: diff --git a/src/main/java/org/olat/core/util/vfs/LocalFolderImpl.java b/src/main/java/org/olat/core/util/vfs/LocalFolderImpl.java
index 46363e52164..11e5869cf10 100644
--- a/src/main/java/org/olat/core/util/vfs/LocalFolderImpl.java
+++ b/src/main/java/org/olat/core/util/vfs/LocalFolderImpl.java
@@ -372,29 +372,39 @@ public class LocalFolderImpl extends LocalImpl implements VFSContainer {
 	}
 
 	@Override
 	public VFSContainer createChildContainer(String name) {
 		File fNewFile = new File(getBasefile(), name);
-		if (!fNewFile.mkdir()) return null;
+		if(!isInPath(name)) {
+			log.warn("Could not create a new container::{} in container::{} - file out of parent directory", name, getBasefile().getAbsolutePath());
+			return null;
+		}
+		if (!fNewFile.mkdir()) {
+			return null;
+		}
 		LocalFolderImpl locFI =  new LocalFolderImpl(fNewFile, this);
 		locFI.setDefaultItemFilter(defaultFilter);
 		return locFI;
 	}
 
 	@Override
 	public VFSLeaf createChildLeaf(String name) {
 		File fNewFile = new File(getBasefile(), name);
 		try {
+			if(!isInPath(name)) {
+				log.warn("Could not create a new leaf::{} in container::{} - file out of parent directory", name, getBasefile().getAbsolutePath());
+				return null;
+			}
 			if(!fNewFile.getParentFile().exists()) {
 				fNewFile.getParentFile().mkdirs();
 			}
 			if (!fNewFile.createNewFile()) {
-				log.warn("Could not create a new leaf::" + name + " in container::" + getBasefile().getAbsolutePath() + " - file alreay exists");
+				log.warn("Could not create a new leaf::{} in container::{} - file alreay exists", name, getBasefile().getAbsolutePath());
 				return null;
 			} 
 		} catch (Exception e) {
-			log.error("Error while creating child leaf::" + name + " in container::" + getBasefile().getAbsolutePath(), e);
+			log.error("Error while creating child leaf::{} in container::{}", name, getBasefile().getAbsolutePath(), e);
 			return null;
 		}
 		return new LocalFileImpl(fNewFile, this);
 	}
 
diff --git a/src/main/java/org/olat/core/util/vfs/VFSContainer.java b/src/main/java/org/olat/core/util/vfs/VFSContainer.java
index eed3ce1cd2d..34d64139c9d 100644
--- a/src/main/java/org/olat/core/util/vfs/VFSContainer.java
+++ b/src/main/java/org/olat/core/util/vfs/VFSContainer.java
@@ -76,18 +76,18 @@ public interface VFSContainer extends VFSItem {
 
 	/**
 	 * Create a new child container (of same type) if possible.
 	 * 
 	 * @param name
-	 * @return VFSItem if successfull, null otherwise.
+	 * @return VFSItem if successful, null otherwise.
 	 */
 	public VFSContainer createChildContainer(String name);
 	
 	/**
 	 * Create a new leaf (of same type) if possible,
 	 * @param name
-	 * @return VFSItem if successfull, null otherwise.
+	 * @return VFSItem if successful, null otherwise.
 	 */
 	public VFSLeaf createChildLeaf(String name);
 	
 	/**
 	 * 
diff --git a/src/main/java/org/olat/modules/fo/restapi/ForumWebService.java b/src/main/java/org/olat/modules/fo/restapi/ForumWebService.java
index 53c2fe36aa1..0a4b6ecf9dc 100644
--- a/src/main/java/org/olat/modules/fo/restapi/ForumWebService.java
+++ b/src/main/java/org/olat/modules/fo/restapi/ForumWebService.java
@@ -596,11 +596,11 @@ public class ForumWebService {
 		byte[] fileAsBytes = Base64.decodeBase64(file);
 		InputStream in = new ByteArrayInputStream(fileAsBytes);
 		return attachToPost(messageKey, filename, in, request);
 	}
 	
-	protected Response attachToPost(Long messageKey, String filename, InputStream file,  HttpServletRequest request) {
+	private Response attachToPost(Long messageKey, String filename, InputStream file,  HttpServletRequest request) {
 		//load message
 		Message mess = fom.loadMessage(messageKey);
 		if(mess == null) {
 			return Response.serverError().status(Status.NOT_FOUND).build();
 		}
@@ -608,11 +608,11 @@ public class ForumWebService {
 			return Response.serverError().status(Status.CONFLICT).build();
 		}
 		return attachToPost(mess, filename, file, request);
 	}
 
-	protected Response attachToPost(Message mess, String filename, InputStream file,  HttpServletRequest request) {
+	private Response attachToPost(Message mess, String filename, InputStream file,  HttpServletRequest request) {
 		Identity identity = getIdentity(request);
 		if(identity == null) {
 			return Response.serverError().status(Status.UNAUTHORIZED).build();
 		} else if (!identity.equalsByPersistableKey(mess.getCreator())) {
 			if(mess.getModifier() == null || !identity.equalsByPersistableKey(mess.getModifier())) {
diff --git a/src/main/java/org/olat/restapi/repository/course/CourseElementWebService.java b/src/main/java/org/olat/restapi/repository/course/CourseElementWebService.java
index a2ed1bdf40e..83448acdf2c 100644
--- a/src/main/java/org/olat/restapi/repository/course/CourseElementWebService.java
+++ b/src/main/java/org/olat/restapi/repository/course/CourseElementWebService.java
@@ -1363,13 +1363,13 @@ public class CourseElementWebService extends AbstractCourseNodeWebService {
 		try {
 			reader = new MultipartReader(request);
 			String filename = reader.getValue("filename", "task");
 			String taskFolderPath = TACourseNode.getTaskFolderPathRelToFolderRoot(course, parentNode.getCourseNode());
 			VFSContainer taskFolder = VFSManager.olatRootContainer(taskFolderPath, null);
-			VFSLeaf singleFile = (VFSLeaf) taskFolder.resolve("/" + filename);
+			VFSLeaf singleFile = (VFSLeaf)taskFolder.resolve(filename);
 			if (singleFile == null) {
-				singleFile = taskFolder.createChildLeaf("/" + filename);
+				singleFile = taskFolder.createChildLeaf(filename);
 			}
 			File file = reader.getFile();
 			if(file != null) {
 				in = new FileInputStream(file);
 				OutputStream out = singleFile.getOutputStream(false);
@@ -2312,23 +2312,23 @@ public class CourseElementWebService extends AbstractCourseNodeWebService {
 			}
 			
 			if(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(moduleConfig.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE))) {
 				if(in != null && StringHelper.containsNonWhitespace(filename)) {
 					VFSContainer rootContainer = course.getCourseFolderContainer();
-					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
+					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
 					if (singleFile == null) {
-						singleFile = rootContainer.createChildLeaf("/" + filename);
+						singleFile = rootContainer.createChildLeaf(filename);
 					}
 	
 					moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename);
 					OutputStream out = singleFile.getOutputStream(false);
 					FileUtils.copy(in, out);
 					FileUtils.closeSafely(out);
 					FileUtils.closeSafely(in);
 				} else if (StringHelper.containsNonWhitespace(filename)) {
 					VFSContainer rootContainer = course.getCourseFolderContainer();
-					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
+					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
 					if(singleFile != null) {
 						moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename);
 					}
 				}
 			}
@@ -2485,13 +2485,13 @@ public class CourseElementWebService extends AbstractCourseNodeWebService {
 
 		@Override
 		public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) {
 			newNode.setDisplayOption(CourseNode.DISPLAY_OPTS_TITLE_DESCRIPTION_CONTENT);
 			VFSContainer rootContainer = course.getCourseFolderContainer();
-			VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
+			VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
 			if (singleFile == null) {
-				singleFile = rootContainer.createChildLeaf("/" + filename);
+				singleFile = rootContainer.createChildLeaf(filename);
 			}
 
 			if(in != null) {
 				moduleConfig.set(SPEditController.CONFIG_KEY_FILE, "/" + filename);
 				
diff --git a/src/main/java/org/olat/restapi/support/MultipartReader.java b/src/main/java/org/olat/restapi/support/MultipartReader.java
index 0aaccafa4ec..cb9582e9ea3 100644
--- a/src/main/java/org/olat/restapi/support/MultipartReader.java
+++ b/src/main/java/org/olat/restapi/support/MultipartReader.java
@@ -56,11 +56,11 @@ public class MultipartReader {
 		try {
 			for(Part part:request.getParts()) {
 				if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) {
 					contentType = part.getContentType();
 					filename = part.getSubmittedFileName();
-					if(filename != null) {
+					if(filename != null && !filename.contains("..")) {
 						filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
 					} else {
 						filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
 					}
 					file = new File(WebappHelper.getTmpDir(), filename);
diff --git a/src/test/java/org/olat/restapi/ForumTest.java b/src/test/java/org/olat/restapi/ForumTest.java
index d8cff77a6a7..d10cf834247 100644
--- a/src/test/java/org/olat/restapi/ForumTest.java
+++ b/src/test/java/org/olat/restapi/ForumTest.java
@@ -385,10 +385,45 @@ public class ForumTest extends OlatRestTestCase {
 		}
 		
 		conn.shutdown();
 	}
 	
+	@Test
+	public void testUploadAttachmentOutOfBox() throws IOException, URISyntaxException {
+		RestConnection conn = new RestConnection();
+		assertTrue(conn.login(id1));
+		
+		URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString())
+			.queryParam("authorKey", id1.getKey())
+			.queryParam("title", "New message with attachment ")
+			.queryParam("body", "A very interesting response in Thread-1 with an attachment").build();
+		HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true);
+		HttpResponse response = conn.execute(method);
+		assertEquals(200, response.getStatusLine().getStatusCode());
+		MessageVO message = conn.parse(response, MessageVO.class);
+		assertNotNull(message);
+		
+		//attachment
+		URL portraitUrl = CoursesElementsTest.class.getResource("portrait.jpg");
+		assertNotNull(portraitUrl);
+		File portrait = new File(portraitUrl.toURI());
+		
+		//upload portrait
+		URI attachUri = getForumUriBuilder().path("posts").path(message.getKey().toString()).path("attachments").build();
+		HttpPost attachMethod = conn.createPost(attachUri, MediaType.APPLICATION_JSON);
+		conn.addMultipart(attachMethod, "../../portrait.jpg", portrait);
+		HttpResponse attachResponse = conn.execute(attachMethod);
+		assertEquals(200, attachResponse.getStatusLine().getStatusCode());
+		
+		//check if the file exists
+		VFSContainer container = forumManager.getMessageContainer(message.getForumKey(), message.getKey());
+		VFSItem uploadedFile = container.resolve("portrait.jpg");
+		Assert.assertNull(uploadedFile);
+		
+		conn.shutdown();
+	}
+	
 	@Test
 	public void testUpload64Attachment() throws IOException, URISyntaxException {
 		RestConnection conn = new RestConnection();
 		assertTrue(conn.login(id1));
 		

Vulnerable code: 		if (!fNewFile.mkdir()) return null;
				log.warn("Could not create a new leaf::" + name + " in container::" + getBasefile().getAbsolutePath() + " - file alreay exists");
			log.error("Error while creating child leaf::" + name + " in container::" + getBasefile().getAbsolutePath(), e);
	 * @return VFSItem if successfull, null otherwise.
	 * @return VFSItem if successfull, null otherwise.
	protected Response attachToPost(Long messageKey, String filename, InputStream file,  HttpServletRequest request) {
	protected Response attachToPost(Message mess, String filename, InputStream file,  HttpServletRequest request) {
			VFSLeaf singleFile = (VFSLeaf) taskFolder.resolve("/" + filename);
				singleFile = taskFolder.createChildLeaf("/" + filename);
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
						singleFile = rootContainer.createChildLeaf("/" + filename);
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
			VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename);
				singleFile = rootContainer.createChildLeaf("/" + filename);
					if(filename != null) {
Fixed code: 		if(!isInPath(name)) {
			log.warn("Could not create a new container::{} in container::{} - file out of parent directory", name, getBasefile().getAbsolutePath());
			return null;
		}
		if (!fNewFile.mkdir()) {
			return null;
		}
			if(!isInPath(name)) {
				log.warn("Could not create a new leaf::{} in container::{} - file out of parent directory", name, getBasefile().getAbsolutePath());
				return null;
			}
				log.warn("Could not create a new leaf::{} in container::{} - file alreay exists", name, getBasefile().getAbsolutePath());
			log.error("Error while creating child leaf::{} in container::{}", name, getBasefile().getAbsolutePath(), e);
	 * @return VFSItem if successful, null otherwise.
	 * @return VFSItem if successful, null otherwise.
	private Response attachToPost(Long messageKey, String filename, InputStream file,  HttpServletRequest request) {
	private Response attachToPost(Message mess, String filename, InputStream file,  HttpServletRequest request) {
			VFSLeaf singleFile = (VFSLeaf)taskFolder.resolve(filename);
				singleFile = taskFolder.createChildLeaf(filename);
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
						singleFile = rootContainer.createChildLeaf(filename);
					VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
			VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve(filename);
				singleFile = rootContainer.createChildLeaf(filename);
					if(filename != null && !filename.contains("..")) {
	@Test
	public void testUploadAttachmentOutOfBox() throws IOException, URISyntaxException {
		RestConnection conn = new RestConnection();
		assertTrue(conn.login(id1));
		
		URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString())
			.queryParam("authorKey", id1.getKey())
			.queryParam("title", "New message with attachment ")
			.queryParam("body", "A very interesting response in Thread-1 with an attachment").build();
		HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true);
		HttpResponse response = conn.execute(method);
		assertEquals(200, response.getStatusLine().getStatusCode());
		MessageVO message = conn.parse(response, MessageVO.class);
		assertNotNull(message);
		
		//attachment
		URL portraitUrl = CoursesElementsTest.class.getResource("portrait.jpg");
		assertNotNull(portraitUrl);
		File portrait = new File(portraitUrl.toURI());
		
		//upload portrait
		URI attachUri = getForumUriBuilder().path("posts").path(message.getKey().toString()).path("attachments").build();
		HttpPost attachMethod = conn.createPost(attachUri, MediaType.APPLICATION_JSON);
		conn.addMultipart(attachMethod, "../../portrait.jpg", portrait);
		HttpResponse attachResponse = conn.execute(attachMethod);
		assertEquals(200, attachResponse.getStatusLine().getStatusCode());
		
		//check if the file exists
		VFSContainer container = forumManager.getMessageContainer(message.getForumKey(), message.getKey());
		VFSItem uploadedFile = container.resolve("portrait.jpg");
		Assert.assertNull(uploadedFile);
		
		conn.shutdown();
	}