Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Added support for password-protected rar archives.

nzbdav-devabe5989cf6a6
diff --git a/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs b/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs
index 1994178b..d9bc9b81 100644
--- a/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs
+++ b/backend/Api/Controllers/TestArrConnection/TestArrConnectionController.cs
@@ -1,7 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using NzbWebDAV.Clients.RadarrSonarr;
-using NzbWebDAV.Clients.Usenet;
-using NzbWebDAV.Exceptions;
namespace NzbWebDAV.Api.Controllers.TestArrConnection;
diff --git a/backend/Extensions/RarHeaderExtensions.cs b/backend/Extensions/RarHeaderExtensions.cs
index 2bbb6b99..c8780e36 100644
--- a/backend/Extensions/RarHeaderExtensions.cs
+++ b/backend/Extensions/RarHeaderExtensions.cs
@@ -1,4 +1,7 @@
-using SharpCompress.Common.Rar.Headers;
+using System.Security.Cryptography;
+using System.Text;
+using NzbWebDAV.Models;
+using SharpCompress.Common.Rar.Headers;
namespace NzbWebDAV.Extensions;
@@ -24,6 +27,11 @@ public static class RarHeaderExtensions
return (long)header.GetReflectionProperty("CompressedSize")!;
}
+ public static long GetUncompressedSize(this IRarHeader header)
+ {
+ return (long)header.GetReflectionProperty("UncompressedSize")!;
+ }
+
public static string GetFileName(this IRarHeader header)
{
return (string)header.GetReflectionProperty("FileName")!;
@@ -45,4 +53,184 @@ public static class RarHeaderExtensions
{
return (bool)header.GetReflectionProperty("IsFirstVolume")!;
}
+
+ public static byte[]? GetR4Salt(this IRarHeader header)
+ {
+ return (byte[]?)header.GetReflectionProperty("R4Salt")!;
+ }
+
+ public static object? GetRar5CryptoInfo(this IRarHeader header)
+ {
+ return header.GetReflectionProperty("Rar5CryptoInfo")!;
+ }
+
+ public static bool GetIsEncrypted(this IRarHeader header)
+ {
+ return (bool)header.GetReflectionProperty("IsEncrypted")!;
+ }
+
+ public static bool GetIsSolid(this IRarHeader header)
+ {
+ return (bool)header.GetReflectionProperty("IsSolid")!;
+ }
+
+ public static AesParams? GetAesParams(this IRarHeader header, string? password)
+ {
+ // sanity checks
+ if (header.HeaderType != HeaderType.File) return null;
+ if (password == null) return null;
+
+ // rar3 aes params
+ var r4Salt = header.GetR4Salt();
+ if (r4Salt != null) return GetRar3AesParams(r4Salt, password, header.GetUncompressedSize());
+
+ // rar5 aes params
+ var rar5CryptoInfo = header.GetRar5CryptoInfo();
+ if (rar5CryptoInfo != null) return GetRar5AesParams(rar5CryptoInfo, password, header.GetUncompressedSize());
+
+ // no aes params
+ return null;
+ }
+
+ private static AesParams? GetRar3AesParams(byte[] salt, string password, long decodedSize)
+ {
+ const int sizeInitV = 0x10;
+ const int sizeSalt30 = 0x08;
+ var aesIV = new byte[sizeInitV];
+
+ var rawLength = 2 * password.Length;
+ var rawPassword = new byte[rawLength + sizeSalt30];
+ var passwordBytes = Encoding.UTF8.GetBytes(password);
+ for (var i = 0; i < password.Length; i++)
+ {
+ rawPassword[i * 2] = passwordBytes[i];
+ rawPassword[(i * 2) + 1] = 0;
+ }
+
+ for (var i = 0; i < salt.Length; i++)
+ {
+ rawPassword[i + rawLength] = salt[i];
+ }
+
+ var msgDigest = SHA1.Create();
+ const int noOfRounds = (1 << 18);
+ const int iblock = 3;
+
+ byte[] digest;
+ var data = new byte[(rawPassword.Length + iblock) * noOfRounds];
+
+ //TODO slow code below, find ways to optimize
+ for (var i = 0; i < noOfRounds; i++)
+ {
+ rawPassword.CopyTo(data, i * (rawPassword.Length + iblock));
+
+ data[(i * (rawPassword.Length + iblock)) + rawPassword.Length + 0] = (byte)i;
+ data[(i * (rawPassword.Length + iblock)) + rawPassword.Length + 1] = (byte)(i >> 8);
+ data[(i * (rawPassword.Length + iblock)) + rawPassword.Length + 2] = (byte)(i >> 16);
+
+ if (i % (noOfRounds / sizeInitV) == 0)
+ {
+ digest = msgDigest.ComputeHash(data, 0, (i + 1) * (rawPassword.Length + iblock));
+ aesIV[i / (noOfRounds / sizeInitV)] = digest[19];
+ }
+ }
+
+ digest = msgDigest.ComputeHash(data);
+ //slow code ends
+
+ var aesKey = new byte[sizeInitV];
+ for (var i = 0; i < 4; i++)
+ {
+ for (var j = 0; j < 4; j++)
+ {
+ aesKey[(i * 4) + j] = (byte)(
+ (
+ ((digest[i * 4] * 0x1000000) & 0xff000000)
+ | (uint)((digest[(i * 4) + 1] * 0x10000) & 0xff0000)
+ | (uint)((digest[(i * 4) + 2] * 0x100) & 0xff00)
+ | (uint)(digest[(i * 4) + 3] & 0xff)
+ ) >> (j * 8)
+ );
+ }
+ }
+
+ return new AesParams()
+ {
+ Iv = aesIV,
+ Key = aesKey,
+ DecodedSize = decodedSize,
+ };
+ }
+
+ private static AesParams? GetRar5AesParams(object rar5CryptoInfo, string password, long decodedSize)
+ {
+ const int derivedKeyLength = 0x10;
+ const int sizePswCheck = 0x08;
+ const int sha256DigestSize = 32;
+ var lg2Count = (int)rar5CryptoInfo.GetReflectionField("LG2Count")!;
+ var salt = (byte[])rar5CryptoInfo.GetReflectionField("Salt")!;
+ var usePswCheck = (bool)rar5CryptoInfo.GetReflectionField("UsePswCheck")!;
+ var pswCheck = (byte[])rar5CryptoInfo.GetReflectionField("PswCheck")!;
+ var initIv = (byte[])rar5CryptoInfo.GetReflectionField("InitV")!;
+
+ var iterations = (1 << lg2Count); // Adjust the number of iterations as needed
+
+ var salt_rar5 = salt.Concat(new byte[] { 0, 0, 0, 1 });
+ var derivedKey = GenerateRarPbkdf2Key(
+ password,
+ salt_rar5.ToArray(),
+ iterations,
+ derivedKeyLength
+ );
+
+ var derivedPswCheck = new byte[sizePswCheck];
+ for (var i = 0; i < sha256DigestSize; i++)
+ {
+ derivedPswCheck[i % sizePswCheck] ^= derivedKey[2][i];
+ }
+
+ if (usePswCheck && !pswCheck.SequenceEqual(derivedPswCheck))
+ {
+ throw new CryptographicException("The password did not match.");
+ }
+
+ return new AesParams()
+ {
+ Iv = initIv,
+ Key = derivedKey[0],
+ DecodedSize = decodedSize,
+ };
+ }
+
+
+ private static List<byte[]> GenerateRarPbkdf2Key(
+ string password,
+ byte[] salt,
+ int iterations,
+ int keyLength
+ )
+ {
+ using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(password));
+ var block = hmac.ComputeHash(salt);
+ var finalHash = (byte[])block.Clone();
+
+ var loop = new int[] { iterations, 17, 17 };
+ var res = new List<byte[]> { };
+
+ for (var x = 0; x < 3; x++)
+ {
+ for (var i = 1; i < loop[x]; i++)
+ {
+ block = hmac.ComputeHash(block);
+ for (var j = 0; j < finalHash.Length; j++)
+ {
+ finalHash[j] ^= block[j];
+ }
+ }
+
+ res.Add((byte[])finalHash.Clone());
+ }
+
+ return res;
+ }
}
\ No newline at end of file
diff --git a/backend/Queue/FileAggregators/RarAggregator.cs b/backend/Queue/FileAggregators/RarAggregator.cs
index 48bf1c97..7aeff8d3 100644
--- a/backend/Queue/FileAggregators/RarAggregator.cs
+++ b/backend/Queue/FileAggregators/RarAggregator.cs
@@ -14,37 +14,32 @@ public class RarAggregator(DavDatabaseClient dbClient, DavItem mountDirectory, b
public override void UpdateDatabase(List<BaseProcessor.Result> processorResults)
{
- var orderedArchiveParts = processorResults
+ var fileSegments = processorResults
.OfType<RarProcessor.Result>()
+ .SelectMany(x => x.StoredFileSegments)
.OrderBy(x => x.PartNumber)
.ToList();
- ProcessArchive(orderedArchiveParts);
+ ProcessArchive(fileSegments);
}
- private void ProcessArchive(List<RarProcessor.Result> archiveParts)
+ private void ProcessArchive(List<RarProcessor.StoredFileSegment> fileSegments)
{
- var archiveFiles = new Dictionary<string, List<DavMultipartFile.FilePart>>();
- foreach (var archivePart in archiveParts)
+ var archiveFiles = new Dictionary<string, List<RarProcessor.StoredFileSegment>>();
+ foreach (var fileSegment in fileSegments)
{
- foreach (var fileSegment in archivePart.StoredFileSegments)
- {
- if (!archiveFiles.ContainsKey(fileSegment.PathWithinArchive))
- archiveFiles.Add(fileSegment.PathWithinArchive, []);
+ if (!archiveFiles.ContainsKey(fileSegment.PathWithinArchive))
+ archiveFiles.Add(fileSegment.PathWithinArchive, []);
- archiveFiles[fileSegment.PathWithinArchive].Add(new DavMultipartFile.FilePart()
- {
- SegmentIds = archivePart.NzbFile.GetSegmentIds(),
- SegmentIdByteRange = LongRange.FromStartAndSize(0, archivePart.PartSize),
- FilePartByteRange = LongRange.FromStartAndSize(fileSegment.Offset, fileSegment.ByteCount),
- });
- }
+ archiveFiles[fileSegment.PathWithinArchive].Add(fileSegment);
}
foreach (var archiveFile in archiveFiles)
{
var pathWithinArchive = archiveFile.Key;
var fileParts = archiveFile.Value.ToArray();
+ var aesParams = fileParts.Select(x => x.AesParams).FirstOrDefault(x => x != null);
+ var fileSize = aesParams?.DecodedSize ?? fileParts.Sum(x => x.ByteRangeWithinPart.Count);
var parentDirectory = EnsureExtractPath(pathWithinArchive);
var name = Path.GetFileName(pathWithinArchive);
@@ -57,9 +52,9 @@ public class RarAggregator(DavDatabaseClient dbClient, DavItem mountDirectory, b
id: Guid.NewGuid(),
parent: parentDirectory,
name: name,
- fileSize: fileParts.Sum(x => x.FilePartByteRange.Count),
+ fileSize: fileSize,
type: DavItem.ItemType.MultipartFile,
- releaseDate: archiveParts.First().ReleaseDate,
+ releaseDate: fileParts.First().ReleaseDate,
lastHealthCheck: checkedFullHealth ? DateTimeOffset.UtcNow : null
);
@@ -68,7 +63,13 @@ public class RarAggregator(DavDatabaseClient dbClient, DavItem mountDirectory, b
Id = davItem.Id,
Metadata = new DavMultipartFile.Meta()
{
- FileParts = fileParts,
+ AesParams = aesParams,
+ FileParts = fileParts.Select(x => new DavMultipartFile.FilePart()
+ {
+ SegmentIds = x.NzbFile.GetSegmentIds(),
+ SegmentIdByteRange = LongRange.FromStartAndSize(0, x.PartSize),
+ FilePartByteRange = x.ByteRangeWithinPart
+ }).ToArray(),
}
};
diff --git a/backend/Queue/FileProcessors/RarProcessor.cs b/backend/Queue/FileProcessors/RarProcessor.cs
index 7a409670..40f51837 100644
--- a/backend/Queue/FileProcessors/RarProcessor.cs
+++ b/backend/Queue/FileProcessors/RarProcessor.cs
@@ -1,11 +1,10 @@
using System.Text.RegularExpressions;
using NzbWebDAV.Clients.Usenet;
-using NzbWebDAV.Exceptions;
using NzbWebDAV.Extensions;
+using NzbWebDAV.Models;
using NzbWebDAV.Queue.DeobfuscationSteps._3.GetFileInfos;
using NzbWebDAV.Streams;
using NzbWebDAV.Utils;
-using SharpCompress.Common;
using SharpCompress.Common.Rar.Headers;
using Usenet.Nzb;
@@ -14,28 +13,34 @@ namespace NzbWebDAV.Queue.FileProcessors;
public class RarProcessor(
GetFileInfosStep.FileInfo fileInfo,
UsenetStreamingClient usenet,
+ string? password,
CancellationToken ct
) : BaseProcessor
{
public override async Task<BaseProcessor.Result?> ProcessAsync()
{
await using var stream = await GetNzbFileStream();
- var headers = await RarUtil.GetRarHeadersAsync(stream, ct);
+ var headers = await RarUtil.GetRarHeadersAsync(stream, password, ct);
+ var archiveName = GetArchiveName();
+ var partNumber = GetPartNumber(headers);
return new Result()
{
- NzbFile = fileInfo.NzbFile,
- PartSize = stream.Length,
- ArchiveName = GetArchiveName(),
- PartNumber = GetPartNumber(headers),
StoredFileSegments = headers
.Where(x => x.HeaderType == HeaderType.File)
.Select(x => new StoredFileSegment()
{
+ NzbFile = fileInfo.NzbFile,
+ PartSize = stream.Length,
+ ArchiveName = archiveName,
+ PartNumber = partNumber,
PathWithinArchive = x.GetFileName(),
- Offset = x.GetDataStartPosition(),
- ByteCount = x.GetAdditionalDataSize(),
+ ByteRangeWithinPart = LongRange.FromStartAndSize(
+ x.GetDataStartPosition(),
+ x.GetAdditionalDataSize()
+ ),
+ AesParams = x.GetAesParams(password),
+ ReleaseDate = fileInfo.ReleaseDate,
}).ToArray(),
- ReleaseDate = fileInfo.ReleaseDate,
};
}
@@ -91,19 +96,20 @@ public class RarProcessor(
}
public new class Result : BaseProcessor.Result
+ {
+ public required StoredFileSegment[] StoredFileSegments { get; init; }
+ }
+
+ public class StoredFileSegment
{
public required NzbFile NzbFile { get; init; }
public required long PartSize { get; init; }
public required string ArchiveName { get; init; }
public required int PartNumber { get; init; }
- public required StoredFileSegment[] StoredFileSegments { get; init; }
public required DateTimeOffset ReleaseDate { get; init; }
- }
- public class StoredFileSegment
- {
public required string PathWithinArchive { get; init; }
- public required long Offset { get; init; }
- public required long ByteCount { get; init; }
+ public required LongRange ByteRangeWithinPart { get; init; }
+ public required AesParams? AesParams { get; init; }
}
}
\ No newline at end of file
diff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.cs
index 224fd544..6972d48e 100644
--- a/backend/Queue/QueueItemProcessor.cs
+++ b/backend/Queue/QueueItemProcessor.cs
@@ -189,7 +189,7 @@ public class QueueItemProcessor(
else if (group.Key == "rar")
foreach (var fileInfo in group)
- yield return new RarProcessor(fileInfo, usenetClient, ct);
+ yield return new RarProcessor(fileInfo, usenetClient, archivePassword, ct);
else if (group.Key == "multipart-mkv")
yield return new MultipartMkvProcessor(group.ToList(), usenetClient, ct);
diff --git a/backend/Utils/RarUtil.cs b/backend/Utils/RarUtil.cs
index 763e9a9a..51e8a86a 100644
--- a/backend/Utils/RarUtil.cs
+++ b/backend/Utils/RarUtil.cs
@@ -1,9 +1,6 @@
using NzbWebDAV.Exceptions;
using NzbWebDAV.Extensions;
-using NzbWebDAV.Models;
using NzbWebDAV.Streams;
-using SharpCompress.Archives.SevenZip;
-using SharpCompress.Common;
using SharpCompress.Common.Rar.Headers;
using SharpCompress.IO;
using SharpCompress.Readers;
@@ -12,57 +9,60 @@ namespace NzbWebDAV.Utils;
public static class RarUtil
{
- public static async Task<List<IRarHeader>> GetRarHeadersAsync(Stream stream, CancellationToken ct)
+ public static async Task<List<IRarHeader>> GetRarHeadersAsync
+ (
+ Stream stream,
+ string? password,
+ CancellationToken ct
+ )
{
await using var cancellableStream = new CancellableStream(stream, ct);
- return await Task.Run(() => GetRarHeaders(cancellableStream), ct);
+ return await Task.Run(() => GetRarHeaders(cancellableStream, password), ct);
}
- private static List<IRarHeader> GetRarHeaders(Stream stream)
+ private static List<IRarHeader> GetRarHeaders(Stream stream, string? password)
{
- try
+ var readerOptions = new ReaderOptions() { Password = password };
+ var headerFactory = new RarHeaderFactory(StreamingMode.Seekable, readerOptions);
+ var headers = new List<IRarHeader>();
+ foreach (var header in headerFactory.ReadHeaders(stream))
{
- var headerFactory = new RarHeaderFactory(StreamingMode.Seekable, new ReaderOptions());
- var headers = new List<IRarHeader>();
- foreach (var header in headerFactory.ReadHeaders(stream))
+ // add archive headers
+ if (header.HeaderType is HeaderType.Archive or HeaderType.EndArchive)
{
- // add archive headers
- if (header.HeaderType is HeaderType.Archive or HeaderType.EndArchive)
- {
- headers.Add(header);
- continue;
- }
+ headers.Add(header);
+ continue;
+ }
- // skip comments
- if (header.HeaderType == HeaderType.Service)
+ // skip comments
+ if (header.HeaderType == HeaderType.Service)
+ {
+ if (header.GetFileName() == "CMT")
{
- if (header.GetFileName() == "CMT")
- {
- var buffer = new byte[header.GetCompressedSize()];
- _ = stream.Read(buffer, 0, buffer.Length);
- }
-
- continue;
+ var buffer = new byte[header.GetCompressedSize()];
+ _ = stream.Read(buffer, 0, buffer.Length);
}
- // we only care about file headers
- if (header.HeaderType != HeaderType.File || header.IsDirectory() ||
- header.GetFileName() == "QO") continue;
+ continue;
+ }
- // we only support stored files (compression method m0).
- if (header.GetCompressionMethod() != 0)
- throw new UnsupportedRarCompressionMethodException(
- "Only rar files with compression method m0 are supported.");
+ // we only care about file headers
+ if (header.HeaderType != HeaderType.File || header.IsDirectory() ||
+ header.GetFileName() == "QO") continue;
- // add the headers
- headers.Add(header);
- }
+ // we only support stored files (compression method m0).
+ if (header.GetCompressionMethod() != 0)
+ throw new UnsupportedRarCompressionMethodException(
+ "Only rar files with compression method m0 are supported.");
- return headers;
- }
- catch (CryptographicException ex)
- {
- throw new PasswordProtectedRarException("Password-protected RARs are not supported");
+ // TODO: support solid archives
+ if (header.GetIsEncrypted() && header.GetIsSolid())
+ throw new Exception("Password-protected rar archives cannot be solid.");
+
+ // add the headers
+ headers.Add(header);
}
+
+ return headers;
}
}
\ No newline at end of file
diff --git a/backend/Utils/SevenZipUtil.cs b/backend/Utils/SevenZipUtil.cs
index e95e7f9c..5afc8138 100644
--- a/backend/Utils/SevenZipUtil.cs
+++ b/backend/Utils/SevenZipUtil.cs
@@ -1,5 +1,4 @@
-using NzbWebDAV.Exceptions;
-using NzbWebDAV.Extensions;
+using NzbWebDAV.Extensions;
using NzbWebDAV.Models;
using NzbWebDAV.Streams;
using SharpCompress.Archives.SevenZip;
diff --git a/backend/WebDav/DatabaseStoreRarFile.cs b/backend/WebDav/DatabaseStoreRarFile.cs
index 972a9005..25452998 100644
--- a/backend/WebDav/DatabaseStoreRarFile.cs
+++ b/backend/WebDav/DatabaseStoreRarFile.cs
@@ -4,7 +4,6 @@ using NzbWebDAV.Clients.Usenet;
using NzbWebDAV.Config;
using NzbWebDAV.Database;
using NzbWebDAV.Database.Models;
-using NzbWebDAV.Models;
using NzbWebDAV.Streams;
using NzbWebDAV.WebDav.Base;