You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ja...@apache.org on 2023/12/13 12:00:29 UTC

(lucene-solr) branch branch_8_11 updated: SOLR-16949: Restrict certain file types from being uploaded to or downloaded from Config Sets

This is an automated email from the ASF dual-hosted git repository.

janhoy pushed a commit to branch branch_8_11
in repository https://gitbox.apache.org/repos/asf/lucene-solr.git


The following commit(s) were added to refs/heads/branch_8_11 by this push:
     new 7e9a2e67f81 SOLR-16949: Restrict certain file types from being uploaded to or downloaded from Config Sets
7e9a2e67f81 is described below

commit 7e9a2e67f812032a049836c3aa0b18bf5cd717f9
Author: Jan Høydahl <ja...@apache.org>
AuthorDate: Wed Dec 13 10:56:47 2023 +0100

    SOLR-16949: Restrict certain file types from being uploaded to or downloaded from Config Sets
---
 lucene/ivy-versions.properties                     |   1 +
 solr/CHANGES.txt                                   |   2 +
 solr/core/ivy.xml                                  |   1 +
 .../org/apache/solr/core/backup/BackupManager.java |  23 ++-
 .../solr/handler/admin/ConfigSetsHandler.java      |  27 +++-
 .../org/apache/solr/util/FileTypeMagicUtil.java    | 156 +++++++++++++++++++++
 .../src/java/org/apache/solr/util/SolrCLI.java     |   2 +
 solr/core/src/resources/magic/executables          |  59 ++++++++
 solr/core/src/test-files/magic/HelloWorld.java.txt |   5 +
 .../test-files/magic/HelloWorldJavaClass.class.bin | Bin 0 -> 426 bytes
 solr/core/src/test-files/magic/README.md           |  12 ++
 solr/core/src/test-files/magic/hello.tar.bin       | Bin 0 -> 4096 bytes
 solr/core/src/test-files/magic/plain.txt           |   1 +
 solr/core/src/test-files/magic/shell.sh.txt        |   2 +
 .../org/apache/solr/cloud/TestConfigSetsAPI.java   |  58 +++++++-
 .../apache/solr/util/FileTypeMagicUtilTest.java    |  54 +++++++
 solr/licenses/simplemagic-1.17.jar.sha1            |   1 +
 solr/licenses/simplemagic-LICENSE-BSD_LIKE.txt     |  15 ++
 solr/licenses/simplemagic-NOTICE.txt               |   0
 .../solr/common/cloud/ZkMaintenanceUtils.java      |   2 +
 20 files changed, 410 insertions(+), 11 deletions(-)

diff --git a/lucene/ivy-versions.properties b/lucene/ivy-versions.properties
index 7c37d2de884..c0afbdc2cf0 100644
--- a/lucene/ivy-versions.properties
+++ b/lucene/ivy-versions.properties
@@ -71,6 +71,7 @@ com.fasterxml.jackson.core.version = 2.15.2
 /com.healthmarketscience.jackcess/jackcess = 3.0.1
 /com.healthmarketscience.jackcess/jackcess-encrypt = 3.0.0
 /com.ibm.icu/icu4j = 62.1
+/com.j256.simplemagic/simplemagic = 1.17
 /com.jayway.jsonpath/json-path = 2.7.0
 /com.lmax/disruptor = 3.4.2
 /com.pff/java-libpst = 0.9.3
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index e71c21e322e..01cd5bf6159 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -64,6 +64,8 @@ Other Changes
 * SOLR-14853: Security: Converted enableRemoteStreaming and enableStreamBody solrconfig options into system properties and env vars.
   Attempts to set them the old way are no-op and log a warning. (David Smiley, janhoy, Ishan Chattopadhyaya)
 
+* SOLR-16949: Restrict certain file types from being uploaded to or downloaded from Config Sets (janhoy, Houston Putman)
+
 ==================  8.11.2 ==================
 
 Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release.
