2dj;%+-0sdb-
zMB#ya=Um^Wr@$uDce${HCSMikJe2}A_KyIcb6=JZf~~HUO)uy*b4$vs{T&KmNP)bH
z9E=mc3!cwZQaFg?ugIfAf7$Ae#WREuJImv-%+O2Et7Qa8nBW1yqZ1FG=f4EO+{sjl
zIdt1QODXXeOj^Nk$-&PAfEQ`|DA%sj4s4Mf(*3XA7Jl7(PqLMfa<~`~O0heNDckn8
znd62FPwr{H6n9BE#yL}~uq6kd_nee0NP5cwUiN4hHxc%t8cVZ`rLZ#oke@pR;DM>=
zIy$Es;1?FDu(-x{l-wf~M4#Jq3EFNG+27;
zZNcUPR@Kn?_S$=%n9VtICAeYL#uUMyp{dlDf^}ZP*v;z`Hho%5AZm&Qj!OBn+cA*Z
zm=?^rNcR0qJfHNrNTvy?O2G!WO}O<^{=!cxbolCx93lZ`=0{3H7oU2*^dHXxk&jy_
zXo-7D&~DJ#fMy*pF&p~!JvbgYl_q&BuopI(SUR|8W-yvc7_XE
zQ--}%yMuD7C%^<5t~|2Onx27^VrEdYmFEGFN39wi+N)GNBI+buD|A0^#W9cn`e4&I
z_=1iYO1I$YcFV!4dL&Sjhu7%Shi+7H5wW0doX$~s!qo(@=!XR%S}*QC`z1w+rOL+4
zLg}%uDEpt&7Gyj3F`Ap(qbRYSi6&TR1jZD9D1EiA%{I~JO`*KZ)RGG_E6ik(bjs;3CDJ}amfszrgiA5vRY
zRrSUshz*SZ6Z-x?2Q!Wm^p?1k35XC7qR@*)Y0!(Tjoo#0Kck~7h1Se%g*F+xq%&`@
zGJMF6?-I=0?u+%i@AJi*+#NX*Qw5GmS0d(nR7KSuU`I3cdg
z4g-daI-Lx>dp8T#1z5MUXwro|ST%pRwKfnU@9yww1$B1$p9JLFsvjTPtGO+lK3lAs
zdB*sd_4=KqE5X#k7jgaF#i!0L0Vo}`u2Q2$4DWGjiX(>cn854*LAG*YLfU5tlx2eO
BeaQd-
literal 0
HcmV?d00001
diff --git a/LibXboxOne.Tests/Resources/RsaKeys/RSA_4096_RSAPRIVATEBLOB.bin b/LibXboxOne.Tests/Resources/RsaKeys/RSA_4096_RSAPRIVATEBLOB.bin
new file mode 100644
index 0000000000000000000000000000000000000000..0a3e462d28d556e1f9a51066675a45c1b4fd3973
GIT binary patch
literal 1051
zcmV+$1myctQ$aES5C8xJ000000ssI20RR910RR9200Ezws^Ksep=v!J#;J*J3GeBg
zD4q|L7x_e#?-az#I>JZn2+wC)0B&om-piT@szU-Y8OV0`~
zDRhmR70#_&bjtLDiFZz#1fMu!bIHfnbyz#C5q}
zaGC$;U<;0_UUl*9F$gR|1q42BPk>K7;&H_LW^g-*c5<;GXk4c^#QAMGXyH`q4%g*p
z$#rW1TI(~jj+0JZ5-cQhp<>%88U~K*RTx$UxKVo=5@F$5H|ddUU$C(N#k$R}uaXce
zo9#HG2?MJCE8~x{t9&XWJ=J8V|Icl1FdJhu&FhXYU#}@R?0P3N+6J;Q{XbkYLa#Ub
zh?o@h7vw*#n3`#QC4$7Azb75~C$$kWU*G8*_($Hr;ErmbhRmWl
z*CIH%@=tPZ%d~*(wQll>|DR0e_ROqV)h{Wbq!zc@L=B>pDppAC*CbrnaMYvzAp4C2
zx@=<_{fijC;VnIdKGK1TmXVXoKl9IP5-2xLp6DNo0*>g0<7g7&7n@cwa3k;RRmK-t
zUu?2H(W$3Q-5q+Y9#PTc#<6J?HZkHe9#DafMf+A=-A*=X
zE1G2H;a-_ukzh)sca{?BsvkJ}bRo$Vu>scvjefNTBy0*&*#>sNV?r%l;ZtKeo
zV^7oX=}jneJw>hDj;h@l0N2$yLbd3I$>N<2FsS6h*osdRcD5IfI^|J(t8$(@q?10i
Vjnk1A$b9X&qkZ2EIJVSr5exLV`?CN5
literal 0
HcmV?d00001
diff --git a/LibXboxOne.Tests/Resources/RsaKeys/RSA_4096_RSAPUBLICBLOB.bin b/LibXboxOne.Tests/Resources/RsaKeys/RSA_4096_RSAPUBLICBLOB.bin
new file mode 100644
index 0000000000000000000000000000000000000000..d9ed738b53a3e3f9a897bb5e0fafb96a6631dd47
GIT binary patch
literal 539
zcmV+$0_6QtQ$aBR5C8xJ000000ssI2000000000100Ezws^Ksep=v!J#;J*J3GeBg
zD4q|L7x_e#?-az#I>JZn2+wC)0B&om-piT@szU-Y8OV0`~
zDRhmR70#_&bjtLDiFZz#1fMu!bIHfnbyz#C5q}
daGC$;U<;0_UUl*9F$gR|1q42BPk>K7;&Fk%{{;X5
literal 0
HcmV?d00001
diff --git a/LibXboxOne.Tests/Resources/RsaKeys/RSA_512_CAPIPRIVATEBLOB.bin b/LibXboxOne.Tests/Resources/RsaKeys/RSA_512_CAPIPRIVATEBLOB.bin
new file mode 100644
index 0000000000000000000000000000000000000000..234b2b92c97177077a7b33fff4ed1d0570ab3adb
GIT binary patch
literal 308
zcmV-40n7de0ssI2qyPX?Q$aES0ssI30096IO3s3Ax&Boz7}@|#_5M>B8nn=#7vdN$M>JL5Ux=Qoj1wb)hEwsR5alWS}bdUWHSPxpx1>ZtJmaN35m11_NT}7%t_F8aDV)CXG2TtlqU*%
n?siQ+u&qIN?QU^J-zbrNV&!bdUbbf_btzRJ@tJz``1g$fI-ekZ
literal 0
HcmV?d00001
diff --git a/LibXboxOne.Tests/Resources/RsaKeys/RSA_512_RSAFULLPRIVATEBLOB.bin b/LibXboxOne.Tests/Resources/RsaKeys/RSA_512_RSAFULLPRIVATEBLOB.bin
new file mode 100644
index 0000000000000000000000000000000000000000..b69c79c6c9b213d55222ecb745fdcf96db06459b
GIT binary patch
literal 315
zcmV-B0mS}NQ$aHT0ssI50000$0000W0000W0000100FW0$HkRQ#Csx&B4~%{#s+s5
zz7$$bAs4%?Er7PblZxHEAmo&Vgn+r_<3~U%V4RFzXOBe%7ZN&dtgEEZN)hY-U_TDO12)03RlIup9k{w|Ud*_v@G;yH
z?{InrmWRMut#kps9z1z4`yyUj*Q|;R60`vEm|6duzXngZJEbt(d_(!Ghgi6_Hq|;C
zjc!n3Rjp&7fTLa?YMD0bjk0mnRSZB31X1`2r4yD7Lwp{n+^4e+m6dS&s~#WR;l#sr)9Pb=dm8Qneq6LE^wo
NBC}uJV*W(zi6K;Qku(4R
literal 0
HcmV?d00001
diff --git a/LibXboxOne.Tests/Resources/RsaKeys/RSA_512_RSAPRIVATEBLOB.bin b/LibXboxOne.Tests/Resources/RsaKeys/RSA_512_RSAPRIVATEBLOB.bin
new file mode 100644
index 0000000000000000000000000000000000000000..ff411d6746ae17548b4e9eb1e3a005753e2c42d4
GIT binary patch
literal 155
zcmWFvb~IvOVqjoqU|?_nVg)E>WMJI*{rJ(TK1ZsRx|A~7UmjyC7uzQi<*O*Zd#!H6
zwgZ#9?(R`|GNrYpVdvAw?he`sb9&;^`(0VZg{<<{tX^`#OYjZjc1DNt|u@d2~!->mkSwMt|8LGA>5zWvN*2RDW8sroIuV^>bxnH{S>7~T GetBytesAsync(string fileName, ResourceType type = ResourceType.Misc)
+ {
+ var file = $"{ResourcePath}/{type}/{fileName}";
+ if (File.Exists(file))
+ {
+ using (FileStream stream = File.OpenRead(file))
+ {
+ byte[] result = new byte[stream.Length];
+ await stream.ReadAsync(result, 0, (int)stream.Length);
+ return result;
+ }
+ }
+ throw new FileNotFoundException(file);
+ }
+ public static string GetString(string fileName, ResourceType type = ResourceType.Misc)
+ {
+ var file = $"{ResourcePath}/{type}/{fileName}";
+ if (File.Exists(file))
+ {
+ return System.Text.Encoding.UTF8.GetString(
+ File.ReadAllBytes(file)
+ );
+ }
+ throw new FileNotFoundException(file);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne.Tests/XbfsTests.cs b/LibXboxOne.Tests/XbfsTests.cs
new file mode 100644
index 0000000..08a489f
--- /dev/null
+++ b/LibXboxOne.Tests/XbfsTests.cs
@@ -0,0 +1,56 @@
+using Xunit;
+using LibXboxOne.Nand;
+
+namespace LibXboxOne.Tests
+{
+ public class XbfsTests
+ {
+ public static XbfsHeader GetHeader()
+ {
+ var data = ResourcesProvider.GetBytes("xbfs_header.bin", ResourceType.DataBlobs);
+ return Shared.BytesToStruct(data);
+ }
+
+ [Fact]
+ public void TestXbfsHeaderParsing()
+ {
+ XbfsHeader header = GetHeader();
+
+ Assert.True(header.IsValid);
+ Assert.True(header.IsHashValid);
+ Assert.Equal(1, header.FormatVersion);
+ Assert.Equal(1, header.SequenceNumber);
+ Assert.Equal(9, header.LayoutVersion);
+ Assert.Equal((ulong)0, header.Reserved08);
+ Assert.Equal((ulong)0, header.Reserved10);
+ Assert.Equal((ulong)0, header.Reserved18);
+ }
+
+ [Fact]
+
+ public void TestXbfsHeaderRehash()
+ {
+ XbfsHeader header = GetHeader();
+ header.Files[0].BlockCount = 123;
+
+ Assert.False(header.IsHashValid);
+ header.Rehash();
+ Assert.True(header.IsHashValid);
+ }
+
+ [Fact]
+ public void TestXbfsOutOfBounds()
+ {
+ XbfsHeader header = GetHeader();
+
+ // Write a file entry past the known filenames array
+ header.Files[XbfsFile.XbfsFilenames.Length + 2] = new XbfsEntry(){
+ LBA=0, BlockCount=1, Reserved=0
+ };
+
+ // Call to ToString will print filenames and should
+ // encouter a file that we don't know the filename of
+ header.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne.Tests/XvdFileTests.cs b/LibXboxOne.Tests/XvdFileTests.cs
new file mode 100644
index 0000000..db0a226
--- /dev/null
+++ b/LibXboxOne.Tests/XvdFileTests.cs
@@ -0,0 +1,282 @@
+using System.IO;
+using Xunit;
+
+namespace LibXboxOne.Tests
+{
+ public class XvdFileTests
+ {
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Dev_Signed_ValidHash_Test()
+ {
+ using (var file = new XvdFile(@"F:\XBone\XVDs\TestXVDs\xvd1"))
+ {
+ Assert.True(file.Load());
+ /*
+ if(XvdFile.SignKeyLoaded)
+ Assert.True(file.Header.IsSignedWithRedKey);
+ */
+ Assert.True(file.IsEncrypted);
+ Assert.True(file.IsDataIntegrityEnabled);
+ Assert.True(file.HashTreeValid);
+ Assert.True(file.DataHashTreeValid);
+ }
+ }
+
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Dev_Signed_InvalidHashTree_Test()
+ {
+ using (var file = new XvdFile(@"F:\XBone\XVDs\TestXVDs\xvd1_brokehash"))
+ {
+ Assert.True(file.Load());
+ /*
+ if (XvdFile.SignKeyLoaded)
+ Assert.True(file.Header.IsSignedWithRedKey);
+ */
+ Assert.True(file.IsEncrypted);
+ Assert.True(file.IsDataIntegrityEnabled);
+ Assert.False(file.HashTreeValid);
+ }
+ }
+
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Dev_Signed_InvalidDataHashTree_Test()
+ {
+ using (var file = new XvdFile(@"F:\XBone\XVDs\TestXVDs\xvd1_brokedatahash"))
+ {
+ Assert.True(file.Load());
+ /*
+ if (XvdFile.SignKeyLoaded)
+ Assert.True(file.Header.IsSignedWithRedKey);
+ */
+ Assert.True(file.IsEncrypted);
+ Assert.True(file.IsDataIntegrityEnabled);
+ Assert.True(file.HashTreeValid);
+ Assert.False(file.DataHashTreeValid);
+ }
+ }
+
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Dev_Signed_XVC_Decrypt_Test()
+ {
+ const string dest = @"F:\XBone\XVDs\TestXVDs\xvd1_decrypted_temp";
+ const string fileToCompare = @"F:\XBone\XVDs\TestXVDs\xvd1_decrypted";
+ if (File.Exists(dest))
+ File.Delete(dest);
+
+ File.Copy(@"F:\XBone\XVDs\TestXVDs\xvd1", dest);
+ using (var file = new XvdFile(dest))
+ {
+ Assert.True(file.Load());
+ /*
+ Assert.True(file.Header.IsSignedWithRedKey);
+ */
+ Assert.True(file.IsEncrypted);
+ Assert.True(file.IsDataIntegrityEnabled);
+ Assert.True(file.HashTreeValid);
+ Assert.True(file.DataHashTreeValid);
+ Assert.True(file.Decrypt());
+ Assert.False(file.IsEncrypted);
+ ulong[] invalid = file.VerifyDataHashTree();
+ Assert.True(invalid.Length == 0);
+ Assert.True(file.VerifyHashTree());
+
+ byte[] ntfsString = file.ReadBytes(0x87003, 4);
+ byte[] expectedString = { 0x4E, 0x54, 0x46, 0x53 };
+ Assert.True(ntfsString.IsEqualTo(expectedString));
+ }
+
+ byte[] generatedHash;
+ using (FileStream stream = File.OpenRead(dest))
+ {
+ generatedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ File.Delete(dest);
+
+ byte[] expectedHash;
+ using (FileStream stream = File.OpenRead(fileToCompare))
+ {
+ expectedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ Assert.True(generatedHash.IsEqualTo(expectedHash));
+ }
+
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Dev_Signed_XVC_Encrypt_Test()
+ {
+ const string dest = @"F:\XBone\XVDs\TestXVDs\xvd1_encrypted_temp";
+ const string fileToCompare = @"F:\XBone\XVDs\TestXVDs\xvd1";
+ if (File.Exists(dest))
+ File.Delete(dest);
+
+ File.Copy(@"F:\XBone\XVDs\TestXVDs\xvd1_decrypted", dest);
+ using (var file = new XvdFile(dest))
+ {
+ Assert.True(file.Load());
+ Assert.False(file.IsEncrypted);
+ Assert.True(file.IsDataIntegrityEnabled);
+ Assert.True(file.HashTreeValid);
+ Assert.True(file.DataHashTreeValid);
+ // Assert.True(file.Encrypt());
+ Assert.True(file.IsEncrypted);
+
+ ulong[] invalid = file.VerifyDataHashTree();
+ Assert.True(invalid.Length == 0);
+ Assert.True(file.VerifyHashTree());
+ }
+
+ byte[] generatedHash;
+ using (FileStream stream = File.OpenRead(dest))
+ {
+ generatedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ File.Delete(dest);
+
+ byte[] expectedHash;
+ using (FileStream stream = File.OpenRead(fileToCompare))
+ {
+ expectedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ Assert.True(generatedHash.IsEqualTo(expectedHash));
+ }
+
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Unsigned_XVD_Decrypt_Test()
+ {
+ const string dest = @"F:\XBone\XVDs\TestXVDs\xvd2_decrypted_temp";
+ const string fileToCompare = @"F:\XBone\XVDs\TestXVDs\xvd2_decrypted";
+ if (File.Exists(dest))
+ File.Delete(dest);
+
+ File.Copy(@"F:\XBone\XVDs\TestXVDs\xvd2", dest);
+ using (var file = new XvdFile(dest))
+ {
+ Assert.True(file.Load());
+ /*
+ Assert.True(file.Header.IsSignedWithRedKey);
+ */
+ Assert.True(file.IsEncrypted);
+ Assert.True(file.IsDataIntegrityEnabled);
+ Assert.True(file.HashTreeValid);
+ Assert.True(file.DataHashTreeValid);
+ Assert.True(file.Decrypt());
+ Assert.False(file.IsEncrypted);
+
+ ulong[] invalid = file.VerifyDataHashTree();
+ Assert.True(invalid.Length == 0);
+ Assert.True(file.VerifyHashTree());
+
+ byte[] ntfsString = file.ReadBytes(0x75003, 4);
+ byte[] expectedString = { 0x4E, 0x54, 0x46, 0x53 };
+ Assert.True(ntfsString.IsEqualTo(expectedString));
+ }
+
+ byte[] generatedHash;
+ using (FileStream stream = File.OpenRead(dest))
+ {
+ generatedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ File.Delete(dest);
+
+ byte[] expectedHash;
+ using (FileStream stream = File.OpenRead(fileToCompare))
+ {
+ expectedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ Assert.True(generatedHash.IsEqualTo(expectedHash));
+ }
+
+ [Fact(Skip="Relies on xvd data blob")]
+ public void Unsigned_XVD_Encrypt_Test()
+ {
+ const string dest = @"F:\XBone\XVDs\TestXVDs\xvd2_encrypted_temp";
+ const string fileToCompare = @"F:\XBone\XVDs\TestXVDs\xvd2";
+ if (File.Exists(dest))
+ File.Delete(dest);
+
+ File.Copy(@"F:\XBone\XVDs\TestXVDs\xvd2_decrypted_orig_mod", dest); // modded with CIK used in xvd2
+ using (var file = new XvdFile(dest))
+ {
+ Assert.True(file.Load());
+ /*
+ Assert.False(file.Header.IsSignedWithRedKey);
+ */
+ Assert.False(file.IsEncrypted);
+ Assert.False(file.IsDataIntegrityEnabled);
+ // Assert.True(file.Encrypt());
+ Assert.True(file.IsEncrypted);
+
+ // copy values from file being compared so the hashes match
+ file.Header.PDUID = new byte[] {0xEA, 0xC8, 0xE2, 0x82, 0x2F, 0x58, 0x32, 0x4F, 0x92, 0x29, 0xE1, 0xAB, 0x6E, 0x8F, 0x91, 0x63};
+ using (FileStream stream = File.OpenRead(fileToCompare))
+ {
+ stream.Position = 0;
+ stream.Read(file.Header.Signature, 0, 0x200);
+ }
+
+ Assert.True(file.AddHashTree());
+
+ ulong[] invalid = file.VerifyDataHashTree();
+ Assert.True(invalid.Length == 0);
+ Assert.True(file.VerifyHashTree());
+ }
+
+ byte[] generatedHash;
+ using (FileStream stream = File.OpenRead(dest))
+ {
+ generatedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ File.Delete(dest);
+
+ byte[] expectedHash;
+ using (FileStream stream = File.OpenRead(fileToCompare))
+ {
+ expectedHash = HashUtils.ComputeSha256(stream);
+ }
+
+ Assert.True(generatedHash.IsEqualTo(expectedHash));
+ }
+
+ /*
+ [Fact(Skip="Relies on xvd data blob")]
+ public void XvdSign_Key_Extract()
+ {
+ var sdkVersions = new List { "XDK_11785" };
+ var versionsTextFile = @"F:\Xbone\Research\xdk_versions.txt";
+ if (File.Exists(versionsTextFile))
+ {
+ string[] sdkVersionArr = File.ReadAllLines(versionsTextFile);
+ foreach (string ver in sdkVersionArr)
+ if (!sdkVersions.Contains(ver.ToUpper()))
+ sdkVersions.Add(ver.ToUpper());
+ }
+
+ foreach (string ver in sdkVersions)
+ {
+ string path = Path.Combine(@"F:\Xbone\Research\", ver);
+ string binPath = Path.Combine(path, "bin");
+ if (Directory.Exists(binPath))
+ path = binPath;
+ if (!File.Exists(Path.Combine(path, "xvdsign.exe")))
+ continue;
+
+ XvdFile.CikFileLoaded = false;
+ XvdFile.OdkKeyLoaded = false;
+ XvdFile.SignKeyLoaded = false;
+ XvdFile.LoadKeysFromSdk(path);
+ Assert.True(XvdFile.CikFileLoaded && XvdFile.OdkKeyLoaded && XvdFile.SignKeyLoaded);
+ }
+
+ XvdFile.CikFileLoaded = false;
+ XvdFile.OdkKeyLoaded = false;
+ XvdFile.SignKeyLoaded = false;
+ }
+ */
+ }
+}
diff --git a/LibXboxOne.Tests/XvdHashBlockTests.cs b/LibXboxOne.Tests/XvdHashBlockTests.cs
new file mode 100644
index 0000000..1dcadde
--- /dev/null
+++ b/LibXboxOne.Tests/XvdHashBlockTests.cs
@@ -0,0 +1,57 @@
+using Xunit;
+
+namespace LibXboxOne.Tests
+{
+ public class XvdHashBlockTests
+ {
+ [Theory]
+ [InlineData(0x4000, 1, 0x1)]
+ [InlineData(0x5427, 1, 0x1)]
+ [InlineData(0x20001, 1, 0x5)]
+ [InlineData(0x20001, 2, 0x1)]
+ [InlineData(0xA43E3, 1, 0x18)]
+ [InlineData(0xA43E3, 2, 0x1)]
+ [InlineData(0xC2BFF, 1, 0x1C)]
+ [InlineData(0xC2BFF, 2, 0x1)]
+ public void TestNumHashBlockCalculation(ulong size, ulong index, ulong expected)
+ {
+ ulong actual = XvdMath.CalculateNumHashBlocksInLevel(size, index, false);
+
+ Assert.Equal(expected, actual);
+ }
+
+ [Theory]
+ [InlineData((XvdType)0, 0x2, 0x4000, 0xE02, 0x0, 0x10, 0x16)]
+ [InlineData((XvdType)1, 0x3, 0xC001, 0x150A, 0x0, 0x74, 0x22)]
+ [InlineData((XvdType)1, 0x3, 0x20001, 0x3772, 0x0, 0x54, 0x59)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0x5F604, 0x0, 0x0, 0x909)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0x5F604, 0x1, 0x58, 0xE)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0x5BB94, 0x1, 0x0, 0xE)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0x5BB94, 0x2, 0xD, 0x0)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0xAB2, 0x0, 0x12, 0x1F)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0xF20B, 0x0, 0x53, 0x17B)]
+ [InlineData((XvdType)1, 0x3, 0x5F653, 0xF60A, 0x0, 0x56, 0x181)]
+ public void TestCalculateHashBlockNumForBlockNum(XvdType xvdType, ulong hashTreeLevels, ulong xvdDataBlockCount,
+ ulong blockNum, uint index,
+ ulong expectedEntryNum, ulong expectedResult)
+ {
+ ulong result = XvdMath.CalculateHashBlockNumForBlockNum(xvdType, hashTreeLevels, xvdDataBlockCount,
+ blockNum, index, out ulong entryNumInBlock);
+
+ Assert.Equal(expectedEntryNum, entryNumInBlock);
+ Assert.Equal(expectedResult, result);
+ }
+
+ [Theory]
+ [InlineData(0x6401, 0x97)]
+ [InlineData(0x5427, 0x7F)]
+ [InlineData(0x20001, 0x304)]
+ [InlineData(0x5F653, 0x8FB)]
+ public void TestCalculateHashTreeBlockCount(ulong xvdDataBlockCount, ulong expected)
+ {
+ ulong result = XvdMath.PagesToBlocks(xvdDataBlockCount);
+
+ Assert.Equal(expected, result);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/AppDirs.cs b/LibXboxOne/AppDirs.cs
new file mode 100644
index 0000000..28571b2
--- /dev/null
+++ b/LibXboxOne/AppDirs.cs
@@ -0,0 +1,38 @@
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+
+namespace LibXboxOne
+{
+ public static class AppDirs
+ {
+ internal static string GetApplicationBaseDirectory()
+ {
+ return Environment.GetFolderPath(
+ RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
+ /*
+ * Windows
+ * Result: C:\Users\\AppData\Local
+ */
+ ? Environment.SpecialFolder.LocalApplicationData
+ /*
+ * Mac OS X
+ * Result: /Users//.config
+ *
+ * Linux
+ * Result: /home//.config
+ */
+ : Environment.SpecialFolder.ApplicationData);
+ }
+
+ public static string GetApplicationConfigDirectory(string appName)
+ {
+ /*
+ * Windows: C:\Users\\AppData\Local\
+ * Linux: /home//.config/
+ * Mac OS X: /Users//.config/
+ */
+ return Path.Combine(GetApplicationBaseDirectory(), appName);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Certificates/BootCapability.cs b/LibXboxOne/Certificates/BootCapability.cs
new file mode 100644
index 0000000..2da3745
--- /dev/null
+++ b/LibXboxOne/Certificates/BootCapability.cs
@@ -0,0 +1,103 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace LibXboxOne.Certificates
+{
+ public enum BootCapability : ushort
+ {
+ CERT_CAP_NONE = 0x0000,
+ CERT_CAP_DELETED = 0xFFFF,
+
+ CERT_CAP_SRA_DEVKIT = 0x2001,
+ CERT_CAP_SRA_DEVKIT_DEBUG = 0x2002,
+ CERT_CAP_SRA_FILE_IO = 0x2003,
+ CERT_CAP_SRA_STREAM = 0x2004,
+ CERT_CAP_SRA_PUSH_DEPLOY = 0x2005,
+ CERT_CAP_SRA_PULL_DEPLOY = 0x2006,
+ CERT_CAP_SRA_PROFILING = 0x2007,
+ CERT_CAP_SRA_JS_PROFILING = 0x2008,
+ CERT_CAP_RECOVERY = 0x3001,
+ CERT_CAP_VS_CRASH_DUMP = 0x3002,
+ CERT_CAP_CRASH_DUMP = 0x3003,
+ CERT_CAP_REMOTE_MGMT = 0x3004,
+ CERT_CAP_VIEW_TRACING = 0x3005,
+ CERT_CAP_TCR_TOOL = 0x3006,
+ CERT_CAP_XSTUDIO = 0x3007,
+ CERT_CAP_GESTURE_BUILDER = 0x3008,
+ CERT_CAP_SPEECH_LAB = 0x3009,
+ CERT_CAP_SMARTGLASS_STUDIO = 0x300A,
+ CERT_CAP_NETWORK_FIDDLER = 0x300B,
+ CERT_CAP_ERA_DEVKIT = 0x4001,
+ CERT_CAP_HW_BERSINGSEA_DEBUG = 0x4002,
+ CERT_CAP_ERA_DEVKIT_DEBUG = 0x4003,
+ CERT_CAP_ERA_FILE_IO = 0x4004,
+ CERT_CAP_ERA_STREAM = 0x4005,
+ CERT_CAP_ERA_PUSH_DEPLOY = 0x4006,
+ CERT_CAP_ERA_PULL_DEPLOY = 0x4007,
+ CERT_CAP_ERA_EXTRA_MEM = 0x4008,
+ CERT_CAP_ERA_PROFILING = 0x4009,
+ CERT_CAP_MS_DEVKIT = 0x6001,
+ CERT_CAP_HW_CPU_DEBUG = 0x6002,
+ CERT_CAP_HW_FW_DEBUG = 0x6003,
+ CERT_CAP_HW_POWER_DEBUG = 0x6004,
+ CERT_CAP_MEMENC_DISABLED = 0x6005,
+ CERT_CAP_MEMENC_FIXED_KEY = 0x6006,
+ CERT_CAP_MEMENC_KEY_0 = 0x6007,
+ CERT_CAP_CERT_MTE_BOOST = 0x6008,
+ CERT_CAP_CERT_RIO_BOOST = 0x6009,
+ CERT_CAP_CERT_TEST_BOOST = 0x600A,
+ CERT_CAP_UPDATE_TESTER = 0x600B,
+ CERT_CAP_RED_CPU_CODE = 0x600C,
+ CERT_CAP_OS_PREVIEW = 0x600D,
+ CERT_CAP_RETAIL_DEBUGGER = 0x600E,
+ CERT_CAP_OFFLINE = 0x600F,
+ CERT_CAP_IGNORE_UPDATESEQUENCE = 0x6010,
+ CERT_CAP_CERT_QASLT = 0x6011,
+ CERT_CAP_GPU_FENCE_DEBUG = 0x6013,
+ CERT_CAP_HW_EN_MEM_SPEED_RETEST = 0x6014,
+ CERT_CAP_HW_EN_MEM_1GB_RETEST = 0x6015,
+ CERT_CAP_HW_EN_FUSE_READ = 0x6016,
+ CERT_CAP_HW_EN_POST_CODE_SECURE = 0x6017,
+ CERT_CAP_HW_EN_FUSE_OVR_RETEST = 0x6018,
+ CERT_CAP_HW_EN_MEM_UNLIM_RETEST = 0x6019,
+ CERT_CAP_ICT_TESTER = 0x601A,
+ CERT_CAP_LOADXVD_TESTER = 0x601B,
+ CERT_CAP_WIDE_THERMAL_THRESHOLDS = 0x601C,
+ CERT_CAP_MS_TESTLAB = 0x601D,
+ CERT_CAP_ALLOW_DISK_LICENSE = 0x601E,
+ CERT_CAP_ALLOW_SYSTEM_DOWNGRADE = 0x601F,
+ CERT_CAP_WIFI_TESTER = 0x6020,
+ CERT_CAP_GREEN_FIDDLER = 0x6021,
+ CERT_CAP_KIOSK_MODE = 0x6022,
+ CERT_CAP_FULL_MEDIA_AUTH = 0x6023,
+ CERT_CAP_HW_DEVTEST = 0x6024,
+ CERT_CAP_ALLOW_FUSE_FA = 0x6025,
+ CERT_CAP_ALLOW_SERIAL_CERT_UPLOAD = 0x6026,
+ CERT_CAP_ALLOW_INSTRUMENTATION = 0x6027,
+ CERT_CAP_WIFI_TESTER_DFS = 0x6028,
+ CERT_CAP_HOSTOS_HW_TEST = 0x6029,
+ CERT_CAP_HOSTOS_ODD_TEST = 0x602A,
+ CERT_CAP_REDUCE_MODE_TESTER = 0x7002,
+ CERT_CAP_SP_DEVKIT = 0x8001,
+ CERT_CAP_HW_SP_DEBUG = 0x8002,
+ CERT_CAP_SCP_DEBUG = 0x8003,
+ CERT_CAP_HW_SDF = 0x8004,
+ CERT_CAP_HW_ALL_DEBUG = 0x8005,
+ CERT_CAP_HW_AEB_DEBUG = 0x8006,
+ CERT_CAP_HW_BTG = 0x8007,
+ CERT_CAP_SP_TESTER = 0x8008,
+ CERT_CAP_SP_DEBUG_BUILD = 0x8009,
+ CERT_CAP_NO_FUSE_BLOW = 0x800A,
+ CERT_CAP_HW_DIS_N_CALIB_RETEST = 0x800B,
+ CERT_CAP_HW_DIS_CRIT_FUSE_CHK_RETEST = 0x800C,
+ CERT_CAP_GREEN_SRA_DEBUG = 0x800D,
+ CERT_CAP_GREEN_ERA_DEBUG = 0x800E,
+ CERT_CAP_HW_DIS_RNG_CHK_SECURE = 0x800F,
+ CERT_CAP_HW_EN_FUSE_OVRD_SECURE = 0x8010,
+ CERT_CAP_GREEN_HOST_DEBUG = 0x8011,
+ CERT_CAP_GREEN_ALLOW_DISK_LICENSES = 0x8012,
+ CERT_CAP_VIRT_CAP_DEVKIT_ANY_EQUIV = 0xF001,
+ CERT_CAP_VIRT_CAP_DEVKIT_INTERNAL_EQUIV = 0xF002,
+ CERT_CAP_VIRT_CAP_SP_DEVKIT_EQUIV = 0xF003
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Certificates/BootCapabilityCert.cs b/LibXboxOne/Certificates/BootCapabilityCert.cs
new file mode 100644
index 0000000..db57abb
--- /dev/null
+++ b/LibXboxOne/Certificates/BootCapabilityCert.cs
@@ -0,0 +1,113 @@
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace LibXboxOne.Certificates
+{
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct BootCapabilityCert
+ {
+ public ushort StructId;
+ public ushort Size;
+ public ushort ProtocolVersion;
+ public ushort IssuerKeyId;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
+ public byte[] IssueDate;
+
+ public DateTime IssueDateTime
+ {
+ get
+ {
+ var filetime = BitConverter.ToInt64(IssueDate, 0);
+ return DateTime.FromFileTime(filetime);
+ }
+ }
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ public byte[] SocId;
+
+ public ushort GenerationId;
+ public byte AllowedStates;
+ public byte LastCapability;
+ public uint Flags;
+ public byte ExpireCentury;
+ public byte ExpireYear;
+ public byte ExpireMonth;
+ public byte ExpireDayOfMonth;
+ public byte ExpireHour;
+ public byte ExpireMinute;
+ public byte ExpireSecond;
+ public byte MinimumSpVersion;
+ public ulong Minimum2blVersion;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ public byte[] Nonce;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x38)]
+ public byte[] Reserved;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x100)]
+ public BootCapability[] Capabilities;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x180)]
+ public byte[] RsaSignature;
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ string fmt = formatted ? " " : "";
+
+ var b = new StringBuilder();
+ b.AppendLineSpace("BootCapabilityCert:");
+
+ if (StructId == 0x00)
+ {
+ b.AppendLineSpace(fmt + "! No or invalid certificate (StructId: 0)\n");
+ return b.ToString();
+ }
+
+ b.AppendLineSpace(fmt + $"StructId: 0x{StructId:X}");
+ b.AppendLineSpace(fmt + $"Size: {Size} (0x{Size:X})");
+ b.AppendLineSpace(fmt + $"IssuerKeyId: {IssuerKeyId} (0x{IssuerKeyId:X})");
+ b.AppendLineSpace(fmt + $"IssueDate: {IssueDateTime}");
+ b.AppendLineSpace(fmt + $"SocId: {Environment.NewLine}{fmt}{SocId.ToHexString()}");
+ b.AppendLineSpace(fmt + $"GenerationId: {GenerationId} (0x{GenerationId:X})");
+ b.AppendLineSpace(fmt + $"AllowedStates: {AllowedStates} (0x{AllowedStates:X})");
+ b.AppendLineSpace(fmt + $"LastCapability: {LastCapability} (0x{LastCapability:X})");
+ b.AppendLineSpace(fmt + $"Flags: {Flags} (0x{Flags:X})");
+
+ var expiry = $"{ExpireCentury}{ExpireYear:00}-{ExpireMonth:00}-{ExpireDayOfMonth:00} {ExpireHour:00}:{ExpireMinute:00}:{ExpireSecond:00}";
+ if (ExpireCentury == 255)
+ expiry = "never!";
+ b.AppendLineSpace(fmt + $"Expiration date: {expiry}");
+
+ b.AppendLineSpace(fmt + $"MinimumSpVersion: {MinimumSpVersion} (0x{MinimumSpVersion:X})");
+ b.AppendLineSpace(fmt + $"Minimum2blVersion: {Minimum2blVersion} (0x{Minimum2blVersion:X})");
+
+ b.AppendLineSpace(fmt + $"Nonce: {Environment.NewLine}{fmt}{Nonce.ToHexString()}");
+ b.AppendLineSpace(fmt + $"Reserved: {Environment.NewLine}{fmt}{Reserved.ToHexString()}");
+ b.AppendLineSpace(fmt + $"RsaSignature: {Environment.NewLine}{fmt}{RsaSignature.ToHexString()}");
+
+ b.AppendLineSpace(fmt + "Boot Capabilities:");
+ for(int i = 0; i < Capabilities.Length; i++)
+ {
+ BootCapability cap = Capabilities[i];
+
+ if (cap == BootCapability.CERT_CAP_NONE
+ || cap == BootCapability.CERT_CAP_DELETED)
+ {
+ continue;
+ }
+ b.AppendLine($"{fmt}-{cap}");
+ }
+
+ b.AppendLine();
+ return b.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Certificates/PspConsoleCert.cs b/LibXboxOne/Certificates/PspConsoleCert.cs
new file mode 100644
index 0000000..d53d1db
--- /dev/null
+++ b/LibXboxOne/Certificates/PspConsoleCert.cs
@@ -0,0 +1,120 @@
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace LibXboxOne.Certificates
+{
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct PspConsoleCert
+ {
+ public UInt16 StructID; // 0x4343 (ASCII: CC = ConsoleCert?)
+
+ public UInt16 Size;
+
+ public UInt16 IssuerKeyId; // Key Version
+
+ public UInt16 ProtocolVer; // unknown
+
+ public UInt32 IssueDate; // POSIX time
+
+ public DateTime IssueDateTime
+ {
+ get
+ {
+ return DateTime.UnixEpoch.AddSeconds(IssueDate);
+ }
+ }
+
+ public UInt32 PspRevisionId; // PSP Version
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ public byte[] SocId;
+
+ public UInt16 GenerationId;
+
+ public byte ConsoleRegion;
+
+ public byte ReservedByte; // 0
+
+ public UInt32 ReservedDword; // 0
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x8)]
+ public byte[] VendorId; // size of 8
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x100)]
+ public byte[] AttestationPubKey; // Public key that is used by the Xbox One ChalResp system
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x100)]
+ public byte[] ReservedPublicKey;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0xC)]
+ public char[] ConsoleSerialNumber;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x8)]
+ public byte[] ConsoleSku;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ public byte[] ConsoleSettingsHash; // Hash of factory settings (SHA-256)
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0xC)]
+ public char[] ConsolePartNumber;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ public byte[] SomeData; // unknown
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x180)]
+ public byte[] RsaSignature;
+
+ public string ConsoleSerialNumberString
+ {
+ get
+ {
+ return new string(ConsoleSerialNumber);
+ }
+ }
+
+ public string ConsolePartNumberString
+ {
+ get
+ {
+ return new string(ConsolePartNumber);
+ }
+ }
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ string fmt = formatted ? " " : "";
+
+ var b = new StringBuilder();
+ b.AppendLineSpace("PspConsoleCert:");
+ b.AppendLineSpace(fmt + $"StructId: 0x{StructID:X}");
+ b.AppendLineSpace(fmt + $"Size: {Size} (0x{Size:X})");
+ b.AppendLineSpace(fmt + $"IssuerKeyId: {IssuerKeyId} (0x{IssuerKeyId:X})");
+ b.AppendLineSpace(fmt + $"ProtocolVer: {ProtocolVer} (0x{ProtocolVer:X})");
+ b.AppendLineSpace(fmt + $"IssueDateTime: {IssueDateTime} ({IssueDate})");
+ b.AppendLineSpace(fmt + $"PspRevisionId: {PspRevisionId} (0x{PspRevisionId:X})");
+ b.AppendLineSpace(fmt + $"SocId: {SocId.ToHexString()}");
+ b.AppendLineSpace(fmt + $"GenerationId: {GenerationId} (0x{GenerationId:X})");
+ b.AppendLineSpace(fmt + $"ConsoleRegion: {ConsoleRegion} (0x{ConsoleRegion:X})");
+ b.AppendLineSpace(fmt + $"ReservedByte: {ReservedByte} (0x{ReservedByte:X})");
+ b.AppendLineSpace(fmt + $"ReservedDword: {ReservedDword} (0x{ReservedDword:X})");
+ b.AppendLineSpace(fmt + $"VendorId: {VendorId.ToHexString()}");
+ b.AppendLineSpace(fmt + $"AttestationPubKey: {Environment.NewLine}{fmt}{AttestationPubKey.ToHexString()}");
+ b.AppendLineSpace(fmt + $"ReservedPublicKey: {Environment.NewLine}{fmt}{ReservedPublicKey.ToHexString()}");
+ b.AppendLineSpace(fmt + $"ConsoleSerialNumberString: {ConsoleSerialNumberString}");
+ b.AppendLineSpace(fmt + $"ConsoleSku: {ConsoleSku.ToHexString()}");
+ b.AppendLineSpace(fmt + $"ConsoleSettingsHash: {ConsoleSettingsHash.ToHexString(String.Empty)}");
+ b.AppendLineSpace(fmt + $"ConsolePartNumberString: {ConsolePartNumberString}");
+ b.AppendLineSpace(fmt + $"SomeData: {SomeData.ToHexString()}");
+ b.AppendLineSpace(fmt + $"RsaSignature: {Environment.NewLine}{fmt}{RsaSignature.ToHexString()}");
+
+ b.AppendLine();
+ return b.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Common.cs b/LibXboxOne/Common.cs
new file mode 100644
index 0000000..854e600
--- /dev/null
+++ b/LibXboxOne/Common.cs
@@ -0,0 +1,13 @@
+using System;
+using System.Reflection;
+
+namespace LibXboxOne
+{
+ public static class Common
+ {
+ public static string AppVersion =>
+ Assembly.GetExecutingAssembly()
+ .GetCustomAttribute()
+ .InformationalVersion;
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Crypto/AesXts.cs b/LibXboxOne/Crypto/AesXts.cs
new file mode 100644
index 0000000..67350b9
--- /dev/null
+++ b/LibXboxOne/Crypto/AesXts.cs
@@ -0,0 +1,106 @@
+using System;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace LibXboxOne
+{
+ class AesXtsTransform : IDisposable
+ {
+ public int BlockSize;
+ private readonly byte[] _tweakBytes;
+ private readonly ICryptoTransform _tweakEncryptor;
+ private readonly ICryptoTransform _dataTransform;
+ private readonly SymmetricAlgorithm _symmetricAlgorithm;
+
+ public AesXtsTransform(byte[] tweakBytes, byte[] dataAesKey, byte[] tweakAesKey, bool encrypt)
+ {
+ if (tweakBytes == null) throw new InvalidDataException("Tweak bytes not provided");
+ if (dataAesKey == null) throw new InvalidDataException("Data AES key not provided");
+ if (tweakAesKey == null) throw new InvalidDataException("Tweak AES key not provided");
+ if (tweakBytes.Length != 16) throw new InvalidDataException("Tweak bytes not 16 bytes");
+ if (dataAesKey.Length != 16) throw new InvalidDataException("Data AES key not 16 bytes");
+ if (tweakAesKey.Length != 16) throw new InvalidDataException("Tweak AES not 16 bytes");
+
+ _tweakBytes = tweakBytes;
+
+ _symmetricAlgorithm = Aes.Create();
+ _symmetricAlgorithm.Padding = PaddingMode.None;
+ _symmetricAlgorithm.Mode = CipherMode.ECB;
+
+ byte[] nullIv = new byte[16];
+ _tweakEncryptor = _symmetricAlgorithm.CreateEncryptor(tweakAesKey, nullIv);
+ _dataTransform = encrypt ? _symmetricAlgorithm.CreateEncryptor(dataAesKey, nullIv) :
+ _symmetricAlgorithm.CreateDecryptor(dataAesKey, nullIv);
+
+ BlockSize = _symmetricAlgorithm.BlockSize / 8;
+ }
+
+ internal static byte[] MultiplyTweak(byte[] tweak)
+ {
+ byte dl = 0;
+ var newTweak = new byte[0x10];
+
+ for (int i = 0; i < 0x10; i++)
+ {
+ byte cl = tweak[i];
+ byte al = cl;
+ al = (byte)(al + al);
+ al = (byte)(al | dl);
+ dl = cl;
+ newTweak[i] = al;
+ dl = (byte)(dl >> 7);
+ }
+ if (dl != 0)
+ newTweak[0] = (byte)(newTweak[0] ^ 0x87);
+ return newTweak;
+ }
+
+ public int TransformDataUnit(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset, uint dataUnit)
+ {
+ byte[] encryptedTweak = new byte[0x10];
+ byte[] tweak = _tweakBytes;
+
+ // Update tweak with data unit number
+ Array.Copy(BitConverter.GetBytes(dataUnit), tweak, 4);
+
+ // Encrypt tweak
+ _tweakEncryptor.TransformBlock(tweak, 0, tweak.Length, encryptedTweak, 0);
+
+ byte[] encryptedTweakOrig = new byte[0x10];
+ Array.Copy(encryptedTweak, encryptedTweakOrig, 0x10);
+
+ int blocks = inputCount / BlockSize;
+
+ // Apply first part of tweak (input-tweak) to input buffer all at once
+ for (int i = 0; i < blocks; i++)
+ {
+ for (int y = 0; y < BlockSize; y++)
+ outputBuffer[outputOffset + (i * BlockSize) + y] = (byte)(inputBuffer[inputOffset + (i * BlockSize) + y] ^ encryptedTweak[y % encryptedTweak.Length]);
+
+ encryptedTweak = MultiplyTweak(encryptedTweak);
+ }
+
+ // AES transform the data...
+ var transformedBytes = _dataTransform.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset);
+
+ // Reset tweak back to original encrypted tweak and then apply output-tweak
+ Array.Copy(encryptedTweakOrig, encryptedTweak, 0x10);
+ for (int i = 0; i < blocks; i++)
+ {
+ for (int y = 0; y < BlockSize; y++)
+ outputBuffer[outputOffset + (i * BlockSize) + y] = (byte)(outputBuffer[outputOffset + (i * BlockSize) + y] ^ encryptedTweak[y % encryptedTweak.Length]);
+
+ encryptedTweak = MultiplyTweak(encryptedTweak);
+ }
+
+ return transformedBytes;
+ }
+
+ public void Dispose()
+ {
+ _tweakEncryptor.Dispose();
+ _dataTransform.Dispose();
+ _symmetricAlgorithm.Dispose();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Crypto/BCryptRsaImport.cs b/LibXboxOne/Crypto/BCryptRsaImport.cs
new file mode 100644
index 0000000..0bfbda9
--- /dev/null
+++ b/LibXboxOne/Crypto/BCryptRsaImport.cs
@@ -0,0 +1,68 @@
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+
+namespace LibXboxOne
+{
+ public enum BCRYPT_RSABLOB_MAGIC : uint
+ {
+ // The key is an RSA public key.
+ RSAPUBLIC = 0x31415352,
+ // The key is an RSA private key.
+ RSAPRIVATE = 0x32415352,
+ // The key is a full RSA private key.
+ RSAFULLPRIVATE = 0x33415352
+ };
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BCRYPT_RSAKEY_BLOB
+ {
+ public BCRYPT_RSABLOB_MAGIC Magic;
+ public uint BitLength;
+ public uint cbPublicExp;
+ public uint cbModulus;
+ public uint cbPrime1;
+ public uint cbPrime2;
+ };
+
+ public sealed class BCryptRsaImport
+ {
+ public static RSAParameters BlobToParameters(byte[] blobData, out int bitLength, out bool isPrivate)
+ {
+ var parameters = new RSAParameters();
+ var reader = new BinaryReader(new MemoryStream(blobData));
+
+ BCRYPT_RSAKEY_BLOB header = reader.ReadStruct();
+ if (header.Magic == BCRYPT_RSABLOB_MAGIC.RSAPUBLIC)
+ isPrivate = false;
+ else if (header.Magic == BCRYPT_RSABLOB_MAGIC.RSAPRIVATE ||
+ header.Magic == BCRYPT_RSABLOB_MAGIC.RSAFULLPRIVATE)
+ isPrivate = true;
+ else
+ throw new InvalidDataException("Unexpected RSA keyblob");
+
+ bitLength = (int)header.BitLength;
+
+ parameters.Exponent = reader.ReadBytes((int)header.cbPublicExp);
+ parameters.Modulus = reader.ReadBytes((int)header.cbModulus);
+
+ if (header.Magic == BCRYPT_RSABLOB_MAGIC.RSAPUBLIC)
+ return parameters;
+
+ // RSAPRIVATEBLOB
+ parameters.P = reader.ReadBytes((int)header.cbPrime1);
+ parameters.Q = reader.ReadBytes((int)header.cbPrime2);
+
+ if (header.Magic == BCRYPT_RSABLOB_MAGIC.RSAPRIVATE)
+ return parameters;
+
+ // RSAFULLPRIVATEBLOB
+ parameters.DP = reader.ReadBytes((int)header.cbPrime1);
+ parameters.DQ = reader.ReadBytes((int)header.cbPrime2);
+ parameters.InverseQ = reader.ReadBytes((int)header.cbPrime1);
+ parameters.D = reader.ReadBytes((int)header.cbModulus);
+
+ return parameters;
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Crypto/HashUtils.cs b/LibXboxOne/Crypto/HashUtils.cs
new file mode 100644
index 0000000..d4d79ed
--- /dev/null
+++ b/LibXboxOne/Crypto/HashUtils.cs
@@ -0,0 +1,69 @@
+using System.IO;
+using System.Security.Cryptography;
+using Org.BouncyCastle.Crypto;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Security;
+
+namespace LibXboxOne
+{
+ public static class HashUtils
+ {
+ public static byte[] ComputeSha256(byte[] data)
+ {
+ return ComputeSha256(data, 0, data.Length);
+ }
+
+ public static byte[] ComputeSha256(Stream stream)
+ {
+ return SHA256.Create().ComputeHash(stream);
+ }
+
+ public static byte[] ComputeSha256(byte[] data, int offset, int length)
+ {
+ return SHA256.Create().ComputeHash(data, offset, length);
+ }
+
+ public static byte[] ComputeSha1(byte[] data)
+ {
+ return ComputeSha1(data, 0, data.Length);
+ }
+
+ public static byte[] ComputeSha1(Stream stream)
+ {
+ return SHA1.Create().ComputeHash(stream);
+ }
+
+ public static byte[] ComputeSha1(byte[] data, int offset, int length)
+ {
+ return SHA1.Create().ComputeHash(data, offset, length);
+ }
+
+ public static bool SignData(byte[] key, string keyType, byte[] data, out byte[] signature) // keyType = RSAFULLPRIVATEBLOB, RSAPRIVATEBLOB, RSAPUBLICBLOB
+ {
+ if (keyType != "RSAFULLPRIVATEBLOB")
+ throw new CryptographicException("Only RSAFULLPRIVATEBLOB can be used for signing");
+
+ var rsaParams = BCryptRsaImport.BlobToParameters(key, out int bitLength, out bool isPrivate);
+ var rsaKey = DotNetUtilities.GetRsaKeyPair(rsaParams).Private;
+ ISigner s = SignerUtilities.GetSigner("SHA256withRSA/PSS");
+
+ s.Init(true, new ParametersWithRandom(rsaKey));
+ s.BlockUpdate(data, 0, data.Length);
+
+ signature = s.GenerateSignature();
+ return true;
+ }
+
+ public static bool VerifySignature(byte[] key, byte[] signature, byte[] data) // keyType = RSAFULLPRIVATEBLOB, RSAPRIVATEBLOB, RSAPUBLICBLOB
+ {
+ var rsaParams = BCryptRsaImport.BlobToParameters(key, out int bitLength, out bool isPrivate);
+ var rsaKey = DotNetUtilities.GetRsaPublicKey(rsaParams);
+ ISigner s = SignerUtilities.GetSigner("SHA256withRSA/PSS");
+
+ s.Init(false, new ParametersWithRandom(rsaKey));
+ s.BlockUpdate(data, 0, data.Length);
+
+ return s.VerifySignature(signature);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Keys/DurangoKeys.cs b/LibXboxOne/Keys/DurangoKeys.cs
new file mode 100644
index 0000000..70aaea2
--- /dev/null
+++ b/LibXboxOne/Keys/DurangoKeys.cs
@@ -0,0 +1,304 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+
+namespace LibXboxOne.Keys
+{
+ public static class DurangoKeys
+ {
+ public static Guid TestCIK => new Guid("33EC8436-5A0E-4F0D-B1CE-3F29C3955039");
+ public static string RedXvdPrivateKey => "RedXvdPrivateKey";
+
+ static readonly Dictionary SignkeyStorage = new Dictionary(){
+ // Xvd signing keys
+ {"RedXvdPrivateKey", new DurangoKeyEntry(KeyType.XvdSigningKey, sha256Hash: "8E2B60377006D87EE850334C42FC200081386A838C65D96D1EA52032AA9628C5", dataSize: 0x91B)},
+ {"GreenXvdPublicKey", new DurangoKeyEntry(KeyType.XvdSigningKey, sha256Hash: "618C5FB1193040AF8BC1C0199B850B4B5C42E43CE388129180284E4EF0B18082", dataSize: 0x21B)},
+ {"GreenGamesPublicKey", new DurangoKeyEntry(KeyType.XvdSigningKey, sha256Hash: "183F0AE05431E4AD91554E88946967C872997227DBE6C85116F5FD2FD2D1229E", dataSize: 0x21B)},
+ };
+
+ static readonly Dictionary OdkStorage = new Dictionary(){
+ {OdkIndex.RedOdk, new DurangoKeyEntry(KeyType.Odk, sha256Hash: "CA37132DFB4B811506AE4DC45F45970FED8FE5E58C1BACB259F1B96145B0EBC6", dataSize: 0x20)}
+ };
+
+ static readonly Dictionary CikStorage = new Dictionary()
+ {
+ {new Guid("33EC8436-5A0E-4F0D-B1CE-3F29C3955039"), new DurangoKeyEntry(KeyType.Cik, sha256Hash: "6786C11B788ED5CCE3C7695425CB82970347180650893D1B5613B2EFB33F9F4E", dataSize: 0x20)}, // TestCIK
+ {new Guid("F0522B7C-7FC1-D806-43E3-68A5DAAB06DA"), new DurangoKeyEntry(KeyType.Cik, sha256Hash: "B767CE5F83224375E663A1E01044EA05E8022C033D96BED952475D87F0566642", dataSize: 0x20)},
+ };
+
+ static DurangoKeys()
+ {
+ }
+
+ public static KeyValuePair[] GetAllXvdSigningKeys()
+ {
+ return SignkeyStorage.ToArray();
+ }
+
+ public static KeyValuePair[] GetAllODK()
+ {
+ return OdkStorage.ToArray();
+ }
+
+ public static KeyValuePair[] GetAllCIK()
+ {
+ return CikStorage.ToArray();
+ }
+
+ public static bool KnowsSignKeySHA256(byte[] sha256Hash, out string keyName)
+ {
+ foreach (var kvp in SignkeyStorage)
+ {
+ if (!kvp.Value.SHA256Hash.IsEqualTo(sha256Hash))
+ continue;
+
+ keyName = kvp.Key;
+ return true;
+ }
+ keyName = "";
+ return false;
+ }
+
+ public static bool KnowsOdkSHA256(byte[] sha256Hash, out OdkIndex keyId)
+ {
+ foreach (var kvp in OdkStorage)
+ {
+ if (!kvp.Value.SHA256Hash.IsEqualTo(sha256Hash))
+ continue;
+
+ keyId = kvp.Key;
+ return true;
+ }
+ keyId = OdkIndex.Invalid;
+ return false;
+ }
+
+ public static bool KnowsCikSHA256(byte[] sha256Hash, out Guid keyGuid)
+ {
+ foreach (var kvp in CikStorage)
+ {
+ if (!kvp.Value.SHA256Hash.IsEqualTo(sha256Hash))
+ continue;
+
+ keyGuid = kvp.Key;
+ return true;
+ }
+ keyGuid = Guid.Empty;
+ return false;
+ }
+
+ public static bool GetOdkIndexFromString(string name, out OdkIndex odkIndex)
+ {
+ // First, try to convert to know Enum values
+ var success = Enum.TryParse(name, true, out odkIndex);
+ if (success)
+ return true;
+
+ odkIndex = OdkIndex.Invalid;
+ success = UInt32.TryParse(name, out uint odkUint);
+ if (success)
+ // Odk Id is valid uint but we don't know its Enum name yet
+ odkIndex = (OdkIndex)odkUint;
+
+ return success;
+ }
+
+ public static int LoadCikKeys(byte[] keyData, out Guid[] loadedKeys)
+ {
+ int foundCount = 0;
+ if (keyData.Length < 0x30 || keyData.Length % 0x30 != 0)
+ throw new Exception("Misaligned CIK, expecting array of 0x30 bytes: 0x10 bytes: GUID, 0x20 bytes: Key");
+
+ int cikKeyCount = keyData.Length / 0x30;
+ loadedKeys = new Guid[cikKeyCount];
+ using (BinaryReader br = new BinaryReader(new MemoryStream(keyData)))
+ {
+ for (int keyIndex = 0; keyIndex < cikKeyCount; keyIndex++)
+ {
+ var guid = new Guid(br.ReadBytes(0x10));
+ var cikKeyData = br.ReadBytes(0x20);
+ var sha256Hash = HashUtils.ComputeSha256(cikKeyData);
+ bool hashMatches = KnowsCikSHA256(sha256Hash, out Guid verifyGuid);
+ var hashString = sha256Hash.ToHexString("");
+
+ if (hashMatches && verifyGuid != guid)
+ {
+ Console.WriteLine($"CIK {guid} with hash {hashString} is known as {verifyGuid}");
+ continue;
+ }
+
+ if (hashMatches && CikStorage[guid].HasKeyData)
+ {
+ // Duplicate key, already loaded
+ Console.WriteLine($"CIK {guid} is already loaded");
+ continue;
+ }
+
+ CikStorage[guid] = new DurangoKeyEntry(KeyType.Cik, cikKeyData);
+ foundCount++;
+ }
+ }
+ return foundCount;
+ }
+
+ public static bool LoadOdkKey(OdkIndex keyId, byte[] keyData, out bool isNewKey)
+ {
+ isNewKey = false;
+ byte[] sha256Hash = HashUtils.ComputeSha256(keyData);
+ DurangoKeyEntry existingKey = GetOdkById(keyId);
+
+ if (existingKey != null)
+ {
+ bool hashMatches = KnowsOdkSHA256(sha256Hash, out OdkIndex verifyKeyId);
+ if (hashMatches && verifyKeyId != keyId)
+ {
+ var hashString = sha256Hash.ToHexString("");
+ Console.WriteLine($"ODK {keyId} with hash {hashString} is known as ODK {verifyKeyId}");
+ return false;
+ }
+
+ if (hashMatches && OdkStorage[keyId].HasKeyData)
+ {
+ // Duplicate key, already loaded
+ Console.WriteLine($"ODK {keyId} is already loaded");
+ return false;
+ }
+
+ if (!hashMatches)
+ {
+ Console.WriteLine($"ODK {keyId} does not match expected hash");
+ return false;
+ }
+
+ OdkStorage[keyId].SetKey(keyData);
+ return true;
+ }
+
+ isNewKey = true;
+ OdkStorage[keyId] = new DurangoKeyEntry(KeyType.Odk, keyData);
+ return true;
+ }
+
+ public static bool LoadSignKey(string desiredKeyName, byte[] keyData, out bool isNewKey, out string keyName)
+ {
+ isNewKey = false;
+ byte[] sha256Hash = HashUtils.ComputeSha256(keyData);
+
+ bool hashMatches = KnowsSignKeySHA256(sha256Hash, out keyName);
+ if (hashMatches && SignkeyStorage[keyName].HasKeyData)
+ {
+ // Duplicate key, already loaded
+ Console.WriteLine($"SignKey {keyName} is already loaded");
+ return false;
+ }
+
+ if (hashMatches)
+ {
+ SignkeyStorage[keyName].SetKey(keyData);
+ return true;
+ }
+
+ // New key, using user-set keyname
+ isNewKey = true;
+ SignkeyStorage[desiredKeyName] = new DurangoKeyEntry(KeyType.Odk, keyData);
+ return true;
+ }
+
+ public static bool LoadKey(KeyType keyType, string keyFilePath)
+ {
+ if (keyFilePath == String.Empty)
+ return false;
+
+ bool success;
+ var isNewKey = false;
+ var keyName = String.Empty;
+ var filename = Path.GetFileNameWithoutExtension(keyFilePath);
+ var keyBytes = File.ReadAllBytes(keyFilePath);
+
+ switch(keyType)
+ {
+ case KeyType.XvdSigningKey:
+ success = LoadSignKey(filename, keyBytes, out isNewKey, out keyName);
+ break;
+ case KeyType.Odk:
+ success = GetOdkIndexFromString(filename, out OdkIndex odkIndex);
+ if (!success)
+ {
+ Console.WriteLine($"Could not get OdkIndex from filename: {filename}");
+ break;
+ }
+ success = LoadOdkKey(odkIndex, keyBytes, out isNewKey);
+ break;
+ case KeyType.Cik:
+ var keyCount = LoadCikKeys(keyBytes, out Guid[] loadedCiks);
+ success = keyCount > 0;
+ break;
+ default:
+ throw new InvalidOperationException("Invalid KeyType supplied");
+ }
+
+ return success;
+ }
+
+ public static int LoadKeysRecursive(string basePath)
+ {
+ int foundCount = 0;
+ foreach (KeyType keyType in Enum.GetValues(typeof(KeyType)))
+ {
+ var keyDirectory = Path.Combine(basePath, keyType.ToString());
+ if (!Directory.Exists(keyDirectory))
+ {
+ Console.WriteLine($"Key directory \"{keyDirectory}\" was not found!");
+ continue;
+ }
+
+ var keyFiles = Directory.GetFiles(keyDirectory);
+ foreach (var keyFilePath in keyFiles)
+ {
+ if (LoadKey(keyType, keyFilePath))
+ {
+ Console.WriteLine($"Loaded key {keyType} from {keyFilePath}");
+ foundCount++;
+ }
+ else
+ Console.WriteLine($"Unable to load key from \"{keyFilePath}\"");
+ }
+ }
+ return foundCount;
+ }
+
+ public static DurangoKeyEntry GetSignkeyByName(string keyName)
+ {
+ return SignkeyStorage.ContainsKey(keyName) ? SignkeyStorage[keyName] : null;
+ }
+
+ public static DurangoKeyEntry GetCikByGuid(Guid keyId)
+ {
+ return CikStorage.ContainsKey(keyId) ? CikStorage[keyId] : null;
+ }
+
+ public static DurangoKeyEntry GetOdkById(OdkIndex keyId)
+ {
+ return OdkStorage.ContainsKey(keyId) ? OdkStorage[keyId] : null;
+ }
+
+ public static bool IsSignkeyLoaded(string keyName)
+ {
+ var key = GetSignkeyByName(keyName);
+ return key != null && key.HasKeyData;
+ }
+
+ public static bool IsCikLoaded(Guid keyId)
+ {
+ var key = GetCikByGuid(keyId);
+ return key != null && key.HasKeyData;
+ }
+
+ public static bool IsOdkLoaded(OdkIndex keyId)
+ {
+ var key = GetOdkById(keyId);
+ return key != null && key.HasKeyData;
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Keys/KeyEntry.cs b/LibXboxOne/Keys/KeyEntry.cs
new file mode 100644
index 0000000..09887f3
--- /dev/null
+++ b/LibXboxOne/Keys/KeyEntry.cs
@@ -0,0 +1,57 @@
+using System;
+
+namespace LibXboxOne.Keys
+{
+ public interface IKeyEntry
+ {
+ bool HasKeyData { get; }
+
+ int DataSize { get; }
+ byte[] SHA256Hash { get; }
+ byte[] KeyData { get; }
+ KeyType KeyType { get; }
+
+ void SetKey(byte[] keyData);
+ }
+
+ public class DurangoKeyEntry : IKeyEntry
+ {
+ public bool HasKeyData => KeyData != null && KeyData.Length == DataSize;
+ public byte[] SHA256Hash { get; }
+ public int DataSize { get; }
+ public byte[] KeyData { get; private set; }
+ public KeyType KeyType { get; }
+
+ public DurangoKeyEntry(KeyType keyType, string sha256Hash, int dataSize)
+ {
+ KeyType = keyType;
+ SHA256Hash = sha256Hash.ToBytes();
+ DataSize = dataSize;
+ if (SHA256Hash.Length != 0x20)
+ throw new DataMisalignedException("Invalid length for SHA256Hash");
+ }
+
+ public DurangoKeyEntry(KeyType keyType, byte[] keyData)
+ {
+ KeyType = keyType;
+ SHA256Hash = HashUtils.ComputeSha256(keyData);
+ DataSize = keyData.Length;
+ KeyData = keyData;
+ }
+
+ public void SetKey(byte[] newKeyData)
+ {
+ if (HasKeyData)
+ throw new InvalidOperationException("KeyData is already filled!");
+ if (newKeyData.Length != DataSize)
+ throw new InvalidProgramException($"Unexpected keydata of length: {newKeyData.Length} bytes");
+
+ KeyData = newKeyData;
+ }
+
+ public override string ToString()
+ {
+ return $"Loaded: {HasKeyData} Hash: {SHA256Hash.ToHexString("")} Size: {DataSize}";
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Keys/KeyType.cs b/LibXboxOne/Keys/KeyType.cs
new file mode 100644
index 0000000..206ddf0
--- /dev/null
+++ b/LibXboxOne/Keys/KeyType.cs
@@ -0,0 +1,9 @@
+namespace LibXboxOne.Keys
+{
+ public enum KeyType
+ {
+ XvdSigningKey,
+ Odk, // Offline Distribution Key, AES256 (32 bytes) key
+ Cik // Content Instance Key, Guid (16 bytes) + AES256 (32 bytes) key
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Keys/OdkIndex.cs b/LibXboxOne/Keys/OdkIndex.cs
new file mode 100644
index 0000000..1a942fc
--- /dev/null
+++ b/LibXboxOne/Keys/OdkIndex.cs
@@ -0,0 +1,10 @@
+namespace LibXboxOne.Keys
+{
+ public enum OdkIndex : uint
+ {
+ StandardOdk = 0,
+ GreenOdk = 1,
+ RedOdk = 2,
+ Invalid = 0xFFFFFFFF
+ }
+}
diff --git a/LibXboxOne/LibXboxOne.csproj b/LibXboxOne/LibXboxOne.csproj
new file mode 100644
index 0000000..a3761e0
--- /dev/null
+++ b/LibXboxOne/LibXboxOne.csproj
@@ -0,0 +1,25 @@
+
+
+
+ net7.0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ <_Parameter1>$(MSBuildProjectName).Tests
+
+
+
diff --git a/LibXboxOne/MiscStructs.cs b/LibXboxOne/MiscStructs.cs
new file mode 100644
index 0000000..236225b
--- /dev/null
+++ b/LibXboxOne/MiscStructs.cs
@@ -0,0 +1,78 @@
+using System.Runtime.InteropServices;
+
+namespace LibXboxOne
+{
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct XviHeader
+ {
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x240)]
+ /* 0x0 */
+ public byte[] Unknown1;
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x240 */
+ public byte[] ContentId;
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x250 */
+ public byte[] VDUID;
+ /* 0x260 */
+ public ulong Unknown4;
+ /* 0x268 */
+ public uint Unknown5; // should be 1
+ /* 0x26C */
+ public uint Unknown6; // should be r9d
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct EkbFile
+ { // EKBs also seem to follow the XvcLicenseBlock format, but with 2 byte block ids instead of 4 byte.
+ // note: this is just here for reference as EKB files are written sequentially like this, but EKB files should be loaded with the XvcLicenseBlock class now since it's assumed that's how the xbox reads them
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x4)]
+ /* 0x0 */
+ public byte[] Magic; // EKB1
+
+ /* 0x4 */
+ public uint HeaderLength; // (length of data proceeding this)
+ /* 0x8 */
+ public ushort Unknown1; // 1?
+ /* 0xA */
+ public uint Unknown2; // 2?
+ /* 0xE */
+ public ushort Unknown3; // 5?
+ /* 0x10 */
+ public ushort Unknown4; // 2?
+ /* 0x12 */
+ public uint Unknown5; // 0x20?
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x16 */
+ public byte[] KeyIdHexChars;
+
+ /* 0x36 */
+ public ushort Unknown7; // 3?
+ /* 0x38 */
+ public uint Unknown8; // 2?
+ /* 0x3C */
+ public ushort Unknown9; // 6? lots of calcs for this
+ /* 0x3E */
+ public ushort Unknown10; // 4?
+ /* 0x40 */
+ public uint Unknown11; // 1?
+ /* 0x44 */
+ public byte Unknown12; // 0x31?
+ /* 0x45 */
+ public ushort Unknown13; // 5?
+ /* 0x47 */
+ public uint Unknown14; // 2?
+ /* 0x4B */
+ public ushort Unknown15; // 1?
+ /* 0x4D */
+ public ushort Unknown16; // 7?
+ /* 0x4F */
+ public uint EncryptedDataLength; // EncryptedDataLength
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x180)]
+ /* 0x53 */
+ public byte[] EncryptedData;
+ }
+}
diff --git a/LibXboxOne/NAND/XbfsEntry.cs b/LibXboxOne/NAND/XbfsEntry.cs
new file mode 100644
index 0000000..465a21e
--- /dev/null
+++ b/LibXboxOne/NAND/XbfsEntry.cs
@@ -0,0 +1,37 @@
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace LibXboxOne.Nand
+{
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ public struct XbfsEntry
+ {
+ /* 0x0 */ public uint LBA;
+ /* 0x4 */ public uint BlockCount;
+ /* 0x8 */ public ulong Reserved;
+
+ public long Length => BlockCount * XbfsFile.BlockSize;
+
+ public long Offset(XbfsFlavor flavor) {
+ var offset = LBA * XbfsFile.BlockSize;
+ if (flavor == XbfsFlavor.XboxSeries && offset >= XbfsFile.SeriesOffsetDiff)
+ offset -= XbfsFile.SeriesOffsetDiff;
+ return offset;
+ }
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.Append($"LBA: 0x{LBA:X} (One: 0x{Offset(XbfsFlavor.XboxOne):X} Series: 0x{Offset(XbfsFlavor.XboxSeries):X}), ");
+ b.Append($"Length: 0x{BlockCount:X} (0x{Length:X}), ");
+ b.Append($"Reserved: 0x{Reserved:X}");
+
+ return b.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/NAND/XbfsFile.cs b/LibXboxOne/NAND/XbfsFile.cs
new file mode 100644
index 0000000..b9a0c81
--- /dev/null
+++ b/LibXboxOne/NAND/XbfsFile.cs
@@ -0,0 +1,304 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Linq;
+
+namespace LibXboxOne.Nand
+{
+ public enum XbfsFlavor {
+ XboxOne,
+ XboxSeries,
+ Invalid,
+ }
+
+ public enum NandSize: ulong
+ {
+ EMMC_LOGICAL = 0x13B00_0000,
+ EMMC_PHYSICAL = 0x13C00_0000,
+ NVME_SERIES = 0x4000_0000,
+ }
+
+ public class XbfsFile
+ {
+ public static readonly int SeriesOffsetDiff = 0x6000;
+ public static readonly int BlockSize = 0x1000;
+ public static readonly int[] XbfsOffsetsXboxOne = { 0x1_0000, 0x81_0000, 0x82_0000 };
+ public static readonly int[] XbfsOffsetsXboxSeries = { 0x0, 0x1800_8000 };
+ public static string[] XbfsFilenames =
+ {
+ "1smcbl_a.bin", // 0
+ "header.bin", // 1
+ "devkit.ini", // 2
+ "mtedata.cfg", // 3
+ "certkeys.bin", // 4
+ "smcerr.log", // 5
+ "system.xvd", // 6
+ "$sospf.xvd", // 7, formerly $sosrst.xvd
+ "download.xvd", // 8
+ "smc_s.cfg", // 9
+ "sp_s.cfg", // 10, keyvault? has serial/partnum/osig, handled by psp.sys (/Device/psp)
+ "os_s.cfg", // 11
+ "smc_d.cfg", // 12
+ "sp_d.cfg", // 13
+ "os_d.cfg", // 14
+ "smcfw.bin", // 15
+ "boot.bin", // 16
+ "host.xvd", // 17
+ "settings.xvd", // 18
+ "1smcbl_b.bin", // 19
+ "bootanim.dat", // 20, this entry and ones below it are only in retail 97xx and above?
+ "obsolete.001", // 21, formerly sostmpl.xvd
+ "update.cfg", // 22
+ "obsolete.002", // 23, formerly sosinit.xvd
+ "hwinit.cfg", // 24
+ "qaslt.xvd", // 25
+ "sp_s.bak", // 26, keyvault backup? has serial/partnum/osig
+ "update2.cfg", // 27
+ "obsolete.003", // 28
+ "dump.lng", // 29
+ "os_d_dev.cfg", // 30
+ "os_glob.cfg", // 31
+ "sp_s.alt", // 32
+ "sysauxf.xvd", // 33
+ };
+
+ private readonly IO _io;
+
+ public XbfsFlavor Flavor = XbfsFlavor.Invalid;
+ public int[] HeaderOffsets;
+ public List XbfsHeaders;
+
+ public readonly string FilePath;
+ public long FileSize => _io.Stream.Length;
+
+ public XbfsFile(string path)
+ {
+ FilePath = path;
+ _io = new IO(path);
+ }
+
+ public static XbfsFlavor FlavorFromSize(long size) {
+ return size switch
+ {
+ (long)NandSize.EMMC_LOGICAL or (long)NandSize.EMMC_PHYSICAL => XbfsFlavor.XboxOne,
+ (long)NandSize.NVME_SERIES => XbfsFlavor.XboxSeries,
+ _ => XbfsFlavor.Invalid,
+ };
+ }
+
+ ///
+ /// Get Filename for XBFS filename from index
+ ///
+ /// Index of file
+ ///
+ public static string GetFilenameForIndex(int index)
+ {
+ if (index >= XbfsFilenames.Length) {
+ return null;
+ }
+
+ return XbfsFilenames[index];
+ }
+
+ ///
+ /// Get index for XBFS filename from filename
+ ///
+ /// Filename
+ /// Returns >= 0 if file is found, -1 otherwise
+ public static int GetFileindexForName(string name)
+ {
+ return Array.IndexOf(XbfsFilenames, name);
+ }
+
+ public Certificates.PspConsoleCert? ReadPspConsoleCertificate()
+ {
+ if (XbfsHeaders == null || XbfsHeaders.Count == 0)
+ return null;
+
+ long spDataSize = SeekToFile("sp_s.cfg");
+ if (spDataSize <= 0)
+ return null;
+
+ // SP_S.cfg: (secure processor secured config? there's also a blank sp_d.cfg which is probably secure processor decrypted config)
+ // 0x0 - 0x200 - signature?
+ // 0x200 - 0x5200 - encrypted data? maybe loaded and decrypted into PSP memory?
+ // 0x5200 - 0x5400 - blank
+ // 0x5400 - 0x5800 - console certificate
+ // 0x5800 - 0x6000 - unknown data, looks like it has some hashes and the OSIG of the BR drive
+ // 0x6000 - 0x6600 - encrypted data?
+ // 0x6600 - 0x7400 - blank
+ // 0x7400 - 0x7410 - unknown data, hash maybe
+ // 0x7410 - 0x40000 - blank
+
+ _io.Stream.Position += 0x5400; // seek to start of unencrypted data in sp_s (console certificate)
+ return _io.Reader.ReadStruct();
+ }
+
+ public Certificates.BootCapabilityCert? ReadBootcapCertificate()
+ {
+ if (XbfsHeaders == null || XbfsHeaders.Count == 0)
+ return null;
+
+ long spDataSize = SeekToFile("certkeys.bin");
+ if (spDataSize <= 0)
+ return null;
+
+ return _io.Reader.ReadStruct();
+ }
+
+ public bool Load()
+ {
+ Flavor = FlavorFromSize(FileSize);
+
+ HeaderOffsets = Flavor switch {
+ XbfsFlavor.XboxOne => XbfsOffsetsXboxOne,
+ XbfsFlavor.XboxSeries => XbfsOffsetsXboxSeries,
+ _ => throw new InvalidDataException($"Invalid xbfs filesize: {FileSize:X}"),
+ };
+
+ // read each XBFS header
+ XbfsHeaders = new List();
+ foreach (int offset in HeaderOffsets)
+ {
+ _io.Stream.Position = offset;
+ var header = _io.Reader.ReadStruct();
+ XbfsHeaders.Add(header);
+ }
+ return true;
+ }
+
+ // returns the size of the file if found
+ public long SeekToFile(string fileName)
+ {
+ int idx = GetFileindexForName(fileName);
+ if (idx < 0)
+ return 0;
+
+ long size = 0;
+ for (int i = 0; i < XbfsHeaders.Count; i++)
+ {
+ if (!XbfsHeaders[i].IsValid)
+ continue;
+ if (idx >= XbfsHeaders[i].Files.Length)
+ continue;
+ var ent = XbfsHeaders[i].Files[idx];
+ if (ent.BlockCount == 0)
+ continue;
+ _io.Stream.Position = ent.Offset(Flavor);
+ size = ent.Length;
+ }
+ return size;
+ }
+
+ public string GetXbfsInfo()
+ {
+ var info = new Dictionary();
+ for (int i = 0; i < XbfsHeaders.Count; i++)
+ {
+ if (!XbfsHeaders[i].IsValid)
+ continue;
+ for (int y = 0; y < XbfsHeaders[i].Files.Length; y++)
+ {
+ var ent = XbfsHeaders[i].Files[y];
+ if (ent.Length == 0)
+ continue;
+ long start = ent.Offset(Flavor);
+ long length = ent.Length;
+ long end = start + length;
+ string addInfo = $"{end:X} {i}_{y}";
+ if (info.ContainsKey(start))
+ info[start] += $" {addInfo}";
+ else
+ info.Add(start, addInfo);
+ }
+ }
+ string infoStr = String.Empty;
+ var keys = info.Keys.ToList();
+ keys.Sort();
+ foreach (var key in keys)
+ infoStr += $"{key:X} - {info[key]}{Environment.NewLine}";
+
+ return infoStr;
+ }
+
+ public void ExtractXbfsData(string folderPath)
+ {
+ if (!Directory.Exists(folderPath)) {
+ Console.WriteLine($"Creating output folder for xbfs extraction '{folderPath}'");
+ Directory.CreateDirectory(folderPath);
+ }
+
+ var doneAddrs = new List();
+ for (int i = 0; i < XbfsHeaders.Count; i++)
+ {
+ if (!XbfsHeaders[i].IsValid)
+ continue;
+ for (int y = 0; y < XbfsHeaders[i].Files.Length; y++)
+ {
+ var ent = XbfsHeaders[i].Files[y];
+ if (ent.BlockCount == 0)
+ continue;
+
+ var xbfsFilename = GetFilenameForIndex(y);
+ string fileName = $"{ent.Offset(Flavor):X}_{ent.Length:X}_{i}_{y}_{xbfsFilename ?? "unknown"}";
+
+ long read = 0;
+ long total = ent.Length;
+ _io.Stream.Position = ent.Offset(Flavor);
+
+ bool writeFile = true;
+ if (doneAddrs.Contains(_io.Stream.Position))
+ {
+ writeFile = false;
+ fileName = $"DUPE_{fileName}";
+ }
+ doneAddrs.Add(_io.Stream.Position);
+
+
+ if (_io.Stream.Position + total > _io.Stream.Length)
+ continue;
+
+ using (var fileIo = new IO(Path.Combine(folderPath, fileName), FileMode.Create))
+ {
+ if (!writeFile) // create empty file for DUPE_* files
+ continue;
+
+ while (read < total)
+ {
+ int toRead = 0x4000;
+ if (total - read < toRead)
+ toRead = (int) (total - read);
+ byte[] data = _io.Reader.ReadBytes(toRead);
+ fileIo.Writer.Write(data);
+ read += toRead;
+ }
+ }
+ }
+ }
+ }
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine("XbfsFile");
+ b.AppendLine($"Flavor: {Flavor}");
+ b.AppendLine($"Size: 0x{FileSize:X} ({FileSize / 1024 / 1024} MB)");
+ b.AppendLine();
+ for (int i = 0; i < XbfsHeaders.Count; i++)
+ {
+ if(!XbfsHeaders[i].IsValid)
+ continue;
+
+ b.AppendLine($"XbfsHeader slot {i}: (0x{HeaderOffsets[i]:X})");
+ b.Append(XbfsHeaders[i].ToString(formatted));
+ }
+ return b.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/NAND/XbfsHeader.cs b/LibXboxOne/NAND/XbfsHeader.cs
new file mode 100644
index 0000000..62c1109
--- /dev/null
+++ b/LibXboxOne/NAND/XbfsHeader.cs
@@ -0,0 +1,85 @@
+using System;
+using System.Text;
+using System.Runtime.InteropServices;
+
+namespace LibXboxOne.Nand
+{
+ // XBFS header, can be at 0x10000, 0x810000 or 0x820000
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct XbfsHeader
+ {
+ public static readonly int DataToHash = 0x3E0;
+ public static readonly string XbfsMagic = "SFBX";
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
+ /* 0x0 */ public char[] Magic; // SFBX
+
+ /* 0x4 */ public byte FormatVersion;
+ /* 0x5 */ public byte SequenceNumber; // Indicates latest filesystem, wraps around: 0xFF -> 0x00
+ /* 0x6 */ public ushort LayoutVersion; // 3
+ /* 0x8 */ public ulong Reserved08; // 0
+ /* 0x10 */ public ulong Reserved10; // 0
+ /* 0x18 */ public ulong Reserved18; // 0
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3A)]
+ /* 0x20 */ public XbfsEntry[] Files;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x3C0 */ public byte[] Reserved3C0;
+
+ /* 0x3D0 */ public Guid SystemXVID; // GUID
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x3E0 */ public byte[] XbfsHash; // SHA256 hash of 0x0 - 0x3E0
+
+ public string MagicString => new string(Magic);
+
+ public bool IsValid => MagicString == XbfsMagic;
+
+ public bool IsHashValid => XbfsHash.IsEqualTo(CalculateHash());
+
+ byte[] CalculateHash()
+ {
+ byte[] data = Shared.StructToBytes(this);
+ return HashUtils.ComputeSha256(data, 0, DataToHash);
+ }
+
+ public void Rehash()
+ {
+ XbfsHash = CalculateHash();
+ }
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ string fmt = formatted ? " " : "";
+
+ var b = new StringBuilder();
+ b.AppendLineSpace(fmt + $"Magic: {new string(Magic)}");
+ b.AppendLineSpace(fmt + $"Format Version: 0x{FormatVersion:X}");
+ b.AppendLineSpace(fmt + $"Sequence Number: 0x{SequenceNumber:X}");
+ b.AppendLineSpace(fmt + $"Layout Version: 0x{LayoutVersion:X}");
+ b.AppendLineSpace(fmt + $"Reserved08: 0x{Reserved08:X}");
+ b.AppendLineSpace(fmt + $"Reserved10: 0x{Reserved10:X}");
+ b.AppendLineSpace(fmt + $"Reserved18: 0x{Reserved18:X}");
+ b.AppendLineSpace(fmt + $"Reserved3C0: {Reserved3C0.ToHexString()}");
+ b.AppendLineSpace(fmt + $"System XVID: {SystemXVID}");
+ b.AppendLineSpace(fmt + $"XBFS header hash: {Environment.NewLine}{fmt}{XbfsHash.ToHexString()} (Valid: {IsHashValid})");
+ b.AppendLine();
+
+ for(int i = 0; i < Files.Length; i++)
+ {
+ XbfsEntry entry = Files[i];
+ if (entry.Length == 0)
+ continue;
+ b.AppendLine($"File {i}: {XbfsFile.GetFilenameForIndex(i) ?? ""} {entry.ToString(formatted)}");
+ }
+
+ return b.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/Shared.cs b/LibXboxOne/Shared.cs
new file mode 100644
index 0000000..a56f833
--- /dev/null
+++ b/LibXboxOne/Shared.cs
@@ -0,0 +1,298 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace LibXboxOne
+{
+ public class Natives
+ {
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdMount(out IntPtr hDiskHandle,
+ out int mountedDiskNum,
+ IntPtr hXvdHandle,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszXvdPath,
+ long unknown,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszMountPoint,
+ int mountFlags);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdMountContentType(out IntPtr hDiskHandle,
+ out int mountedDiskNum,
+ IntPtr hXvdHandle,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszXvdPath,
+ long xvdContentType,
+ long unknown,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszMountPoint,
+ int mountFlags);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdVmMount(out IntPtr hDiskHandle,
+ IntPtr hXvdHandle,
+ long vmNumber,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszXvdPath,
+ long unknown,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszMountPoint,
+ int mountFlags);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdUnmountDiskNumber(IntPtr hXvdHandle,
+ int diskNum);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdUnmountFile(IntPtr hXvdHandle,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszXvdPath);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdVmUnmountFile(IntPtr hXvdHandle,
+ long vmId,
+ [MarshalAs(UnmanagedType.LPWStr)] string pszXvdPath);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdOpenAdapter(out IntPtr phXvdHandle);
+
+ [DllImport("xsapi.dll", SetLastError = true)]
+ public static extern uint XvdCloseAdapter(IntPtr phXvdHandle);
+
+ [DllImport("kernel32.dll")]
+ public static extern int DeviceIoControl(IntPtr hDevice, int
+ dwIoControlCode, ref short lpInBuffer, int nInBufferSize, IntPtr
+ lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr
+ lpOverlapped);
+ }
+// ReSharper disable once InconsistentNaming
+ public class IO : IDisposable
+ {
+ public BinaryReader Reader;
+ public BinaryWriter Writer;
+ public Stream Stream;
+
+ public IO(string filePath)
+ {
+ Stream = new FileStream(filePath, FileMode.Open);
+ InitIo();
+ }
+
+ public IO(string filePath, FileMode mode)
+ {
+ Stream = new FileStream(filePath, mode);
+ InitIo();
+ }
+
+ public IO(Stream baseStream)
+ {
+ Stream = baseStream;
+ InitIo();
+ }
+
+ public void Dispose()
+ {
+ Stream.Dispose();
+ Reader.Dispose();
+ Writer.Dispose();
+ }
+
+ public bool AddBytes(long numBytes)
+ {
+ const int blockSize = 0x1000;
+
+ long startPos = Stream.Position;
+ long startSize = Stream.Length;
+ long endPos = startPos + numBytes;
+ long endSize = Stream.Length + numBytes;
+
+ Stream.SetLength(endSize);
+
+ long totalWrite = startSize - startPos;
+
+ while (totalWrite > 0)
+ {
+ int toRead = totalWrite < blockSize ? (int)totalWrite : blockSize;
+
+ Stream.Position = startPos + (totalWrite - toRead);
+ var data = Reader.ReadBytes(toRead);
+
+ Stream.Position = startPos + (totalWrite - toRead);
+ var blankData = new byte[toRead];
+ Writer.Write(blankData);
+
+ Stream.Position = endPos + (totalWrite - toRead);
+ Writer.Write(data);
+
+ totalWrite -= toRead;
+ }
+
+ Stream.Position = startPos;
+
+ return true;
+ }
+
+ public bool DeleteBytes(long numBytes)
+ {
+ if (Stream.Position + numBytes > Stream.Length)
+ return false;
+
+ const int blockSize = 0x1000;
+
+ long startPos = Stream.Position;
+ long endPos = startPos + numBytes;
+ long endSize = Stream.Length - numBytes;
+ long i = 0;
+
+ while (i < endSize)
+ {
+ long totalRemaining = endSize - i;
+ int toRead = totalRemaining < blockSize ? (int)totalRemaining : blockSize;
+
+ Stream.Position = endPos + i;
+ byte[] data = Reader.ReadBytes(toRead);
+
+ Stream.Position = startPos + i;
+ Writer.Write(data);
+
+ i += toRead;
+ }
+
+ Stream.SetLength(endSize);
+ return true;
+ }
+
+ private void InitIo()
+ {
+ Reader = new BinaryReader(Stream);
+ Writer = new BinaryWriter(Stream);
+ }
+ }
+ public static class Shared
+ {
+ public static string FindFile(string fileName)
+ {
+ string test = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
+ if (File.Exists(test))
+ return test;
+ string[] drives = Directory.GetLogicalDrives();
+ foreach (string drive in drives)
+ {
+ test = Path.Combine(drive, fileName);
+ if (File.Exists(test))
+ return test;
+ }
+ return String.Empty;
+ }
+
+ ///
+ /// Reads in a block from a file and converts it to the struct
+ /// type specified by the template parameter
+ ///
+ ///
+ ///
+ ///
+ public static T ReadStruct(this BinaryReader reader)
+ {
+ var size = Marshal.SizeOf(typeof (T));
+ // Read in a byte array
+ var bytes = reader.ReadBytes(size);
+
+ return BytesToStruct(bytes);
+ }
+
+ public static bool WriteStruct(this BinaryWriter writer, T structure)
+ {
+ byte[] bytes = StructToBytes(structure);
+
+ writer.Write(bytes);
+
+ return true;
+ }
+
+ public static T BytesToStruct(byte[] bytes)
+ {
+ // Pin the managed memory while, copy it out the data, then unpin it
+ var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
+ var theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
+ handle.Free();
+
+ return theStructure;
+ }
+
+ public static byte[] StructToBytes(T structure)
+ {
+ var bytes = new byte[Marshal.SizeOf(typeof(T))];
+
+ // Pin the managed memory while, copy in the data, then unpin it
+ var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
+ Marshal.StructureToPtr(structure, handle.AddrOfPinnedObject(), true);
+ handle.Free();
+
+ return bytes;
+ }
+
+ public static string ToHexString(this byte[] bytes, string seperator = " ")
+ {
+ return bytes.Aggregate("", (current, b) => $"{current}{b:X2}{seperator}");
+ }
+
+ public static string ToHexString(this uint[] array, string seperator = " ")
+ {
+ return array.Aggregate("", (current, b) => $"{current}0x{b:X8}{seperator}");
+ }
+
+ public static string ToHexString(this ushort[] array, string seperator = " ")
+ {
+ return array.Aggregate("", (current, b) => $"{current}0x{b:X4}{seperator}");
+ }
+
+ public static byte[] ToBytes(this string hexString)
+ {
+ hexString = hexString.Replace(" ", "");
+
+ byte[] retval = new byte[hexString.Length / 2];
+ for (int i = 0; i < hexString.Length; i += 2)
+ retval[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
+ return retval;
+ }
+
+ public static bool IsArrayEmpty(this byte[] bytes)
+ {
+ return bytes.All(b => b == 0);
+ }
+ public static bool IsEqualTo(this byte[] byte1, byte[] byte2)
+ {
+ if (byte1.Length != byte2.Length)
+ return false;
+
+ for (int i = 0; i < byte1.Length; i++)
+ if (byte1[i] != byte2[i])
+ return false;
+
+ return true;
+ }
+
+ public static void AppendLineSpace(this StringBuilder b, string str)
+ {
+ b.AppendLine(str + " ");
+ }
+
+ public static ushort EndianSwap(this ushort num)
+ {
+ byte[] data = BitConverter.GetBytes(num);
+ Array.Reverse(data);
+ return BitConverter.ToUInt16(data, 0);
+ }
+
+ public static uint EndianSwap(this uint num)
+ {
+ byte[] data = BitConverter.GetBytes(num);
+ Array.Reverse(data);
+ return BitConverter.ToUInt32(data, 0);
+ }
+
+ public static ulong EndianSwap(this ulong num)
+ {
+ byte[] data = BitConverter.GetBytes(num);
+ Array.Reverse(data);
+ return BitConverter.ToUInt64(data, 0);
+ }
+ }
+}
diff --git a/LibXboxOne/ThirdParty/ProgressBar.cs b/LibXboxOne/ThirdParty/ProgressBar.cs
new file mode 100644
index 0000000..23eeb74
--- /dev/null
+++ b/LibXboxOne/ThirdParty/ProgressBar.cs
@@ -0,0 +1,101 @@
+using System;
+using System.Text;
+using System.Threading;
+
+///
+/// An ASCII progress bar
+///
+namespace LibXboxOne
+{
+ // Source: https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54
+ // License: MIT
+ public class ProgressBar : IDisposable, IProgress
+ {
+ private const int blockCount = 30;
+ private readonly TimeSpan animationInterval = TimeSpan.FromSeconds(1.0 / 8);
+ private const string animation = @"|/-\";
+
+ private readonly Timer timer;
+
+ private long totalItems = 0;
+ private long currentItem = 0;
+ private string description = String.Empty;
+ private string currentText = string.Empty;
+ private bool disposed = false;
+ private int animationIndex = 0;
+
+ public ProgressBar(long items, string unitDescription="") {
+ totalItems = items;
+ description = unitDescription;
+ timer = new Timer(TimerHandler);
+
+ // A progress bar is only for temporary display in a console window.
+ // If the console output is redirected to a file, draw nothing.
+ // Otherwise, we'll end up with a lot of garbage in the target file.
+ if (!Console.IsOutputRedirected) {
+ ResetTimer();
+ }
+ }
+
+ public void Report(long current) {
+ Interlocked.Exchange(ref currentItem, current);
+ }
+
+ private void TimerHandler(object state) {
+ lock (timer) {
+ if (disposed) return;
+
+ double progress = (double)(currentItem + 1) / totalItems;
+ int progressBlockCount = (int) (progress * blockCount);
+ int percent = (int) (progress * 100);
+ string text = string.Format("{0,3}% [{1}{2}] {3}/{4} {5} {6}",
+ percent,
+ new string('#', progressBlockCount), new string('-', blockCount - progressBlockCount),
+ currentItem,
+ totalItems,
+ description,
+ animation[animationIndex++ % animation.Length]);
+ UpdateText(text);
+
+ ResetTimer();
+ }
+ }
+
+ private void UpdateText(string text) {
+ // Get length of common portion
+ int commonPrefixLength = 0;
+ int commonLength = Math.Min(currentText.Length, text.Length);
+ while (commonPrefixLength < commonLength && text[commonPrefixLength] == currentText[commonPrefixLength]) {
+ commonPrefixLength++;
+ }
+
+ // Backtrack to the first differing character
+ StringBuilder outputBuilder = new StringBuilder();
+ outputBuilder.Append('\b', currentText.Length - commonPrefixLength);
+
+ // Output new suffix
+ outputBuilder.Append(text.Substring(commonPrefixLength));
+
+ // If the new text is shorter than the old one: delete overlapping characters
+ int overlapCount = currentText.Length - text.Length;
+ if (overlapCount > 0) {
+ outputBuilder.Append(' ', overlapCount);
+ outputBuilder.Append('\b', overlapCount);
+ }
+
+ Console.Write(outputBuilder);
+ currentText = text;
+ }
+
+ private void ResetTimer() {
+ timer.Change(animationInterval, TimeSpan.FromMilliseconds(-1));
+ }
+
+ public void Dispose() {
+ lock (timer) {
+ disposed = true;
+ UpdateText(string.Empty);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/ThirdParty/TableParserExtensions.cs b/LibXboxOne/ThirdParty/TableParserExtensions.cs
new file mode 100644
index 0000000..616a868
--- /dev/null
+++ b/LibXboxOne/ThirdParty/TableParserExtensions.cs
@@ -0,0 +1,117 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Reflection;
+using System.Text;
+
+namespace LibXboxOne.ThirdParty
+{
+ // TableParserExtensions class from https://github.com/Robert-McGinley/TableParser
+ public static class TableParserExtensions
+ {
+ public static string ToStringTable(this IEnumerable values, string[] columnHeaders, params Func[] valueSelectors)
+ {
+ return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
+ }
+
+ public static string ToStringTable(this T[] values, string[] columnHeaders, params Func[] valueSelectors)
+ {
+ Debug.Assert(columnHeaders.Length == valueSelectors.Length);
+
+ var arrValues = new string[values.Length + 1, valueSelectors.Length];
+
+ // Fill headers
+ for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
+ {
+ arrValues[0, colIndex] = columnHeaders[colIndex];
+ }
+
+ // Fill table rows
+ for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
+ {
+ for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
+ {
+ object value = valueSelectors[colIndex].Invoke(values[rowIndex - 1]);
+
+ arrValues[rowIndex, colIndex] = value != null ? value.ToString() : "null";
+ }
+ }
+
+ return ToStringTable(arrValues);
+ }
+
+ public static string ToStringTable(this string[,] arrValues)
+ {
+ int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
+ var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);
+
+ var sb = new StringBuilder();
+ for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
+ {
+ for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
+ {
+ // Print cell
+ string cell = arrValues[rowIndex, colIndex];
+ cell = cell.PadRight(maxColumnsWidth[colIndex]);
+ sb.Append(" | ");
+ sb.Append(cell);
+ }
+
+ // Print end of line
+ sb.Append(" | ");
+ sb.AppendLine();
+
+ // Print splitter
+ if (rowIndex == 0)
+ {
+ sb.AppendFormat(" |{0}| ", headerSpliter);
+ sb.AppendLine();
+ }
+ }
+
+ return sb.ToString();
+ }
+
+ private static int[] GetMaxColumnsWidth(string[,] arrValues)
+ {
+ var maxColumnsWidth = new int[arrValues.GetLength(1)];
+ for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
+ {
+ for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
+ {
+ int newLength = arrValues[rowIndex, colIndex].Length;
+ int oldLength = maxColumnsWidth[colIndex];
+
+ if (newLength > oldLength)
+ {
+ maxColumnsWidth[colIndex] = newLength;
+ }
+ }
+ }
+
+ return maxColumnsWidth;
+ }
+
+ public static string ToStringTable(this IEnumerable values, params Expression>[] valueSelectors)
+ {
+ var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
+ var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
+ return ToStringTable(values, headers, selectors);
+ }
+
+ private static PropertyInfo GetProperty(Expression> expresstion)
+ {
+ switch (expresstion.Body)
+ {
+ case UnaryExpression expression when expression.Operand is MemberExpression memberExpression:
+ return memberExpression.Member as PropertyInfo;
+ case MemberExpression expression1:
+ return expression1.Member as PropertyInfo;
+ default:
+ return null;
+ }
+ }
+ }
+}
diff --git a/LibXboxOne/XVD/XVDEnums.cs b/LibXboxOne/XVD/XVDEnums.cs
new file mode 100644
index 0000000..8810b71
--- /dev/null
+++ b/LibXboxOne/XVD/XVDEnums.cs
@@ -0,0 +1,111 @@
+using System;
+
+namespace LibXboxOne
+{
+ public enum XvdType : uint
+ {
+ Fixed = 0,
+ Dynamic = 1
+ }
+
+ public enum XvdContentType : uint
+ {
+ Data = 0,
+ Title = 1,
+ SystemOS = 2,
+ EraOS = 3,
+ Scratch = 4,
+ ResetData = 5,
+ Application = 6,
+ HostOS = 7,
+ X360STFS = 8,
+ X360FATX = 9,
+ X360GDFX = 0xA,
+ Updater = 0xB,
+ OfflineUpdater = 0xC,
+ Template = 0xD,
+ MteHost = 0xE,
+ MteApp = 0xF,
+ MteTitle = 0x10,
+ MteEraOS = 0x11,
+ EraTools = 0x12,
+ SystemTools = 0x13,
+ SystemAux = 0x14,
+ AcousticModel = 0x15,
+ SystemCodecsVolume = 0x16,
+ QasltPackage = 0x17,
+ AppDlc = 0x18,
+ TitleDlc = 0x19,
+ UniversalDlc = 0x1A,
+ SystemDataVolume = 0x1B,
+ TestVolume = 0x1C,
+ HardwareTestVolume = 0x1D,
+ KioskContent = 0x1E,
+ HostProfiler = 0x20,
+ Uwa = 0x21,
+ Unknown22 = 0x22,
+ Unknown23 = 0x23,
+ Unknown24 = 0x24,
+ ServerAgent = 0x25
+ }
+
+ [Flags]
+ public enum XvcRegionFlags : uint
+ {
+ Resident = 1,
+ InitialPlay = 2,
+ Preview = 4,
+ FileSystemMetadata = 8,
+ Present = 0x10,
+ OnDemand = 0x20,
+ Available = 0x40,
+ }
+
+ [Flags]
+ public enum XvdVolumeFlags : uint
+ {
+ ReadOnly = 1,
+ EncryptionDisabled = 2, // data decrypted, no encrypted CIKs
+ DataIntegrityDisabled = 4, // unsigned and unhashed
+ LegacySectorSize = 8,
+ ResiliencyEnabled = 0x10,
+ SraReadOnly = 0x20,
+ RegionIdInXts = 0x40,
+ EraSpecific = 0x80
+ }
+
+ [Flags]
+ public enum XvcRegionPresenceInfo : byte
+ {
+ IsPresent = 1, // not set = "not present"
+ IsAvailable = 2, // not set = "unavailable"
+
+ //value >> 4 = discnum
+ Disc1 = 0x10,
+ Disc2 = 0x20,
+ Disc3 = 0x30,
+ Disc4 = 0x40,
+ Disc5 = 0x50,
+ Disc6 = 0x60,
+ Disc7 = 0x70,
+ Disc8 = 0x80,
+ Disc9 = 0x90,
+ Disc10 = 0xA0,
+ Disc11 = 0xB0,
+ Disc12 = 0xC0,
+ Disc13 = 0xD0,
+ Disc14 = 0xE0,
+ Disc15 = 0xF0
+ }
+
+ public enum XvdUserDataType : uint
+ {
+ PackageFiles = 0
+ }
+
+ [Flags]
+ public enum XvdSegmentMetadataSegmentFlags : ushort
+ {
+ KeepEncryptedOnDisk = 1,
+ }
+}
diff --git a/LibXboxOne/XVD/XVDFile.cs b/LibXboxOne/XVD/XVDFile.cs
new file mode 100644
index 0000000..90b9d25
--- /dev/null
+++ b/LibXboxOne/XVD/XVDFile.cs
@@ -0,0 +1,1254 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using System.Xml;
+using LibXboxOne.Keys;
+using LibXboxOne.ThirdParty;
+
+namespace LibXboxOne
+{
+ public class XvdFile : IDisposable
+ {
+ #region Constants
+
+ public static readonly ulong HEADER_SIGNATURE_SIZE = 0x200;
+ public static readonly ulong XVD_HEADER_SIZE = 0x2E00;
+ public static readonly ulong XVD_HEADER_INCL_SIGNATURE_SIZE = HEADER_SIGNATURE_SIZE + XVD_HEADER_SIZE;
+
+ public static readonly uint PAGE_SIZE = 0x1000;
+ public static readonly uint BLOCK_SIZE = 0xAA000;
+ public static readonly uint SECTOR_SIZE = 4096;
+ public static readonly uint LEGACY_SECTOR_SIZE = 512;
+ public static readonly uint INVALID_SECTOR = 0xFFFFFFFF;
+
+ public static readonly uint HASH_ENTRY_LENGTH = 0x18;
+ public static readonly uint HASH_ENTRY_LENGTH_ENCRYPTED = 0x14;
+
+ public static readonly uint HASH_ENTRIES_IN_PAGE = PAGE_SIZE / HASH_ENTRY_LENGTH; // 0xAA
+ public static readonly uint PAGES_PER_BLOCK = BLOCK_SIZE / PAGE_SIZE; // 0xAA
+
+ public static readonly uint DATA_BLOCKS_IN_LEVEL0_HASHTREE = HASH_ENTRIES_IN_PAGE; // 0xAA
+ public static readonly uint DATA_BLOCKS_IN_LEVEL1_HASHTREE = HASH_ENTRIES_IN_PAGE * DATA_BLOCKS_IN_LEVEL0_HASHTREE; // 0x70E4
+ public static readonly uint DATA_BLOCKS_IN_LEVEL2_HASHTREE = HASH_ENTRIES_IN_PAGE * DATA_BLOCKS_IN_LEVEL1_HASHTREE; // 0x4AF768
+ public static readonly uint DATA_BLOCKS_IN_LEVEL3_HASHTREE = HASH_ENTRIES_IN_PAGE * DATA_BLOCKS_IN_LEVEL2_HASHTREE; // 0x31C84B10
+ #endregion
+
+ public static bool DisableDataHashChecking = false;
+ public static bool PrintProgressToConsole = false;
+ public static bool DisableSaveAfterModification = false;
+
+ public XvdHeader Header;
+ public XvcInfo XvcInfo;
+
+ public List RegionHeaders;
+ public List UpdateSegments;
+ public List RegionSpecifiers;
+ public List RegionPresenceInfo;
+
+ public bool HashTreeValid;
+ public bool DataHashTreeValid;
+ public bool XvcDataHashValid;
+
+ public bool CikIsDecrypted;
+
+ public static XvdContentType[] XvcContentTypes =
+ { // taken from bit test 0x07018042 (00000111000000011000000001000010)
+ // idx of each set bit (from right to left) is an XVC-enabled content type
+ XvdContentType.Title,
+ XvdContentType.Application,
+ XvdContentType.MteApp,
+ XvdContentType.MteTitle,
+ XvdContentType.AppDlc,
+ XvdContentType.TitleDlc,
+ XvdContentType.UniversalDlc
+ };
+
+ public OdkIndex OverrideOdk { get; set; }
+ public XvdFilesystem Filesystem { get; private set; }
+
+ private readonly IO _io;
+
+ public readonly string FilePath;
+
+ public long FileSize => _io.Stream.Length;
+
+ public DateTime TimeCreated => DateTime.FromFileTime(Header.FileTimeCreated);
+
+ public bool IsXvcFile => XvcContentTypes.Contains(Header.ContentType);
+
+ public bool IsEncrypted => !Header.VolumeFlags.HasFlag(XvdVolumeFlags.EncryptionDisabled);
+
+ public bool IsDataIntegrityEnabled => !Header.VolumeFlags.HasFlag(XvdVolumeFlags.DataIntegrityDisabled);
+
+ public bool IsResiliencyEnabled => Header.VolumeFlags.HasFlag(XvdVolumeFlags.ResiliencyEnabled);
+
+ public bool UsesLegacySectorSize => Header.VolumeFlags.HasFlag(XvdVolumeFlags.LegacySectorSize);
+
+ public ulong EmbeddedXvdOffset => XVD_HEADER_INCL_SIGNATURE_SIZE;
+
+ public ulong MduOffset => XvdMath.PageNumberToOffset(Header.EmbeddedXvdPageCount) +
+ EmbeddedXvdOffset;
+
+ public ulong HashTreeOffset => Header.MutableDataLength + MduOffset;
+
+ public ulong HashTreePageCount =>
+ XvdMath.CalculateNumberHashPages(out _,
+ Header.NumberOfHashedPages,
+ IsResiliencyEnabled);
+
+ public ulong HashTreeLevels {
+ get
+ {
+ XvdMath.CalculateNumberHashPages(out ulong tmpHashTreeLevels,
+ Header.NumberOfHashedPages,
+ IsResiliencyEnabled);
+ return tmpHashTreeLevels;
+ }
+ }
+
+ public ulong UserDataOffset =>
+ (IsDataIntegrityEnabled ? XvdMath.PageNumberToOffset(HashTreePageCount) : 0) +
+ HashTreeOffset;
+
+ public ulong XvcInfoOffset =>
+ XvdMath.PageNumberToOffset(Header.UserDataPageCount) +
+ UserDataOffset;
+
+ public ulong DynamicHeaderOffset =>
+ XvdMath.PageNumberToOffset(Header.XvcInfoPageCount) +
+ XvcInfoOffset;
+
+ public ulong DriveDataOffset =>
+ XvdMath.PageNumberToOffset(Header.DynamicHeaderPageCount) +
+ DynamicHeaderOffset;
+
+ public uint DataHashEntryLength => IsEncrypted ? HASH_ENTRY_LENGTH_ENCRYPTED : HASH_ENTRY_LENGTH;
+
+ // Used to calculate absolute offset for dynamic data
+ public ulong DynamicBaseOffset => XvcInfoOffset;
+
+ public ulong StaticDataLength { get; private set; }
+
+ public XvdFile(string path)
+ {
+ FilePath = path;
+ _io = new IO(path);
+ OverrideOdk = OdkIndex.Invalid;
+ }
+
+ public uint ReadBat(ulong requestedBlock)
+ {
+ ulong absoluteAddress = DynamicHeaderOffset + (requestedBlock * sizeof(uint));
+ if (absoluteAddress > (DynamicHeaderOffset + Header.DynamicHeaderLength - sizeof(uint)))
+ {
+ throw new InvalidDataException(
+ $"Out-of-bounds block 0x{requestedBlock:X} requested, addr: 0x{absoluteAddress:X}. " +
+ $"Dynamic header range: 0x{DynamicHeaderOffset:X}-0x{DynamicHeaderOffset+Header.DynamicHeaderLength:X}");
+ }
+
+ _io.Stream.Position = (long)absoluteAddress;
+ return _io.Reader.ReadUInt32();
+ }
+
+ public uint ReadUInt32(long offset)
+ {
+ _io.Stream.Seek(offset, SeekOrigin.Begin);
+ return _io.Reader.ReadUInt32();
+ }
+
+ public byte[] ReadBytes(long offset, int length)
+ {
+ _io.Stream.Seek(offset, SeekOrigin.Begin);
+ return _io.Reader.ReadBytes(length);
+ }
+
+ public int WriteBytes(long offset, byte[] data)
+ {
+ _io.Stream.Seek(offset, SeekOrigin.Begin);
+ _io.Writer.Write(data);
+ return data.Length;
+ }
+
+ public byte[] ReadPage(ulong pageNumber)
+ {
+ return ReadBytes((long)XvdMath.PageNumberToOffset(pageNumber), (int)PAGE_SIZE);
+ }
+
+ public int WritePage(ulong pageNumber, byte[] data)
+ {
+ return WriteBytes((long)XvdMath.PageNumberToOffset(pageNumber), data);
+ }
+
+ public bool VirtualToLogicalDriveOffset(ulong virtualOffset, out ulong logicalOffset)
+ {
+ logicalOffset = 0;
+
+ if (virtualOffset >= Header.DriveSize)
+ throw new InvalidOperationException(
+ $"Virtual offset 0x{virtualOffset:X} is outside drivedata length 0x{Header.DriveSize:X}");
+ if (Header.Type > XvdType.Dynamic)
+ throw new NotSupportedException($"Xvd type {Header.Type} is unhandled");
+
+
+ if (Header.Type == XvdType.Dynamic)
+ {
+ var dataStartOffset = virtualOffset + XvdMath.PageNumberToOffset(Header.NumberOfMetadataPages);
+ var pageNumber = XvdMath.OffsetToPageNumber(dataStartOffset);
+ var inBlockOffset = XvdMath.InBlockOffset(dataStartOffset);
+ var firstDynamicPage = XvdMath.QueryFirstDynamicPage(Header.NumberOfMetadataPages);
+
+ if (pageNumber >= firstDynamicPage)
+ {
+ var firstDynamicPageBytes = XvdMath.PageNumberToOffset(firstDynamicPage);
+ var blockNumber = XvdMath.OffsetToBlockNumber(dataStartOffset - firstDynamicPageBytes);
+ ulong allocatedBlock = ReadBat(blockNumber);
+ if (allocatedBlock == INVALID_SECTOR)
+ return false;
+
+ dataStartOffset = XvdMath.PageNumberToOffset(allocatedBlock) + inBlockOffset;
+ pageNumber = XvdMath.OffsetToPageNumber(dataStartOffset);
+ }
+
+ var dataBackingBlockNum = XvdMath.ComputeDataBackingPageNumber(Header.Type,
+ HashTreeLevels,
+ HashTreePageCount,
+ pageNumber);
+ logicalOffset = XvdMath.PageNumberToOffset(dataBackingBlockNum);
+ logicalOffset += XvdMath.InPageOffset(dataStartOffset);
+ logicalOffset += XvdMath.PageNumberToOffset(Header.EmbeddedXvdPageCount);
+ logicalOffset += Header.MutableDataLength;
+ logicalOffset += XVD_HEADER_INCL_SIGNATURE_SIZE;
+ logicalOffset += PAGE_SIZE;
+ }
+ else
+ { // Xvd type fixed
+ logicalOffset = virtualOffset;
+ logicalOffset += XvdMath.PageNumberToOffset(Header.EmbeddedXvdPageCount);
+ logicalOffset += Header.MutableDataLength;
+ logicalOffset += XvdMath.PageNumberToOffset(Header.NumberOfMetadataPages);
+ logicalOffset += XVD_HEADER_INCL_SIGNATURE_SIZE;
+ logicalOffset += PAGE_SIZE;
+ }
+
+ return true;
+ }
+
+ uint[] GetAllBATEntries()
+ {
+ var batEntryCount = XvdMath.BytesToBlocks(Header.DriveSize);
+ uint[] BatEntries = new uint[batEntryCount];
+
+ for (ulong i=0; i < batEntryCount; i++)
+ BatEntries[i] = ReadBat(i);
+
+ return BatEntries;
+ }
+
+ ulong CalculateStaticDataLength()
+ {
+ switch (Header.Type)
+ {
+ case XvdType.Dynamic:
+ {
+ var smallestPage = GetAllBATEntries().Min();
+ return XvdMath.PageNumberToOffset(smallestPage)
+ - XvdMath.PageNumberToOffset(Header.DynamicHeaderPageCount)
+ - XvdMath.PageNumberToOffset(Header.XvcInfoPageCount);
+ }
+ case XvdType.Fixed:
+ return 0;
+
+ default:
+ throw new InvalidProgramException("Unsupported XvdType");
+ }
+ }
+
+ private void CryptHeaderCik(bool encrypt)
+ {
+ if ((!encrypt && CikIsDecrypted) || IsXvcFile)
+ {
+ CikIsDecrypted = true;
+ return;
+ }
+
+ var odkToUse = OverrideOdk == OdkIndex.Invalid ? Header.ODKKeyslotID : OverrideOdk;
+
+ var odkKey = DurangoKeys.GetOdkById(odkToUse);
+ if (odkKey == null)
+ throw new InvalidOperationException(
+ $"ODK with Id \'{Header.ODKKeyslotID}\' not found! Cannot crypt CIK in header");
+
+ if (!odkKey.HasKeyData)
+ throw new InvalidOperationException(
+ $"ODK with Id \'{Header.ODKKeyslotID}\' is known but not loaded! Cannot crypt CIK in header");
+
+ byte[] nullIv = new byte[16];
+
+ var cipher = Aes.Create();
+ cipher.Mode = CipherMode.ECB;
+ cipher.Padding = PaddingMode.None;
+
+ var transform = encrypt ? cipher.CreateEncryptor(odkKey.KeyData, nullIv) :
+ cipher.CreateDecryptor(odkKey.KeyData, nullIv);
+
+ transform.TransformBlock(Header.KeyMaterial, 0, Header.KeyMaterial.Length, Header.KeyMaterial, 0);
+
+ CikIsDecrypted = !encrypt;
+ }
+
+ private bool CryptXvcRegion(int regionIdx, bool encrypt)
+ {
+ if (XvcInfo.ContentID == null || !XvcInfo.IsAnyKeySet || regionIdx > XvcInfo.RegionCount || RegionHeaders == null || regionIdx >= RegionHeaders.Count)
+ return false;
+
+ XvcRegionHeader header = RegionHeaders[regionIdx];
+ if (encrypt && header.KeyId == XvcConstants.XVC_KEY_NONE)
+ header.KeyId = 0;
+
+ if (header.Length <= 0 || header.Offset <= 0 || header.KeyId == XvcConstants.XVC_KEY_NONE || header.KeyId + 1 > XvcInfo.KeyCount)
+ return false;
+
+ GetXvcKey(header.KeyId, out var key);
+
+ if (key == null)
+ return false;
+
+ return CryptSectionXts(encrypt, key, (uint)header.Id, header.Offset, header.Length);
+ }
+
+ internal bool CryptSectionXts(bool encrypt, byte[] key, uint headerId, ulong offset, ulong length)
+ {
+ var startPage = XvdMath.OffsetToPageNumber(offset - UserDataOffset);
+ ulong numPages = XvdMath.BytesToPages(length);
+
+ // Pre-read data unit numbers to minimize needing to seek around the file
+ List dataUnits = null;
+ if (IsDataIntegrityEnabled)
+ {
+ dataUnits = new List();
+ for (uint page = 0; page < numPages; page++)
+ {
+ // fetch dataUnit from hash table entry for this page
+ // TODO: seems we'll have to insert dataUnit when re-adding hashtables...
+
+ // last 4 bytes of hash entry = dataUnit
+ _io.Stream.Position = (long)CalculateHashEntryOffsetForBlock(startPage + page, 0) + 0x14;
+ dataUnits.Add(_io.Reader.ReadUInt32());
+ }
+ }
+
+ var tweakAesKey = new byte[0x10];
+ var dataAesKey = new byte[0x10];
+
+ var tweak = new byte[0x10];
+
+ // Split tweak- / Data AES key
+ Array.Copy(key, tweakAesKey, 0x10);
+ Array.Copy(key, 0x10, dataAesKey, 0, 0x10);
+
+ // Copy VDUID and header Id as tweak
+ var headerIdBytes = BitConverter.GetBytes(headerId);
+ Array.Copy(Header.VDUID, 0, tweak, 0x8, 0x8);
+ Array.Copy(headerIdBytes, 0, tweak, 0x4, 0x4);
+
+ var cipher = new AesXtsTransform(tweak, dataAesKey, tweakAesKey, encrypt);
+
+ // Perform crypto!
+ if (PrintProgressToConsole)
+ Console.WriteLine($"\r\nCrypting section 0x{offset:X} - 0x{offset + length:X} (HeaderId: 0x{headerId:X}):");
+
+ _io.Stream.Position = (long)offset;
+
+ using (var progress = new ProgressBar((long)numPages, "pages"))
+ {
+ for (uint page = 0; page < numPages; page++)
+ {
+ if (PrintProgressToConsole)
+ progress.Report((long)page);
+
+ var transformedData = new byte[PAGE_SIZE];
+
+ var pageOffset = _io.Stream.Position;
+ var origData = _io.Reader.ReadBytes((int)PAGE_SIZE);
+
+ cipher.TransformDataUnit(origData, 0, origData.Length, transformedData, 0, dataUnits?[(int)page] ?? page);
+
+ _io.Stream.Position = pageOffset;
+ _io.Writer.Write(transformedData);
+ }
+ }
+
+ return true;
+ }
+
+ public byte[] ExtractEmbeddedXvd()
+ {
+ if (Header.EmbeddedXVDLength == 0)
+ return null;
+ _io.Stream.Position = (long)EmbeddedXvdOffset;
+ return _io.Reader.ReadBytes((int)Header.EmbeddedXVDLength);
+ }
+
+ public byte[] ExtractUserData()
+ {
+ if (Header.UserDataLength == 0)
+ return null;
+ _io.Stream.Position = (long)UserDataOffset;
+ return _io.Reader.ReadBytes((int)Header.UserDataLength);
+ }
+
+ public bool Decrypt()
+ {
+ if (!IsEncrypted)
+ return true;
+
+ CryptHeaderCik(false);
+ if (!CikIsDecrypted)
+ return false;
+
+ bool success;
+
+ if (IsXvcFile)
+ {
+ for (int i = 0; i < RegionHeaders.Count; i++)
+ {
+ XvcRegionHeader header = RegionHeaders[i];
+ if (header.Length <= 0 || header.Offset <= 0 || header.KeyId == XvcConstants.XVC_KEY_NONE || header.KeyId + 1 > XvcInfo.KeyCount)
+ continue;
+ if (!CryptXvcRegion(i, false))
+ return false;
+ }
+ success = true;
+ }
+ else
+ {
+ // todo: check with more non-xvc xvds and see if they use any other headerId besides 0x1
+ success = CryptSectionXts(false, Header.KeyMaterial, 0x1, UserDataOffset,
+ (ulong)_io.Stream.Length - UserDataOffset);
+ }
+
+ if (!success)
+ return false;
+
+ Header.VolumeFlags ^= XvdVolumeFlags.EncryptionDisabled;
+
+ if (!DisableSaveAfterModification)
+ return Save();
+
+ return true;
+ }
+
+ public bool Encrypt(Guid cikKeyId)
+ {
+ if (IsEncrypted)
+ return true;
+
+ bool success;
+
+ if (!IsXvcFile)
+ {
+ if (Header.KeyMaterial.IsArrayEmpty())
+ {
+ // generate a new CIK if there's none specified
+ var rng = new Random();
+ Header.KeyMaterial = new byte[0x20];
+ rng.NextBytes(Header.KeyMaterial);
+ }
+
+ // todo: check with more non-xvc xvds and see if they use any other headerId besides 0x1
+ success = CryptSectionXts(true, Header.KeyMaterial, 0x1, UserDataOffset,
+ (ulong)_io.Stream.Length - UserDataOffset);
+ }
+ else
+ {
+ if (cikKeyId != Guid.Empty) // if cikKeyId is set, set the XvcInfo key accordingly
+ {
+ var key = DurangoKeys.GetCikByGuid(cikKeyId);
+ if (key == null)
+ {
+ throw new InvalidOperationException($"Desired CIK with GUID {cikKeyId} is unknown");
+ }
+
+ if (!key.HasKeyData)
+ {
+ throw new InvalidOperationException($"Desired CIK with GUID {cikKeyId} is known but not loaded");
+ }
+
+ XvcInfo.EncryptionKeyIds[0].KeyId = cikKeyId.ToByteArray();
+ }
+
+ for (int i = 0; i < RegionHeaders.Count; i++)
+ {
+ var header = RegionHeaders[i];
+ if (header.Length <= 0 || header.Offset <= 0 || header.KeyId + 1 > XvcInfo.KeyCount && header.KeyId != XvcConstants.XVC_KEY_NONE)
+ continue;
+
+ if (header.Id == XvcRegionId.Header ||
+ header.Id == XvcRegionId.EmbeddedXvd ||
+ header.Id == XvcRegionId.MetadataXvc)
+ continue; // skip XVD header / EXVD / XVC info
+
+ if (!CryptXvcRegion(i, true))
+ return false;
+ }
+ success = true;
+ }
+
+ if (!success)
+ return false;
+
+ CryptHeaderCik(true);
+
+ Header.VolumeFlags ^= XvdVolumeFlags.EncryptionDisabled;
+
+ // seems the readonly flag gets set when encrypting
+ if (!Header.VolumeFlags.HasFlag(XvdVolumeFlags.ReadOnly))
+ {
+ Header.VolumeFlags ^= XvdVolumeFlags.ReadOnly;
+ }
+
+ if (!DisableSaveAfterModification)
+ return Save();
+
+ return true;
+ }
+
+ public bool Save()
+ {
+ if (Header.XvcDataLength > 0 && IsXvcFile)
+ {
+ _io.Stream.Position = (long)XvcInfoOffset;
+
+ XvcInfo.RegionCount = (uint)RegionHeaders.Count;
+ XvcInfo.UpdateSegmentCount = (uint)UpdateSegments.Count;
+ if (RegionSpecifiers != null)
+ XvcInfo.RegionSpecifierCount = (uint)RegionSpecifiers.Count;
+
+ _io.Writer.WriteStruct(XvcInfo);
+
+ for (int i = 0; i < XvcInfo.RegionCount; i++)
+ _io.Writer.WriteStruct(RegionHeaders[i]);
+
+ for (int i = 0; i < XvcInfo.UpdateSegmentCount; i++)
+ _io.Writer.WriteStruct(UpdateSegments[i]);
+
+ if (RegionSpecifiers != null)
+ for (int i = 0; i < XvcInfo.RegionSpecifierCount; i++)
+ _io.Writer.WriteStruct(RegionSpecifiers[i]);
+ }
+
+ if (IsDataIntegrityEnabled)
+ {
+ if (PrintProgressToConsole)
+ Console.WriteLine("Calculating data hashes:");
+
+// ReSharper disable once UnusedVariable
+ ulong[] invalidBlocks = VerifyDataHashTree(true);
+// ReSharper disable once UnusedVariable
+ bool hashTreeValid = CalculateHashTree();
+ }
+
+ _io.Stream.Position = 0;
+ _io.Writer.WriteStruct(Header);
+
+ return true;
+ }
+
+ public bool Load()
+ {
+ _io.Stream.Position = 0;
+ Header = _io.Reader.ReadStruct();
+
+ CikIsDecrypted = !IsEncrypted;
+
+ if (DriveDataOffset >= (ulong)_io.Stream.Length)
+ return false;
+
+ if (Header.XvcDataLength > 0 && IsXvcFile)
+ {
+ _io.Stream.Position = (long)XvcInfoOffset;
+
+ XvcInfo = _io.Reader.ReadStruct();
+
+ if (XvcInfo.Version >= 1)
+ {
+ RegionHeaders = new List();
+ for (int i = 0; i < XvcInfo.RegionCount; i++)
+ RegionHeaders.Add(_io.Reader.ReadStruct());
+
+ UpdateSegments = new List();
+ for (int i = 0; i < XvcInfo.UpdateSegmentCount; i++)
+ UpdateSegments.Add(_io.Reader.ReadStruct());
+
+ if(XvcInfo.Version >= 2) // RegionSpecifiers / RegionPresenseInfo only seems to be used on XvcInfo v2
+ {
+ RegionSpecifiers = new List();
+ for (int i = 0; i < XvcInfo.RegionSpecifierCount; i++)
+ RegionSpecifiers.Add(_io.Reader.ReadStruct());
+
+ if(Header.MutableDataPageCount > 0)
+ {
+ RegionPresenceInfo = new List();
+ _io.Stream.Position = (long)MduOffset;
+ for (int i = 0; i < XvcInfo.RegionCount; i++)
+ RegionPresenceInfo.Add((XvcRegionPresenceInfo)_io.Reader.ReadByte());
+ }
+ }
+ }
+ }
+
+ DataHashTreeValid = true;
+ HashTreeValid = true;
+
+ if (IsDataIntegrityEnabled)
+ {
+ if (!DisableDataHashChecking)
+ {
+ if(PrintProgressToConsole)
+ Console.WriteLine("Verifying data hashes, use -nd to disable:");
+
+ ulong[] invalidBlocks = VerifyDataHashTree();
+ DataHashTreeValid = invalidBlocks.Length <= 0;
+ }
+ HashTreeValid = VerifyHashTree();
+ }
+
+ XvcDataHashValid = VerifyXvcHash();
+ StaticDataLength = CalculateStaticDataLength();
+ Filesystem = new XvdFilesystem(this);
+ return true;
+ }
+
+ public bool VerifyXvcHash(bool rehash = false)
+ {
+ if (!IsXvcFile)
+ return true;
+
+ ulong hashTreeSize = HashTreePageCount * PAGE_SIZE;
+
+ var ms = new MemoryStream();
+ var msIo = new IO(ms);
+ msIo.Writer.WriteStruct(XvcInfo);
+
+ // fix region headers to match pre-hashtable
+ for (int i = 0; i < XvcInfo.RegionCount; i++)
+ {
+ var region = RegionHeaders[i];
+ region.Hash = 0;
+
+ if (IsDataIntegrityEnabled)
+ {
+ if (HashTreeOffset >= region.Offset && region.Offset + region.Length > HashTreeOffset)
+ region.Length -= hashTreeSize;
+ else if (region.Offset > HashTreeOffset)
+ region.Offset -= hashTreeSize;
+ }
+
+ msIo.Writer.WriteStruct(region);
+ }
+
+ for (int i = 0; i < XvcInfo.UpdateSegmentCount; i++)
+ {
+ var segment = UpdateSegments[i];
+
+ var hashTreeEnd = XvdMath.BytesToPages(HashTreeOffset) + HashTreePageCount;
+ if (segment.PageNum >= hashTreeEnd)
+ segment.PageNum -= (uint)HashTreePageCount;
+
+ segment.Hash = 0;
+
+ msIo.Writer.WriteStruct(segment);
+ }
+
+ if (RegionSpecifiers != null)
+ for (int i = 0; i < XvcInfo.RegionSpecifierCount; i++)
+ msIo.Writer.WriteStruct(RegionSpecifiers[i]);
+
+ if(Header.XvcDataLength > msIo.Stream.Length)
+ msIo.Stream.SetLength(Header.XvcDataLength);
+
+ if (IsDataIntegrityEnabled)
+ {
+ // remove hash table offset from the special regions
+ if (XvcInfo.InitialPlayOffset > HashTreeOffset)
+ {
+ msIo.Stream.Position = 0xD28;
+ msIo.Writer.Write(XvcInfo.InitialPlayOffset - hashTreeSize);
+ }
+
+ if (XvcInfo.PreviewOffset > HashTreeOffset)
+ {
+ msIo.Stream.Position = 0xD40;
+ msIo.Writer.Write(XvcInfo.PreviewOffset - hashTreeSize);
+ }
+ }
+
+ byte[] xvcData = ms.ToArray();
+ msIo.Dispose();
+ byte[] hash = HashUtils.ComputeSha256(xvcData);
+ bool isValid = Header.OriginalXvcDataHash.IsEqualTo(hash);
+
+ if (rehash)
+ Header.OriginalXvcDataHash = hash;
+
+ return isValid; //todo: investigate why this gets the correct hash for dev XVCs but fails for retail ones, might be to do with retail XVC data having a content ID that doesn't match with VDUID/UDUID
+ }
+
+ public bool AddHashTree()
+ {
+ if (IsDataIntegrityEnabled)
+ return true;
+
+ if (!AddData(HashTreeOffset, (uint)HashTreePageCount))
+ return false;
+
+ Header.VolumeFlags ^= XvdVolumeFlags.DataIntegrityDisabled;
+
+ // todo: calculate hash tree
+
+ if (!DisableSaveAfterModification)
+ return Save();
+
+ return true;
+ }
+
+ internal bool AddData(ulong offset, ulong numPages)
+ {
+ var page = XvdMath.OffsetToPageNumber(offset);
+ var length = numPages * PAGE_SIZE;
+
+ _io.Stream.Position = (long)offset;
+ if (!_io.AddBytes((long)length))
+ return false;
+
+ if (!IsXvcFile)
+ return true;
+
+ if (XvcInfo.InitialPlayOffset > offset)
+ XvcInfo.InitialPlayOffset += length;
+
+ if (XvcInfo.PreviewOffset > offset)
+ XvcInfo.PreviewOffset += length;
+
+ for (int i = 0; i < RegionHeaders.Count; i++)
+ {
+ var region = RegionHeaders[i];
+ region.Hash = 0; // ???
+
+ if (offset >= region.Offset && region.Offset + region.Length > offset)
+ region.Length += length; // offset is part of region, add to length
+ else if (region.Offset > offset)
+ region.Offset += length; // offset is before region, add to offset
+
+ RegionHeaders[i] = region;
+ }
+
+ for (int i = 0; i < UpdateSegments.Count; i++)
+ {
+ var segment = UpdateSegments[i];
+ if (segment.PageNum < page)
+ continue;
+
+ segment.PageNum += (uint)numPages;
+ UpdateSegments[i] = segment;
+ }
+
+ return true;
+ }
+
+ internal bool RemoveData(ulong offset, ulong numPages)
+ {
+ var page = XvdMath.OffsetToPageNumber(offset);
+ var length = numPages * PAGE_SIZE;
+
+ _io.Stream.Position = (long)offset;
+ if (!_io.DeleteBytes((long)length))
+ return false;
+
+ if (!IsXvcFile)
+ return true;
+
+ if (XvcInfo.InitialPlayOffset > offset)
+ XvcInfo.InitialPlayOffset -= length;
+
+ if (XvcInfo.PreviewOffset > offset)
+ XvcInfo.PreviewOffset -= length;
+
+ for (int i = 0; i < RegionHeaders.Count; i++)
+ {
+ var region = RegionHeaders[i];
+ region.Hash = 0; // ???
+
+ if (offset >= region.Offset && region.Offset + region.Length > offset)
+ region.Length -= length; // offset is part of region, reduce length
+ else if (region.Offset > offset)
+ region.Offset -= length; // offset is before region, reduce offset
+
+ RegionHeaders[i] = region; // region is a copy instead of a reference due to it being a struct, so we have to replace the original data ourselves
+ }
+
+ for(int i = 0; i < UpdateSegments.Count; i++)
+ {
+ var segment = UpdateSegments[i];
+ if (segment.PageNum < page)
+ continue;
+
+ segment.PageNum -= (uint)numPages;
+ UpdateSegments[i] = segment;
+ }
+
+ return true;
+ }
+
+ public bool AddMutableData()
+ {
+ if (!IsXvcFile || XvcInfo.ContentID == null || RegionHeaders == null)
+ {
+ Console.WriteLine("Package is not XVC or has no Xvc data");
+ return false;
+ }
+
+ ulong pageCount = XvdMath.BytesToPages((ulong)RegionHeaders.Count);
+ byte[] mutableData = new byte[XvdMath.PageNumberToOffset(pageCount)];
+
+ if (Header.MutableDataPageCount > 0)
+ return true;
+
+ if (!AddData(MduOffset, pageCount))
+ return false;
+
+ for (int i=0; i < RegionHeaders.Count; i++)
+ {
+ XvcRegionHeader region = RegionHeaders[i];
+ bool isPresent = (long)(region.Offset + region.Length) <= FileSize;
+ // Assume that every Xvc region is available (probably means downloadable)
+ mutableData[i] = (byte)(XvcRegionPresenceInfo.IsAvailable
+ | (isPresent ? XvcRegionPresenceInfo.IsPresent : 0));
+ }
+
+
+ WriteBytes((long)MduOffset, mutableData);
+ Header.MutableDataPageCount = (byte)pageCount;
+
+ if (!DisableSaveAfterModification)
+ return Save();
+
+ return true;
+ }
+
+ public bool RemoveMutableData()
+ {
+ if (Header.MutableDataPageCount <= 0)
+ return true;
+
+ if (!RemoveData(MduOffset, Header.MutableDataPageCount))
+ return false;
+
+ Header.MutableDataPageCount = 0;
+
+ if (!DisableSaveAfterModification)
+ return Save();
+
+ return true;
+ }
+
+ public bool RemoveHashTree()
+ {
+ if (!IsDataIntegrityEnabled)
+ return true;
+
+ if (!RemoveData(HashTreeOffset, HashTreePageCount))
+ return false;
+
+ Header.VolumeFlags ^= XvdVolumeFlags.DataIntegrityDisabled;
+
+ for (int i = 0; i < Header.TopHashBlockHash.Length; i++)
+ Header.TopHashBlockHash[i] = 0;
+
+ if (!DisableSaveAfterModification)
+ return Save();
+
+ return true;
+ }
+
+ public ulong CalculateHashEntryOffsetForBlock(ulong blockNum, uint hashLevel)
+ {
+ var hashBlock = XvdMath.CalculateHashBlockNumForBlockNum(Header.Type, HashTreeLevels, Header.NumberOfHashedPages, blockNum, hashLevel, out var entryNum);
+ return HashTreeOffset + XvdMath.PageNumberToOffset(hashBlock) + (entryNum * HASH_ENTRY_LENGTH);
+ }
+
+ public ulong[] VerifyDataHashTree(bool rehash = false)
+ {
+ ulong dataBlockCount = XvdMath.OffsetToPageNumber((ulong)_io.Stream.Length - UserDataOffset);
+ var invalidBlocks = new List();
+
+ using (var progress = new ProgressBar((long)dataBlockCount, "blocks"))
+ {
+ for (ulong i = 0; i < dataBlockCount; i++)
+ {
+ if (PrintProgressToConsole)
+ progress.Report((long)i);
+
+ var hashEntryOffset = CalculateHashEntryOffsetForBlock(i, 0);
+ _io.Stream.Position = (long)hashEntryOffset;
+
+ byte[] oldhash = _io.Reader.ReadBytes((int)DataHashEntryLength);
+
+ var dataToHashOffset = XvdMath.PageNumberToOffset(i) + UserDataOffset;
+ _io.Stream.Position = (long)dataToHashOffset;
+
+ byte[] data = _io.Reader.ReadBytes((int)PAGE_SIZE);
+ byte[] hash = HashUtils.ComputeSha256(data);
+ Array.Resize(ref hash, (int)DataHashEntryLength);
+
+ if (hash.IsEqualTo(oldhash))
+ continue;
+
+ invalidBlocks.Add(i);
+ if (!rehash)
+ continue;
+ _io.Stream.Position = (long)hashEntryOffset;
+ _io.Writer.Write(hash);
+ }
+ }
+
+ return invalidBlocks.ToArray();
+ }
+
+ public bool CalculateHashTree()
+ {
+ uint blocksPerLevel = 0xAA;
+ uint hashTreeLevel = 1;
+ while (hashTreeLevel < HashTreeLevels)
+ {
+ uint dataBlockNum = 0;
+ if (Header.NumberOfHashedPages != 0)
+ {
+ while (dataBlockNum < Header.NumberOfHashedPages)
+ {
+ _io.Stream.Position = (long)CalculateHashEntryOffsetForBlock(dataBlockNum, hashTreeLevel - 1);
+ byte[] blockHash = HashUtils.ComputeSha256(_io.Reader.ReadBytes((int)PAGE_SIZE));
+ Array.Resize(ref blockHash, (int)HASH_ENTRY_LENGTH);
+
+ _io.Stream.Position = (long)CalculateHashEntryOffsetForBlock(dataBlockNum, hashTreeLevel);
+
+ byte[] oldHash = _io.Reader.ReadBytes((int)HASH_ENTRY_LENGTH);
+ if (!blockHash.IsEqualTo(oldHash))
+ {
+ _io.Stream.Position -= (int)HASH_ENTRY_LENGTH; // todo: maybe return a list of blocks that needed rehashing
+ _io.Writer.Write(blockHash);
+ }
+
+ dataBlockNum += blocksPerLevel;
+ }
+ }
+ hashTreeLevel++;
+ blocksPerLevel = blocksPerLevel * 0xAA;
+ }
+ _io.Stream.Position = (long)HashTreeOffset;
+ byte[] hash = HashUtils.ComputeSha256(_io.Reader.ReadBytes((int)PAGE_SIZE));
+ Header.TopHashBlockHash = hash;
+
+ return true;
+ }
+
+ public bool VerifyHashTree()
+ {
+ if (!IsDataIntegrityEnabled)
+ return true;
+
+ _io.Stream.Position = (long)HashTreeOffset;
+ byte[] hash = HashUtils.ComputeSha256(_io.Reader.ReadBytes((int)PAGE_SIZE));
+ if (!Header.TopHashBlockHash.IsEqualTo(hash))
+ return false;
+
+ if (HashTreeLevels == 1)
+ return true;
+
+ var blocksPerLevel = 0xAA;
+ ulong topHashTreeBlock = 0;
+ uint hashTreeLevel = 1;
+ while (hashTreeLevel < HashTreeLevels)
+ {
+ uint dataBlockNum = 0;
+ if (Header.NumberOfHashedPages != 0)
+ {
+ while (dataBlockNum < Header.NumberOfHashedPages)
+ {
+ _io.Stream.Position = (long)CalculateHashEntryOffsetForBlock(dataBlockNum, hashTreeLevel - 1);
+ byte[] blockHash = HashUtils.ComputeSha256(_io.Reader.ReadBytes((int)PAGE_SIZE));
+ Array.Resize(ref blockHash, (int)HASH_ENTRY_LENGTH);
+
+ var upperHashBlockOffset = CalculateHashEntryOffsetForBlock(dataBlockNum, hashTreeLevel);
+ topHashTreeBlock = XvdMath.OffsetToPageNumber(upperHashBlockOffset - HashTreeOffset);
+ _io.Stream.Position = (long)upperHashBlockOffset;
+
+ byte[] expectedHash = _io.Reader.ReadBytes((int)HASH_ENTRY_LENGTH);
+ if (!expectedHash.IsEqualTo(blockHash))
+ {
+ // wrong hash
+ return false;
+ }
+ dataBlockNum += (uint)blocksPerLevel;
+ }
+ }
+ hashTreeLevel++;
+ blocksPerLevel = blocksPerLevel * 0xAA;
+ }
+ if (topHashTreeBlock != 0)
+ {
+ Console.WriteLine(@"Top level hash page calculated to be at {0}, should be 0!", topHashTreeBlock);
+ }
+ return true;
+ }
+
+ public bool GetXvcKey(ushort keyIndex, out byte[] keyOutput)
+ {
+ keyOutput = null;
+ if (XvcInfo.EncryptionKeyIds == null || XvcInfo.EncryptionKeyIds.Length < 1 || XvcInfo.KeyCount == 0)
+ return false;
+
+ XvcEncryptionKeyId xvcKeyEntry = XvcInfo.EncryptionKeyIds[keyIndex];
+ if (xvcKeyEntry.IsKeyNulled)
+ return false;
+
+ return GetXvcKeyByGuid(new Guid(xvcKeyEntry.KeyId), out keyOutput);
+ }
+
+ public bool GetXvcKeyByGuid(Guid keyGuid, out byte[] keyOutput)
+ {
+ keyOutput = null;
+
+ if (XvcInfo.EncryptionKeyIds == null || XvcInfo.EncryptionKeyIds.Length < 1 || XvcInfo.KeyCount == 0)
+ return false;
+
+ bool keyFound = false;
+ foreach(var xvcKey in XvcInfo.EncryptionKeyIds)
+ {
+ if (new Guid(xvcKey.KeyId) == keyGuid)
+ {
+ keyFound = true;
+ }
+ }
+
+ if (!keyFound)
+ {
+ Console.WriteLine($"Key {keyGuid} is not used by this XVC");
+ return false;
+ }
+
+ if(DurangoKeys.IsCikLoaded(keyGuid))
+ {
+ keyOutput = DurangoKeys.GetCikByGuid(keyGuid).KeyData;
+ return true;
+ }
+
+ Console.WriteLine($"Did not find CIK {keyGuid} loaded in Keystorage");
+ Console.WriteLine("Checking for XML licenses...");
+
+ string licenseFolder = Path.GetDirectoryName(FilePath);
+ if (Path.GetFileName(licenseFolder) == "MSXC")
+ licenseFolder = Path.GetDirectoryName(licenseFolder);
+
+ if (String.IsNullOrEmpty(licenseFolder))
+ return false;
+
+ licenseFolder = Path.Combine(licenseFolder, "Licenses");
+
+ if (!Directory.Exists(licenseFolder))
+ return false;
+
+ foreach (string file in Directory.GetFiles(licenseFolder, "*.xml"))
+ {
+ var xml = new XmlDocument();
+ xml.Load(file);
+
+ var xmlns = new XmlNamespaceManager(xml.NameTable);
+ xmlns.AddNamespace("resp", "http://schemas.microsoft.com/xboxlive/security/clas/LicResp/v1");
+
+ XmlNode licenseNode = xml.SelectSingleNode("//resp:SignedLicense", xmlns);
+ if (licenseNode == null)
+ continue;
+
+ string signedLicense = licenseNode.InnerText;
+ byte[] signedLicenseBytes = Convert.FromBase64String(signedLicense);
+
+ var licenseXml = new XmlDocument();
+ licenseXml.LoadXml(Encoding.ASCII.GetString(signedLicenseBytes));
+
+ var xmlns2 = new XmlNamespaceManager(licenseXml.NameTable);
+ xmlns2.AddNamespace("resp", "http://schemas.microsoft.com/xboxlive/security/clas/LicResp/v1");
+
+ XmlNode keyIdNode = licenseXml.SelectSingleNode("//resp:KeyId", xmlns2);
+ if (keyIdNode == null)
+ continue;
+
+ if (keyGuid != new Guid(keyIdNode.InnerText))
+ continue;
+
+ XmlNode licenseBlockNode = licenseXml.SelectSingleNode("//resp:SPLicenseBlock", xmlns2);
+ if (licenseBlockNode == null)
+ continue;
+
+ string licenseBlock = licenseBlockNode.InnerText;
+ byte[] licenseBlockBytes = Convert.FromBase64String(licenseBlock);
+
+ var block = new XvcLicenseBlock(licenseBlockBytes);
+ var keyIdBlock = block.GetBlockWithId(XvcLicenseBlockId.KeyId);
+ if (keyIdBlock == null)
+ continue;
+
+ if (!(new Guid(keyIdBlock.BlockData) == keyGuid))
+ continue;
+
+ var decryptKeyBlock = block.GetBlockWithId(XvcLicenseBlockId.EncryptedCik);
+ if (decryptKeyBlock == null)
+ continue;
+
+ keyOutput = decryptKeyBlock.BlockData;
+ Console.WriteLine($"Xvd CIK key found in {file}");
+ // todo: decrypt/deobfuscate the key
+
+ return true;
+ }
+ return false;
+ }
+
+ #region ToString
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+
+ string fmt = formatted ? " " : "";
+
+ b.AppendLine("XvdMiscInfo:");
+ b.AppendLineSpace(fmt + $"Page Count: 0x{Header.NumberOfHashedPages:X}");
+ b.AppendLineSpace(fmt + $"Embedded XVD Offset: 0x{EmbeddedXvdOffset:X}");
+ b.AppendLineSpace(fmt + $"MDU Offset: 0x{MduOffset:X}");
+ b.AppendLineSpace(fmt + $"HashTree Offset: 0x{HashTreeOffset:X}");
+ b.AppendLineSpace(fmt + $"User Data Offset: 0x{UserDataOffset:X}");
+ b.AppendLineSpace(fmt + $"XVC Data Offset: 0x{XvcInfoOffset:X}");
+ b.AppendLineSpace(fmt + $"Dynamic Header Offset: 0x{DynamicHeaderOffset:X}");
+ b.AppendLineSpace(fmt + $"Drive Data Offset: 0x{DriveDataOffset:X}");
+
+ if (IsDataIntegrityEnabled)
+ {
+ b.AppendLineSpace(fmt + $"Hash Tree Page Count: 0x{HashTreePageCount:X}");
+ b.AppendLineSpace(fmt + $"Hash Tree Levels: 0x{HashTreeLevels:X}");
+ b.AppendLineSpace(fmt + $"Hash Tree Valid: {HashTreeValid}");
+
+ if (!DisableDataHashChecking)
+ b.AppendLineSpace(fmt + $"Data Hash Tree Valid: {DataHashTreeValid}");
+ }
+
+ if(IsXvcFile)
+ b.AppendLineSpace(fmt + $"XVC Data Hash Valid: {XvcDataHashValid}");
+
+ b.AppendLine();
+ b.Append(Header.ToString(formatted));
+
+ if (IsXvcFile && XvcInfo.ContentID != null)
+ {
+ b.AppendLine();
+ bool xvcKeyFound = GetXvcKey(0, out var decryptKey);
+ if (xvcKeyFound)
+ {
+ b.AppendLine($"Decrypt key for xvc keyslot 0: {decryptKey.ToHexString()}");
+ b.AppendLine("(key is wrong though until the obfuscation/encryption on it is figured out)");
+ b.AppendLine();
+ }
+
+ b.AppendLine(XvcInfo.ToString(formatted));
+ }
+
+ if(RegionHeaders != null)
+ for (int i = 0; i < RegionHeaders.Count; i++)
+ {
+ b.AppendLine();
+ string presenceInfo = "";
+ if (RegionPresenceInfo != null && RegionPresenceInfo.Count > i)
+ {
+ var presenceFlags = RegionPresenceInfo[i];
+ presenceInfo = " (";
+ presenceInfo += (presenceFlags.HasFlag(XvcRegionPresenceInfo.IsPresent) ? "present" : "not present") + ", ";
+ presenceInfo += presenceFlags.HasFlag(XvcRegionPresenceInfo.IsAvailable) ? "available" : "unavailable";
+ if (((int)presenceFlags & 0xF0) != 0)
+ {
+ presenceInfo += $", on disc {(int)presenceFlags >> 4}";
+ }
+ presenceInfo += ")";
+ }
+ b.AppendLine($"Region {i}{presenceInfo}");
+ b.Append(RegionHeaders[i].ToString(formatted));
+ }
+
+ if (UpdateSegments != null && UpdateSegments.Count > 0)
+ {
+ // have to add segments to a seperate List so we can store the index of them...
+ var segments = new List>();
+ for (int i = 0; i < UpdateSegments.Count; i++)
+ {
+ if (UpdateSegments[i].Hash == 0)
+ break;
+ segments.Add(Tuple.Create(i, UpdateSegments[i]));
+ }
+
+ b.AppendLine();
+ b.AppendLine("Update Segments:");
+ b.AppendLine();
+ b.AppendLine(segments.ToStringTable(
+ new[] { "Id", "PageNum (Offset)", "Hash" },
+ a => a.Item1, a => $"0x{a.Item2.PageNum:X} (0x{XvdMath.PageNumberToOffset(a.Item2.PageNum):X})", a => $"0x{a.Item2.Hash:X}"));
+ }
+
+
+ if (RegionSpecifiers != null && RegionSpecifiers.Count > 0)
+ {
+ // have to add specifiers to a seperate List so we can store the index of them...
+ var specs = new List>();
+ for (int i = 0; i < RegionSpecifiers.Count; i++)
+ {
+ specs.Add(Tuple.Create(i, RegionSpecifiers[i]));
+ }
+
+ b.AppendLine();
+ b.AppendLine("Region Specifiers:");
+ b.AppendLine();
+ b.AppendLine(specs.ToStringTable(
+ new[] { "Id", "RegionId", "Key", "Value" },
+ a => a.Item1, a => $"0x{a.Item2.RegionId:X}", a => a.Item2.Key, a => a.Item2.Value));
+ }
+
+ if (!IsEncrypted)
+ {
+ b.AppendLine();
+ try
+ {
+ b.Append(Filesystem.ToString(formatted));
+ }
+ catch (Exception e)
+ {
+ b.AppendLine($"Failed to get XvdFilesystem info, error: {e}");
+ }
+ }
+ else
+ b.AppendLine($"Cannot get XvdFilesystem from encrypted package");
+
+ return b.ToString();
+ }
+ #endregion
+
+ public void Dispose()
+ {
+ _io.Dispose();
+ }
+ }
+}
diff --git a/LibXboxOne/XVD/XVDLicenseBlock.cs b/LibXboxOne/XVD/XVDLicenseBlock.cs
new file mode 100644
index 0000000..20d2e3b
--- /dev/null
+++ b/LibXboxOne/XVD/XVDLicenseBlock.cs
@@ -0,0 +1,143 @@
+using System;
+
+namespace LibXboxOne
+{
+ public enum XvcLicenseBlockId : uint
+ {
+ // EKB block IDs follow
+
+ EkbUnknown1 = 1, // length 0x2, value 0x5
+ EkbKeyIdString = 2, // length 0x20
+ EkbUnknown2 = 3, // length 0x2, value 0x7
+ EkbUnknown4 = 4, // length 0x1, value 0x31
+ EkbUnknown5 = 5, // length 0x2, value 0x1
+ EkbEncryptedCik = 7, // length 0x180
+
+ // SPLicenseBlock block IDs follow
+
+ LicenseSection = 0x14,
+ Unknown1 = 0x15,
+ Unknown2 = 0x16,
+ UplinkKeyId = 0x18,
+ KeyId = 0x1A,
+ EncryptedCik = 0x1B,
+ DiscIdSection = 0x1C,
+ Unknown3 = 0x1E,
+ Unknown4 = 0x24,
+ DiscId = 0x25,
+ SignatureSection = 0x28,
+ Unknown5 = 0x29,
+ Unknown6 = 0x2C,
+ PossibleHash = 0x2A,
+ PossibleSignature = 0x2B, // length 0x100, could be the encrypted CIK if it's encrypted in the same way as EKB files
+
+ // UWP SPLicenseBlock block IDs follow
+
+ UwpUnknown0 = 0x0,
+ EncryptedDeviceKey = 0x1,
+ DeviceLicenseDeviceId = 0x2,
+ LicenseExpirationTime = 0x20,
+ LicenseInformation = 0xC9,
+ PackedContentKeys = 0xCA,
+ LicenseId = 0xCB,
+ SignatureBlock = 0xCC,
+ LicenseEntryIds = 0xCD,
+ PackageFullName = 0xCE,
+ UwpUnknown1 = 0xCF,
+ HardwareId = 0xD0,
+ UwpUnknown2 = 0xD1,
+ LicenseDeviceId = 0xD2,
+ PollingTime = 0xD3,
+ LicensePolicies = 0xD4,
+ UwpUnknown3 = 0xD5,
+ KeyholderPublicSigningKey = 0xDC,
+ KeyholderPolicies = 0xDD,
+ KeyholderKeyLicenseId = 0xDE,
+ ClepSignState = 0x12D,
+ UwpUnknown4 = 0x12E,
+
+ }
+
+ // XvcLicenseBlock can load in SPLicenseBlock data and EKB data
+ public class XvcLicenseBlock
+ {
+ public XvcLicenseBlockId BlockId;
+ public uint BlockSize;
+ public byte[] BlockData;
+
+ public XvcLicenseBlock BlockDataAsBlock => BlockData.Length < MinBlockLength ? null : new XvcLicenseBlock(BlockData, IsEkbFile);
+
+ public byte[] NextBlockData;
+ public XvcLicenseBlock NextBlockDataAsBlock => NextBlockData.Length < MinBlockLength ? null : new XvcLicenseBlock(NextBlockData, IsEkbFile);
+
+ public bool IsEkbFile;
+
+ public int MinBlockLength = 8;
+
+ public XvcLicenseBlock(byte[] data, bool isEkbFile = false)
+ {
+ IsEkbFile = isEkbFile;
+ int idLen = IsEkbFile ? 2 : 4;
+ int szLen = 4;
+
+ if (data.Length >= idLen)
+ BlockId = (XvcLicenseBlockId)(isEkbFile ? BitConverter.ToUInt16(data, 0) : BitConverter.ToUInt32(data, 0));
+
+ if (isEkbFile && BlockId == (XvcLicenseBlockId)0x4b45)
+ {
+ // if its an ekb file and we read the magic of the EKB skip 2 bytes
+ idLen = 4;
+ BlockId = (XvcLicenseBlockId)BitConverter.ToUInt16(data, 2);
+ }
+
+ if (!isEkbFile && BlockId == (XvcLicenseBlockId)0x31424b45)
+ {
+ // if we're not an EKB file but we read the EKB magic act like its an EKB
+ IsEkbFile = true;
+ idLen = 4;
+ BlockId = (XvcLicenseBlockId)BitConverter.ToUInt16(data, 2);
+ }
+
+ if (data.Length >= idLen + szLen)
+ BlockSize = BitConverter.ToUInt32(data, idLen);
+
+ if (data.Length < BlockSize + (idLen + szLen))
+ return;
+
+ BlockData = new byte[BlockSize];
+ Array.Copy(data, idLen + szLen, BlockData, 0, BlockSize);
+
+ if (data.Length - (BlockSize + (idLen + szLen)) <= 0)
+ return;
+
+ NextBlockData = new byte[data.Length - (BlockSize + (idLen + szLen))];
+ Array.Copy(data, BlockSize + (idLen + szLen), NextBlockData, 0, NextBlockData.Length);
+
+ idLen = IsEkbFile ? 2 : 4;
+ szLen = 4;
+ MinBlockLength = idLen + szLen;
+ }
+ public XvcLicenseBlock GetBlockWithId(XvcLicenseBlockId id)
+ {
+ int idLen = IsEkbFile ? 2 : 4;
+ int szLen = 4;
+
+ if (BlockId == id)
+ return this;
+
+ XvcLicenseBlock block;
+ if (BlockSize > idLen + szLen && BlockSize >= idLen + szLen + BlockDataAsBlock.BlockSize)
+ {
+ block = BlockDataAsBlock.GetBlockWithId(id);
+ if (block != null)
+ return block;
+ }
+
+ if (NextBlockData.Length <= idLen + szLen || NextBlockData.Length < idLen + szLen + NextBlockDataAsBlock.BlockSize)
+ return null;
+
+ block = NextBlockDataAsBlock.GetBlockWithId(id);
+ return block;
+ }
+ }
+}
diff --git a/LibXboxOne/XVD/XVDMount.cs b/LibXboxOne/XVD/XVDMount.cs
new file mode 100644
index 0000000..342d2f5
--- /dev/null
+++ b/LibXboxOne/XVD/XVDMount.cs
@@ -0,0 +1,80 @@
+using System;
+
+namespace LibXboxOne
+{
+ [Flags]
+ public enum XvdMountFlags
+ {
+ None = 0x0,
+ ReadOnly = 0x1,
+ Boot = 0x2, // Used with XvdVmMount
+ MountEmbeddedXvd = 0x8,
+ AsRemovable = 0x20
+ }
+
+ public class XvdMount
+ {
+ public static bool MountXvd(string filepath, string mountPoint, XvdMountFlags flags=0)
+ {
+ // Setup Xvd handle
+ ulong result = Natives.XvdOpenAdapter(out var pHandle);
+
+ if (result != 0x10000000)
+ {
+ Console.WriteLine("XvdOpenAdapter failed. Result: 0x{0:X}", result);
+ return false;
+ }
+
+ result = Natives.XvdMount(out var pDiskHandle, out var diskNum, pHandle, filepath, 0, mountPoint, (int)flags);
+
+ // Check for errors
+ if (result == 0x80070002)
+ {
+ Console.WriteLine("Failed to find XVD file!");
+ }
+ else if (result == 0xC0000043)
+ {
+ Console.WriteLine("Xvd file is already mounted or being used by another process!");
+ }
+ else if (result != 0)
+ {
+ Console.WriteLine("XvdMount error: 0x{0:X}", result);
+ }
+ else
+ {
+ Console.WriteLine($"Package {filepath} attached as disk number {diskNum}");
+ }
+
+ Natives.XvdCloseAdapter(pHandle);
+ return result == 0;
+ }
+
+ public static bool UnmountXvd(string filepath)
+ {
+ // Setup XVD Handle
+ ulong result = Natives.XvdOpenAdapter(out var pHandle);
+
+ if (result != 0x10000000)
+ {
+ Console.WriteLine("XvdOpenAdapter failed. Result: 0x{0:X}", result);
+ return false;
+ }
+
+ // UnMount XVD file
+ result = Natives.XvdUnmountFile(pHandle, filepath);
+
+ //Check for errors
+ if (result == 0x80070002)
+ {
+ Console.WriteLine("Failed to find XVD file!");
+ }
+ else if (result != 0)
+ {
+ Console.WriteLine("XvdMount error: 0x{0:X}", result);
+ }
+
+ Natives.XvdCloseAdapter(pHandle);
+ return result == 0;
+ }
+ }
+}
diff --git a/LibXboxOne/XVD/XVDStructs.cs b/LibXboxOne/XVD/XVDStructs.cs
new file mode 100644
index 0000000..1139522
--- /dev/null
+++ b/LibXboxOne/XVD/XVDStructs.cs
@@ -0,0 +1,643 @@
+using System;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using LibXboxOne.Keys;
+
+namespace LibXboxOne
+{
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct XvdHeader
+ {
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x200)]
+ /* 0x0 */ public byte[] Signature; // RSA signature of the hash of 0x200-0xe00
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
+ /* 0x0 (from signature) */ public char[] Magic; // msft-xvd
+
+ /* 0x8 */ public XvdVolumeFlags VolumeFlags;
+ /* 0xC */ public uint FormatVersion; // 3 in latest xvds
+ /* 0x10 */ public long FileTimeCreated;
+ /* 0x18 */ public ulong DriveSize;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x20 */ public byte[] VDUID; // DriveID / ContentID
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x30 */ public byte[] UDUID; // UserID
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x40 */ public byte[] TopHashBlockHash;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x60 */ public byte[] OriginalXvcDataHash; // hash of XVC data pre-hashtables, with no PDUIDs
+
+ /* 0x80 */ public XvdType Type;
+ /* 0x84 */ public XvdContentType ContentType; // if above 0x1A = not an XVC
+ /* 0x88 */ public uint EmbeddedXVDLength;
+ /* 0x8C */ public uint UserDataLength; // aka Persistent Local Storage ?
+ /* 0x90 */ public uint XvcDataLength;
+ /* 0x94 */ public uint DynamicHeaderLength;
+ /* 0x98 */ public uint BlockSize; // always 0x000AA000, value seems to be used (staticly built into the exe) during xvdsign en/decryption
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x4)]
+ /* 0x9C */ public XvdExtEntry[] ExtEntries;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x8)]
+ /* 0xFC */ public ushort[] Capabilities;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x10C */ public byte[] PECatalogHash;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x12C */ public byte[] EmbeddedXVD_PDUID;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x13C */ public byte[] Reserved13C;
+
+ // encrypted CIK is only used in non-XVC XVDs, field is decrypted with ODK and then used as the CIK to decrypt data blocks
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x14C */ public byte[] KeyMaterial;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
+ /* 0x16C */ public byte[] UserDataHash;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x18C */ public char[] SandboxId;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x19C */ public byte[] ProductId;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x1AC */ public byte[] PDUID; // BuildID, changed with every XVD package creation
+
+ /* 0x1BC */ public ushort PackageVersion1;
+ /* 0x1BE */ public ushort PackageVersion2;
+ /* 0x1C0 */ public ushort PackageVersion3;
+ /* 0x1C2 */ public ushort PackageVersion4;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x1C4 */ public ushort[] PECatalogCaps;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x80)]
+ /* 0x1E4 */ public byte[] PECatalogs;
+
+ /* 0x264 */ public uint WriteableExpirationDate;
+ /* 0x268 */ public uint WriteablePolicyFlags;
+ /* 0x26C */ public uint PersistentLocalStorageSize;
+
+ // NEW FIELDS: only seen in SoDTest windows-XVC!
+ /* 0x270 */ public byte MutableDataPageCount;
+ /* 0x271 */ public byte Unknown271;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x272 */ public byte[] Unknown272;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0xA)]
+ /* 0x282 */ public byte[] Reserved282;
+ /* 0x28C */ public long SequenceNumber;
+ /* 0x294 */ public ushort RequiredSystemVersion1;
+ /* 0x296 */ public ushort RequiredSystemVersion2;
+ /* 0x298 */ public ushort RequiredSystemVersion3;
+ /* 0x29A */ public ushort RequiredSystemVersion4;
+
+ /* 0x29C */ public OdkIndex ODKKeyslotID; // 0x2 for test ODK, 0x0 for retail ODK? (makepkg doesn't set this for test ODK crypted packages?)
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0xB54)]
+ /* 0x2A0 */ public byte[] Reserved2A0;
+ /* 0xDF4 */ public ulong ResilientDataOffset;
+ /* 0xDFC */ public uint ResilientDataLength;
+
+ /* 0xE00 = END */
+
+ public ulong MutableDataLength => XvdMath.PageNumberToOffset(MutableDataPageCount);
+ public ulong UserDataPageCount => XvdMath.BytesToPages(UserDataLength);
+ public ulong XvcInfoPageCount => XvdMath.BytesToPages(XvcDataLength);
+ public ulong EmbeddedXvdPageCount => XvdMath.BytesToPages(EmbeddedXVDLength);
+ public ulong DynamicHeaderPageCount => XvdMath.BytesToPages(DynamicHeaderLength);
+ public ulong DrivePageCount => XvdMath.BytesToPages(DriveSize);
+ public ulong NumberOfHashedPages => DrivePageCount + UserDataPageCount + XvcInfoPageCount + DynamicHeaderPageCount;
+ public ulong NumberOfMetadataPages => UserDataPageCount + XvcInfoPageCount + DynamicHeaderPageCount;
+ public ulong SectorSize => VolumeFlags.HasFlag(XvdVolumeFlags.LegacySectorSize) ?
+ XvdFile.LEGACY_SECTOR_SIZE :
+ XvdFile.SECTOR_SIZE;
+
+ public bool IsSigned
+ {
+ get
+ {
+ // Some console-signed xvds only have 0x10/0x20 bytes of signature area filled
+ // -> Consider such packages unsigned
+ var data = new byte[Signature.Length - 0x20];
+ Array.Copy(Signature, 0x20, data, 0, data.Length);
+ return !data.IsArrayEmpty();
+ }
+ }
+
+ byte[] GetHeaderWithoutSignature()
+ {
+ var rawHeader = Shared.StructToBytes(this);
+ byte[] headerData = new byte[rawHeader.Length - Signature.Length];
+ // Copy headerdata, skipping signature
+ Array.Copy(rawHeader, Signature.Length, headerData, 0, headerData.Length);
+ return headerData;
+ }
+
+ public string SignedBy
+ {
+ get
+ {
+ if (!IsSigned)
+ return "";
+
+ var headerData = GetHeaderWithoutSignature();
+ foreach(var signKey in DurangoKeys.GetAllXvdSigningKeys())
+ {
+ if(signKey.Value.KeyData != null && HashUtils.VerifySignature(signKey.Value.KeyData, Signature, headerData))
+ return signKey.Key;
+ }
+ return "";
+ }
+ }
+
+ public bool Resign(byte[] key, string keyType)
+ {
+ var headerData = GetHeaderWithoutSignature();
+ return HashUtils.SignData(key, keyType, headerData, out Signature);
+ }
+
+ public bool ResignWithRedKey()
+ {
+ var key = DurangoKeys.GetSignkeyByName("RedXvdPrivateKey");
+ if (key == null || !key.HasKeyData)
+ throw new InvalidOperationException("Private Xvd Red key is not loaded, cannot resign xvd header");
+
+ return Resign(key.KeyData, "RSAFULLPRIVATEBLOB");
+ }
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine("XvdHeader:");
+
+ string fmt = formatted ? " " : "";
+
+ if (!Enum.IsDefined(typeof(XvdContentType), ContentType))
+ b.AppendLineSpace(fmt + $"Unknown content type 0x{ContentType:X}");
+
+ b.AppendLineSpace(fmt + $"Signed by: {SignedBy}");
+
+ b.AppendLineSpace(fmt + $"Using ODK keyslot: {ODKKeyslotID}");
+
+ b.AppendLineSpace(fmt + $"Read-only flag {(VolumeFlags.HasFlag(XvdVolumeFlags.ReadOnly) ? "set" : "not set")}");
+
+ b.AppendLineSpace(fmt + (VolumeFlags.HasFlag(XvdVolumeFlags.EncryptionDisabled)
+ ? "Decrypted"
+ : "Encrypted"));
+
+ b.AppendLineSpace(fmt + (VolumeFlags.HasFlag(XvdVolumeFlags.DataIntegrityDisabled)
+ ? "Data integrity disabled (doesn't use hash tree)"
+ : "Data integrity enabled (uses hash tree)"));
+
+ b.AppendLineSpace(fmt + (VolumeFlags.HasFlag(XvdVolumeFlags.LegacySectorSize)
+ ? "Legacy Sector Size (512 bytes)"
+ : "Sector Size (4096 bytes)"));
+
+ b.AppendLineSpace(fmt + $"ResiliencyEnabled {(VolumeFlags.HasFlag(XvdVolumeFlags.ResiliencyEnabled) ? "set" : "not set")}");
+ b.AppendLineSpace(fmt + $"SraReadOnly {(VolumeFlags.HasFlag(XvdVolumeFlags.SraReadOnly) ? "set" : "not set")}");
+
+ b.AppendLineSpace(fmt + $"RegionIdInXts {(VolumeFlags.HasFlag(XvdVolumeFlags.RegionIdInXts) ? "set" : "not set")}");
+ b.AppendLineSpace(fmt + $"EraSpecific {(VolumeFlags.HasFlag(XvdVolumeFlags.EraSpecific) ? "set" : "not set")}");
+
+ b.AppendLine();
+
+ b.AppendLineSpace(fmt + $"Magic: {new string(Magic)}");
+ b.AppendLineSpace(fmt + $"Volume Flags: 0x{VolumeFlags:X}");
+ b.AppendLineSpace(fmt + $"Format Version: 0x{FormatVersion:X}");
+
+ b.AppendLineSpace(fmt + $"File Time Created: {DateTime.FromFileTime(FileTimeCreated)}");
+ b.AppendLineSpace(fmt + $"Drive Size: 0x{DriveSize:X}");
+
+ b.AppendLineSpace(fmt + $"VDUID / Drive Id: {new Guid(VDUID)}");
+ b.AppendLineSpace(fmt + $"UDUID / User Id: {new Guid(UDUID)}");
+
+ b.AppendLineSpace(fmt + $"Top Hash Block Hash: {Environment.NewLine}{fmt}{TopHashBlockHash.ToHexString()}");
+ b.AppendLineSpace(fmt + $"Original XVC Data Hash: {Environment.NewLine}{fmt}{OriginalXvcDataHash.ToHexString()}");
+
+ b.AppendLineSpace(fmt + $"XvdType: {Type}");
+ b.AppendLineSpace(fmt + $"Content Type: 0x{ContentType:X} ({ContentType})");
+ b.AppendLineSpace(fmt + $"Embedded XVD PDUID/Build Id: {new Guid(EmbeddedXVD_PDUID)}");
+ b.AppendLineSpace(fmt + $"Embedded XVD Length: 0x{EmbeddedXVDLength:X}");
+ b.AppendLineSpace(fmt + $"User Data Length: 0x{UserDataLength:X}");
+ b.AppendLineSpace(fmt + $"XVC Data Length: 0x{XvcDataLength:X}");
+ b.AppendLineSpace(fmt + $"Dynamic Header Length: 0x{DynamicHeaderLength:X}");
+ b.AppendLineSpace(fmt + $"BlockSize: 0x{BlockSize:X}");
+ b.AppendLineSpace(fmt + $"Ext Entries: {ExtEntries.Count(e => !e.IsEmpty)}");
+ foreach(XvdExtEntry entry in ExtEntries.Where(e => !e.IsEmpty))
+ b.AppendLineSpace(fmt + entry.ToString(true));
+
+ b.AppendLineSpace(fmt + $"Capabilities: {Capabilities.ToHexString()}");
+
+ b.AppendLineSpace(fmt + $"PE Catalog Hash: {PECatalogHash.ToHexString()}");
+ b.AppendLineSpace(fmt + $"Userdata hash: {UserDataHash.ToHexString()}");
+
+ b.AppendLineSpace(fmt + $"PE Catalog Caps: {PECatalogCaps.ToHexString()}");
+ b.AppendLineSpace(fmt + $"PE Catalogs: {PECatalogs.ToHexString()}");
+
+ b.AppendLineSpace(fmt + $"Writeable Expiration Date: 0x{WriteableExpirationDate:X}");
+ b.AppendLineSpace(fmt + $"Writeable Policy flags: 0x{WriteablePolicyFlags:X}");
+ b.AppendLineSpace(fmt + $"Persistent Local storage length: 0x{PersistentLocalStorageSize:X}");
+ b.AppendLineSpace(fmt + $"Mutable data page count: 0x{MutableDataPageCount:X} (0x{MutableDataLength:X} bytes)");
+
+ b.AppendLineSpace(fmt + $"Sandbox Id: {new string(SandboxId).Replace("\0", "")}");
+ b.AppendLineSpace(fmt + $"Product Id: {new Guid(ProductId)}");
+ b.AppendLineSpace(fmt + $"PDUID/Build Id: {new Guid(PDUID)}");
+ b.AppendLineSpace(fmt + $"Sequence Number: {SequenceNumber}");
+ b.AppendLineSpace(fmt + $"Package Version: {PackageVersion4}.{PackageVersion3}.{PackageVersion2}.{PackageVersion1}");
+ b.AppendLineSpace(fmt + $"Required System Version: {RequiredSystemVersion4}.{RequiredSystemVersion3}.{RequiredSystemVersion2}.{RequiredSystemVersion1}");
+ b.AppendLineSpace(fmt + $"ODK Keyslot ID: {ODKKeyslotID}");
+ b.AppendLineSpace(fmt + $"KeyMaterial: {Environment.NewLine}{fmt}{KeyMaterial.ToHexString()}");
+ b.AppendLineSpace(fmt + $"Resilient Data offset: 0x{ResilientDataOffset:X}");
+ b.AppendLineSpace(fmt + $"Resilient Data length: 0x{ResilientDataLength:X}");
+
+ if (Unknown271 != 0)
+ b.AppendLineSpace(fmt + $"Unknown271: 0x{Unknown271:X}");
+
+ if (!Unknown272.IsArrayEmpty())
+ b.AppendLineSpace(fmt + $"Unknown272: {Unknown272.ToHexString()}");
+
+ if (!Reserved13C.IsArrayEmpty())
+ b.AppendLineSpace(fmt + $"Reserved13C: {Environment.NewLine}{fmt}{Reserved13C.ToHexString()}");
+ if (!Reserved13C.IsArrayEmpty())
+ b.AppendLineSpace(fmt + $"Reserved13C: {Environment.NewLine}{fmt}{Reserved13C.ToHexString()}");
+ if (!Reserved2A0.IsArrayEmpty())
+ b.AppendLineSpace(fmt + $"Reserved2A0: {Environment.NewLine}{fmt}{Reserved2A0.ToHexString()}");
+
+ return b.ToString();
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvdExtEntry
+ {
+ /* 0x00 */ public uint Code;
+ /* 0x04 */ public uint Length;
+ /* 0x08 */ public ulong Offset;
+ /* 0x10 */ public uint DataLength;
+ /* 0x14 */ public uint Reserved;
+
+ /* 0x18 = END */
+
+ public bool IsEmpty => Code == 0 && Length == 0 && Offset == 0 && DataLength == 0 && Reserved == 0;
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ string fmt = formatted ? " " : "";
+ return fmt + $"XvdExtEntry: Code: {Code:X}, Length: {Length:X}, Offset: {Offset:X}, DataLength: {DataLength:X}";
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ public struct XvcUpdateSegment
+ {
+ /* 0x0 */ public uint PageNum;
+ /* 0x4 */ public ulong Hash;
+
+ /* 0xC = END */
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine("XvcUpdateSegment");
+ b.AppendLine();
+
+ string fmt = formatted ? " " : "";
+
+ b.AppendLineSpace(fmt + $"PageNum: 0x{PageNum:X} (@ 0x{XvdMath.PageNumberToOffset(PageNum)})");
+ b.AppendLineSpace(fmt + $"Hash: 0x{Hash:X}");
+
+ return b.ToString();
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvcRegionSpecifier
+ {
+ /* 0x0 */ public XvcRegionId RegionId;
+ /* 0x4 */ public uint Padding4;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x40)]
+ /* 0x8 */ public string Key;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x80)]
+ /* 0x88 */ public string Value;
+
+ /* 0x188 = END */
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine("XvcRegionSpecifier");
+ b.AppendLine();
+
+ string fmt = formatted ? " " : "";
+
+ b.AppendLineSpace(fmt + $"Region ID: 0x{(uint)RegionId:X} {RegionId})");
+ b.AppendLineSpace(fmt + $"Key: {Key}");
+ b.AppendLineSpace(fmt + $"Value: {Value}");
+
+ if (Padding4 != 0)
+ b.AppendLineSpace(fmt + $"Padding4: 0x{Padding4:X}");
+
+ return b.ToString();
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvcRegionHeader
+ {
+ /* 0x0 */ public XvcRegionId Id;
+ /* 0x4 */ public ushort KeyId;
+ /* 0x6 */ public ushort Padding6;
+ /* 0x8 */ public XvcRegionFlags Flags;
+ /* 0xC */ public uint FirstSegmentIndex;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
+ /* 0x10 */ public string Description; // XVC-HD = Header, XVC-EXVD = Embedded XVD, XVC-MD = XVC metadata, FS-MD = FileSystem metadata
+
+ /* 0x50 */ public ulong Offset;
+ /* 0x58 */ public ulong Length;
+ /* 0x60 */ public ulong Hash; // aka RegionPDUID
+
+ /* 0x68 */ public ulong Unknown68;
+ /* 0x70 */ public ulong Unknown70;
+ /* 0x78 */ public ulong Unknown78;
+
+ /* 0x80 = END */
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine($"XvcRegionHeader (ID/EncryptionIV: 0x{(uint)Id:X} {Id}):");
+
+ string fmt = formatted ? " " : "";
+
+ if (Padding6 != 0)
+ b.AppendLineSpace(fmt + "Padding6 != 0");
+ if (Unknown68 != 0)
+ b.AppendLineSpace(fmt + "Unknown68 != 0");
+ if (Unknown70 != 0)
+ b.AppendLineSpace(fmt + "Unknown70 != 0");
+ if (Unknown78 != 0)
+ b.AppendLineSpace(fmt + "Unknown78 != 0");
+
+ string keyid = KeyId.ToString("X");
+ if (KeyId == XvcConstants.XVC_KEY_NONE)
+ keyid += " (not encrypted)";
+ b.AppendLineSpace(fmt + $"Description: {Description.Replace("\0", "")}");
+ b.AppendLineSpace(fmt + $"Key ID: 0x{keyid}");
+ b.AppendLineSpace(fmt + $"Flags: 0x{(uint)Flags:X}");
+ if (Flags.HasFlag(XvcRegionFlags.Resident))
+ b.AppendLineSpace(fmt + " - Resident");
+ if (Flags.HasFlag(XvcRegionFlags.InitialPlay))
+ b.AppendLineSpace(fmt + " - InitialPlay");
+ if (Flags.HasFlag(XvcRegionFlags.Preview))
+ b.AppendLineSpace(fmt + " - Preview");
+ if (Flags.HasFlag(XvcRegionFlags.FileSystemMetadata))
+ b.AppendLineSpace(fmt + " - FileSystemMetadata");
+ if (Flags.HasFlag(XvcRegionFlags.Present))
+ b.AppendLineSpace(fmt + " - Present");
+ if (Flags.HasFlag(XvcRegionFlags.OnDemand))
+ b.AppendLineSpace(fmt + " - OnDemand");
+ if (Flags.HasFlag(XvcRegionFlags.Available))
+ b.AppendLineSpace(fmt + " - Available");
+
+ b.AppendLineSpace(fmt + $"Offset: 0x{Offset:X}");
+ b.AppendLineSpace(fmt + $"Length: 0x{Length:X}");
+ b.AppendLineSpace(fmt + $"Hash: 0x{Hash:X}");
+ b.AppendLineSpace(fmt + $"First Segment Index: {FirstSegmentIndex}");
+ b.AppendLine();
+
+ if (Unknown68 != 0)
+ b.AppendLineSpace(fmt + $"Unknown68: 0x{Unknown68:X}");
+ if (Unknown70 != 0)
+ b.AppendLineSpace(fmt + $"Unknown70: 0x{Unknown70:X}");
+ if (Unknown78 != 0)
+ b.AppendLineSpace(fmt + $"Unknown78: 0x{Unknown78:X}");
+ if (Padding6 != 0)
+ b.AppendLineSpace(fmt + $"Padding6: 0x{Padding6:X}");
+
+ return b.ToString();
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct XvcEncryptionKeyId
+ {
+ public bool IsKeyNulled => KeyId == null || KeyId.IsArrayEmpty();
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ public byte[] KeyId;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+ public struct XvcInfo
+ {
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x0 */ public byte[] ContentID;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0xC0)]
+ /* 0x10 */ public XvcEncryptionKeyId[] EncryptionKeyIds;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x100)]
+ /* 0xC10 */ public byte[] Description; // unicode?
+
+ /* 0xD10 */ public uint Version;
+ /* 0xD14 */ public uint RegionCount;
+ /* 0xD18 */ public uint Flags;
+ /* 0xD1C */ public ushort PaddingD1C;
+ /* 0xD1E */ public ushort KeyCount;
+ /* 0xD20 */ public uint UnknownD20;
+ /* 0xD24 */ public uint InitialPlayRegionId;
+ /* 0xD28 */ public ulong InitialPlayOffset;
+ /* 0xD30 */ public long FileTimeCreated;
+ /* 0xD38 */ public uint PreviewRegionId;
+ /* 0xD3C */ public uint UpdateSegmentCount;
+ /* 0xD40 */ public ulong PreviewOffset;
+ /* 0xD48 */ public ulong UnusedSpace;
+ /* 0xD50 */ public uint RegionSpecifierCount;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x54)]
+ /* 0xD54 */ public byte[] ReservedD54;
+
+ /* 0xDA8 = END (actually 0x2000 but rest is read in XVDFile class) */
+
+ public bool IsUsingTestCik
+ {
+ get
+ {
+ Guid testCik = new Guid("33EC8436-5A0E-4F0D-B1CE-3F29C3955039");
+ return EncryptionKeyIds != null &&
+ EncryptionKeyIds.Length > 0 &&
+ EncryptionKeyIds[0].KeyId.IsEqualTo(testCik.ToByteArray());
+ }
+ }
+
+ public bool IsAnyKeySet
+ {
+ get { return EncryptionKeyIds.Any(keyId => !keyId.IsKeyNulled); }
+ }
+
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine("XvcInfo:");
+
+ string fmt = formatted ? " " : "";
+
+ if (Flags != 0)
+ b.AppendLineSpace(fmt + "Flags != 0");
+ if (PaddingD1C != 0)
+ b.AppendLineSpace(fmt + "PaddingD1C != 0");
+ if (UnknownD20 != 0)
+ b.AppendLineSpace(fmt + "UnknownD20 != 0");
+ if (PreviewRegionId != 0)
+ b.AppendLineSpace(fmt + "PreviewRegionId != 0");
+ if (PreviewOffset != 0)
+ b.AppendLineSpace(fmt + "PreviewOffset != 0");
+ if (UnusedSpace != 0)
+ b.AppendLineSpace(fmt + "UnusedSpace != 0");
+ if (!ReservedD54.IsArrayEmpty())
+ b.AppendLineSpace(fmt + "Reserved != null");
+
+ var signType = "Unsigned/not crypted (/LU)";
+ if (KeyCount > 0)
+ if (IsUsingTestCik)
+ signType = "Test-crypted (/LT)";
+ else if (!IsAnyKeySet)
+ signType = "Unsigned with KeyCount > 0";
+ else
+ signType = "Submission-crypted (not using test key) (/L)";
+
+ b.AppendLineSpace(fmt + signType);
+ b.AppendLineSpace(fmt + $"/updcompat type {(UpdateSegmentCount == 0 ? "1" : "2")}");
+
+ b.AppendLine();
+
+ b.AppendLineSpace(fmt + $"ContentID: {new Guid(ContentID)}");
+ for(int i = 0; i < EncryptionKeyIds.Length; i++)
+ if(!EncryptionKeyIds[i].IsKeyNulled)
+ b.AppendLineSpace(fmt + $"Encryption Key {i} GUID: {new Guid(EncryptionKeyIds[i].KeyId)}");
+
+ b.AppendLine();
+
+ b.AppendLineSpace(fmt + $"Description: {Encoding.Unicode.GetString(Description).Replace("\0", "")}");
+ b.AppendLineSpace(fmt + $"Version: 0x{Version:X}");
+ b.AppendLineSpace(fmt + $"Region Count: 0x{RegionCount:X}");
+ b.AppendLineSpace(fmt + $"Flags: 0x{Flags:X}");
+ b.AppendLineSpace(fmt + $"Key Count: 0x{KeyCount:X}");
+ b.AppendLineSpace(fmt + $"InitialPlay Region Id: 0x{InitialPlayRegionId:X}");
+ b.AppendLineSpace(fmt + $"InitialPlay Offset: 0x{InitialPlayOffset:X}");
+ b.AppendLineSpace(fmt + $"File Time Created: {DateTime.FromFileTime(FileTimeCreated)}");
+ b.AppendLineSpace(fmt + $"Preview Region Id: 0x{PreviewRegionId:X}");
+ b.AppendLineSpace(fmt + $"Update Segment Count: {UpdateSegmentCount}");
+ b.AppendLineSpace(fmt + $"Preview Offset: 0x{PreviewOffset:X}");
+ b.AppendLineSpace(fmt + $"Unused Space: 0x{UnusedSpace:X}");
+ b.AppendLine();
+
+ if (PaddingD1C != 0)
+ b.AppendLineSpace(fmt + $"PaddingD1C: 0x{PaddingD1C:X}");
+
+ if (UnknownD20 != 0)
+ b.AppendLineSpace(fmt + $"UnknownD20: 0x{UnknownD20:X}");
+
+ if (!ReservedD54.IsArrayEmpty())
+ b.AppendLineSpace(fmt + $"ReservedD54: {Environment.NewLine}{fmt}{ReservedD54.ToHexString()}");
+
+ return b.ToString();
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvdUserDataHeader
+ {
+ /* 0x0 */ public uint Length;
+ /* 0x4 */ public uint Version;
+ /* 0x8 */ public XvdUserDataType Type; // Only 0?
+ /* 0xc */ public uint Unknown; // thought this was data length, but apparently it isn't
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvdUserDataPackageFilesHeader
+ {
+ /* 0x0 */ public uint Version;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
+ /* 0x4 */ public string PackageFullName;
+ /* 0x108 */ public uint FileCount;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvdUserDataPackageFileEntry
+ {
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
+ /* 0x0 */ public string FilePath;
+ /* 0x104 */ public uint Size;
+ /* 0x108 */ public uint Offset;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public struct XvdSegmentMetadataHeader
+ {
+ /* 0x0 */ public uint Magic; // 20 50 46 58 (' PFX' / 'XFP ')
+ /* 0x4 */ public uint Version0; // 4 is currently used
+ /* 0x8 */ public uint Version1;
+ /* 0xc */ public uint HeaderLength;
+ /* 0x10 */ public uint SegmentCount;
+ /* 0x14 */ public uint FilePathsLength; // BlockSize?
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
+ /* 0x18 */ public byte[] PDUID;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3c)]
+ /* 0x28 */
+ public byte[] Unknown;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1, Size = 0x10)]
+ public struct XvdSegmentMetadataSegment
+ {
+ /* 0x0 */ public XvdSegmentMetadataSegmentFlags Flags;
+ /* 0x2 */ public ushort PathLength;
+ /* 0x4 */ public uint PathOffset;
+ /* 0x8 */ public ulong FileSize;
+ }
+}
diff --git a/LibXboxOne/XVD/XvcConstants.cs b/LibXboxOne/XVD/XvcConstants.cs
new file mode 100644
index 0000000..f56f9b3
--- /dev/null
+++ b/LibXboxOne/XVD/XvcConstants.cs
@@ -0,0 +1,7 @@
+namespace LibXboxOne
+{
+ public static class XvcConstants
+ {
+ public const ushort XVC_KEY_NONE = 0xFFFF;
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/XVD/XvcRegionId.cs b/LibXboxOne/XVD/XvcRegionId.cs
new file mode 100644
index 0000000..88dba24
--- /dev/null
+++ b/LibXboxOne/XVD/XvcRegionId.cs
@@ -0,0 +1,12 @@
+namespace LibXboxOne
+{
+ public enum XvcRegionId : uint
+ {
+ MetadataXvc = 0x40000001,
+ MetadataFilesystem = 0x40000002,
+ Unknown = 0x40000003,
+ EmbeddedXvd = 0x40000004,
+ Header = 0x40000005,
+ MutableData = 0x40000006
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/XVD/XvdFilesystem.cs b/LibXboxOne/XVD/XvdFilesystem.cs
new file mode 100644
index 0000000..adeb086
--- /dev/null
+++ b/LibXboxOne/XVD/XvdFilesystem.cs
@@ -0,0 +1,351 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Diagnostics;
+using DiscUtils;
+using DiscUtils.Ntfs;
+using DiscUtils.Partitions;
+using DiscUtils.Streams;
+
+namespace LibXboxOne
+{
+ public class XvdFilesystem
+ {
+ XvdFile _xvdFile { get; }
+ XvdFilesystemStream _fs { get; }
+
+ XvdType XvdFsType => _xvdFile.Header.Type;
+ uint SectorSize => (uint)_xvdFile.Header.SectorSize;
+ ulong FilesystemSize => _xvdFile.Header.DriveSize;
+ Geometry DiskGeometry =>
+ Geometry.FromCapacity((long)FilesystemSize, (int)SectorSize);
+
+ const long CHUNK_SIZE = (16 * 1024 * 1024); // 16 MB
+
+ public XvdFilesystem(XvdFile file)
+ {
+ _xvdFile = file;
+ _fs = new XvdFilesystemStream(_xvdFile);
+ }
+
+ bool GetGptPartitionTable(out GuidPartitionTable partitionTable)
+ {
+ try
+ {
+ partitionTable = new GuidPartitionTable(_fs, DiskGeometry);
+ }
+ catch (Exception)
+ {
+ partitionTable = null;
+ }
+
+ // CHECKME: Count refers to the number of PARTITION TABLES, not partitions?
+ if (partitionTable == null || partitionTable.Count <= 0)
+ {
+ Debug.WriteLine("No GPT partition table detected");
+ return false;
+ }
+
+ return true;
+ }
+
+ bool GetMbrPartitionTable(out BiosPartitionTable partitionTable)
+ {
+ try
+ {
+ partitionTable = new BiosPartitionTable(_fs, DiskGeometry);
+ }
+ catch (Exception)
+ {
+ partitionTable = null;
+ }
+
+ // CHECKME: Count refers to the number of PARTITION TABLES, not partitions?
+ if (partitionTable == null || partitionTable.Count <= 0)
+ {
+ Debug.WriteLine("No MBR partition table detected");
+ return false;
+ }
+
+ return true;
+ }
+
+ PartitionTable OpenDisk()
+ {
+ // Gathering partitions manually so Geometry can be provided
+ // explicitly. This ensures that 4k sectors are properly set.
+ PartitionTable partitionTable;
+ if (GetGptPartitionTable(out GuidPartitionTable gptTable))
+ {
+ partitionTable = (PartitionTable)gptTable;
+ }
+ else if (GetMbrPartitionTable(out BiosPartitionTable mbrTable))
+ {
+ partitionTable = (PartitionTable)mbrTable;
+ }
+ else
+ {
+ Debug.WriteLine("No valid partition table detected");
+ return null;
+ }
+
+ if (partitionTable.Partitions == null || partitionTable.Partitions.Count <= 0)
+ {
+ Debug.WriteLine("Partition table holds no partitions");
+ return null;
+ }
+
+ return partitionTable;
+ }
+
+ IEnumerable IterateFilesystem(int partitionNumber)
+ {
+ IEnumerable IterateSubdir(DiscUtils.DiscDirectoryInfo subdir)
+ {
+ foreach(var dir in subdir.GetDirectories())
+ {
+ foreach(var subfile in IterateSubdir(dir))
+ {
+ yield return subfile;
+ }
+ }
+
+ var files = subdir.GetFiles();
+ foreach(var f in files)
+ {
+ yield return f;
+ }
+ }
+
+ PartitionTable disk = OpenDisk();
+ if (disk == null)
+ {
+ Debug.WriteLine("IterateFilesystem: Failed to open disk");
+ yield break;
+ }
+ else if (disk.Partitions.Count - 1 < partitionNumber)
+ {
+ Debug.WriteLine($"IterateFilesystem: Partition {partitionNumber} does not exist");
+ yield break;
+ }
+
+ using (var partitionStream = disk.Partitions[partitionNumber].Open())
+ {
+ NtfsFileSystem fs = new DiscUtils.Ntfs.NtfsFileSystem(partitionStream);
+
+ foreach(var file in IterateSubdir(fs.Root))
+ {
+ yield return file;
+ }
+
+ fs.Dispose();
+ partitionStream.Dispose();
+ }
+ }
+
+ public bool ExtractFilesystem(string outputDirectory, int partitionNumber=0)
+ {
+ foreach (var file in IterateFilesystem(partitionNumber))
+ {
+ Console.WriteLine(file.DirectoryName + file.Name);
+ /* Assemble destination path and create directory */
+ var destDir = outputDirectory;
+ var parentDirs = file.DirectoryName.Split('\\');
+ foreach(var pd in parentDirs)
+ {
+ destDir = Path.Combine(destDir, pd);
+ }
+ Directory.CreateDirectory(destDir);
+
+ /* Write out file */
+ var destFile = Path.Combine(destDir, file.Name);
+ using(var srcFile = file.OpenRead())
+ {
+ using(var dstFs = File.Create(destFile))
+ {
+ while(dstFs.Length < srcFile.Length)
+ {
+ var readSize = Math.Min(CHUNK_SIZE, srcFile.Length - srcFile.Position);
+ var data = new byte[readSize];
+ if (srcFile.Read(data, 0, data.Length) != data.Length)
+ throw new InvalidOperationException(
+ $"Failed to read {srcFile} from raw image");
+
+ dstFs.Write(data, 0, data.Length);
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public bool ExtractFilesystemImage(string targetFile, bool createVhd)
+ {
+ using (var destFs = File.Open(targetFile, FileMode.Create))
+ {
+ byte[] buffer = new byte[XvdFile.PAGE_SIZE];
+
+ for (long offset = 0; offset < _fs.Length; offset += XvdFile.PAGE_SIZE)
+ {
+ _fs.Read(buffer, 0, buffer.Length);
+ destFs.Write(buffer, 0, buffer.Length);
+ }
+ }
+ return true;
+ }
+
+ void InitializeVhdManually(DiscUtils.Vhd.Disk vhdDisk)
+ {
+ BiosPartitionTable.Initialize(vhdDisk, WellKnownPartitionType.WindowsNtfs);
+ // GuidPartitionTable.Initialize(vhdDisk, WellKnownPartitionType.WindowsNtfs);
+
+ var volMgr = new VolumeManager(vhdDisk);
+ var logicalVolume = volMgr.GetLogicalVolumes()[0];
+
+ var label = $"XVDTool conversion";
+
+ using (var destNtfs = NtfsFileSystem.Format(logicalVolume, label, new NtfsFormatOptions()))
+ {
+ destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;
+
+ // NOTE: For VHD creation we just assume a single partition
+ foreach (var file in IterateFilesystem(partitionNumber: 0))
+ {
+ var fh = file.OpenRead();
+
+ if (!destNtfs.Exists(file.DirectoryName))
+ {
+ destNtfs.CreateDirectory(file.DirectoryName);
+ }
+
+ using (Stream dest = destNtfs.OpenFile(file.FullName, FileMode.Create,
+ FileAccess.ReadWrite))
+ {
+ fh.CopyTo(dest);
+ dest.Flush();
+ }
+
+ fh.Close();
+ }
+ }
+ }
+
+ void InitializeVhdViaPump(DiscUtils.Vhd.Disk vhdDisk)
+ {
+ if (SectorSize != XvdFile.LEGACY_SECTOR_SIZE)
+ {
+ throw new InvalidOperationException(
+ "Initializing VHD via pump is only supported for 512 byte sectors");
+ }
+
+ var pump = new StreamPump(_fs, vhdDisk.Content, (int)XvdFile.LEGACY_SECTOR_SIZE);
+ pump.Run();
+ }
+
+ // Source: https://github.com/DiscUtils/DiscUtils/issues/137
+ public bool ConvertToVhd(string outputFile)
+ {
+ using (FileStream destVhdFs = File.Open(outputFile, FileMode.Create, FileAccess.ReadWrite))
+ {
+ DiscUtils.Vhd.Disk vhdDisk;
+ if (XvdFsType == XvdType.Fixed)
+ {
+ Console.WriteLine("Initializing fixed VHD...");
+ vhdDisk = DiscUtils.Vhd.Disk.InitializeFixed(destVhdFs,
+ Ownership.None,
+ (long)FilesystemSize
+ + (long)(FilesystemSize / 10));
+ }
+ else if (XvdFsType == XvdType.Dynamic)
+ {
+ Console.WriteLine("Initializing dynamic VHD...");
+ vhdDisk = DiscUtils.Vhd.Disk.InitializeDynamic(destVhdFs,
+ Ownership.None,
+ (long)FilesystemSize
+ + (long)(FilesystemSize / 10));
+ }
+ else
+ throw new InvalidOperationException();
+
+ if (SectorSize == XvdFile.LEGACY_SECTOR_SIZE)
+ {
+ Console.WriteLine("Pumping data as-is to vhd (legacy sector size)");
+ InitializeVhdViaPump(vhdDisk);
+ }
+ else
+ {
+ Console.WriteLine("Creating vhd manually (4k sectors)");
+ InitializeVhdManually(vhdDisk);
+ }
+ }
+ return true;
+ }
+
+ public string FileInfoToString(DiscFileInfo info)
+ {
+ return $"{info.FullName} ({info.Length} bytes)";
+ }
+
+ public override string ToString()
+ {
+ return ToString(true);
+ }
+
+ public string ToString(bool formatted)
+ {
+ var b = new StringBuilder();
+ b.AppendLine("XvdFilesystem:");
+
+ string fmt = formatted ? " " : "";
+
+ if (_xvdFile.IsEncrypted)
+ {
+ b.AppendLineSpace(fmt + "Cannot get XvdFilesystem info from encrypted package");
+ return b.ToString();
+ }
+
+ var disk = OpenDisk();
+ if (disk == null)
+ {
+ b.AppendLineSpace(fmt + "No partition table found on disk!");
+ return b.ToString();
+ }
+
+ b.AppendLineSpace(fmt + "Partitions:");
+ var partitions = disk.Partitions;
+ for (int i = 0; i < partitions.Count; i++)
+ {
+ var part = partitions[i];
+ b.AppendLineSpace(fmt + fmt + $"- Partition {i}:");
+
+ b.AppendLineSpace(fmt + fmt + fmt + $" BIOS-type: {part.TypeAsString} ({part.BiosType} / 0x{part.BiosType:X})");
+ b.AppendLineSpace(fmt + fmt + fmt + $" GUID-type: {part.GuidType}");
+ b.AppendLineSpace(fmt + fmt + fmt + $" First sector: {part.FirstSector} (0x{part.FirstSector:X})");
+ b.AppendLineSpace(fmt + fmt + fmt + $" Last sector: {part.LastSector} (0x{part.LastSector:X})");
+ b.AppendLineSpace(fmt + fmt + fmt + $" Sector count: {part.SectorCount} (0x{part.SectorCount:X})");
+ b.AppendLine();
+ }
+
+ b.AppendLineSpace(fmt + "Filesystem content:");
+ try
+ {
+ for (int partitionNumber = 0; partitionNumber < partitions.Count; partitionNumber++)
+ {
+ b.AppendLineSpace(fmt + fmt + $":: Partition {partitionNumber}:");
+ foreach (var file in IterateFilesystem(partitionNumber))
+ {
+ b.AppendLineSpace(fmt + fmt + FileInfoToString(file));
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ b.AppendLineSpace(fmt + fmt + $"Failed to list filesystem content. Error: {e}");
+ }
+
+ return b.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/XVD/XvdFilesystemStream.cs b/LibXboxOne/XVD/XvdFilesystemStream.cs
new file mode 100644
index 0000000..0c82ac2
--- /dev/null
+++ b/LibXboxOne/XVD/XvdFilesystemStream.cs
@@ -0,0 +1,152 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace LibXboxOne
+{
+ public class XvdFilesystemStream : Stream
+ {
+ readonly XvdFile _xvdFile;
+
+ public override bool CanRead => true;
+ public override bool CanSeek => true;
+ // Disable writing for now
+ public override bool CanWrite => false;
+
+ public override long Length => (long)_xvdFile.Header.DriveSize;
+ public override long Position { get; set; }
+
+ // Absolute offset in Xvd of DriveData start
+ long DriveBaseOffset => (long)_xvdFile.DriveDataOffset;
+ // Absolute offset to use for calculation BAT target offset
+ long DynamicBaseOffset => (long)_xvdFile.DynamicBaseOffset;
+ // Length of static data for XvdType.Dynamic
+ long StaticDataLength => (long)_xvdFile.StaticDataLength;
+
+ public XvdFilesystemStream(XvdFile file)
+ {
+ _xvdFile = file;
+ Position = 0;
+ }
+
+ public override void Flush()
+ {
+ }
+
+ byte[] InternalRead(int count)
+ {
+ var offset = DriveBaseOffset + Position;
+ return InternalReadAbsolute(offset, count);
+ }
+
+ byte[] InternalReadAbsolute(long offset, int count)
+ {
+ Debug.WriteLine($"InternalReadAbsolute: Reading 0x{count:X} @ 0x{offset:X}");
+ var data = _xvdFile.ReadBytes(offset, count);
+ if (data.Length <= 0)
+ throw new IOException("InternalReadAbsolute got nothing...");
+
+ // Debug.WriteLine($"Got {data.Length:X} bytes: {data.ToHexString("")}");
+ Position += data.Length;
+ return data;
+ }
+
+ byte[] ReadDynamic(int count)
+ {
+ int positionInBuffer = 0;
+ int bytesRemaining = count;
+ byte[] destBuffer = new byte[count];
+
+ while (positionInBuffer < count)
+ {
+ byte[] data = new byte[0];
+ if (Position < StaticDataLength)
+ {
+ // Read a chunk from non-dynamic area, next iteration will read dynamic data
+ int maxReadLength = (int)(StaticDataLength - Position);
+ int length = bytesRemaining > maxReadLength ? maxReadLength : bytesRemaining;
+ data = InternalRead(length);
+ }
+ else
+ {
+ // Lookup block allocation table for real data offset
+ var targetVirtualOffset = (ulong)(Position - StaticDataLength);
+ ulong blockNumber = XvdMath.OffsetToBlockNumber(targetVirtualOffset);
+ long inBlockOffset = (long)XvdMath.InBlockOffset(targetVirtualOffset);
+ int maxReadLength = (int)(XvdFile.BLOCK_SIZE - inBlockOffset);
+ int length = bytesRemaining > maxReadLength ? maxReadLength : bytesRemaining;
+
+ var targetPage = _xvdFile.ReadBat(blockNumber);
+ if (targetPage == XvdFile.INVALID_SECTOR)
+ {
+ data = new byte[length];
+ // Advance stream position cause we are not actually reading data
+ Position += length;
+ }
+ else
+ {
+ long targetPhysicalOffset = DynamicBaseOffset
+ + (long)XvdMath.PageNumberToOffset(targetPage)
+ + inBlockOffset;
+
+ data = InternalReadAbsolute(targetPhysicalOffset, length);
+ }
+ }
+
+ Array.Copy(data, 0, destBuffer, positionInBuffer, data.Length);
+ positionInBuffer += data.Length;
+ bytesRemaining -= data.Length;
+ }
+
+ return destBuffer;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ byte[] dataRead;
+
+ if (Position + count > Length)
+ throw new IOException("Desired range out-of-bounds for stream");
+ else if (offset + count > buffer.Length)
+ throw new IOException("Target buffer to small to hold read data");
+
+ else if (_xvdFile.Header.Type == XvdType.Fixed)
+ dataRead = InternalRead(count);
+ else if (_xvdFile.Header.Type == XvdType.Dynamic)
+ dataRead = ReadDynamic(count);
+
+ else
+ throw new IOException($"Unsupported XvdType: {_xvdFile.Header.Type}");
+
+ Array.Copy(dataRead, 0, buffer, offset, count);
+ return dataRead.Length;
+ }
+
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ switch (origin)
+ {
+ case SeekOrigin.Begin:
+ Position = offset;
+ break;
+ case SeekOrigin.Current:
+ Position += offset;
+ break;
+ case SeekOrigin.End:
+ Position = Length + offset;
+ break;
+ }
+ return Position;
+ }
+
+ public override void SetLength(long value)
+ {
+ throw new NotImplementedException();
+ }
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibXboxOne/XVD/XvdMath.cs b/LibXboxOne/XVD/XvdMath.cs
new file mode 100644
index 0000000..0639314
--- /dev/null
+++ b/LibXboxOne/XVD/XvdMath.cs
@@ -0,0 +1,188 @@
+using System;
+
+namespace LibXboxOne
+{
+ public static class XvdMath
+ {
+ public static bool PagesAligned(ulong page)
+ {
+ return (page & (XvdFile.PAGE_SIZE - 1)) == 0;
+ }
+
+ public static ulong PageAlign(ulong offset)
+ {
+ return offset & 0xFFFFFFFFFFFFF000;
+ }
+
+ public static ulong InBlockOffset(ulong offset)
+ {
+ return offset - ((offset / XvdFile.BLOCK_SIZE) * XvdFile.BLOCK_SIZE);
+ }
+
+ public static ulong InPageOffset(ulong offset)
+ {
+ return offset & (XvdFile.PAGE_SIZE - 1);
+ }
+
+ public static ulong BlockNumberToOffset(ulong blockNumber)
+ {
+ return blockNumber * XvdFile.BLOCK_SIZE;
+ }
+
+ public static ulong PageNumberToOffset(ulong pageNumber)
+ {
+ return pageNumber * XvdFile.PAGE_SIZE;
+ }
+
+ public static ulong BytesToBlocks(ulong bytes)
+ {
+ return (bytes + XvdFile.BLOCK_SIZE - 1) / XvdFile.BLOCK_SIZE;
+ }
+
+ public static ulong PagesToBlocks(ulong pages)
+ {
+ return (pages + XvdFile.PAGES_PER_BLOCK - 1) / XvdFile.PAGES_PER_BLOCK;
+ }
+
+ public static ulong BytesToPages(ulong bytes)
+ {
+ return (bytes + XvdFile.PAGE_SIZE - 1) / XvdFile.PAGE_SIZE;
+ }
+
+ public static ulong OffsetToBlockNumber(ulong offset)
+ {
+ return offset / XvdFile.BLOCK_SIZE;
+ }
+
+ public static ulong OffsetToPageNumber(ulong offset)
+ {
+ return offset / XvdFile.PAGE_SIZE;
+ }
+
+ public static ulong SectorsToBytes(ulong sectors)
+ {
+ return sectors * XvdFile.SECTOR_SIZE;
+ }
+
+ public static ulong LegacySectorsToBytes(ulong sectors)
+ {
+ return sectors * XvdFile.LEGACY_SECTOR_SIZE;
+ }
+
+ public static ulong ComputePagesSpanned(ulong startOffset, ulong lengthBytes)
+ {
+ return OffsetToPageNumber(startOffset + lengthBytes - 1) -
+ OffsetToPageNumber(lengthBytes) + 1;
+ }
+
+ public static ulong QueryFirstDynamicPage(ulong metaDataPagesCount)
+ {
+ return XvdFile.PAGES_PER_BLOCK * PagesToBlocks(metaDataPagesCount);
+ }
+
+ public static ulong ComputeDataBackingPageNumber(XvdType type, ulong numHashLevels, ulong hashPageCount, ulong dataPageNumber)
+ {
+ if (type > XvdType.Dynamic) // Invalid Xvd Type!
+ return dataPageNumber;
+
+ return dataPageNumber + hashPageCount;
+ }
+
+ public static ulong CalculateHashBlockNumForBlockNum(XvdType type, ulong hashTreeLevels, ulong numberOfHashedPages,
+ ulong blockNum, uint hashLevel, out ulong entryNumInBlock,
+ bool resilient=false, bool unknown=false)
+ {
+ ulong HashBlockExponent(ulong blockCount)
+ {
+ return (ulong)Math.Pow(0xAA, blockCount);
+ }
+
+ ulong result = 0xFFFF;
+ entryNumInBlock = 0;
+
+ if ((uint)type > 1 || hashLevel > 3)
+ return result; // Invalid data
+
+ if (hashLevel == 0)
+ entryNumInBlock = blockNum % 0xAA;
+ else
+ entryNumInBlock = blockNum / HashBlockExponent(hashLevel) % 0xAA;
+
+ if (hashLevel == 3)
+ return 0;
+
+ result = blockNum / HashBlockExponent(hashLevel + 1);
+ hashTreeLevels -= hashLevel + 1;
+
+ if (hashLevel == 0 && hashTreeLevels > 0)
+ {
+ result += (numberOfHashedPages + HashBlockExponent(2) - 1) / HashBlockExponent(2);
+ hashTreeLevels--;
+ }
+
+ if ((hashLevel == 0 || hashLevel == 1) && hashTreeLevels > 0)
+ {
+ result += (numberOfHashedPages + HashBlockExponent(3) - 1) / HashBlockExponent(3);
+ hashTreeLevels--;
+ }
+
+ if (hashTreeLevels > 0)
+ result += (numberOfHashedPages + HashBlockExponent(4) - 1) / HashBlockExponent(4);
+
+ if (resilient)
+ result *= 2;
+ if (unknown)
+ result++;
+
+ return result;
+ }
+
+ public static ulong CalculateNumHashBlocksInLevel(ulong size, ulong hashLevel, bool resilient)
+ {
+ ulong hashBlocks = 0;
+
+ switch (hashLevel)
+ {
+ case 0:
+ hashBlocks = (size + XvdFile.DATA_BLOCKS_IN_LEVEL0_HASHTREE - 1) / XvdFile.DATA_BLOCKS_IN_LEVEL0_HASHTREE;
+ break;
+ case 1:
+ hashBlocks = (size + XvdFile.DATA_BLOCKS_IN_LEVEL1_HASHTREE - 1) / XvdFile.DATA_BLOCKS_IN_LEVEL1_HASHTREE;
+ break;
+ case 2:
+ hashBlocks = (size + XvdFile.DATA_BLOCKS_IN_LEVEL2_HASHTREE - 1) / XvdFile.DATA_BLOCKS_IN_LEVEL2_HASHTREE;
+ break;
+ case 3:
+ hashBlocks = (size + XvdFile.DATA_BLOCKS_IN_LEVEL3_HASHTREE - 1) / XvdFile.DATA_BLOCKS_IN_LEVEL3_HASHTREE;
+ break;
+ }
+
+ if (resilient)
+ hashBlocks *= 2;
+
+ return hashBlocks;
+ }
+
+ public static ulong CalculateNumberHashPages(out ulong hashTreeLevels, ulong hashedPagesCount, bool resilient)
+ {
+ ulong hashTreePageCount = (hashedPagesCount + XvdFile.HASH_ENTRIES_IN_PAGE - 1) / XvdFile.HASH_ENTRIES_IN_PAGE;
+ hashTreeLevels = 1;
+
+ if (hashTreePageCount > 1)
+ {
+ ulong result = 2;
+ while (result > 1)
+ {
+ result = CalculateNumHashBlocksInLevel(hashedPagesCount, hashTreeLevels, false);
+ hashTreeLevels += 1;
+ hashTreePageCount += result;
+ }
+ }
+
+ if (resilient)
+ hashTreePageCount *= 2;
+
+ return hashTreePageCount;
+ }
+ }
+}
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..8c9cbef
--- /dev/null
+++ b/README.md
@@ -0,0 +1,61 @@
+# XvdTool.Streaming
+
+Rewritten and optimized version of XVDTool that lets you view information and extract files from streamed (remote, by URL) XVC/XVD files.
+Also allows for very fast extraction/decryption/hash-verification of local XVC/XVD files.
+
+Commands supported for both local and streamed types:
+- `info`
+ - Lets you view detailed information (headers, regions, segments, files) for a given file.
+- `extract`
+ - Lets you extract and decrypted the embedded files contained within a XVC.
+ *Note: Only supports the newer type of XVC which do not just contain a disk partition. (SegmentMetadata.bin)*
+
+Commands only supported by local files:
+- `verify`
+ - Validates the embedded hashes to check for any corruption.
+- `decrypt`
+ - Decrypts the file contents.
+
+Some speed estimates on an NVMe drive:
+- File extraction from local file (Hash Check enabled): ~200MB/s
+- File extraction from local file (Hash Check disbaled): ~800MB/s
+- Local file decryption: ~1GB/s
+
+Please note that you still need to acquire the respective CIK for a package before you are able to extract or decrypt it.
+For further information on that, check out [CikExtractor](https://github.com/LukeFZ/CikExtractor).
+
+For further information about XVC/XVD files in general, check out the original [XVDTool repository](https://github.com/emoose/xvdtool).
+
+Thanks to [emoose](https://github.com/emoose), [tuxuser](https://github.com/tuxuser) & contributors for developing the original [XVDTool](https://github.com/emoose/xvdtool).
+
+### Usage
+```
+USAGE:
+ XvdTool.Streaming.exe [OPTIONS]
+
+EXAMPLES:
+ XvdTool.Streaming.exe info c:/file.msixvc
+ XvdTool.Streaming.exe info c:/file.msixvc -o log.txt
+ XvdTool.Streaming.exe info https://assets1.xboxlive.com/...
+ XvdTool.Streaming.exe extract c:/file.msixvc
+ XvdTool.Streaming.exe extract c:/file.msixvc -o c:/output
+
+OPTIONS:
+ -h, --help Prints help information
+ -v, --version Prints version information
+
+COMMANDS:
+ info