Skip to content

Commit a0e96de

Browse files
committed
test: add tests for tar path traversal
1 parent 2b8ff8f commit a0e96de

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
<TargetFrameworks>netcoreapp3.1;net46</TargetFrameworks>
66
<ApplicationIcon />
77
<StartupObject />
8+
<LangVersion>8</LangVersion>
89
</PropertyGroup>
910

1011
<ItemGroup>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using System.IO;
2+
using System.Text;
3+
using ICSharpCode.SharpZipLib.Core;
4+
using ICSharpCode.SharpZipLib.Tar;
5+
using static ICSharpCode.SharpZipLib.Tests.TestSupport.Utils;
6+
using NUnit.Framework;
7+
8+
namespace ICSharpCode.SharpZipLib.Tests.Tar
9+
{
10+
[TestFixture]
11+
public class TarArchiveTests
12+
{
13+
[Test]
14+
[Category("Tar")]
15+
[Category("CreatesTempFile")]
16+
public void ExtractingContentsWithNonTraversalPathSucceeds()
17+
{
18+
Assert.DoesNotThrow(() => ExtractTarOK("output", "test-good", allowTraverse: false));
19+
}
20+
21+
[Test]
22+
[Category("Tar")]
23+
[Category("CreatesTempFile")]
24+
public void ExtractingContentsWithExplicitlyAllowedTraversalPathSucceeds()
25+
{
26+
Assert.DoesNotThrow(() => ExtractTarOK("output", "../file", allowTraverse: true));
27+
}
28+
29+
[Test]
30+
[Category("Tar")]
31+
[Category("CreatesTempFile")]
32+
[TestCase("output", "../file")]
33+
[TestCase("output", "../output.txt")]
34+
public void ExtractingContentsWithDisallowedPathsFails(string outputDir, string fileName)
35+
{
36+
Assert.Throws<InvalidNameException>(() => ExtractTarOK(outputDir, fileName, allowTraverse: false));
37+
}
38+
39+
public void ExtractTarOK(string outputDir, string fileName, bool allowTraverse)
40+
{
41+
var fileContent = Encoding.UTF8.GetBytes("file content");
42+
using var tempDir = new TempDir();
43+
44+
var tempPath = tempDir.Fullpath;
45+
var extractPath = Path.Combine(tempPath, outputDir);
46+
var expectedOutputFile = Path.Combine(extractPath, fileName);
47+
48+
using var archiveStream = new MemoryStream();
49+
50+
Directory.CreateDirectory(extractPath);
51+
52+
using (var tos = new TarOutputStream(archiveStream, Encoding.UTF8){IsStreamOwner = false})
53+
{
54+
var entry = TarEntry.CreateTarEntry(fileName);
55+
entry.Size = fileContent.Length;
56+
tos.PutNextEntry(entry);
57+
tos.Write(fileContent, 0, fileContent.Length);
58+
tos.CloseEntry();
59+
}
60+
61+
archiveStream.Position = 0;
62+
63+
using (var ta = TarArchive.CreateInputTarArchive(archiveStream, Encoding.UTF8))
64+
{
65+
ta.ProgressMessageEvent += (archive, entry, message)
66+
=> TestContext.WriteLine($"{entry.Name} {entry.Size} {message}");
67+
ta.ExtractContents(extractPath, allowTraverse);
68+
}
69+
70+
Assert.That(File.Exists(expectedOutputFile));
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)