diff --git a/solr/core/ivy.xml b/solr/core/ivy.xml
index 97796c4291b..18c61c2e266 100644
--- a/solr/core/ivy.xml
+++ b/solr/core/ivy.xml
@@ -45,6 +45,7 @@
     <dependency org="com.google.guava" name="failureaccess" rev="${/com.google.guava/failureaccess}" conf="compile"/>
     <dependency org="com.google.guava" name="listenablefuture" rev="${/com.google.guava/listenablefuture}" conf="compile"/>
     <dependency org="com.google.j2objc" name="j2objc-annotations" rev="${/com.google.j2objc/j2objc-annotations}" conf="compile"/>
+    <dependency org="com.j256.simplemagic" name="simplemagic" rev="${/com.j256.simplemagic/simplemagic}" conf="compile"/>
     <dependency org="org.locationtech.spatial4j" name="spatial4j" rev="${/org.locationtech.spatial4j/spatial4j}" conf="compile"/>
     <dependency org="org.antlr" name="antlr4-runtime" rev="${/org.antlr/antlr4-runtime}"/>
     <dependency org="org.apache.commons" name="commons-math3" rev="${/org.apache.commons/commons-math3}" conf="compile"/>
diff --git a/solr/core/src/java/org/apache/solr/core/backup/BackupManager.java b/solr/core/src/java/org/apache/solr/core/backup/BackupManager.java
index 470216b1a94..afaf6190e71 100644
--- a/solr/core/src/java/org/apache/solr/core/backup/BackupManager.java
+++ b/solr/core/src/java/org/apache/solr/core/backup/BackupManager.java
@@ -27,6 +27,7 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
+import org.apache.solr.util.FileTypeMagicUtil;
 
 import com.google.common.base.Preconditions;
 import org.apache.lucene.store.IOContext;
