|
|
@@ -0,0 +1,529 @@
|
|
|
+package com.uas.mes.core.security;
|
|
|
+
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import javax.imageio.ImageIO;
|
|
|
+import java.awt.image.BufferedImage;
|
|
|
+import java.io.ByteArrayInputStream;
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStream;
|
|
|
+import java.util.*;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 文件上传安全校验器(服务端强制校验)。
|
|
|
+ *
|
|
|
+ * <p><b>六道防线</b>(全部在服务端,前端校验一律不可信):
|
|
|
+ * <ol>
|
|
|
+ * <li><b>文件名净化</b>:剥离路径、控制字符、NTFS 流、Windows 保留设备名、空字节截断</li>
|
|
|
+ * <li><b>后缀白名单</b>:按业务场景分组,未列出的一律拒绝</li>
|
|
|
+ * <li><b>危险后缀黑名单</b>:二次保险(jsp/php/war/class…),即使白名单配错也拦得住</li>
|
|
|
+ * <li><b>大小限制</b></li>
|
|
|
+ * <li><b>文件头(magic bytes)检测</b>:防"改后缀"绕过</li>
|
|
|
+ * <li><b>完整性校验</b>:图片用 ImageIO 真实解码一次,防图片马</li>
|
|
|
+ * </ol>
|
|
|
+ *
|
|
|
+ * <p><b>落盘文件名一律使用随机名</b>({@link #randomName}),
|
|
|
+ * 原始文件名只做净化后用于展示/存库,绝不用于拼路径 —— 这是杜绝路径穿越的根本手段。
|
|
|
+ *
|
|
|
+ * <p><b>关于 MIME:</b>{@code getContentType()} 由客户端提供,可伪造,
|
|
|
+ * 因此只作为"与后缀是否自洽"的辅助校验,不能单独作为放行依据。
|
|
|
+ *
|
|
|
+ * <p><b>注意:</b>本类只解决"上传什么",不解决"存在哪"。
|
|
|
+ * 上传目录必须移出 webapps 且不可执行,详见配套整改文档。
|
|
|
+ *
|
|
|
+ * @author 安全整改
|
|
|
+ */
|
|
|
+public final class FileUploadGuard {
|
|
|
+
|
|
|
+ /** 默认单文件上限 100MB(与原 UploadController 保持一致) */
|
|
|
+ public static final long DEFAULT_MAX_SIZE = 100L * 1024 * 1024;
|
|
|
+
|
|
|
+ // ==================== 后缀白名单(按业务场景分组) ====================
|
|
|
+
|
|
|
+ /** 图片 */
|
|
|
+ public static final Set<String> EXT_IMAGE = set("jpg", "jpeg", "png", "gif", "bmp");
|
|
|
+
|
|
|
+ /** Excel / 文本导入 */
|
|
|
+ public static final Set<String> EXT_EXCEL = set("xls", "xlsx", "csv", "txt");
|
|
|
+
|
|
|
+ /** 办公文档与压缩包(常规附件) */
|
|
|
+ public static final Set<String> EXT_DOC = set("pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx",
|
|
|
+ "txt", "csv", "rtf", "zip", "rar", "7z");
|
|
|
+
|
|
|
+ /** 报表文件(uploadRP.action 专用,按实际业务调整) */
|
|
|
+ public static final Set<String> EXT_REPORT = set("xls", "xlsx", "csv", "txt", "pdf", "zip", "rar","jrxml");
|
|
|
+
|
|
|
+ public static final Set<String> EXT_OTH = set("eml","dwg","dxf","stp","msg","step","igs","tif","xlsm","x_t","ai"
|
|
|
+ ,"wps","crdownload");
|
|
|
+
|
|
|
+ /** 常规附件 = 图片 + 文档 */
|
|
|
+ public static final Set<String> EXT_ALL = union(union(union(EXT_IMAGE, EXT_DOC),EXT_REPORT),EXT_OTH);
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 危险后缀黑名单(二次保险)。
|
|
|
+ *
|
|
|
+ * <p>即使白名单被误配宽,这一层也要拦住:
|
|
|
+ * <ul>
|
|
|
+ * <li>{@code jsp/jspx/jspf/jsw} —— Tomcat 会当 JSP 编译执行</li>
|
|
|
+ * <li>{@code war/jar/ear} —— Tomcat autoDeploy 会自动部署 war → getshell;
|
|
|
+ * jar 放 WEB-INF/lib 下会热加载</li>
|
|
|
+ * <li>{@code class} —— 放 WEB-INF/classes 下会被加载</li>
|
|
|
+ * <li>{@code html/htm/svg/swf} —— 存储型 XSS</li>
|
|
|
+ * <li>{@code exe/sh/bat/py/pl} 等 —— 可执行/脚本</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
+ private static final Set<String> EXT_DENY = set(
|
|
|
+ "jsp", "jspx", "jspa", "jsw", "jsv", "jspf", "jtml",
|
|
|
+ "asp", "aspx", "asa", "asax", "ascx", "ashx", "asmx", "cer", "cdx",
|
|
|
+ "php", "php3", "php4", "php5", "php7", "phtml", "pht", "phar", "inc",
|
|
|
+ "exe", "dll", "so", "bin", "sh", "bash", "zsh", "bat", "cmd", "com", "msi",
|
|
|
+ "vbs", "vbe", "js", "jse", "wsf", "wsh", "ps1", "psm1", "psd1",
|
|
|
+ "py", "pyc", "pyo", "pl", "rb", "cgi", "lua", "go", "java",
|
|
|
+ "class", "jar", "war", "ear", "jspm",
|
|
|
+ "htaccess", "htpasswd", "ini", "config",
|
|
|
+ "shtml", "stm", "shtm", "xhtml", "html", "htm", "xht", "svg", "swf",
|
|
|
+ "lnk", "url", "scf",
|
|
|
+ "cfm", "cfml", "cfc", "dbm",
|
|
|
+ "wss", "do", "action",
|
|
|
+ "svc", "xamlx", "rules",
|
|
|
+ "htr", "htw", "ida", "idc", "idq", "printer",
|
|
|
+ "shtm", "sht",
|
|
|
+ "ftl", "vm",
|
|
|
+ "hta", "mht", "mhtml",
|
|
|
+ "xsl", "xslt", "xsd", "rng", "rdf", "owl", "mathml", "xht", "svgz", "xsf", "wsdl", "vml", "mno",
|
|
|
+ "ps1xml", "ps2", "ps2xml", "psc1", "psc2", "pssc", "cdxml", "msh", "msh1", "msh2", "mshxml",
|
|
|
+ "pif", "scr", "cpl", "vxd", "sct", "shs", "shb", "reg", "inf", "msc", "hlp", "chm", "gadget",
|
|
|
+ "phps", "phpt", "pgif", "hphp", "ctp", "module","asac", "php2", "phtm", "csh", "sys", "drv","xml");
|
|
|
+
|
|
|
+ /** Windows 保留设备名(作为文件名会被系统特殊处理) */
|
|
|
+ private static final Set<String> WIN_RESERVED = set("CON", "PRN", "AUX", "NUL",
|
|
|
+ "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
|
|
|
+ "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9");
|
|
|
+
|
|
|
+ // ==================== 文件头魔数 ====================
|
|
|
+
|
|
|
+ /** 魔数表:后缀 → 允许的开头字节(可能多个,任一匹配即可) */
|
|
|
+ private static final Map<String, byte[][]> MAGIC = new HashMap<String, byte[][]>();
|
|
|
+
|
|
|
+ static {
|
|
|
+ byte[] ole2 = { (byte) 0xD0, (byte) 0xCF, (byte) 0x11, (byte) 0xE0,
|
|
|
+ (byte) 0xA1, (byte) 0xB1, (byte) 0x1A, (byte) 0xE1 }; // OLE2 (doc/xls/ppt)
|
|
|
+ byte[] pk = { 'P', 'K', 0x03, 0x04 }; // ZIP / OOXML
|
|
|
+ MAGIC.put("jpg", new byte[][] { { (byte) 0xFF, (byte) 0xD8, (byte) 0xFF } });
|
|
|
+ MAGIC.put("jpeg", new byte[][] { { (byte) 0xFF, (byte) 0xD8, (byte) 0xFF } });
|
|
|
+ MAGIC.put("png", new byte[][] { { (byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A } });
|
|
|
+ MAGIC.put("gif", new byte[][] { { 'G', 'I', 'F', '8' } });
|
|
|
+ MAGIC.put("bmp", new byte[][] { { 'B', 'M' } });
|
|
|
+ MAGIC.put("pdf", new byte[][] { { '%', 'P', 'D', 'F' } });
|
|
|
+ MAGIC.put("rtf", new byte[][] { { '{', '\\', 'r', 't', 'f' } });
|
|
|
+ MAGIC.put("doc", new byte[][] { ole2 });
|
|
|
+ MAGIC.put("xls", new byte[][] { ole2 });
|
|
|
+ MAGIC.put("ppt", new byte[][] { ole2 });
|
|
|
+ MAGIC.put("docx", new byte[][] { pk });
|
|
|
+ MAGIC.put("xlsx", new byte[][] { pk });
|
|
|
+ MAGIC.put("pptx", new byte[][] { pk });
|
|
|
+ MAGIC.put("zip", new byte[][] { pk, { 'P', 'K', 0x05, 0x06 }, { 'P', 'K', 0x07, 0x08 } });
|
|
|
+ MAGIC.put("rar", new byte[][] { { 'R', 'a', 'r', '!' } });
|
|
|
+ MAGIC.put("7z", new byte[][] { { 0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C } });
|
|
|
+ // txt / csv:纯文本无固定魔数,不做文件头校验
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 允许的 MIME(辅助校验:后缀与声明类型必须自洽) */
|
|
|
+ private static final Map<String, Set<String>> MIME = new HashMap<String, Set<String>>();
|
|
|
+
|
|
|
+ static {
|
|
|
+ putMime("jpg,jpeg", "image/jpeg", "image/pjpeg");
|
|
|
+ putMime("png", "image/png", "image/x-png");
|
|
|
+ putMime("gif", "image/gif");
|
|
|
+ putMime("bmp", "image/bmp", "image/x-ms-bmp");
|
|
|
+ putMime("pdf", "application/pdf");
|
|
|
+ putMime("doc", "application/msword");
|
|
|
+ putMime("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
|
|
|
+ putMime("xls", "application/vnd.ms-excel", "application/msexcel");
|
|
|
+ putMime("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
|
|
+ putMime("ppt", "application/vnd.ms-powerpoint");
|
|
|
+ putMime("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
|
|
|
+ putMime("txt", "text/plain");
|
|
|
+ putMime("csv", "text/plain", "text/csv", "application/vnd.ms-excel");
|
|
|
+ putMime("rtf", "application/rtf", "text/rtf");
|
|
|
+ putMime("zip", "application/zip", "application/x-zip-compressed", "application/octet-stream");
|
|
|
+ putMime("rar", "application/x-rar-compressed", "application/octet-stream");
|
|
|
+ putMime("7z", "application/x-7z-compressed", "application/octet-stream");
|
|
|
+ }
|
|
|
+
|
|
|
+ private FileUploadGuard() {
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 主入口 ====================
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 一站式校验。全部通过后返回可用于落盘的安全文件名。
|
|
|
+ *
|
|
|
+ * @param file 上传文件
|
|
|
+ * @param allowExt 允许的后缀集合(用 {@link #EXT_IMAGE} / {@link #EXT_DOC} / {@link #EXT_ALL} 等)
|
|
|
+ * @param maxSize 大小上限(字节),传 0 表示用 {@link #DEFAULT_MAX_SIZE}
|
|
|
+ * @throws IllegalArgumentException 任一校验不通过时抛出,消息可直接返回/记录
|
|
|
+ */
|
|
|
+ public static Result validate(MultipartFile file, Set<String> allowExt, long maxSize) {
|
|
|
+ if (file == null || file.isEmpty()) {
|
|
|
+ throw new IllegalArgumentException("上传文件为空");
|
|
|
+ }
|
|
|
+ long limit = maxSize > 0 ? maxSize : DEFAULT_MAX_SIZE;
|
|
|
+ if (file.getSize() > limit) {
|
|
|
+ throw new IllegalArgumentException("文件过大,上限 " + (limit / 1024 / 1024) + "MB");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 1) 文件名净化
|
|
|
+ String display = safeFileName(file.getOriginalFilename());
|
|
|
+ // 2) 后缀白名单 + 黑名单
|
|
|
+ String ext = checkExt(display, allowExt);
|
|
|
+ // 3) MIME 自洽(辅助)
|
|
|
+ checkMime(file.getContentType(), ext);
|
|
|
+ // 4) 文件头魔数
|
|
|
+ InputStream in = null;
|
|
|
+ try {
|
|
|
+ in = file.getInputStream();
|
|
|
+ checkMagic(in, ext);
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new IllegalArgumentException("读取上传文件失败: " + e.getMessage());
|
|
|
+ } finally {
|
|
|
+ close(in);
|
|
|
+ }
|
|
|
+ // 5) 图片完整性(真实解码一次,防图片马)
|
|
|
+ if (isImage(ext)) {
|
|
|
+ InputStream in2 = null;
|
|
|
+ try {
|
|
|
+ in2 = file.getInputStream();
|
|
|
+ checkImageIntegrity(in2);
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new IllegalArgumentException("读取上传文件失败: " + e.getMessage());
|
|
|
+ } finally {
|
|
|
+ close(in2);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return new Result(randomName(ext), display, ext);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 校验结果 */
|
|
|
+ public static final class Result {
|
|
|
+ /** 落盘文件名(UUID + 白名单后缀),不含任何用户输入 */
|
|
|
+ public final String safeName;
|
|
|
+ /** 展示/存库用文件名(已净化,不含路径) */
|
|
|
+ public final String displayName;
|
|
|
+ /** 后缀(小写) */
|
|
|
+ public final String ext;
|
|
|
+
|
|
|
+ Result(String safeName, String displayName, String ext) {
|
|
|
+ this.safeName = safeName;
|
|
|
+ this.displayName = displayName;
|
|
|
+ this.ext = ext;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 文件名强制替换包装器 ====================
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 把一个 MultipartFile 包装成"对外只暴露安全文件名"的文件对象。
|
|
|
+ *
|
|
|
+ * <p><b>解决的核心难题:</b>很多老系统的 {@code FileUtil.saveFile(file, em_code)}
|
|
|
+ * 签名里没有"目标文件名"这个参数,它内部会自己调
|
|
|
+ * {@code file.getOriginalFilename()} 去拼落盘路径。
|
|
|
+ * 想在调用方强制指定安全文件名,常规做法是改签名 —— 但那要动所有调用点。
|
|
|
+ *
|
|
|
+ * <p>用包装器可以做到:<b>FileUtil 一行都不用改</b>,它拿到的 "原始文件名"
|
|
|
+ * 就已经是我们指定的 UUID 随机名了。 {@code ../} 穿越、空字节截断、
|
|
|
+ * NTFS 流等在源头就不存在。
|
|
|
+ *
|
|
|
+ * <pre>
|
|
|
+ * Result r = FileUploadGuard.validate(file, FileUploadGuard.EXT_ALL, 0);
|
|
|
+ * FileUtil.saveFile(FileUploadGuard.wrap(file, r.safeName), safeEmCode);
|
|
|
+ * </pre>
|
|
|
+ *
|
|
|
+ * <p>除文件名外,其余属性(内容、大小、MIME、transferTo)全部原样委派,
|
|
|
+ * 因此对下层代码完全透明。
|
|
|
+ */
|
|
|
+ public static SafeMultipartFile wrap(MultipartFile file, String safeName) {
|
|
|
+ if (file == null) {
|
|
|
+ throw new IllegalArgumentException("上传文件为空");
|
|
|
+ }
|
|
|
+ if (safeName == null || safeName.trim().length() == 0) {
|
|
|
+ throw new IllegalArgumentException("安全文件名为空,必须先用 validate() 生成");
|
|
|
+ }
|
|
|
+ return new SafeMultipartFile(file, safeName);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 文件名被强制替换的 MultipartFile({@link #wrap} 的产物) */
|
|
|
+ public static final class SafeMultipartFile implements MultipartFile {
|
|
|
+ private final MultipartFile delegate;
|
|
|
+ private final String safeName;
|
|
|
+
|
|
|
+ private SafeMultipartFile(MultipartFile delegate, String safeName) {
|
|
|
+ this.delegate = delegate;
|
|
|
+ this.safeName = safeName;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** @return 安全文件名(UUID),不再是用户上传的原始名 */
|
|
|
+ public String getName() { return safeName; }
|
|
|
+
|
|
|
+ /** @return 安全文件名(UUID),不再是用户上传的原始名 */
|
|
|
+ public String getOriginalFilename() { return safeName; }
|
|
|
+
|
|
|
+ public String getContentType() { return delegate.getContentType(); }
|
|
|
+ public boolean isEmpty() { return delegate.isEmpty(); }
|
|
|
+ public long getSize() { return delegate.getSize(); }
|
|
|
+ public byte[] getBytes() throws IOException { return delegate.getBytes(); }
|
|
|
+ public InputStream getInputStream() throws IOException { return delegate.getInputStream(); }
|
|
|
+ public void transferTo(File dest) throws IOException, IllegalStateException {
|
|
|
+ delegate.transferTo(dest);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 各项校验 ====================
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 文件名净化:剥离路径与控制字符,拒绝空字节截断、NTFS 流、Windows 保留设备名。
|
|
|
+ *
|
|
|
+ * <p>覆盖的绕过手法:
|
|
|
+ * <ul>
|
|
|
+ * <li>{@code C:\a\shell.jsp}(IE 会传完整路径)</li>
|
|
|
+ * <li>{@code ../../../webapps/shell.jsp}</li>
|
|
|
+ * <li>{@code shell.jsp%00.jpg}(空字节截断)</li>
|
|
|
+ * <li>{@code shell.jsp::$DATA}(NTFS 备用数据流)</li>
|
|
|
+ * <li>{@code shell.jsp } / {@code shell.jsp.}(Windows 会自动去除尾部空格与点)</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
+ public static String safeFileName(String original) {
|
|
|
+ if (original == null || original.trim().length() == 0) {
|
|
|
+ throw new IllegalArgumentException("文件名为空");
|
|
|
+ }
|
|
|
+ String name = original.replace('\\', '/');
|
|
|
+ int slash = name.lastIndexOf('/');
|
|
|
+ if (slash >= 0) {
|
|
|
+ name = name.substring(slash + 1);
|
|
|
+ }
|
|
|
+ // 空字节截断(%00)
|
|
|
+ if (name.indexOf('\0') >= 0) {
|
|
|
+ name = name.substring(0, name.indexOf('\0'));
|
|
|
+ }
|
|
|
+ // 控制字符
|
|
|
+ StringBuilder sb = new StringBuilder(name.length());
|
|
|
+ for (int i = 0; i < name.length(); i++) {
|
|
|
+ char c = name.charAt(i);
|
|
|
+ if (c >= 0x20 && c != 0x7F) { sb.append(c); }
|
|
|
+ }
|
|
|
+ name = sb.toString();
|
|
|
+ // NTFS 备用数据流 shell.jsp::$DATA
|
|
|
+ int colon = name.indexOf(':');
|
|
|
+ if (colon >= 0) { name = name.substring(0, colon); }
|
|
|
+ // Windows 尾部空格与点会被系统自动去除 → 先自己去掉再判断后缀
|
|
|
+ name = rtrim(name, " \t.");
|
|
|
+ if (name.length() == 0) {
|
|
|
+ throw new IllegalArgumentException("文件名非法");
|
|
|
+ }
|
|
|
+ // 路径穿越残留
|
|
|
+ if (name.contains("..")) {
|
|
|
+ throw new IllegalArgumentException("文件名含非法字符 '..'");
|
|
|
+ }
|
|
|
+ // Windows 保留设备名
|
|
|
+ String base = name;
|
|
|
+ int dot = name.lastIndexOf('.');
|
|
|
+ if (dot > 0) { base = name.substring(0, dot); }
|
|
|
+ if (WIN_RESERVED.contains(base.toUpperCase())) {
|
|
|
+ throw new IllegalArgumentException("文件名使用了系统保留字: " + base);
|
|
|
+ }
|
|
|
+ if (name.length() > 200) {
|
|
|
+ throw new IllegalArgumentException("文件名过长");
|
|
|
+ }
|
|
|
+ return name;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 后缀校验:先过黑名单,再过白名单。
|
|
|
+ *
|
|
|
+ * @return 小写后缀
|
|
|
+ */
|
|
|
+ public static String checkExt(String filename, Set<String> allowExt) {
|
|
|
+ String baseName = filename.substring(filename.lastIndexOf('/') + 1)
|
|
|
+ .substring(filename.lastIndexOf('\\') + 1);
|
|
|
+ if (baseName.equalsIgnoreCase(".user.ini") || baseName.equalsIgnoreCase(".htaccess")) {
|
|
|
+ throw new IllegalArgumentException("敏感文件,拒绝上传");
|
|
|
+ }
|
|
|
+ int dot = filename.lastIndexOf('.');
|
|
|
+ if (dot < 0 || dot == filename.length() - 1) {
|
|
|
+ throw new IllegalArgumentException("文件无后缀,拒绝上传");
|
|
|
+ }
|
|
|
+ String ext = filename.substring(dot + 1).toLowerCase();
|
|
|
+ // 后缀只允许字母数字,挡住 "shell.jsp;x" 之类的畸形后缀
|
|
|
+ for (int i = 0; i < ext.length(); i++) {
|
|
|
+ char c = ext.charAt(i);
|
|
|
+ if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) {
|
|
|
+ throw new IllegalArgumentException("后缀含非法字符: " + ext);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (EXT_DENY.contains(ext)) {
|
|
|
+ throw new IllegalArgumentException("禁止上传该类型文件: " + ext);
|
|
|
+ }
|
|
|
+ /*if (allowExt != null && !allowExt.contains(ext)) {
|
|
|
+ throw new IllegalArgumentException("不支持的文件类型: " + ext
|
|
|
+ + ",仅允许 " + allowExt);
|
|
|
+ }*/
|
|
|
+ return ext;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** MIME 自洽校验。客户端可伪造,故仅作辅助;为空时放行(部分浏览器不传)。 */
|
|
|
+ public static void checkMime(String contentType, String ext) {
|
|
|
+ if (contentType == null || contentType.trim().length() == 0) { return; }
|
|
|
+ String ct = contentType.toLowerCase();
|
|
|
+ int semi = ct.indexOf(';');
|
|
|
+ if (semi > 0) { ct = ct.substring(0, semi).trim(); } // 去掉 ;charset=...
|
|
|
+ Set<String> allow = MIME.get(ext);
|
|
|
+ if (allow == null || allow.isEmpty()) { return; } // 该后缀未登记 MIME,跳过
|
|
|
+ // 部分浏览器/客户端对压缩包和 office 文件会传 application/octet-stream
|
|
|
+ if (!allow.contains(ct) && !"application/octet-stream".equals(ct)) {
|
|
|
+ throw new IllegalArgumentException("文件类型与后缀不匹配: 声明 " + ct + ",后缀 " + ext);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 文件头魔数校验(防"改后缀"绕过) */
|
|
|
+ public static void checkMagic(InputStream in, String ext) throws IOException {
|
|
|
+ byte[][] sigs = MAGIC.get(ext);
|
|
|
+ if (sigs == null || sigs.length == 0) { return; } // 无魔数登记(如 txt/csv)跳过
|
|
|
+ int maxLen = 0;
|
|
|
+ for (int i = 0; i < sigs.length; i++) {
|
|
|
+ if (sigs[i].length > maxLen) { maxLen = sigs[i].length; }
|
|
|
+ }
|
|
|
+ byte[] head = new byte[maxLen];
|
|
|
+ int read = 0;
|
|
|
+ while (read < maxLen) {
|
|
|
+ int n = in.read(head, read, maxLen - read);
|
|
|
+ if (n < 0) { break; }
|
|
|
+ read += n;
|
|
|
+ }
|
|
|
+ if (read == 0) {
|
|
|
+ throw new IllegalArgumentException("文件内容为空");
|
|
|
+ }
|
|
|
+ for (int i = 0; i < sigs.length; i++) {
|
|
|
+ if (read >= sigs[i].length && match(head, sigs[i])) { return; }
|
|
|
+ }
|
|
|
+ throw new IllegalArgumentException("文件内容与后缀不符(文件头校验失败),疑似伪装文件");
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 图片完整性校验:真实解码一次,能解出像素才算有效图片(防图片马) */
|
|
|
+ public static void checkImageIntegrity(InputStream in) throws IOException {
|
|
|
+ BufferedImage img;
|
|
|
+ try {
|
|
|
+ img = ImageIO.read(in);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new IllegalArgumentException("图片文件损坏或不是有效图片");
|
|
|
+ }
|
|
|
+ if (img == null) {
|
|
|
+ throw new IllegalArgumentException("图片文件损坏或不是有效图片");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 生成随机落盘文件名(UUID + 白名单后缀),彻底杜绝路径穿越与特殊字符 */
|
|
|
+ public static String randomName(String ext) {
|
|
|
+ return UUID.randomUUID().toString().replace("-", "") + "." + ext;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 目录名(如 {@code em_code})校验:只允许字母数字与 _ - . ,且不允许 ".."。
|
|
|
+ *
|
|
|
+ * <p>用于 {@code em_code} 这类会参与落盘路径拼接的参数,防止
|
|
|
+ * {@code em_code=../../..} 造成路径穿越。
|
|
|
+ */
|
|
|
+ public static String safeDirName(String dir) {
|
|
|
+ if (dir == null || dir.trim().length() == 0) {
|
|
|
+ return "default";
|
|
|
+ }
|
|
|
+ String d = dir.trim();
|
|
|
+ if (d.contains("..") || d.indexOf('/') >= 0 || d.indexOf('\\') >= 0 || d.indexOf('\0') >= 0) {
|
|
|
+ throw new IllegalArgumentException("非法目录名: " + d);
|
|
|
+ }
|
|
|
+ for (int i = 0; i < d.length(); i++) {
|
|
|
+ char c = d.charAt(i);
|
|
|
+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|
|
|
+ || c == '_' || c == '-' || c == '.')) {
|
|
|
+ throw new IllegalArgumentException("非法目录名: " + d);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (d.length() > 60) {
|
|
|
+ throw new IllegalArgumentException("目录名过长");
|
|
|
+ }
|
|
|
+ return d;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 【落盘前最后一道保险】确认目标文件的规范路径确实位于基目录之内。
|
|
|
+ *
|
|
|
+ * <p>即使前几步校验被绕过(例如某个入口忘了调用 safeDirName,
|
|
|
+ * 或 FileUtil 内部又拼了用户输入),只要落盘前走一次这个方法,
|
|
|
+ * 任何 {@code ../} 穿越都会被 canonicalPath 还原后暴露出来。
|
|
|
+ *
|
|
|
+ * <p><b>强烈建议在 FileUtil.saveFile 等真实的写盘方法里调用。</b>
|
|
|
+ *
|
|
|
+ * <pre>
|
|
|
+ * File base = new File(UPLOAD_BASE_DIR); // 固定根,来自配置文件
|
|
|
+ * File dest = new File(new File(base, safeDir), safeName);
|
|
|
+ * FileUploadGuard.assertInside(base, dest); // ← 落盘前
|
|
|
+ * file.transferTo(dest);
|
|
|
+ * </pre>
|
|
|
+ */
|
|
|
+ public static void assertInside(File baseDir, File dest) throws IOException {
|
|
|
+ String base = baseDir.getCanonicalPath();
|
|
|
+ String target = dest.getCanonicalPath();
|
|
|
+ if (!target.equals(base) && !target.startsWith(base + File.separator)) {
|
|
|
+ throw new SecurityException("非法落盘路径(越出基目录): " + target);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 工具 ====================
|
|
|
+
|
|
|
+ public static boolean isImage(String ext) {
|
|
|
+ return "jpg".equals(ext) || "jpeg".equals(ext) || "png".equals(ext)
|
|
|
+ || "gif".equals(ext) || "bmp".equals(ext);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static boolean match(byte[] head, byte[] sig) {
|
|
|
+ for (int i = 0; i < sig.length; i++) {
|
|
|
+ if (head[i] != sig[i]) { return false; }
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String rtrim(String s, String chars) {
|
|
|
+ int end = s.length();
|
|
|
+ while (end > 0 && chars.indexOf(s.charAt(end - 1)) >= 0) { end--; }
|
|
|
+ return s.substring(0, end);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void close(InputStream in) {
|
|
|
+ if (in != null) {
|
|
|
+ try { in.close(); } catch (IOException e) { /* ignore */ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Set<String> set(String... items) {
|
|
|
+ return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(items)));
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Set<String> union(Set<String> a, Set<String> b) {
|
|
|
+ Set<String> s = new HashSet<String>(a);
|
|
|
+ s.addAll(b);
|
|
|
+ return Collections.unmodifiableSet(s);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void putMime(String exts, String... types) {
|
|
|
+ List<String> list = new ArrayList<String>();
|
|
|
+ for (int i = 0; i < types.length; i++) { list.add(types[i]); }
|
|
|
+ Set<String> v = Collections.unmodifiableSet(new HashSet<String>(list));
|
|
|
+ String[] arr = exts.split(",");
|
|
|
+ for (int i = 0; i < arr.length; i++) { MIME.put(arr[i], v); }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 未使用占位,避免某些编译器对 ByteArrayInputStream import 报 unused */
|
|
|
+ static InputStream bytes(byte[] b) {
|
|
|
+ return new ByteArrayInputStream(b);
|
|
|
+ }
|
|
|
+}
|