Repository Public License
1import Foundation2import UniformTypeIdentifiers34/// Why a downloaded file deserves care before it is opened.5public enum DownloadRiskReason: String, Sendable, Codable, CaseIterable {6 /// Program or library the system can run.7 case executable8 /// Installer package or disk image.9 case installer10 /// Script an interpreter runs.11 case script12 /// Changes system or application configuration when opened (profiles, registry files, Terminal settings).13 case configuration14 /// A shortcut that opens something else (another URL, a remote volume, a command).15 case shortcut16 /// A dangerous extension hidden behind a harmless-looking one (`invoice.pdf.exe`).17 case disguisedExtension18 /// The MIME type announces a program while the name does not.19 case typeMismatch20 /// Archive: its content is not inspected.21 case archive22 /// Office document format that can carry macros.23 case macroDocument24 /// Local web page or SVG: runs scripts when opened in a browser.25 case activeContent26}2728public struct DownloadRisk: Sendable, Hashable, Codable {29 public enum Level: Int, Sendable, Codable, Comparable {30 case safe, caution, dangerous31 public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue }32 }3334 public var level: Level35 public var reasons: [DownloadRiskReason]3637 public static let safe = DownloadRisk(level: .safe, reasons: [])3839 /// Opening the file from the browser needs an explicit confirmation by the user.40 public var requiresOpenConfirmation: Bool { level == .dangerous }41}4243/// Classifies a download by file name and MIME type. A list of this kind is never complete: it catches the44/// well-known program, installer and script formats of macOS, Windows, Linux, Android and iOS, and anything45/// `UTType` knows to be executable. It does not inspect file content.46public enum DownloadRiskClassifier {47 static let executables: Set<String> = [48 "app", "exe", "com", "scr", "pif", "cpl", "msc", "gadget", "dll", "sys", "drv", "ocx", "bin", "run", "out", "elf",49 "jar", "jnlp", "class", "dylib", "so", "kext", "bundle", "plugin", "prefpane", "qlgenerator", "saver", "wdgt",50 "action", "workflow", "appex", "xpc", "framework", "osx", "air", "xbe", "xap", "appimage",51 ]52 static let installers: Set<String> = [53 "pkg", "mpkg", "dmg", "iso", "img", "sparseimage", "sparsebundle", "toast", "cdr", "msi", "msp", "msix", "msixbundle",54 "appx", "appxbundle", "deb", "rpm", "apk", "aab", "xapk", "ipa", "snap", "flatpak", "flatpakref", "vsix", "crx", "xpi",55 "safariextz",56 ]57 static let scripts: Set<String> = [58 "sh", "bash", "zsh", "csh", "tcsh", "ksh", "fish", "command", "tool", "py", "pyc", "pyw", "pyz", "rb", "pl", "pm", "php",59 "js", "mjs", "cjs", "jse", "vbs", "vbe", "vb", "wsf", "wsh", "wsc", "ps1", "psm1", "psd1", "ps1xml", "bat", "cmd", "hta",60 "scpt", "scptd", "applescript", "jxa", "lua", "tcl", "awk", "sed", "r", "swift", "scf", "sct", "msh", "nsh",61 ]62 static let configurations: Set<String> = [63 "mobileconfig", "mobileprovision", "provisionprofile", "configprofile", "reg", "inf", "terminal", "service",64 "desktop", "shortcut", "ics_cmd", "appinstaller", "settingcontent-ms", "application", "library-ms",65 ]66 static let shortcuts: Set<String> = ["webloc", "inetloc", "fileloc", "url", "lnk", "website", "search-ms", "afploc", "ftploc", "nfsloc", "vncloc", "alias"]67 static let archives: Set<String> = ["zip", "rar", "7z", "tar", "gz", "tgz", "bz2", "tbz", "tbz2", "xz", "txz", "zst", "lz", "lzma", "cab",68 "ace", "arj", "z", "cpio", "xar", "sit", "sitx", "war", "ear", "aar"]69 static let macroDocuments: Set<String> = ["docm", "dotm", "xlsm", "xltm", "xlam", "xlsb", "pptm", "potm", "ppam", "ppsm", "sldm", "xll", "doc",70 "xls", "ppt", "rtf", "odt", "ods", "odp", "one", "pub", "slk", "iqy", "chm", "hlp"]71 static let activeContent: Set<String> = ["html", "htm", "xhtml", "xht", "mht", "mhtml", "shtml", "svg", "svgz", "xml", "xsl", "xslt", "swf", "webarchive"]72 /// Extensions people expect to be harmless: seeing one just before a dangerous extension is the trick.73 static let harmlessLooking: Set<String> = ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "rtf", "csv", "jpg", "jpeg", "png", "gif",74 "bmp", "tif", "tiff", "heic", "webp", "mp3", "mp4", "m4a", "mov", "avi", "mkv", "wav", "zip", "epub"]7576 static let dangerousMIMETypes: [String: DownloadRiskReason] = [77 "application/x-msdownload": .executable, "application/x-msdos-program": .executable, "application/x-dosexec": .executable,78 "application/vnd.microsoft.portable-executable": .executable, "application/x-executable": .executable,79 "application/x-mach-binary": .executable, "application/x-elf": .executable, "application/x-sharedlib": .executable,80 "application/java-archive": .executable, "application/x-java-archive": .executable, "application/x-java-jnlp-file": .executable,81 "application/x-apple-diskimage": .installer, "application/x-msi": .installer, "application/x-ms-installer": .installer,82 "application/vnd.apple.installer+xml": .installer, "application/vnd.android.package-archive": .installer,83 "application/x-debian-package": .installer, "application/x-rpm": .installer, "application/x-redhat-package-manager": .installer,84 "application/x-iso9660-image": .installer, "application/x-xpinstall": .installer, "application/x-chrome-extension": .installer,85 "application/x-sh": .script, "application/x-shellscript": .script, "text/x-shellscript": .script, "application/x-csh": .script,86 "application/x-python": .script, "application/x-python-code": .script, "text/x-python": .script, "application/x-perl": .script,87 "text/x-perl": .script, "application/x-ruby": .script, "application/x-php": .script, "application/x-httpd-php": .script,88 "application/javascript": .script, "text/javascript": .script, "application/x-javascript": .script, "application/hta": .script,89 "application/x-bat": .script, "application/x-msdos-batch": .script, "text/vbscript": .script, "application/x-powershell": .script,90 "application/x-applescript": .script,91 "application/x-apple-aspen-config": .configuration,92 ]9394 private static func reason(forExtension ext: String) -> (DownloadRiskReason, DownloadRisk.Level)? {95 if executables.contains(ext) { return (.executable, .dangerous) }96 if installers.contains(ext) { return (.installer, .dangerous) }97 if scripts.contains(ext) { return (.script, .dangerous) }98 if configurations.contains(ext) { return (.configuration, .dangerous) }99 if shortcuts.contains(ext) { return (.shortcut, .dangerous) }100 // The explicit lists come first: the system's type tree calls macro-enabled office documents101 // "executable", which would put a spreadsheet on the same level as an installer.102 if macroDocuments.contains(ext) { return (.macroDocument, .caution) }103 if activeContent.contains(ext) { return (.activeContent, .caution) }104 if archives.contains(ext) { return (.archive, .caution) }105 if let type = UTType(filenameExtension: ext), !type.isDynamic {106 if type.conforms(to: .executable) || type.conforms(to: .application) || type.conforms(to: .unixExecutable)107 || type.conforms(to: .pluginBundle) || type.conforms(to: .framework) { return (.executable, .dangerous) }108 if type.conforms(to: .script) || type.conforms(to: .shellScript) { return (.script, .dangerous) }109 if type.conforms(to: .diskImage) { return (.installer, .dangerous) }110 if type.conforms(to: .aliasFile) || type.conforms(to: .symbolicLink) || type.conforms(to: .internetLocation) {111 return (.shortcut, .dangerous)112 }113 if type.conforms(to: .archive) { return (.archive, .caution) }114 }115 return nil116 }117118 /// Risk of a file by its (already sanitised) name and announced MIME type.119 ///120 /// The extension decides how the system opens the file, so it weighs most. A file without an extension is121 /// judged by its MIME type. A program-like MIME type on a harmless extension is only `caution`: the system122 /// would open the file as what its name says.123 public static func classify(filename: String, mimeType: String? = nil) -> DownloadRisk {124 var level = DownloadRisk.Level.safe125 var reasons: [DownloadRiskReason] = []126 func add(_ reason: DownloadRiskReason, _ reasonLevel: DownloadRisk.Level) {127 if !reasons.contains(reason) { reasons.append(reason) }128 level = max(level, reasonLevel)129 }130131 let parts = filename.lowercased().split(separator: ".", omittingEmptySubsequences: false).map(String.init)132 let extensions = parts.count > 1 ? Array(parts.dropFirst()) : []133 let last = extensions.last ?? ""134 let mime = DownloadFilename.normalizedMIMEType(mimeType)135136 if let (reason, reasonLevel) = reason(forExtension: last) {137 add(reason, reasonLevel)138 if reasonLevel == .dangerous, extensions.count >= 2, harmlessLooking.contains(extensions[extensions.count - 2]) {139 add(.disguisedExtension, .dangerous)140 }141 }142 // `photo.jpg.zip` is an ordinary archive, but `run.sh.gz` or `setup.exe.zip` still deserve the reason143 // of what is inside the wrapper.144 if extensions.count >= 2, DownloadFilename.compoundSuffixes.contains(last) || archives.contains(last),145 let (inner, _) = reason(forExtension: extensions[extensions.count - 2]),146 [.executable, .installer, .script].contains(inner) {147 add(inner, .caution)148 }149 if let reason = dangerousMIMETypes[mime] {150 if last.isEmpty { add(reason, .dangerous) } else if level < .dangerous { add(.typeMismatch, .caution) }151 } else if last.isEmpty, !mime.isEmpty, let type = UTType(mimeType: mime), !type.isDynamic,152 type.conforms(to: .executable) || type.conforms(to: .script) {153 add(type.conforms(to: .script) ? .script : .executable, .dangerous)154 }155 return DownloadRisk(level: level, reasons: reasons)156 }157}158