@@ -302,8 +303,16 @@ public class BackupManager {
         if (children.size() == 0) {
           log.debug("Writing file {}", file);
           byte[] data = zkClient.getData(zkPath + "/" + file, null, null, true);
-          try (OutputStream os = repository.createOutput(repository.resolve(dir, file))) {
-            os.write(data);
+          if (!FileTypeMagicUtil.isFileForbiddenInConfigset(data)) {
+            try (OutputStream os = repository.createOutput(repository.resolve(dir, file))) {
+              os.write(data);
+            }
+          } else {
+            String mimeType = FileTypeMagicUtil.INSTANCE.guessMimeType(data);
+            log.warn(
+                "Not including zookeeper file {} in backup, as it matched the MAGIC signature of a forbidden mime type {}",
+                file,
+                mimeType);
           }
         } else {
           URI uri = repository.resolve(dir, file);
@@ -329,7 +338,15 @@ public class BackupManager {
           try (IndexInput is = repository.openInput(sourceDir, file, IOContext.DEFAULT)) {
             byte[] arr = new byte[(int) is.length()]; // probably ok since the config file should be small.
             is.readBytes(arr, 0, (int) is.length());
-            zkClient.makePath(zkNodePath, arr, true);
+            if (!FileTypeMagicUtil.isFileForbiddenInConfigset(arr)) {
+              zkClient.makePath(zkNodePath, arr, true);
+            } else {
+              String mimeType = FileTypeMagicUtil.INSTANCE.guessMimeType(arr);
+              log.warn(
+                  "Not restoring configset file {} to zookeeper, as it matched the MAGIC signature of a forbidden mime type {}",
+                  file,
+                  mimeType);
+            }
           } catch (KeeperException | InterruptedException e) {
             throw new IOException(SolrZkClient.checkInterrupted(e));
           }
diff --git a/solr/core/src/java/org/apache/solr/handler/admin/ConfigSetsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/ConfigSetsHandler.java
index c84243c0245..bd29a4dee96 100644
--- a/solr/core/src/java/org/apache/solr/handler/admin/ConfigSetsHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/admin/ConfigSetsHandler.java
@@ -24,6 +24,7 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
@@ -56,6 +57,7 @@ import org.apache.solr.response.SolrQueryResponse;
 import org.apache.solr.security.AuthenticationPlugin;
 import org.apache.solr.security.AuthorizationContext;
 import org.apache.solr.security.PermissionNameProvider;
+import org.apache.solr.util.FileTypeMagicUtil;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.slf4j.Logger;
@@ -203,9 +205,17 @@ public class ConfigSetsHandler extends RequestHandlerBase implements PermissionN
         try {
           // Create a node for the configuration in zookeeper
           // For creating the baseZnode, the cleanup parameter is only allowed to be true when singleFilePath is not passed.
-          createBaseZnode(zkClient, overwritesExisting, requestIsTrusted, configPathInZk);
-          String filePathInZk = configPathInZk + "/" + fixedSingleFilePath;
-          zkClient.makePath(filePathInZk, IOUtils.toByteArray(inputStream), CreateMode.PERSISTENT, null, !allowOverwrite, true);
+          byte[] bytes = IOUtils.toByteArray(inputStream);
+          if (!FileTypeMagicUtil.isFileForbiddenInConfigset(bytes)) {
+            createBaseZnode(zkClient, overwritesExisting, requestIsTrusted, configPathInZk);
+            String filePathInZk = configPathInZk + "/" + fixedSingleFilePath;
+            zkClient.makePath(filePathInZk, bytes, CreateMode.PERSISTENT, null, !allowOverwrite, true);
+          } else {
+            String mimeType = FileTypeMagicUtil.INSTANCE.guessMimeType(bytes);
+            throw new SolrException(ErrorCode.BAD_REQUEST,
+                String.format(Locale.ROOT, "Not uploading file %s to configset, as it matched the MAGIC signature of a forbidden mime type %s",
+                    fixedSingleFilePath, mimeType));
+          }
         } catch(KeeperException.NodeExistsException nodeExistsException) {
           throw new SolrException(ErrorCode.BAD_REQUEST,
                   "The path " + singleFilePath + " for configSet " + configSetName + " already exists. In order to overwrite, provide overwrite=true or use an HTTP PUT with the V2 API.");
@@ -244,8 +254,15 @@ public class ConfigSetsHandler extends RequestHandlerBase implements PermissionN
       if (zipEntry.isDirectory()) {
         zkClient.makePath(filePathInZk, false,  true);
       } else {
-        createZkNodeIfNotExistsAndSetData(zkClient, filePathInZk,
-            IOUtils.toByteArray(zis));
+        byte[] bytes = IOUtils.toByteArray(zis);
+        if (!FileTypeMagicUtil.isFileForbiddenInConfigset(bytes)) {
+          createZkNodeIfNotExistsAndSetData(zkClient, filePathInZk, bytes);
+        } else {
+          String mimeType = FileTypeMagicUtil.INSTANCE.guessMimeType(bytes);
+          throw new SolrException(ErrorCode.BAD_REQUEST,
+              String.format(Locale.ROOT, "Not uploading file %s to configset, as it matched the MAGIC signature of a forbidden mime type %s",
+                  zipEntry.getName(), mimeType));
+        }
       }
     }
     zis.close();
diff --git a/solr/core/src/java/org/apache/solr/util/FileTypeMagicUtil.java b/solr/core/src/java/org/apache/solr/util/FileTypeMagicUtil.java
new file mode 100644
index 00000000000..4f558dd79f3
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/util/FileTypeMagicUtil.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.util;
+
+import com.j256.simplemagic.ContentInfo;
+import com.j256.simplemagic.ContentInfoUtil;
+import com.j256.simplemagic.ContentType;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+import org.apache.solr.common.SolrException;
+
+/** Utility class to guess the mime type of file based on its magic number. */
+public class FileTypeMagicUtil implements ContentInfoUtil.ErrorCallBack {
+  private final ContentInfoUtil util;
+  private static final Set<String> SKIP_FOLDERS = new HashSet<>(Arrays.asList(".", ".."));
+
+  public static FileTypeMagicUtil INSTANCE = new FileTypeMagicUtil();
+
+  FileTypeMagicUtil() {
+    try {
+      util = new ContentInfoUtil("/magic/executables", this);
+    } catch (IOException e) {
+      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error parsing magic file", e);
+    }
+  }
+
+  /**
+   * Asserts that an entire configset folder is legal to upload.
+   *
+   * @param confPath the path to the folder
+   * @throws SolrException if an illegal file is found in the folder structure
+   */
+  public static void assertConfigSetFolderLegal(Path confPath) throws IOException {
+    Files.walkFileTree(confPath, new SimpleFileVisitor<Path>() {
+      @Override
+      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+        // Read first 100 bytes of the file to determine the mime type
+        try(InputStream fileStream = Files.newInputStream(file)) {
+          byte[] bytes = new byte[100];
+          fileStream.read(bytes);
+          if (FileTypeMagicUtil.isFileForbiddenInConfigset(bytes)) {
+            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
+                String.format(Locale.ROOT, "Not uploading file %s to configset, as it matched the MAGIC signature of a forbidden mime type %s",
+                    file, FileTypeMagicUtil.INSTANCE.guessMimeType(bytes)));
+          }
+          return FileVisitResult.CONTINUE;
+        }
+      }
+
+      @Override
+      public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
+        if (SKIP_FOLDERS.contains(dir.getFileName().toString())) return FileVisitResult.SKIP_SUBTREE;
+
+        return FileVisitResult.CONTINUE;
+      }
+    });
+  }
+
+  /**
+   * Guess the mime type of file based on its magic number.
+   *
+   * @param stream input stream of the file
+   * @return string with content-type or "application/octet-stream" if unknown
+   */
+  public String guessMimeType(InputStream stream) {
+    try {
+      ContentInfo info = util.findMatch(stream);
+      if (info == null) {
+        return ContentType.OTHER.getMimeType();
+      }
+      return info.getContentType().getMimeType();
+    } catch (IOException e) {
+      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
+    }
+  }
+
+  /**
+   * Guess the mime type of file bytes based on its magic number.
+   *
+   * @param bytes the first bytes at start of the file
+   * @return string with content-type or "application/octet-stream" if unknown
+   */
+  public String guessMimeType(byte[] bytes) {
+    return guessMimeType(new ByteArrayInputStream(bytes));
+  }
+
+  @Override
+  public void error(String line, String details, Exception e) {
+    throw new SolrException(
+        SolrException.ErrorCode.SERVER_ERROR,
+        String.format(Locale.ROOT, "%s: %s", line, details),
+        e);
+  }
+
+  /**
+   * Determine forbidden file type based on magic bytes matching of the file itself. Forbidden types
+   * are:
+   *
+   * <ul>
+   *   <li><code>application/x-java-applet</code>: java class file
+   *   <li><code>application/zip</code>: jar or zip archives
+   *   <li><code>application/x-tar</code>: tar archives
+   *   <li><code>text/x-shellscript</code>: shell or bash script
+   * </ul>
+   *
+   * @param fileStream stream from the file content
+   * @return true if file is among the forbidden mime-types
+   */
+  public static boolean isFileForbiddenInConfigset(InputStream fileStream) {
+    return forbiddenTypes.contains(FileTypeMagicUtil.INSTANCE.guessMimeType(fileStream));
+  }
+
+  /**
+   * Determine forbidden file type based on magic bytes matching of the first bytes of the file.
+   *
+   * @param bytes byte array of the file content
+   * @return true if file is among the forbidden mime-types
+   */
+  public static boolean isFileForbiddenInConfigset(byte[] bytes) {
+    return isFileForbiddenInConfigset(new ByteArrayInputStream(bytes));
+  }
+
+  private static final Set<String> forbiddenTypes =
+      new HashSet<>(
+          Arrays.asList(
+              System.getProperty(
+                      "solr.configset.upload.mimetypes.forbidden",
+                      "application/x-java-applet,application/zip,application/x-tar,text/x-shellscript")
+                  .split(",")));
+
+}
diff --git a/solr/core/src/java/org/apache/solr/util/SolrCLI.java b/solr/core/src/java/org/apache/solr/util/SolrCLI.java
index c9fd315c158..2ea24c2c4ca 100755
--- a/solr/core/src/java/org/apache/solr/util/SolrCLI.java
+++ b/solr/core/src/java/org/apache/solr/util/SolrCLI.java
@@ -1971,6 +1971,7 @@ public class SolrCLI {
 
         echoIfVerbose("Uploading " + confPath.toAbsolutePath().toString() +
             " for config " + confname + " to ZooKeeper at " + cloudSolrClient.getZkHost(), cli);
+        FileTypeMagicUtil.assertConfigSetFolderLegal(confPath);
         ((ZkClientClusterStateProvider) cloudSolrClient.getClusterStateProvider()).uploadConfig(confPath, confname);
       }
 
@@ -2265,6 +2266,7 @@ public class SolrCLI {
         echo("Uploading " + confPath.toAbsolutePath().toString() +
             " for config " + cli.getOptionValue("confname") + " to ZooKeeper at " + zkHost);
 
+        FileTypeMagicUtil.assertConfigSetFolderLegal(confPath);
         zkClient.upConfig(confPath, confName);
       } catch (Exception e) {
         log.error("Could not complete upconfig operation for reason: ", e);
diff --git a/solr/core/src/resources/magic/executables b/solr/core/src/resources/magic/executables
new file mode 100644
index 00000000000..4960a7af18e
--- /dev/null
+++ b/solr/core/src/resources/magic/executables
@@ -0,0 +1,59 @@
+# POSIX tar archives
+# URL: https://en.wikipedia.org/wiki/Tar_(computing)
+# Reference: https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5&manpath=FreeBSD+8-current
+# header mainly padded with nul bytes
+500	quad		0
+!:strength /2
+# filename or extended attribute printable strings in range space null til umlaut ue
+>0	ubeshort	>0x1F00
+>>0	ubeshort	<0xFCFD
+# last 4 header bytes often null but tar\0 in gtarfail2.tar gtarfail.tar-bad
+# at https://sourceforge.net/projects/s-tar/files/testscripts/
+>>>508	ubelong&0x8B9E8DFF	0
+# nul, space or ascii digit 0-7 at start of mode
+>>>>100	ubyte&0xC8	=0
+>>>>>101 ubyte&0xC8	=0
+# nul, space at end of check sum
+>>>>>>155 ubyte&0xDF	=0
+# space or ascii digit 0 at start of check sum
+>>>>>>>148	ubyte&0xEF	=0x20
+# check for specific 1st member name that indicates other mime type and file name suffix
+>>>>>>>>0	string		TpmEmuTpms/permall
+!:mime	application/x-tar
+!:ext	tar
+# other stuff in padding
+# some implementations add new fields to the blank area at the end of the header record
+# created for example by DOS TAR 3.20g 1994 Tim V.Shapore with -j option
+>>257	ulong		!0		tar archive (old)
+!:mime	application/x-tar
+!:ext	tar
+# magic in newer, GNU, posix variants
+>257	string		=ustar
+# 2 last char of magic and UStar version because string expression does not work
+# 2 space characters followed by a null for GNU variant
+>>261	ubelong		=0x72202000	POSIX tar archive (GNU)
+!:mime	application/x-gtar
+!:ext	tar/gtar
+
+
+# Zip archives (Greg Roelofs, c/o zip-bugs@wkuvx1.wku.edu)
+0	string		PK\005\006	Zip archive data (empty)
+0	string		PK\003\004  Zip archive data
+!:strength +1
+!:mime application/zip
+!:ext zip/cbz
+
+
+# JAVA
+0	belong		0xcafebabe
+>4	ubelong		>30		compiled Java class data,
+!:mime	application/x-java-applet
+#!:mime	application/java-byte-code
+!:ext	class
+
+
+# SHELL scripts
+#0	string/w	:			shell archive or script for antique kernel text
+0	regex	\^#!\\s?(/bin/|/usr/)		POSIX shell script text executable
+!:mime	text/x-shellscript
+!:ext	sh/bash
\ No newline at end of file
diff --git a/solr/core/src/test-files/magic/HelloWorld.java.txt b/solr/core/src/test-files/magic/HelloWorld.java.txt
new file mode 100644
index 00000000000..ca9518d2afa
--- /dev/null
+++ b/solr/core/src/test-files/magic/HelloWorld.java.txt
@@ -0,0 +1,5 @@
+class HelloWorld {
+  public static void main(String[] args) {
+    System.out.println("Hellow world");
+  }
+}
\ No newline at end of file
diff --git a/solr/core/src/test-files/magic/HelloWorldJavaClass.class.bin b/solr/core/src/test-files/magic/HelloWorldJavaClass.class.bin
new file mode 100644
index 00000000000..e15d0a6c5b9
Binary files /dev/null and b/solr/core/src/test-files/magic/HelloWorldJavaClass.class.bin differ
diff --git a/solr/core/src/test-files/magic/README.md b/solr/core/src/test-files/magic/README.md
new file mode 100644
index 00000000000..4ccb09cdf09
--- /dev/null
+++ b/solr/core/src/test-files/magic/README.md
@@ -0,0 +1,12 @@
+The two binary files were created by the following commands:
+
+```bash
+echo "Hello" > hello.txt && \
+  tar -cvf hello.tar.bin hello.txt && \
+  rm hello.txt
+
+cp HelloWorld.java.txt HelloWorld.java && \
+  javac HelloWorld.java && \
+  mv HelloWorld.class HelloWorldJavaClass.class.bin && \
+  rm HelloWorld.java
+```
\ No newline at end of file
diff --git a/solr/core/src/test-files/magic/hello.tar.bin b/solr/core/src/test-files/magic/hello.tar.bin
new file mode 100644
index 00000000000..68ca23c362a
Binary files /dev/null and b/solr/core/src/test-files/magic/hello.tar.bin differ
diff --git a/solr/core/src/test-files/magic/plain.txt b/solr/core/src/test-files/magic/plain.txt
new file mode 100644
index 00000000000..70c379b63ff
--- /dev/null
+++ b/solr/core/src/test-files/magic/plain.txt
@@ -0,0 +1 @@
+Hello world
\ No newline at end of file
diff --git a/solr/core/src/test-files/magic/shell.sh.txt b/solr/core/src/test-files/magic/shell.sh.txt
new file mode 100644
index 00000000000..9ea411e111d
--- /dev/null
+++ b/solr/core/src/test-files/magic/shell.sh.txt
@@ -0,0 +1,2 @@
+#! /usr/bin/env bash
+echo Hello
\ No newline at end of file
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
index bf7422902f7..1fb94498e96 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
@@ -22,7 +22,6 @@ import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequestWrapper;
-
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileInputStream;
@@ -34,6 +33,7 @@ import java.io.OutputStream;
 import java.lang.invoke.MethodHandles;
 import java.net.URI;
 import java.nio.ByteBuffer;
+import java.nio.file.Files;
 import java.security.Principal;
 import java.util.Arrays;
 import java.util.Collection;
@@ -46,6 +46,7 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Properties;
 import java.util.Set;
 import java.util.zip.ZipEntry;
@@ -90,17 +91,17 @@ import org.apache.solr.common.util.Utils;
 import org.apache.solr.common.util.ValidatingJsonMap;
 import org.apache.solr.core.ConfigSetProperties;
 import org.apache.solr.core.TestDynamicLoading;
-import org.apache.solr.security.BasicAuthPlugin;
 import org.apache.solr.security.AuthorizationContext;
 import org.apache.solr.security.AuthorizationPlugin;
 import org.apache.solr.security.AuthorizationResponse;
+import org.apache.solr.security.BasicAuthPlugin;
 import org.apache.solr.servlet.SolrDispatchFilter;
 import org.apache.solr.util.ExternalPaths;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.data.Stat;
 import org.junit.After;
 import org.junit.AfterClass;
-import org.apache.zookeeper.data.Stat;
 import org.junit.Assume;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -903,6 +904,19 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
         params("q", "*:*")).getResults().get(0).get("id"));
   }
 
