Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.
Python ai-agentsanti-detectantidetect-browserbot-detectionbrowser-automationcaptcha-bypasschromiumcloudflarecloudflare-bypassfingerprintheadless-browserplaywrightpuppeteerpythonrecaptchaseleniumstealth-browserundetectedweb-scrapingwebscraping
refactor(download): unpack verified archives directly
CloakHQ5010f99556c5
diff --git a/cloakbrowser/download.py b/cloakbrowser/download.pyindex cf681bb..768ee56 100644--- a/cloakbrowser/download.py+++ b/cloakbrowser/download.py@@ -933,40 +933,21 @@ def _extract_archive(def _extract_tar(archive_path: Path, dest_dir: Path) -> None:- """Extract tar.gz archive with path traversal protection."""+ """Extract tar.gz. Archive is signature-verified before extraction, so unpack+ as-is. filter="fully_trusted" pins legacy behavior (3.14 defaults to "data",+ which mangles macOS .app symlinks/perms); fallback covers Python < 3.12."""with tarfile.open(archive_path, "r:gz") as tar:- safe_members = []- for member in tar.getmembers():- # Allow symlinks — macOS .app bundles require them (Framework layout)- if member.issym() or member.islnk():- link_target = member.linkname- if os.path.isabs(link_target) or ".." in link_target.split("/"):- logger.warning(- "Skipping suspicious symlink: %s -> %s",- member.name,- link_target,- )- continue- else:- member_path = (dest_dir / member.name).resolve()- if not str(member_path).startswith(str(dest_dir.resolve())):- raise RuntimeError(- f"Archive contains path traversal: {member.name}"- )- safe_members.append(member)-- tar.extractall(dest_dir, members=safe_members)+ try:+ tar.extractall(dest_dir, filter="fully_trusted")+ except TypeError:+ tar.extractall(dest_dir)def _extract_zip(archive_path: Path, dest_dir: Path) -> None:- """Extract zip archive with path traversal protection."""+ """Extract zip. Signature-verified before extraction, so unpack as-is."""import zipfilewith zipfile.ZipFile(archive_path, "r") as zf:- for info in zf.infolist():- member_path = (dest_dir / info.filename).resolve()- if not str(member_path).startswith(str(dest_dir.resolve())):- raise RuntimeError(f"Archive contains path traversal: {info.filename}")zf.extractall(dest_dir)diff --git a/dotnet/src/CloakBrowser/Download.cs b/dotnet/src/CloakBrowser/Download.csindex c2c5b4e..a65b4b2 100644--- a/dotnet/src/CloakBrowser/Download.cs+++ b/dotnet/src/CloakBrowser/Download.cs@@ -989,79 +989,18 @@ public static class DownloadCloakLog.Info("Binary ready: {0}", bp);}- /// <summary>- /// Resolves an archive entry to an absolute path under <paramref name="destinationDir"/>,- /// guarding against path-traversal / zip-slip. The combined path is normalized via- /// <see cref="Path.GetFullPath(string)"/> and must stay within the (also normalized)- /// destination directory - comparison accounts for a trailing directory separator and- /// uses <see cref="StringComparison.Ordinal"/>. Throws <see cref="InvalidOperationException"/>- /// (naming the offending entry) when the entry escapes the destination.- /// </summary>- internal static string ResolveSafeEntryPath(string destinationDir, string entryName)- {- var destFull = Path.GetFullPath(destinationDir);- // Ensure a trailing separator so a sibling like "<dest>foo" can't masquerade as- // being inside "<dest>".- var destPrefix = destFull.EndsWith(Path.DirectorySeparatorChar)- ? destFull- : destFull + Path.DirectorySeparatorChar;-- var memberPath = Path.GetFullPath(Path.Combine(destFull, entryName));-- if (!string.Equals(memberPath, destFull, StringComparison.Ordinal) &&- !memberPath.StartsWith(destPrefix, StringComparison.Ordinal))- {- throw new InvalidOperationException($"Archive contains path traversal: {entryName}");- }-- return memberPath;- }-private static void ExtractTar(string archivePath, string destDir){+ // Signature-verified before extraction, so unpack as-is (symlinks included:+ // macOS .app bundles need them for the Framework layout).using var fileStream = File.OpenRead(archivePath);using var gzip = new GZipStream(fileStream, CompressionMode.Decompress);- using var reader = new TarReader(gzip);-- TarEntry? entry;- while ((entry = reader.GetNextEntry()) != null)- {- // Allow symlinks - macOS .app bundles require them (Framework layout).- if (entry.EntryType is TarEntryType.SymbolicLink or TarEntryType.HardLink)- {- var linkTarget = entry.LinkName;- if (Path.IsPathRooted(linkTarget) || linkTarget.Split('/').Contains(".."))- {- CloakLog.Warning("Skipping suspicious symlink: {0} -> {1}", entry.Name, linkTarget);- continue;- }- var linkPath = Path.Combine(destDir, entry.Name);- Directory.CreateDirectory(Path.GetDirectoryName(linkPath)!);- entry.ExtractToFile(linkPath, overwrite: true);- continue;- }-- var memberPath = ResolveSafeEntryPath(destDir, entry.Name);-- if (entry.EntryType == TarEntryType.Directory)- {- Directory.CreateDirectory(memberPath);- continue;- }-- Directory.CreateDirectory(Path.GetDirectoryName(memberPath)!);- entry.ExtractToFile(memberPath, overwrite: true);- }+ TarFile.ExtractToDirectory(gzip, destDir, overwriteFiles: true);}private static void ExtractZip(string archivePath, string destDir){- using var zf = ZipFile.OpenRead(archivePath);- foreach (var info in zf.Entries)- {- // Validate every entry up-front; throws on any zip-slip attempt.- ResolveSafeEntryPath(destDir, info.FullName);- }+ // Signature-verified before extraction, so unpack as-is.ZipFile.ExtractToDirectory(archivePath, destDir, overwriteFiles: true);}diff --git a/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs b/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.csindex b6dedf5..6c05463 100644--- a/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs@@ -1,6 +1,5 @@using System.IO;using System.IO.Compression;-using System.Runtime.InteropServices;using CloakBrowser;using Xunit;@@ -113,67 +112,3 @@ public class WrapperVersionNewerTestsAssert.True(Download.WrapperVersionNewer("0.4.0", "0.x.0"));}}--/// <summary>-/// Tests for the archive-extraction path-traversal (zip-slip) guard-/// <see cref="Download.ResolveSafeEntryPath(string, string)"/>, shared by-/// <c>ExtractTar</c> and <c>ExtractZip</c>.-/// </summary>-public class PathTraversalTests-{- private static string DestDir() =>- Path.Combine(Path.GetTempPath(), "cloak-extract-test");-- [Fact]- public void Normal_entry_resolves_inside_destination()- {- var dest = DestDir();- var resolved = Download.ResolveSafeEntryPath(dest, "sub/file.txt");-- var destFull = Path.GetFullPath(dest);- var expected = Path.GetFullPath(Path.Combine(destFull, "sub/file.txt"));-- Assert.Equal(expected, resolved);- // The resolved path stays under the destination directory.- Assert.StartsWith(destFull + Path.DirectorySeparatorChar, resolved, System.StringComparison.Ordinal);- }-- [Fact]- public void Parent_relative_entry_throws()- {- var dest = DestDir();- var ex = Assert.Throws<System.InvalidOperationException>(- () => Download.ResolveSafeEntryPath(dest, "../evil.txt"));- // The message names the offending entry.- Assert.Contains("../evil.txt", ex.Message);- }-- [Fact]- public void Absolute_entry_path_throws()- {- var dest = DestDir();- // An absolute entry path escapes the destination via Path.Combine semantics.- var absolute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)- ? @"C:\Windows\evil.txt"- : "/etc/evil.txt";-- var ex = Assert.Throws<System.InvalidOperationException>(- () => Download.ResolveSafeEntryPath(dest, absolute));- Assert.Contains(absolute, ex.Message);- }-- [Fact]- public void Windows_backslash_traversal_throws()- {- // "..\..\evil" is only a traversal where backslash is a path separator (Windows).- // On other platforms backslash is an ordinary filename character, so skip.- if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))- return;-- var dest = DestDir();- const string entry = @"..\..\evil";- var ex = Assert.Throws<System.InvalidOperationException>(- () => Download.ResolveSafeEntryPath(dest, entry));- Assert.Contains(entry, ex.Message);- }-}diff --git a/js/src/download.ts b/js/src/download.tsindex c984d5b..13f414f 100644--- a/js/src/download.ts+++ b/js/src/download.ts@@ -1040,7 +1040,8 @@ async function extractArchive(if (archivePath.endsWith(".zip")) {await extractZip(archivePath, destDir);} else {- await extractTar(archivePath, destDir);+ // Signature-verified before extraction, so unpack as-is.+ await tarExtract({ file: archivePath, cwd: destDir, strip: 0 });}// Flatten single subdirectory if needed@@ -1062,23 +1063,6 @@ async function extractArchive(}}-async function extractTar(archivePath: string, destDir: string): Promise<void> {- await tarExtract({- file: archivePath,- cwd: destDir,- strip: 0,- filter: (entryPath: string) => {- if (path.isAbsolute(entryPath) || entryPath.includes("..")) {- console.warn(- `[cloakbrowser] Skipping suspicious archive entry: ${entryPath}`- );- return false;- }- return true;- },- });-}-async function extractZip(archivePath: string, destDir: string): Promise<void> {// Brief delay to ensure OS fully releases file handles (Windows)await new Promise(resolve => setTimeout(resolve, 500));diff --git a/tests/test_extract.py b/tests/test_extract.pyindex b06aa49..59537be 100644--- a/tests/test_extract.py+++ b/tests/test_extract.py@@ -43,39 +43,25 @@ class TestExtractTar:assert (dest / "chrome").read_bytes() == b"binary"assert (dest / "lib" / "libfoo.so").read_bytes() == b"lib"- def test_path_traversal_blocked(self, tmp_path):- archive = tmp_path / "evil.tar.gz"- with tarfile.open(archive, "w:gz") as tar:- info = tarfile.TarInfo(name="../../../etc/passwd")- info.size = 4- tar.addfile(info, io.BytesIO(b"evil"))-- dest = tmp_path / "out"- dest.mkdir()- with pytest.raises(RuntimeError, match="path traversal"):- _extract_tar(archive, dest)-- def test_suspicious_symlink_skipped(self, tmp_path):- """Symlinks with absolute targets are skipped (logged as warning)."""+ def test_symlink_extracted(self, tmp_path):+ """Symlinks extract as-is — the archive is signature-verified before+ extraction, so no per-member sanitization is applied (macOS .app+ Framework layout depends on symlinks)."""archive = tmp_path / "symlink.tar.gz"with tarfile.open(archive, "w:gz") as tar:- # Normal fileinfo = tarfile.TarInfo(name="chrome")info.size = 6tar.addfile(info, io.BytesIO(b"binary"))- # Suspicious symlink- sym = tarfile.TarInfo(name="evil_link")+ sym = tarfile.TarInfo(name="chrome_link")sym.type = tarfile.SYMTYPE- sym.linkname = "/etc/passwd"+ sym.linkname = "chrome"tar.addfile(sym)dest = tmp_path / "out"dest.mkdir()_extract_tar(archive, dest)- # Normal file extractedassert (dest / "chrome").exists()- # Suspicious symlink was skipped- assert not (dest / "evil_link").exists()+ assert (dest / "chrome_link").is_symlink()# ---------------------------------------------------------------------------@@ -101,16 +87,6 @@ class TestExtractZip:assert (dest / "chrome.exe").read_bytes() == b"binary"assert (dest / "lib" / "foo.dll").read_bytes() == b"lib"- def test_path_traversal_blocked(self, tmp_path):- archive = tmp_path / "evil.zip"- with zipfile.ZipFile(archive, "w") as zf:- zf.writestr("../../../etc/passwd", "evil")-- dest = tmp_path / "out"- dest.mkdir()- with pytest.raises(RuntimeError, match="path traversal"):- _extract_zip(archive, dest)-# ---------------------------------------------------------------------------# Directory flattening