+  @Test
+  public void testUploadWithForbiddenContent() throws Exception {
+    // Uploads a config set containing a script, a class file and jar file, will return 400 error
+    long res = uploadForbiddenConfigSet(
+        "forbidden",
+        "suffix",
+        "foo",
+        true,
+        false,
+        true);
+    assertEquals(400, res);
+  }
+
   private static String getSecurityJson() throws KeeperException, InterruptedException {
     String securityJson = "{\n" +
             "  'authentication':{\n" +
@@ -955,6 +969,12 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
                                 configSetName, suffix, username, overwrite, cleanup, v2);
   }
 
+  private long uploadForbiddenConfigSet(String configSetName, String suffix, String username,
+                                        boolean overwrite, boolean cleanup, boolean v2) throws IOException {
+    return uploadGivenConfigSet(createTempZipFileWithForbiddenContent("magic"),
+        configSetName, suffix, username, overwrite, cleanup, v2);
+  }
+
   private long uploadBadConfigSet(String configSetName, String suffix, String username,
                                   boolean overwrite, boolean cleanup, boolean v2) throws IOException {
     
@@ -1319,6 +1339,38 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
     return new StringBuilder(new String(Utils.toJSON(map), UTF_8));
   }
 
+  /** Create a zip file (in the temp directory) containing files with forbidden content */
+  private File createTempZipFileWithForbiddenContent(String resourcePath) {
+    try {
+      final File zipFile = createTempFile("configset", "zip").toFile();
+      final File directory = SolrTestCaseJ4.getFile(resourcePath);
+      if (log.isInfoEnabled()) {
+        log.info("Directory: {}", directory.getAbsolutePath());
+      }
+      zipWithForbiddenContent(directory, zipFile);
+      if (log.isInfoEnabled()) {
+        log.info("Zipfile: {}", zipFile.getAbsolutePath());
+      }
+      return zipFile;
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static void zipWithForbiddenContent(File directory, File zipfile)
+      throws IOException {
+    OutputStream out = Files.newOutputStream(zipfile.toPath());
+    assertTrue(directory.isDirectory());
+    try (ZipOutputStream zout = new ZipOutputStream(out)) {
+      // Copy in all files from the directory
+      for (File file : Objects.requireNonNull(directory.listFiles())) {
+        zout.putNextEntry(new ZipEntry(file.getName()));
+        zout.write(Files.readAllBytes(file.toPath()));
+        zout.closeEntry();
+      }
+    }
+  }
+
   public static class CreateNoErrorChecking extends ConfigSetAdminRequest.Create {
     @SuppressWarnings({"rawtypes"})
     public ConfigSetAdminRequest setAction(ConfigSetAction action) {
diff --git a/solr/core/src/test/org/apache/solr/util/FileTypeMagicUtilTest.java b/solr/core/src/test/org/apache/solr/util/FileTypeMagicUtilTest.java
new file mode 100644
index 00000000000..b8e9a35a3d9
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/util/FileTypeMagicUtilTest.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.util;
+
+import org.apache.solr.SolrTestCaseJ4;
+
+public class FileTypeMagicUtilTest extends SolrTestCaseJ4 {
+  public void testGuessMimeType() {
+    assertEquals(
+        "application/x-java-applet",
+        FileTypeMagicUtil.INSTANCE.guessMimeType(
+            FileTypeMagicUtil.class.getResourceAsStream("/magic/HelloWorldJavaClass.class.bin")));
+    assertEquals(
+        "application/zip",
+        FileTypeMagicUtil.INSTANCE.guessMimeType(
+            FileTypeMagicUtil.class.getResourceAsStream(
+                "/runtimecode/containerplugin.v.1.jar.bin")));
+    assertEquals(
+        "application/x-tar",
+        FileTypeMagicUtil.INSTANCE.guessMimeType(
+            FileTypeMagicUtil.class.getResourceAsStream("/magic/hello.tar.bin")));
+    assertEquals(
+        "text/x-shellscript",
+        FileTypeMagicUtil.INSTANCE.guessMimeType(
+            FileTypeMagicUtil.class.getResourceAsStream("/magic/shell.sh.txt")));
+  }
+
+  public void testIsFileForbiddenInConfigset() {
+    assertTrue(
+        FileTypeMagicUtil.isFileForbiddenInConfigset(
+            FileTypeMagicUtil.class.getResourceAsStream("/magic/HelloWorldJavaClass.class.bin")));
+    assertTrue(
+        FileTypeMagicUtil.isFileForbiddenInConfigset(
+            FileTypeMagicUtil.class.getResourceAsStream("/magic/shell.sh.txt")));
+    assertFalse(
+        FileTypeMagicUtil.isFileForbiddenInConfigset(
+            FileTypeMagicUtil.class.getResourceAsStream("/magic/plain.txt")));
+  }
+}
diff --git a/solr/licenses/simplemagic-1.17.jar.sha1 b/solr/licenses/simplemagic-1.17.jar.sha1
new file mode 100644
index 00000000000..cf101094cc8
--- /dev/null
+++ b/solr/licenses/simplemagic-1.17.jar.sha1
@@ -0,0 +1 @@
+b6e2d1e47d7172e57fa858a2e3940c09a590e61e
diff --git a/solr/licenses/simplemagic-LICENSE-BSD_LIKE.txt b/solr/licenses/simplemagic-LICENSE-BSD_LIKE.txt
new file mode 100644
index 00000000000..9228230f933
--- /dev/null
+++ b/solr/licenses/simplemagic-LICENSE-BSD_LIKE.txt
@@ -0,0 +1,15 @@
+ISC License (https://opensource.org/licenses/ISC)
+
+Copyright 2021, Gray Watson
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
diff --git a/solr/licenses/simplemagic-NOTICE.txt b/solr/licenses/simplemagic-NOTICE.txt
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java
index 04e80ac1947..e6c2fc3ae01 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java
@@ -301,6 +301,7 @@ public class ZkMaintenanceUtils {
           log.info("uploadToZK skipping '{}' due to filenameExclusions '{}'", filename, filenameExclusions);
           return FileVisitResult.CONTINUE;
         }
+        // TODO: Cannot check MAGIC header for file since FileTypeMagicUtil is in core
         String zkNode = createZkNodeName(zkPath, rootPath, file);
         try {
           // if the path exists (and presumably we're uploading data to it) just set its data
@@ -348,6 +349,7 @@ public class ZkMaintenanceUtils {
       if (children.size() == 0) {
         // If we didn't copy data down, then we also didn't create the file. But we still need a marker on the local
         // disk so create an empty file.
+        // TODO: Cannot check MAGIC header for file since FileTypeGuesser is in core
         if (copyDataDown(zkClient, zkPath, file.toFile()) == 0) {
           Files.createFile(file);
         }